Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(desktop): a tray icon keeps the app running when the window closes (#707)

Yaowei Zheng9eabc71d433c
diff --git a/changelog/unreleased/2026-09-12-desktop-tray.md b/changelog/unreleased/2026-09-12-desktop-tray.md
new file mode 100644
index 00000000..055ff7c5
--- /dev/null
+++ b/changelog/unreleased/2026-09-12-desktop-tray.md
@@ -0,0 +1,25 @@
+# A tray icon for the desktop shell
+
+- **Date:** 2026-09-12
+- **Type:** feature
+- **Scope:** `desktop`, `server`, `web`
+- **PR:** [#707](https://github.com/Prism-Shadow/penguin-harness/pull/707)
+- **Issue:** [#569](https://github.com/Prism-Shadow/penguin-harness/issues/569)
+
+[中文版](2026-09-12-desktop-tray.zh.md)
+
+The desktop app took a place in the system tray — the Windows notification area, the macOS menu bar, the Linux tray — for as long as it runs, and closing the main window came to hide it there by default, leaving the embedded server and its background tasks running with a one-click way back.
+
+## Details
+
+- The icon is rendered by `scripts/render-icon.mjs` and committed under `build/tray/`: a 32px colour image (with a 64px `@2x`) for Windows and Linux, taken from the app's own artwork, and a 16px monochrome template image (with a 32px `@2x`) that the macOS menu bar inverts with its own appearance. The menu bar image is the penguin's outline alone, taken out of the brand mark by the render script rather than shrunk from the whole of it. A template image is a mask — the menu bar paints every non-transparent pixel in its own colour — so the whole artwork gives up almost all of itself: the white backdrop flattens to a filled square, and the belly, which the artwork draws as a hole letting that backdrop through, flattens to nothing. What was left covered 19% of the canvas, nearly all of it antialiasing. Keeping the body path's outer subpath alone gives the outline with the belly solid; the two arcs sweeping around the penguin, the highlights and the eye are separate paths and are not drawn. Framed to the square its bounding box inscribes, so it fills the bar's width instead of sitting in the artwork's rounded-square padding, it covers 35%. Two assertions hold that: the template images carry no colour, and neither falls below 30% — a 4:3 silhouette in a square canvas cannot go much past a third without losing the beak and the tail to the crop. `scripts/build-assets.mjs` stages the set into `dist/tray/`, where the shell looks it up relative to the app directory, so a source run and a packaged app read the same layout. The tooltip is the app name, dev suffix included.
+- A left click on the icon brings the main window forward: shown when it was hidden, restored when minimized, recreated when it had been closed. A right click — Ctrl+click on macOS — opens the menu: **Open PenguinHarness**; **New Session** and **Models**, which navigate the main window to `/chat/new` and `/models`; the **Keep running in the tray when the window closes** checkbox; and **Quit**, which exits through the existing graceful server stop.
+- The two clicks are what the platform supports: on Linux the menu is attached to the icon itself and the desktop decides which click opens it, while on macOS and Windows a left click shows the window and a right click opens the menu.
+- **Keep running in the tray when the window closes** is on by default, and closing the window then only hides it, on all three platforms. Turning it off restores the previous behaviour: on macOS the window closes and the app stays in the Dock, on Windows and Linux the app quits. So does turning the icon off — with nothing in the tray to bring a hidden window back, the close goes through rather than hiding it.
+- **Settings › Appearance** gained a **Tray icon** switch, on by default, which turns the icon off and on with no restart: it leaves the tray the moment the switch moves, and comes back the same way. The row appears only in the desktop app's own window; a browser signed into the same server does not get it. The switch reaches the shell over the message channel the client updater already uses (`GET` / `PUT /api/desktop/tray`), so the window stays a plain browser with no IPC bridge of its own.
+- The tray menu reads in the language the window does. The shell cannot see that preference — it lives in the browser's localStorage, and the desktop design keeps that boundary one-way — so the page reports its UI language over the same `PUT /api/desktop/tray` the Appearance switch uses, on load and whenever it changes. The shell keeps the last report beside the two switches, so a fresh launch draws the right menu before any window has finished loading; until anything has been reported it follows the device language, by the same rule the Web App applies to its own "follow the system" default. The six labels are written twice in `tray-menu.ts` rather than read from the Web App's catalogs: the shell is a separate process that starts before any page loads and cannot import from `packages/web`, and a type makes a missing translation a compile error rather than a blank entry.
+- The tray route's PUT became a patch — `showTrayIcon`, `locale`, or both — because the switch and the language are written by different parts of the page at different moments, and neither should have to restate the other's value. A request that asks for nothing is refused rather than relayed.
+- Both preferences are stored in `userData/tray.json`; a missing or malformed file reads as on for each of them independently, and a write that fails is logged and nothing more.
+- A second launch of the app, and a Dock click on macOS, now surface a window hidden in the tray instead of only focusing or recreating one.
+- A platform that cannot host a tray icon — a Linux desktop without a tray, a headless run — logs the failure and continues without one, and closing the window there keeps its previous per-platform behaviour.
+- Deliberately not included: a recent-sessions submenu and a running-activity indicator on the icon. Both need the shell to ask the server what is going on, and the relay between them carries nothing but a shutdown token, update status and this one preference.
diff --git a/changelog/unreleased/2026-09-12-desktop-tray.zh.md b/changelog/unreleased/2026-09-12-desktop-tray.zh.md
new file mode 100644
index 00000000..ae0c56fb
--- /dev/null
+++ b/changelog/unreleased/2026-09-12-desktop-tray.zh.md
@@ -0,0 +1,33 @@
+# 桌面应用的系统托盘图标
+
+- **Date:** 2026-09-12
+- **Type:** feature
+- **Scope:** `desktop`, `server`, `web`
+- **PR:** [#707](https://github.com/Prism-Shadow/penguin-harness/pull/707)
+- **Issue:** [#569](https://github.com/Prism-Shadow/penguin-harness/issues/569)
+
+[English](2026-09-12-desktop-tray.md)
+
+桌面应用运行期间在系统托盘(Windows 通知区、macOS 菜单栏、Linux 托盘)常驻一个图标,关闭主窗口默认改为收进托盘:内嵌 server 与后台任务继续运行,一次点击即可回到窗口。
+
+## 细节
+
+- 图标由 `scripts/render-icon.mjs` 渲染并入库到 `build/tray/`:Windows 与 Linux 用 32px 彩色图(另有 64px `@2x`),取自应用自身的品牌图形;macOS 用 16px 单色 Template 图(另有 32px `@2x`),由菜单栏随明暗自动反色。菜单栏那张只取企鹅自身的轮廓,由渲染脚本从品牌图形中提取,而不是把整幅图缩小。Template 图是一张蒙版——菜单栏把其中每个非透明像素都涂成自己的颜色——因此整幅图会丢掉绝大部分:白色底板压平后成为一个实心方块,而肚皮在原图里本就是一个让底板透出来的孔洞,压平后什么都不剩。余下的部分只占画布 19%,且几乎全是抗锯齿的灰边。只取躯干路径的外层子路径,即得到肚皮为实心的轮廓;企鹅周围的两道弧线、高光与眼睛都是另外的路径,不予绘制。再以其包围盒内接的正方形取景,使其填满菜单栏的宽度、而不是留着品牌图形圆角方块的内边距,占比为 35%。两条断言守住这一点:Template 图中不得含有颜色,且占比不得低于 30%——4:3 的剪影放进正方形画布,再往上就要把喙与尾巴裁掉了。`scripts/build-assets.mjs` 将整套复制进 `dist/tray/`,壳按应用目录的相对路径查找,源码运行与打包应用读同一套布局。提示文字为应用名,含开发实例的 dev 后缀。
+- 左键点击图标把主窗口带到前台:隐藏则显示、最小化则还原、已关闭则重建。右键(macOS 亦可 Ctrl + 点击)弹出菜单:**Open PenguinHarness**;**New Session** 与 **Models**,在主窗口内导航到 `/chat/new` 与 `/models`;**Keep running in the tray when the window closes** 复选项;以及 **Quit**,走既有的优雅停止 server 的退出路径。
+- 两种点击各按平台的支持程度落地:Linux 上菜单直接挂在图标上,由桌面环境决定哪一种点击打开它;macOS 与 Windows 上则是左键显示窗口、右键弹出菜单。
+- **Keep running in the tray when the window closes** 默认开启,三平台关窗都只隐藏窗口。关掉它则恢复原有行为:macOS 关窗后应用保留在 Dock,Windows 与 Linux 关窗即退出。关掉托盘图标同理——托盘里没有图标可以把隐藏的窗口唤回来,关窗就直接放行,不再隐藏。
+- **设置 › 外观** 新增 **托盘图标** 开关,默认开启,无需重启即时生效:关掉图标立刻从托盘消失,打开同样立刻回来。该行只在桌面应用自己的窗口里出现,浏览器登录同一个 server 时没有。开关经由客户端更新已有的消息通道抵达壳(`GET` / `PUT /api/desktop/tray`),窗口仍是纯浏览器,不引入自己的 IPC 通道。
+- 托盘菜单与窗口使用同一种语言。这项偏好壳自己看不到——它存在浏览器的 localStorage 里,而桌面端的设计
+ 刻意让这道边界只能单向通过——因此由页面经 Appearance 开关所用的同一个 `PUT /api/desktop/tray` 上报:
+ 载入时报一次,此后每次切换再报。壳把最近一次上报与那两个开关存在一起,于是重新启动时,早在任何窗口
+ 加载完成之前,菜单就已经是对的;在任何上报到达之前则跟随设备语言,与 Web App 自身「跟随系统」默认值
+ 所用的规则相同。那六条文案在 `tray-menu.ts` 中写了两份,而不是去读 Web App 的词典:壳是一个独立进程,
+ 在任何页面加载之前就已启动,且无法从 `packages/web` 导入;类型会让漏译成为编译错误,而不是一条空白
+ 菜单项。
+- 托盘路由的 PUT 改为接受一个补丁——`showTrayIcon`、`locale`,或两者皆有——因为开关与语言由页面的不同
+ 部分在不同时刻写入,任何一方都不应为了改自己的值而重述对方的值。什么都不要求的请求会被拒绝,而不是
+ 转发给壳。
+- 两个偏好都存于 `userData/tray.json`;文件缺失或格式不对时各自按开启处理,写入失败只记日志,不做别的。
+- 二次启动应用、以及 macOS 上点击 Dock 图标,现在都会把收进托盘的窗口重新显示出来,而不只是聚焦或重建窗口。
+- 无法承载托盘图标的环境(没有托盘的 Linux 桌面、无头运行)会记录失败并继续运行,此时关窗仍保持各平台原有行为。
+- 本批刻意不做:最近会话子菜单与图标上的「有任务在跑」指示。两者都需要壳向 server 查询状态,而目前二者之间的通道只往来 shutdown token、更新状态与这一个偏好。
diff --git a/packages/desktop/build/tray/tray.png b/packages/desktop/build/tray/tray.png
new file mode 100644
index 00000000..531f4090
Binary files /dev/null and b/packages/desktop/build/tray/tray.png differ
diff --git a/packages/desktop/build/tray/[email protected] b/packages/desktop/build/tray/[email protected]
new file mode 100644
index 00000000..b99c4563
Binary files /dev/null and b/packages/desktop/build/tray/[email protected] differ
diff --git a/packages/desktop/build/tray/trayTemplate.png b/packages/desktop/build/tray/trayTemplate.png
new file mode 100644
index 00000000..aa4063da
Binary files /dev/null and b/packages/desktop/build/tray/trayTemplate.png differ
diff --git a/packages/desktop/build/tray/[email protected] b/packages/desktop/build/tray/[email protected]
new file mode 100644
index 00000000..40ff23f7
Binary files /dev/null and b/packages/desktop/build/tray/[email protected] differ
diff --git a/packages/desktop/scripts/build-assets.mjs b/packages/desktop/scripts/build-assets.mjs
index 8a66d22c..20db5a6f 100644
--- a/packages/desktop/scripts/build-assets.mjs
+++ b/packages/desktop/scripts/build-assets.mjs
@@ -13,8 +13,9 @@
* run, and core's bundled loader resolves them by name from the bundle's own location. The
* server's web-dist lookup is likewise satisfied by electron-builder's file mapping when
* packaging; a source run falls back to packages/web/dist on its own.)
- * - `dist/icon.png` — the runtime window icon, read app-path-relative (see src/app-icon.ts).
- * build/ is electron-builder's buildResources directory and does not ship inside the app.
+ * - `dist/icon.png`, `dist/tray/*.png` — the runtime window and tray icons, read
+ * app-path-relative (see src/app-icon.ts). build/ is electron-builder's buildResources
+ * directory and does not ship inside the app.
* - `bin/penguin`, `bin/penguin.cmd` — the CLI launchers, whose script text lives in
* src/launcher.ts so it is unit-tested with the rest of the shell.
* - `dist/install.sh`, `dist/install.ps1` — the release installers, which the Machines page
@@ -61,6 +62,22 @@ if (!fs.existsSync(iconSrc)) {
}
fs.copyFileSync(iconSrc, path.join(distDir, "icon.png"));
+// The tray set travels whole: each icon has an @2x sibling the image loader picks up on a
+// high-DPI display, and macOS takes the template variant instead of the colour one.
+const traySrcDir = path.join(pkgDir, "build", "tray");
+const trayIcons = fs.existsSync(traySrcDir)
+ ? fs.readdirSync(traySrcDir).filter((name) => name.endsWith(".png"))
+ : [];
+if (trayIcons.length === 0) {
+ console.error("[build-assets] build/tray/ has no icons — run `node scripts/render-icon.mjs`.");
+ process.exit(1);
+}
+const trayDistDir = path.join(distDir, "tray");
+fs.mkdirSync(trayDistDir, { recursive: true });
+for (const name of trayIcons) {
+ fs.copyFileSync(path.join(traySrcDir, name), path.join(trayDistDir, name));
+}
+
// node-pty, resolved from the package that depends on it: under pnpm it is installed into
// packages/server/node_modules, out of reach of any lookup anchored in this package.
const serverRequire = createRequire(path.resolve(pkgDir, "..", "server", "package.json"));
@@ -97,5 +114,5 @@ fs.chmodSync(path.join(binDir, "penguin"), 0o755);
fs.writeFileSync(path.join(binDir, "penguin.cmd"), windowsLauncherScript());
console.log(
- `[build-assets] done: dist/icon.png, dist/install.{sh,ps1}, bin/, ${NODE_PTY_RELDIR.join("/")} (${ptyFiles.length} files, bindings: ${bindings.join(", ")})`,
+ `[build-assets] done: dist/icon.png, dist/tray/ (${trayIcons.length} icons), dist/install.{sh,ps1}, bin/, ${NODE_PTY_RELDIR.join("/")} (${ptyFiles.length} files, bindings: ${bindings.join(", ")})`,
);
diff --git a/packages/desktop/scripts/render-icon.mjs b/packages/desktop/scripts/render-icon.mjs
index e98fa2ba..949be647 100644
--- a/packages/desktop/scripts/render-icon.mjs
+++ b/packages/desktop/scripts/render-icon.mjs
@@ -11,6 +11,14 @@
* give it the same optical size as native macOS app icons.
* - build/icons/<N>x<N>.png 128/256/512 freedesktop set for the Linux targets
* (used as-is, no conversion).
+ * - build/tray/tray.png 32×32 (+ @2x 64×64) colour tray icon for the Windows
+ * notification area and Linux trays.
+ * - build/tray/trayTemplate.png
+ * 16×16 (+ @2x 32×32) macOS menu bar image: a black silhouette
+ * on transparency, which the menu bar inverts with its own
+ * appearance. Reduced to the penguin's outline alone, with the
+ * belly solid and the arcs around it dropped — see penguinOutline
+ * below for why the whole mark cannot survive 16 pixels.
*
* Regenerate: node packages/desktop/scripts/render-icon.mjs
* Rasterizes via the Playwright chromium already installed for packages/landing (no new
@@ -29,13 +37,63 @@ const REPO_ROOT = path.resolve(PKG_DIR, "..", "..");
const SVG_PATH = path.join(REPO_ROOT, "packages", "web", "public", "penguin-logo.svg");
const BUILD_DIR = path.join(PKG_DIR, "build");
const ICON_SET_DIR = path.join(BUILD_DIR, "icons");
+const TRAY_DIR = path.join(BUILD_DIR, "tray");
// Resolve @playwright/test from the landing package's context (it is not a dependency
// of this package, and must not become one).
const requireLanding = createRequire(path.join(REPO_ROOT, "packages", "landing", "package.json"));
const { chromium } = requireLanding("@playwright/test");
-const svgDataUrl = `data:image/svg+xml;base64,${readFileSync(SVG_PATH).toString("base64")}`;
+const svgSource = readFileSync(SVG_PATH, "utf8");
+const dataUrl = (svg) => `data:image/svg+xml;base64,${Buffer.from(svg, "utf8").toString("base64")}`;
+const svgDataUrl = dataUrl(svgSource);
+
+/**
+ * The penguin's own outline, lifted out of the brand mark for the macOS menu bar image.
+ *
+ * A template image is a mask: the menu bar paints every non-transparent pixel in its own colour
+ * and throws the original away. Handing it the whole artwork gives up almost all of it — the
+ * white backdrop flattens to a filled square, and the belly, which the artwork draws as a hole
+ * letting that backdrop through, flattens to nothing. What survives at 16px is a wisp.
+ *
+ * So the mark is reduced to one shape before it is rasterized. The body path carries the penguin
+ * as two subpaths, the outline and the belly cut out of it; taking the first alone gives the
+ * outline with the belly solid. The two arcs sweeping around the penguin, its highlights and its
+ * eye are separate paths and are simply not drawn — at this size they are noise.
+ *
+ * Matched on the body path's gradient reference rather than its geometry, so a reworked
+ * illustration fails the render loudly instead of quietly shipping the wrong shape.
+ */
+const BODY_FILL = 'fill="url(#a)"';
+function penguinOutline(source) {
+ const path = source.match(/<path\s+fill="url\(#a\)"\s+d="([^"]+)"/)?.[1];
+ if (path === undefined) return null;
+ // Subpaths start at M or m; the second one is the belly, cut out of the first.
+ const subpaths = path.match(/[Mm][^Mm]*/g) ?? [];
+ return subpaths.length === 2 ? subpaths[0] : null;
+}
+const outline = penguinOutline(svgSource);
+if (outline === null) {
+ console.error(
+ `[render-icon] could not take the penguin's outline out of ${path.relative(REPO_ROOT, SVG_PATH)}: ` +
+ `expected one ${BODY_FILL} path of exactly two subpaths (the outline and the belly cut from it). ` +
+ `Check the artwork and update penguinOutline().`,
+ );
+ process.exit(1);
+}
+
+/**
+ * Wraps the outline in a square viewBox that its bounding box exactly inscribes, so the mark
+ * fills the menu bar's width instead of sitting inside the artwork's rounded-square padding.
+ *
+ * It is a wide shape — about 4:3 — in a square canvas, so a band above and below is unavoidable;
+ * cropping past the bounding box takes the beak off one side and the tail off the other. That
+ * bounds the coverage at roughly a third of the canvas, which the icon test pins.
+ */
+function squareAround({ x, y, width, height }) {
+ const side = Math.max(width, height);
+ return `${x + width / 2 - side / 2} ${y + height / 2 - side / 2} ${side} ${side}`;
+}
/**
* Apple's 1024px app-icon template keeps the full rounded-square artwork inside an
@@ -52,13 +110,39 @@ const targets = [
{ size: 512, outPath: path.join(ICON_SET_DIR, "512x512.png"), artworkRatio: 1 },
{ size: 256, outPath: path.join(ICON_SET_DIR, "256x256.png"), artworkRatio: 1 },
{ size: 128, outPath: path.join(ICON_SET_DIR, "128x128.png"), artworkRatio: 1 },
+ { size: 32, outPath: path.join(TRAY_DIR, "tray.png"), artworkRatio: 1 },
+ { size: 64, outPath: path.join(TRAY_DIR, "[email protected]"), artworkRatio: 1 },
+ { size: 16, outPath: path.join(TRAY_DIR, "trayTemplate.png"), artworkRatio: 1, template: true },
+ {
+ size: 32,
+ outPath: path.join(TRAY_DIR, "[email protected]"),
+ artworkRatio: 1,
+ template: true,
+ },
];
mkdirSync(ICON_SET_DIR, { recursive: true });
+mkdirSync(TRAY_DIR, { recursive: true });
const browser = await chromium.launch();
try {
- for (const { size, outPath, artworkRatio } of targets) {
+ // The bounding box comes from the renderer rather than a constant: it is a property of the
+ // artwork, and a hand-copied number is what goes stale when the artwork moves.
+ const measure = await browser.newPage();
+ await measure.setContent(
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1254 1254"><path d="${outline}"/></svg>`,
+ );
+ const box = await measure.evaluate(() => {
+ const { x, y, width, height } = document.querySelector("path").getBBox();
+ return { x, y, width, height };
+ });
+ await measure.close();
+ const templateDataUrl = dataUrl(
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${squareAround(box)}">` +
+ `<path fill="#000" d="${outline}"/></svg>`,
+ );
+
+ for (const { size, outPath, artworkRatio, template = false } of targets) {
const artworkSize = size * artworkRatio;
const page = await browser.newPage({
viewport: { width: size, height: size },
@@ -68,7 +152,7 @@ try {
`<style>html,body{margin:0;padding:0;width:100%;height:100%;background:transparent}` +
`body{display:flex;align-items:center;justify-content:center}` +
`img{display:block;width:${artworkSize}px;height:${artworkSize}px}</style>` +
- `<img src="${svgDataUrl}">`,
+ `<img src="${template ? templateDataUrl : svgDataUrl}">`,
);
await page.evaluate(() => document.querySelector("img").decode());
const png = await page.screenshot({
diff --git a/packages/desktop/src/app-icon.ts b/packages/desktop/src/app-icon.ts
index 9ac8d294..61e96680 100644
--- a/packages/desktop/src/app-icon.ts
+++ b/packages/desktop/src/app-icon.ts
@@ -1,13 +1,16 @@
/**
- * Runtime window icon — pure path logic, no Electron imports (unit-tested).
+ * Runtime window and tray icons — pure path logic, no Electron imports (unit-tested).
*
- * Only Linux (and Windows dev runs) need it: a packaged Windows app gets its taskbar
- * icon from the exe resources electron-builder embeds, and macOS ignores BrowserWindow
- * icons entirely (the Dock icon comes from the bundle's icns). The committed master is
- * build/icon.png (rendered by scripts/render-icon.mjs), which is electron-builder's
- * buildResources directory and does not ship inside the app; scripts/build-assets.mjs
- * copies it into dist/, so the same app-path-relative lookup serves both a source run and
- * a packaged app.
+ * The window icon is only needed on Linux (and Windows dev runs): a packaged Windows app gets
+ * its taskbar icon from the exe resources electron-builder embeds, and macOS ignores
+ * BrowserWindow icons entirely (the Dock icon comes from the bundle's icns). The tray icon is
+ * needed on all three, in two forms — macOS takes a monochrome template image the menu bar
+ * inverts with its own appearance, the other two a small colour image.
+ *
+ * The committed masters are build/icon.png and build/tray/*.png (rendered by
+ * scripts/render-icon.mjs), which is electron-builder's buildResources directory and does not
+ * ship inside the app; scripts/build-assets.mjs copies them into dist/, so the same
+ * app-path-relative lookup serves both a source run and a packaged app.
*/
import fs from "node:fs";
import path from "node:path";
@@ -26,3 +29,25 @@ export function resolveWindowIcon(appPath: string, platform: NodeJS.Platform): s
const iconPath = windowIconPathFor(appPath, platform);
return iconPath !== null && fs.existsSync(iconPath) ? iconPath : null;
}
+
+/**
+ * Tray icon location relative to the app directory. The `…Template` name is what tells macOS
+ * to treat the image as a mask; each file has an `@2x` sibling that the image loader picks up
+ * on a high-DPI display.
+ */
+export function trayIconRelPath(platform: NodeJS.Platform): string[] {
+ return platform === "darwin"
+ ? ["dist", "tray", "trayTemplate.png"]
+ : ["dist", "tray", "tray.png"];
+}
+
+/** The tray-icon path for a platform, whether or not the file is there. */
+export function trayIconPathFor(appPath: string, platform: NodeJS.Platform): string {
+ return path.join(appPath, ...trayIconRelPath(platform));
+}
+
+/** Same, but only when the file exists — a missing icon leaves the app without a tray. */
+export function resolveTrayIcon(appPath: string, platform: NodeJS.Platform): string | null {
+ const iconPath = trayIconPathFor(appPath, platform);
+ return fs.existsSync(iconPath) ? iconPath : null;
+}
diff --git a/packages/desktop/src/main.ts b/packages/desktop/src/main.ts
index 0e5da442..4112d58f 100644
--- a/packages/desktop/src/main.ts
+++ b/packages/desktop/src/main.ts
@@ -19,6 +19,12 @@
* Attach mode: when a live server (e.g. `penguin web`) already owns the data root, the
* window loads that instance instead — normal login page, deliberate degradation.
*
+ * Tray: a system-tray icon is shown for as long as the app runs, and by default closing the
+ * window only hides it, so the server and its background tasks keep running (see tray.ts;
+ * both preferences live in userData/tray.json and Quit still goes through the graceful
+ * stop). Settings › Appearance turns the icon off and on, reaching the shell over the same
+ * utilityProcess relay the client updater uses.
+ *
* Dev isolation: an unpackaged run takes a dev-suffixed identity (own userData, and with
* it the single-instance lock and sticky port) and defaults to the ~/.penguin/dev-data
* root, so it runs beside an installed release build (see app-identity.ts).
@@ -36,16 +42,27 @@ import { liveServerLock } from "@prismshadow/penguin-server/lock";
import { appIdentity, desktopDataRoot } from "./app-identity.js";
import { embeddedCliEntry } from "./launcher.js";
import { webDistEntry, webDistFor } from "./web-dist.js";
-import { resolveWindowIcon } from "./app-icon.js";
+import { resolveTrayIcon, resolveWindowIcon } from "./app-icon.js";
import { installCliCommand, ensureCliCommand, currentCliInstallKind } from "./cli-install.js";
import { applyLoginShellEnv } from "./login-shell-env.js";
import { installAppMenu } from "./menu.js";
import { startEmbeddedServer, stopEmbeddedServer } from "./server-process.js";
import type { EmbeddedServer } from "./server-process.js";
+import { resolveTrayLocale } from "./tray-menu.js";
+import type { TrayLocale } from "./tray-menu.js";
+import { installTray } from "./tray.js";
+import type { TrayHandle } from "./tray.js";
+import {
+ parseTrayCommand,
+ readTrayPrefs,
+ trayStatusMessage,
+ updateTrayPrefs,
+} from "./tray-prefs.js";
import { getUpdaterStatus, handleUpdaterCommand, initUpdater, onUpdaterStatus } from "./updater.js";
import { parseUpdaterCommand, updaterStatusMessage } from "./updater-status.js";
import {
desktopLoginUrl,
+ hidesOnClose,
isAppUrl,
isLocalSurfaceUrl,
MAX_SERVER_RESTARTS,
@@ -65,7 +82,18 @@ app.setName(identity.name);
if (process.platform === "win32") app.setAppUserModelId(identity.appUserModelId);
let win: BrowserWindow | null = null;
+let tray: TrayHandle | null = null;
+/** The Appearance switch's value; the tray exists exactly while this is true and one could be created. */
+let showTrayIcon = true;
+/**
+ * The language the tray menu is drawn in. Seeded from the stored report, or from the device
+ * when there is none, so the first menu of a fresh launch is already right — the Web App's
+ * own report arrives only once a window has loaded far enough to send it.
+ */
+let trayLocale: TrayLocale = "en";
let server: EmbeddedServer | null = null;
+/** The live server child, for pushes that are not answers to one of its messages. */
+let relayChild: EmbeddedServer["child"] | null = null;
/** App origin (embedded or attached); null until boot resolves. */
let appOrigin: string | null = null;
let quitting = false;
@@ -98,6 +126,19 @@ function createWindow(url: string): void {
},
});
win.once("ready-to-show", () => win?.show());
+ // Close-to-tray: the window goes away, the app and its embedded server stay, and the tray
+ // icon is the way back. Every real exit — the tray's Quit, the app menu's, an OS logout —
+ // passes through before-quit first, which is what `quitting` reports.
+ win.on("close", (event) => {
+ const hide = hidesOnClose({
+ quitting,
+ trayShown: tray !== null,
+ closeToTray: tray?.closeToTray() ?? false,
+ });
+ if (!hide) return;
+ event.preventDefault();
+ win?.hide();
+ });
win.on("closed", () => {
win = null;
});
@@ -152,19 +193,136 @@ function createWindow(url: string): void {
}
/**
- * Client-update relay over the utilityProcess port: forward the account-menu row's
- * check/install frames to the updater, push every status fold back (plus the current
- * snapshot now — the fresh child, restarts included, must not start blind). The
- * subscription dies with the child; the next start wires the next one.
+ * Bring the main window forward, whatever state it is in: hidden by close-to-tray, minimized,
+ * or gone entirely (a closed window with close-to-tray off). Used by the tray icon, a second
+ * launch, and the macOS Dock.
+ */
+function showMainWindow(): void {
+ if (win === null) {
+ if (appOrigin !== null) createWindow(`${appOrigin}/`);
+ return;
+ }
+ if (win.isMinimized()) win.restore();
+ win.show();
+ win.focus();
+}
+
+/**
+ * Tray navigation. The window is a plain browser, so a destination is just a URL to load —
+ * no IPC channel into the Web App. Before boot resolves an origin there is nowhere to go, and
+ * showing the window is the whole action. A window that has to be created starts on the
+ * destination rather than on the app root: loading `/` first would boot the whole Web App
+ * only to abort it a tick later, with the aborted load's rejection going unhandled.
+ */
+function navigateMainWindow(target: string): void {
+ if (appOrigin === null) {
+ showMainWindow();
+ return;
+ }
+ const url = `${appOrigin}${target}`;
+ if (win === null) {
+ createWindow(url);
+ return;
+ }
+ showMainWindow();
+ void win.loadURL(url);
+}
+
+// --- tray -----------------------------------------------------------------
+
+/**
+ * Creates the tray icon if the preference asks for one and there is none. Idempotent: the
+ * app installs exactly one tray, and a platform that cannot host one (a Linux desktop
+ * without a tray, a headless run) simply leaves `tray` null — see installTray.
+ */
+function openTray(): void {
+ // `quitting`: before-quit takes the icon down, and a frame still in flight from the
+ // page must not put one back for the seconds the graceful server stop takes.
+ if (quitting || !showTrayIcon || tray !== null) return;
+ tray = installTray({
+ userDataDir: app.getPath("userData"),
+ iconPath: resolveTrayIcon(app.getAppPath(), process.platform),
+ appName: app.name,
+ locale: trayLocale,
+ onShowWindow: showMainWindow,
+ onNavigate: navigateMainWindow,
+ onQuit: () => app.quit(),
+ log: (line) => process.stdout.write(`[shell] ${line}\n`),
+ });
+}
+
+/**
+ * Applies Settings › Appearance's tray switch: the icon appears or goes at once, no
+ * restart, and the choice is stored for the next launch. Turning it off also turns off
+ * close-to-tray in effect — with no icon the window's close handler stops intercepting
+ * (see hidesOnClose), so the window can never hide where nothing could bring it back.
*/
-function wireUpdaterRelay(child: EmbeddedServer["child"]): void {
+function setShowTrayIcon(next: boolean): void {
+ showTrayIcon = next;
+ try {
+ updateTrayPrefs(app.getPath("userData"), { showTrayIcon: next });
+ } catch (err) {
+ process.stdout.write(`[shell] the tray preference could not be saved: ${String(err)}\n`);
+ }
+ if (next) {
+ openTray();
+ } else {
+ tray?.dispose();
+ tray = null;
+ }
+ pushTrayStatus();
+}
+
+/** Tells the page what the tray is actually doing, which is what its switch renders. */
+function pushTrayStatus(): void {
+ relayChild?.postMessage(trayStatusMessage(showTrayIcon, trayLocale));
+}
+
+/**
+ * Applies the Web App's UI language to the tray menu. The menu is built per popup, so a
+ * change costs nothing until the next one is opened — except on Linux, where the menu is
+ * attached to the icon and has to be rebuilt in place; the tray handle does that itself.
+ */
+function setTrayLocale(next: TrayLocale): void {
+ if (next === trayLocale) return;
+ trayLocale = next;
+ try {
+ updateTrayPrefs(app.getPath("userData"), { locale: next });
+ } catch (err) {
+ process.stdout.write(`[shell] the tray language could not be saved: ${String(err)}\n`);
+ }
+ tray?.setLocale(next);
+ pushTrayStatus();
+}
+
+/**
+ * Shell relay over the utilityProcess port: forward the account-menu row's check/install
+ * frames to the updater and the Appearance switch's frames to the tray, push every updater
+ * status fold back, and push both current states now — the fresh child, restarts included,
+ * must not start blind. The subscription dies with the child; the next start wires the next
+ * one.
+ */
+function wireShellRelay(child: EmbeddedServer["child"]): void {
+ relayChild = child;
child.on("message", (message: unknown) => {
const action = parseUpdaterCommand(message);
- if (action !== null) handleUpdaterCommand(action);
+ if (action !== null) {
+ handleUpdaterCommand(action);
+ return;
+ }
+ const command = parseTrayCommand(message);
+ if (command !== null) {
+ if (command.locale !== undefined) setTrayLocale(command.locale);
+ if (command.showTrayIcon !== undefined) setShowTrayIcon(command.showTrayIcon);
+ }
});
const unsubscribe = onUpdaterStatus((status) => child.postMessage(updaterStatusMessage(status)));
- child.on("exit", () => unsubscribe());
+ child.on("exit", () => {
+ unsubscribe();
+ if (relayChild === child) relayChild = null;
+ });
child.postMessage(updaterStatusMessage(getUpdaterStatus()));
+ pushTrayStatus();
}
/** Starts (or restarts) the embedded server and points the window at the claim link. */
@@ -196,7 +354,7 @@ async function startServerAndWindow(dataRoot: string): Promise<void> {
});
server = started;
appOrigin = started.origin;
- wireUpdaterRelay(started.child);
+ wireShellRelay(started.child);
// A run that stays up for a minute is healthy: reset the restart budget so a crash
// days later starts a fresh 1s/2s/4s ladder instead of hitting the cap immediately.
const healthyTimer = setTimeout(() => {
@@ -260,26 +418,25 @@ async function boot(): Promise<void> {
if (!app.requestSingleInstanceLock()) {
app.quit();
} else {
- app.on("second-instance", () => {
- if (win !== null) {
- if (win.isMinimized()) win.restore();
- win.focus();
- }
- });
+ app.on("second-instance", () => showMainWindow());
app.on("window-all-closed", () => {
// macOS keeps the app alive in the Dock; elsewhere closing the window quits.
if (process.platform !== "darwin") app.quit();
});
- app.on("activate", () => {
- if (win === null && appOrigin !== null) createWindow(`${appOrigin}/`);
- });
+ // Dock click: the window may be hidden in the tray rather than gone, so show before recreate.
+ app.on("activate", () => showMainWindow());
// Quit path: stop the embedded server gracefully first (shutdown endpoint → kill),
// then let the quit proceed. Attach mode has no child to stop.
app.on("before-quit", (event) => {
quitting = true;
+ // The icon goes as soon as the app is on its way out, rather than lingering through the
+ // graceful server stop; nulling it keeps the second pass (after the stop) from destroying
+ // an already destroyed tray.
+ tray?.dispose();
+ tray = null;
if (server !== null && stopPromise === null) {
event.preventDefault();
const running = server;
@@ -305,6 +462,16 @@ if (!app.requestSingleInstanceLock()) {
includeCliInstall: currentCliInstallKind() !== null,
onInstallCli: () => void installCliCommand(win),
});
+ // Before boot, and whatever the window is doing: the icon is there for as long as the
+ // app runs. Its menu's navigation entries tolerate an origin that is not resolved yet,
+ // and the close-to-tray preference has to be in hand before the first window close can
+ // happen.
+ const trayPrefs = readTrayPrefs(app.getPath("userData"));
+ showTrayIcon = trayPrefs.showTrayIcon;
+ // Nothing has reported a language yet on a first launch, so the device decides — the
+ // same rule the Web App applies to its own "follow the system" default.
+ trayLocale = trayPrefs.locale ?? resolveTrayLocale(app.getLocale());
+ openTray();
initUpdater(() => win);
await boot();
// Install or repair the bundled 'penguin' command. Runs every launch: that is what
diff --git a/packages/desktop/src/tray-menu.ts b/packages/desktop/src/tray-menu.ts
new file mode 100644
index 00000000..38f4cd52
--- /dev/null
+++ b/packages/desktop/src/tray-menu.ts
@@ -0,0 +1,101 @@
+/**
+ * The tray menu as data — pure, no Electron imports (unit-tested). src/tray.ts turns it
+ * into a native menu and binds the actions.
+ *
+ * The entries are deliberately few: the window is the product, and the tray is the way back
+ * to it. The two navigation entries are ordinary in-window URL loads, so the window stays a
+ * plain browser and the shell gains no channel into the Web App.
+ *
+ * The labels are written twice here rather than read from the Web App's catalogs: the shell
+ * is a separate process that starts before any page is loaded and must draw a menu whether or
+ * not one ever is, and it cannot import from `packages/web` — nothing in this package depends
+ * on it. Six strings is the whole surface, and the type below makes a missing translation a
+ * compile error rather than a menu that silently falls back to English.
+ */
+
+/** What a menu entry does when it is clicked. */
+export type TrayAction = "open" | "new-session" | "models" | "toggle-close-to-tray" | "quit";
+
+export interface TrayMenuItem {
+ action?: TrayAction;
+ label?: string;
+ type?: "separator" | "checkbox";
+ checked?: boolean;
+}
+
+/**
+ * In-window destinations of the navigation entries, relative to the app origin.
+ *
+ * "New Session" is the draft route and not `/chat`: the chat page with no session in the path
+ * redirects to the most recent conversation, so a bare `/chat` reopens the last session rather
+ * than starting one. `new` is the Web App's draft sentinel (`DRAFT_SESSION_ID` in
+ * features/chat/chat-page.tsx), repeated here because this package does not depend on the Web
+ * App — the test pins the two together.
+ */
+export const TRAY_NAV_PATHS: Record<"new-session" | "models", string> = {
+ "new-session": "/chat/new",
+ models: "/models",
+};
+
+/** The two languages the Web App has, which the tray follows. */
+export type TrayLocale = "zh" | "en";
+
+/** One language's menu wording. `open` takes the app name, which carries a dev suffix unpackaged. */
+interface TrayLabels {
+ open: (appName: string) => string;
+ newSession: string;
+ models: string;
+ closeToTray: string;
+ quit: string;
+}
+
+export const TRAY_LABELS: Record<TrayLocale, TrayLabels> = {
+ en: {
+ open: (appName) => `Open ${appName}`,
+ newSession: "New Session",
+ models: "Models",
+ closeToTray: "Keep running in the tray when the window closes",
+ quit: "Quit",
+ },
+ zh: {
+ // The app name is a proper noun and stays as it is, here as everywhere else.
+ open: (appName) => `打开 ${appName}`,
+ newSession: "新建会话",
+ models: "模型",
+ closeToTray: "关闭窗口后继续在托盘中运行",
+ quit: "退出",
+ },
+};
+
+/**
+ * The device language the shell falls back to until the Web App reports its own — the same
+ * rule the Web App applies to `navigator.language` when its own preference is "follow the
+ * system", so an untouched install agrees with itself across the window and the tray.
+ */
+export function resolveTrayLocale(language: string | undefined): TrayLocale {
+ return language?.toLowerCase().startsWith("zh") ? "zh" : "en";
+}
+
+/** The menu entries, in order, in the given language. */
+export function trayMenuTemplate(opts: {
+ appName: string;
+ closeToTray: boolean;
+ locale: TrayLocale;
+}): TrayMenuItem[] {
+ const t = TRAY_LABELS[opts.locale];
+ return [
+ { action: "open", label: t.open(opts.appName) },
+ { type: "separator" },
+ { action: "new-session", label: t.newSession },
+ { action: "models", label: t.models },
+ { type: "separator" },
+ {
+ action: "toggle-close-to-tray",
+ label: t.closeToTray,
+ type: "checkbox",
+ checked: opts.closeToTray,
+ },
+ { type: "separator" },
+ { action: "quit", label: t.quit },
+ ];
+}
diff --git a/packages/desktop/src/tray-prefs.ts b/packages/desktop/src/tray-prefs.ts
new file mode 100644
index 00000000..63bfc7b2
--- /dev/null
+++ b/packages/desktop/src/tray-prefs.ts
@@ -0,0 +1,132 @@
+/**
+ * The tray preferences — on disk, and on the wire. Pure path, file and frame logic, no
+ * Electron imports (unit-tested).
+ *
+ * Two booleans live in `userData/tray.json`:
+ *
+ * - `showTrayIcon` — whether the app keeps an icon in the system tray at all. It is the
+ * Web App's Settings › Appearance switch, relayed to the shell over the utilityProcess
+ * message channel the client updater already uses (see main.ts and the server's
+ * services/desktop-update-port.ts).
+ * - `closeToTray` — whether closing the main window hides it into the tray instead of
+ * following the platform's default close semantics. It is the tray menu's own checkbox.
+ *
+ * and one language:
+ *
+ * - `locale` — the Web App's UI language, reported over the same channel, so the tray menu
+ * reads the way the window does. The shell cannot see that preference itself: it lives in
+ * the browser's localStorage. Null until a page has reported one, and after that it is kept
+ * so a fresh launch draws the right menu before any window has finished loading.
+ *
+ * Both are conveniences, never a reason for the shell to fail to start — a missing or
+ * malformed file reads as the defaults (both on), and a failed write is the caller's line
+ * in the log.
+ */
+import fs from "node:fs";
+import path from "node:path";
+import type {
+ DesktopTrayCommandMessage,
+ DesktopTrayStatusMessage,
+} from "@prismshadow/penguin-server/api";
+import type { TrayLocale } from "./tray-menu.js";
+
+/** Preference file name, inside the app's userData directory. */
+export const TRAY_PREFS_FILE = "tray.json";
+
+export interface TrayPrefs {
+ /** The tray icon is shown for as long as the app runs. */
+ showTrayIcon: boolean;
+ /** Closing the main window hides it and leaves the app (and its server) running. */
+ closeToTray: boolean;
+ /** The Web App's UI language as last reported; null until one has been, meaning follow the device. */
+ locale: TrayLocale | null;
+}
+
+export const DEFAULT_TRAY_PREFS: TrayPrefs = {
+ showTrayIcon: true,
+ closeToTray: true,
+ locale: null,
+};
+
+/** Location of the preference file for a userData directory. */
+export function trayPrefsPath(userDataDir: string): string {
+ return path.join(userDataDir, TRAY_PREFS_FILE);
+}
+
+/** Reads the preferences; anything unreadable, unparsable or ill-typed reads as the default. */
+export function readTrayPrefs(userDataDir: string): TrayPrefs {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(fs.readFileSync(trayPrefsPath(userDataDir), "utf8"));
+ } catch {
+ return { ...DEFAULT_TRAY_PREFS };
+ }
+ if (typeof parsed !== "object" || parsed === null) return { ...DEFAULT_TRAY_PREFS };
+ const at = (key: keyof TrayPrefs): unknown =>
+ (parsed as Partial<Record<keyof TrayPrefs, unknown>>)[key];
+ const bool = (key: "showTrayIcon" | "closeToTray"): boolean => {
+ const value = at(key);
+ return typeof value === "boolean" ? value : DEFAULT_TRAY_PREFS[key];
+ };
+ const locale = at("locale");
+ return {
+ showTrayIcon: bool("showTrayIcon"),
+ closeToTray: bool("closeToTray"),
+ // Anything else, including the absence this file had before the field existed, means
+ // nothing has been reported yet and the device language decides.
+ locale: locale === "zh" || locale === "en" ? locale : null,
+ };
+}
+
+/** Writes the preferences. Throws on failure: the caller decides how to report it. */
+export function writeTrayPrefs(userDataDir: string, prefs: TrayPrefs): void {
+ fs.mkdirSync(userDataDir, { recursive: true });
+ const file = trayPrefsPath(userDataDir);
+ // Write-then-rename: a crash mid-write leaves the previous file, not a truncated one that
+ // would read as the default and silently forget the preference.
+ const staging = `${file}.tmp`;
+ fs.writeFileSync(staging, `${JSON.stringify(prefs, null, 2)}\n`);
+ fs.renameSync(staging, file);
+}
+
+/**
+ * Read-modify-write of one field. Both writers (the Appearance switch and the tray menu's
+ * checkbox) go through this, so neither can clobber the other's value with a snapshot it
+ * read before the other wrote.
+ */
+export function updateTrayPrefs(userDataDir: string, patch: Partial<TrayPrefs>): TrayPrefs {
+ const next = { ...readTrayPrefs(userDataDir), ...patch };
+ writeTrayPrefs(userDataDir, next);
+ return next;
+}
+
+// --- the wire, to and from the Web App's Appearance settings -----------------
+
+/** Wraps what the tray is currently doing for the port push. */
+export function trayStatusMessage(
+ showTrayIcon: boolean,
+ locale: TrayLocale,
+): DesktopTrayStatusMessage {
+ return { type: "desktop-tray-status", status: { showTrayIcon, locale } };
+}
+
+/**
+ * Validates one server-relayed tray command off the port. Null when the frame is not one, and
+ * an empty patch when it is one carrying nothing this build understands — a distinction the
+ * caller needs, because a frame it cannot read is not a frame it should treat as a tray push.
+ */
+export function parseTrayCommand(data: unknown): TrayCommand | null {
+ if (typeof data !== "object" || data === null) return null;
+ const msg = data as Partial<DesktopTrayCommandMessage>;
+ if (msg.type !== "desktop-tray-command") return null;
+ const patch: TrayCommand = {};
+ if (typeof msg.showTrayIcon === "boolean") patch.showTrayIcon = msg.showTrayIcon;
+ if (msg.locale === "zh" || msg.locale === "en") patch.locale = msg.locale;
+ return patch;
+}
+
+/** What one relayed command asks the shell to change; every field optional, as the route's patch is. */
+export interface TrayCommand {
+ showTrayIcon?: boolean;
+ locale?: TrayLocale;
+}
diff --git a/packages/desktop/src/tray.ts b/packages/desktop/src/tray.ts
new file mode 100644
index 00000000..b06afc0e
--- /dev/null
+++ b/packages/desktop/src/tray.ts
@@ -0,0 +1,148 @@
+/**
+ * The system tray icon: a lightweight entry point that survives closing the window, so the
+ * app can keep serving in the background without leaving the user hunting for a way back in.
+ *
+ * Electron-facing and untested, like main.ts and menu.ts — the menu entries, the preference
+ * file and the icon lookup are pure modules beside it, and they carry the tests.
+ *
+ * How the menu is opened splits by platform, for reasons noted at the split below.
+ */
+import { Menu, nativeImage, Tray } from "electron";
+import type { MenuItemConstructorOptions } from "electron";
+import { TRAY_NAV_PATHS, trayMenuTemplate } from "./tray-menu.js";
+import type { TrayLocale, TrayMenuItem } from "./tray-menu.js";
+import { readTrayPrefs, updateTrayPrefs } from "./tray-prefs.js";
+
+export interface TrayHandle {
+ /** The live preference: the window's close handler asks at close time, not at install time. */
+ closeToTray(): boolean;
+ /** Redraws the menu in another language, for when the Web App's changes while the app runs. */
+ setLocale(locale: TrayLocale): void;
+ dispose(): void;
+}
+
+export interface TrayOptions {
+ userDataDir: string;
+ /** Resolved tray image, or null when the asset is missing (see app-icon.ts). */
+ iconPath: string | null;
+ appName: string;
+ /** The language the menu is drawn in, until the Web App reports a different one. */
+ locale: TrayLocale;
+ onShowWindow: () => void;
+ onNavigate: (path: string) => void;
+ onQuit: () => void;
+ log: (line: string) => void;
+}
+
+/**
+ * Installs the tray icon, or returns null when the platform cannot host one — a Linux desktop
+ * without a tray implementation, or a headless CI run. The tray is a convenience; nothing
+ * about it may keep the app from starting.
+ */
+export function installTray(opts: TrayOptions): TrayHandle | null {
+ if (opts.iconPath === null) {
+ opts.log("no tray icon asset was found; running without a tray icon");
+ return null;
+ }
+ let prefs = readTrayPrefs(opts.userDataDir);
+ let locale = opts.locale;
+ let tray: Tray;
+ try {
+ const image = nativeImage.createFromPath(opts.iconPath);
+ // A template image is drawn as a mask, so the menu bar inverts it with its own light or
+ // dark appearance. Electron also infers this from the `…Template` file name; saying it
+ // here keeps the behavior if the asset is ever renamed.
+ if (process.platform === "darwin") image.setTemplateImage(true);
+ tray = new Tray(image);
+ } catch (err) {
+ opts.log(`the tray icon could not be created: ${String(err)}`);
+ return null;
+ }
+ tray.setToolTip(opts.appName);
+
+ function setCloseToTray(next: boolean): void {
+ // Optimistic: the checkbox shows the click even when the write below fails.
+ prefs = { ...prefs, closeToTray: next };
+ try {
+ // Read-modify-write: the Appearance switch writes showTrayIcon into the same file,
+ // and this snapshot was taken when the tray was installed.
+ prefs = updateTrayPrefs(opts.userDataDir, { closeToTray: next });
+ } catch (err) {
+ opts.log(`the tray preference could not be saved: ${String(err)}`);
+ }
+ // An attached menu is a snapshot: rebuild it so the checkbox shows what was just written.
+ attachMenu();
+ }
+
+ function nativeItem(item: TrayMenuItem): MenuItemConstructorOptions {
+ if (item.type === "separator") return { type: "separator" };
+ const base: MenuItemConstructorOptions = { label: item.label };
+ switch (item.action) {
+ case "open":
+ return { ...base, click: opts.onShowWindow };
+ case "new-session":
+ return { ...base, click: () => opts.onNavigate(TRAY_NAV_PATHS["new-session"]) };
+ case "models":
+ return { ...base, click: () => opts.onNavigate(TRAY_NAV_PATHS.models) };
+ case "toggle-close-to-tray":
+ return {
+ ...base,
+ type: "checkbox",
+ checked: item.checked === true,
+ click: (menuItem) => setCloseToTray(menuItem.checked),
+ };
+ case "quit":
+ return { ...base, click: opts.onQuit };
+ default:
+ return base;
+ }
+ }
+
+ // Built fresh for each popup (and re-attached on each toggle where the menu is attached), so
+ // the checkbox shows the preference as it stands rather than as it was at install.
+ function buildMenu(): Menu {
+ const template = trayMenuTemplate({
+ appName: opts.appName,
+ closeToTray: prefs.closeToTray,
+ locale,
+ });
+ return Menu.buildFromTemplate(template.map(nativeItem));
+ }
+
+ // How the menu is reached splits by platform. The AppIndicator / StatusNotifierItem trays
+ // most Linux desktops use emit neither `click` nor `right-click`, and an attached context
+ // menu is the only reliable way to open one there — the desktop itself decides which click
+ // opens it. On macOS an attached menu opens on a left click too, which would cost the icon
+ // its one-click path back to the window, so those two pop the menu by hand.
+ const ATTACHES_MENU = process.platform === "linux";
+
+ /** No-op off Linux: the menu is built per popup there instead. */
+ function attachMenu(): void {
+ if (ATTACHES_MENU) tray.setContextMenu(buildMenu());
+ }
+
+ // Registered everywhere: harmless on a tray that never emits it, and where the click does
+ // arrive it is the shortest way back to the window. Where it does not, the menu's first
+ // entry opens the window instead.
+ tray.on("click", (event) => {
+ // macOS treats Ctrl+click as a right click; where the OS still delivers it as a plain
+ // click, this keeps it on the menu rather than raising the window.
+ if (process.platform === "darwin" && event.ctrlKey) {
+ tray.popUpContextMenu(buildMenu());
+ return;
+ }
+ opts.onShowWindow();
+ });
+ if (!ATTACHES_MENU) tray.on("right-click", () => tray.popUpContextMenu(buildMenu()));
+ attachMenu();
+
+ return {
+ closeToTray: () => prefs.closeToTray,
+ setLocale: (next) => {
+ locale = next;
+ // Only Linux holds a built menu; elsewhere the next popup picks the language up.
+ attachMenu();
+ },
+ dispose: () => tray.destroy(),
+ };
+}
diff --git a/packages/desktop/src/util.ts b/packages/desktop/src/util.ts
index e3ed0625..47f592d8 100644
--- a/packages/desktop/src/util.ts
+++ b/packages/desktop/src/util.ts
@@ -66,3 +66,21 @@ export const MAX_SERVER_RESTARTS = 3;
export function restartDelayMs(attempt: number): number {
return Math.min(1000 * 2 ** attempt, 8000);
}
+
+/**
+ * Whether closing the main window hides it into the tray instead of destroying it.
+ *
+ * All three conditions are load-bearing. A quit already under way never hides — the close
+ * that Electron runs on the way out has to complete. `trayShown` matters because without
+ * an icon there is no way back to a hidden window: the close must proceed instead, which
+ * leaves the app in the Dock on macOS and quits it on Windows and Linux through
+ * window-all-closed. A running app with no window and no tray icon is a state the user
+ * cannot escape, so it is one this must never produce.
+ */
+export function hidesOnClose(state: {
+ quitting: boolean;
+ trayShown: boolean;
+ closeToTray: boolean;
+}): boolean {
+ return !state.quitting && state.trayShown && state.closeToTray;
+}
diff --git a/packages/desktop/test/app-icon.test.ts b/packages/desktop/test/app-icon.test.ts
index babb6e9f..83e5543f 100644
--- a/packages/desktop/test/app-icon.test.ts
+++ b/packages/desktop/test/app-icon.test.ts
@@ -2,8 +2,16 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
+import { colouredPixels, inkCoverage, readPixels } from "./png-pixels.js";
import { afterAll, describe, expect, it } from "vitest";
-import { resolveWindowIcon, WINDOW_ICON_RELPATH, windowIconPathFor } from "../src/app-icon.js";
+import {
+ resolveTrayIcon,
+ resolveWindowIcon,
+ trayIconPathFor,
+ trayIconRelPath,
+ WINDOW_ICON_RELPATH,
+ windowIconPathFor,
+} from "../src/app-icon.js";
describe("windowIconPathFor", () => {
it("is null on macOS (window icons are ignored; the bundle icns owns the Dock)", () => {
@@ -46,3 +54,72 @@ describe("packaged app icons", () => {
expect(fs.existsSync(path.join(pkgDir, "build", "icon-mac.png"))).toBe(true);
});
});
+
+describe("trayIconRelPath", () => {
+ it("takes the monochrome template image on macOS and the colour one elsewhere", () => {
+ expect(trayIconRelPath("darwin")).toEqual(["dist", "tray", "trayTemplate.png"]);
+ expect(trayIconRelPath("linux")).toEqual(["dist", "tray", "tray.png"]);
+ expect(trayIconRelPath("win32")).toEqual(["dist", "tray", "tray.png"]);
+ });
+
+ it("resolves inside the app dir", () => {
+ expect(trayIconPathFor("/app", "darwin")).toBe(path.join("/app", ...trayIconRelPath("darwin")));
+ });
+});
+
+describe("resolveTrayIcon", () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-desktop-tray-icon-"));
+ afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));
+
+ it("returns the path only when the file exists, on every platform", () => {
+ expect(resolveTrayIcon(tmp, "linux")).toBeNull();
+ expect(resolveTrayIcon(tmp, "darwin")).toBeNull();
+ const iconPath = path.join(tmp, ...trayIconRelPath("linux"));
+ fs.mkdirSync(path.dirname(iconPath), { recursive: true });
+ fs.writeFileSync(iconPath, "png");
+ expect(resolveTrayIcon(tmp, "linux")).toBe(iconPath);
+ // The macOS template image is a separate file: still missing, still null.
+ expect(resolveTrayIcon(tmp, "darwin")).toBeNull();
+ });
+});
+
+describe("committed tray masters", () => {
+ const pkgDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+
+ /** Width and height out of a PNG's IHDR chunk, which starts at a fixed offset. */
+ function pngSize(file: string): [number, number] {
+ const header = fs.readFileSync(file).subarray(16, 24);
+ return [header.readUInt32BE(0), header.readUInt32BE(4)];
+ }
+
+ it.each<[string, number]>([
+ ["tray.png", 32],
+ ["trayTemplate.png", 16],
+ ])("ships %s at %ipx for scripts/build-assets.mjs to stage", (name, size) => {
+ expect(pngSize(path.join(pkgDir, "build", "tray", name))).toEqual([size, size]);
+ });
+
+ it.each(["trayTemplate.png", "[email protected]"])("draws %s as a template image", (name) => {
+ // A template image is a mask: the menu bar paints every non-transparent pixel in its own
+ // colour and throws the original away. Colour in one is not merely ignored, it is a sign the
+ // file was rendered down the wrong path — and the result on screen is a black blob.
+ expect(colouredPixels(readPixels(path.join(pkgDir, "build", "tray", name)))).toBe(0);
+ });
+
+ it.each(["trayTemplate.png", "[email protected]"])("gives %s enough weight to read", (name) => {
+ // The first menu bar mark here was the whole brand illustration flattened and shrunk. The
+ // backdrop became a filled square, the belly — drawn as a hole letting that backdrop through
+ // — became nothing, and what was left covered 19% of the canvas, nearly all of it
+ // antialiasing: a wisp beside the solid marks around it. Reducing it to the penguin's
+ // outline, belly solid and arcs dropped, roughly doubles that.
+ //
+ // The ceiling is the shape, not the rendering. A 4:3 silhouette in a square canvas leaves a
+ // band above and below, and cropping past its bounding box takes off the beak and the tail,
+ // so a third of the canvas is about all this outline can cover. The floor sits below the
+ // measured 35% by enough not to trip on an antialiasing difference, and far enough above the
+ // old 19% to catch a return to the flattened illustration.
+ expect(inkCoverage(readPixels(path.join(pkgDir, "build", "tray", name)))).toBeGreaterThan(0.3);
+ });
+});
diff --git a/packages/desktop/test/png-pixels.ts b/packages/desktop/test/png-pixels.ts
new file mode 100644
index 00000000..80035cdf
--- /dev/null
+++ b/packages/desktop/test/png-pixels.ts
@@ -0,0 +1,101 @@
+/**
+ * Just enough PNG decoding to assert what a committed icon actually looks like.
+ *
+ * The tray masters are generated artwork checked into the tree, so nothing else notices when a
+ * re-render quietly changes what they are — a mark can come back too faint to read, or a
+ * template can come back coloured, and both still load and still pass a size check. Reading the
+ * pixels is the only way to hold those properties.
+ *
+ * Handles the one shape `scripts/render-icon.mjs` emits: 8-bit RGBA, non-interlaced. Anything
+ * else throws rather than guessing, so a change in the renderer's output surfaces here instead
+ * of silently weakening the assertions.
+ */
+import { readFileSync } from "node:fs";
+import { inflateSync } from "node:zlib";
+
+export interface Pixels {
+ width: number;
+ height: number;
+ /** Straight RGBA, four bytes per pixel, row-major. */
+ data: Buffer;
+}
+
+/** Undoes a scanline's filter in place, given the already-reconstructed row above it. */
+function unfilter(type: number, line: Buffer, out: Buffer, prev: Buffer, bpp: number): void {
+ for (let i = 0; i < line.length; i++) {
+ const a = i >= bpp ? out[i - bpp]! : 0;
+ const b = prev[i]!;
+ const c = i >= bpp ? prev[i - bpp]! : 0;
+ const x = line[i]!;
+ let add: number;
+ if (type === 0) add = 0;
+ else if (type === 1) add = a;
+ else if (type === 2) add = b;
+ else if (type === 3) add = (a + b) >> 1;
+ else if (type === 4) {
+ const p = a + b - c;
+ const pa = Math.abs(p - a);
+ const pb = Math.abs(p - b);
+ const pc = Math.abs(p - c);
+ add = pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
+ } else throw new Error(`unsupported PNG filter ${type}`);
+ out[i] = (x + add) & 0xff;
+ }
+}
+
+/** Decodes an 8-bit RGBA PNG. */
+export function readPixels(file: string): Pixels {
+ const buf = readFileSync(file);
+ let at = 8;
+ let width = 0;
+ let height = 0;
+ const idat: Buffer[] = [];
+ while (at < buf.length) {
+ const length = buf.readUInt32BE(at);
+ const type = buf.toString("ascii", at + 4, at + 8);
+ const body = buf.subarray(at + 8, at + 8 + length);
+ if (type === "IHDR") {
+ width = body.readUInt32BE(0);
+ height = body.readUInt32BE(4);
+ const [depth, colour, , , interlace] = [body[8]!, body[9]!, 0, 0, body[12]!];
+ if (depth !== 8 || colour !== 6 || interlace !== 0)
+ throw new Error(`expected 8-bit RGBA non-interlaced, got depth ${depth} colour ${colour}`);
+ } else if (type === "IDAT") idat.push(body);
+ else if (type === "IEND") break;
+ at += 12 + length;
+ }
+ const raw = inflateSync(Buffer.concat(idat));
+ const stride = width * 4;
+ const data = Buffer.alloc(height * stride);
+ let read = 0;
+ for (let y = 0; y < height; y++) {
+ const filter = raw[read]!;
+ read += 1;
+ const line = raw.subarray(read, read + stride);
+ read += stride;
+ const row = data.subarray(y * stride, (y + 1) * stride);
+ const prev = y > 0 ? data.subarray((y - 1) * stride, y * stride) : Buffer.alloc(stride);
+ unfilter(filter, line, row, prev, 4);
+ }
+ return { width, height, data };
+}
+
+/**
+ * How much of the canvas the mark actually paints, 0 to 1, counting a half-transparent pixel as
+ * half — which is what the compositor does, and so what the eye gets.
+ */
+export function inkCoverage({ width, height, data }: Pixels): number {
+ let ink = 0;
+ for (let i = 3; i < data.length; i += 4) ink += data[i]! / 255;
+ return ink / (width * height);
+}
+
+/** Pixels that are neither transparent nor black — none, in a macOS template image. */
+export function colouredPixels({ data }: Pixels): number {
+ let coloured = 0;
+ for (let i = 0; i < data.length; i += 4) {
+ if (data[i + 3]! < 8) continue;
+ if (data[i] !== 0 || data[i + 1] !== 0 || data[i + 2] !== 0) coloured += 1;
+ }
+ return coloured;
+}
diff --git a/packages/desktop/test/tray-menu.test.ts b/packages/desktop/test/tray-menu.test.ts
new file mode 100644
index 00000000..b5bfda7f
--- /dev/null
+++ b/packages/desktop/test/tray-menu.test.ts
@@ -0,0 +1,114 @@
+import { describe, expect, it } from "vitest";
+import { readFileSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import {
+ TRAY_LABELS,
+ TRAY_NAV_PATHS,
+ resolveTrayLocale,
+ trayMenuTemplate,
+} from "../src/tray-menu.js";
+import type { TrayLocale } from "../src/tray-menu.js";
+
+describe("trayMenuTemplate", () => {
+ it("lists the actions in order, separated into groups", () => {
+ const template = trayMenuTemplate({
+ appName: "PenguinHarness",
+ closeToTray: true,
+ locale: "en",
+ });
+ expect(template.map((item) => item.action ?? item.type)).toEqual([
+ "open",
+ "separator",
+ "new-session",
+ "models",
+ "separator",
+ "toggle-close-to-tray",
+ "separator",
+ "quit",
+ ]);
+ });
+
+ it("names the app in the first entry, dev suffix included", () => {
+ expect(
+ trayMenuTemplate({ appName: "PenguinHarness", closeToTray: true, locale: "en" })[0]?.label,
+ ).toBe("Open PenguinHarness");
+ expect(
+ trayMenuTemplate({ appName: "PenguinHarness Dev", closeToTray: true, locale: "en" })[0]
+ ?.label,
+ ).toBe("Open PenguinHarness Dev");
+ });
+
+ it("shows the close-to-tray preference as a checkbox", () => {
+ for (const closeToTray of [true, false]) {
+ const item = trayMenuTemplate({ appName: "PenguinHarness", closeToTray, locale: "en" }).find(
+ (entry) => entry.action === "toggle-close-to-tray",
+ );
+ expect(item).toEqual({
+ action: "toggle-close-to-tray",
+ label: TRAY_LABELS.en.closeToTray,
+ type: "checkbox",
+ checked: closeToTray,
+ });
+ }
+ });
+
+ it("navigates inside the window, so every destination is an app-origin path", () => {
+ for (const target of Object.values(TRAY_NAV_PATHS)) expect(target.startsWith("/")).toBe(true);
+ });
+
+ it("opens a draft for New Session, not the last conversation", () => {
+ // `/chat` with no session in the path redirects to the most recent conversation, so the
+ // entry has to name the Web App's draft sentinel. This package cannot import it — it does
+ // not depend on the Web App — so the literal is checked against the source that owns it.
+ const chatPage = readFileSync(
+ resolve(dirname(fileURLToPath(import.meta.url)), "../../web/src/features/chat/chat-page.tsx"),
+ "utf8",
+ );
+ const draftId = /export const DRAFT_SESSION_ID = "([^"]+)"/.exec(chatPage)?.[1];
+ expect(draftId, "DRAFT_SESSION_ID moved or was renamed in the Web App").toBeDefined();
+ expect(TRAY_NAV_PATHS["new-session"]).toBe(`/chat/${draftId}`);
+ });
+
+ it("draws every entry in the language it is given", () => {
+ const zh = trayMenuTemplate({ appName: "PenguinHarness", closeToTray: true, locale: "zh" });
+ const en = trayMenuTemplate({ appName: "PenguinHarness", closeToTray: true, locale: "en" });
+ // Same entries, same order, different wording: the language must not change the menu.
+ expect(zh.map((i) => i.action ?? i.type)).toEqual(en.map((i) => i.action ?? i.type));
+ expect(zh.map((i) => i.label)).toEqual([
+ "打开 PenguinHarness",
+ undefined,
+ "新建会话",
+ "模型",
+ undefined,
+ "关闭窗口后继续在托盘中运行",
+ undefined,
+ "退出",
+ ]);
+ // The app name is a proper noun and survives translation.
+ expect(zh[0]?.label).toContain("PenguinHarness");
+ });
+
+ it("carries the same wording keys in both languages", () => {
+ // A language missing an entry would draw that one blank rather than fall back, so the
+ // shapes have to match. The type says so too; this says so at the value.
+ const shape = (locale: TrayLocale) => Object.keys(TRAY_LABELS[locale]).sort();
+ expect(shape("zh")).toEqual(shape("en"));
+ for (const locale of ["zh", "en"] as const) {
+ for (const [key, value] of Object.entries(TRAY_LABELS[locale])) {
+ if (typeof value === "string") expect(value, `${locale}.${key}`).not.toBe("");
+ }
+ }
+ });
+});
+
+describe("resolveTrayLocale", () => {
+ it("follows the device the way the Web App follows the browser", () => {
+ // Mirrors resolveSystemLocale in packages/web/src/state/locale.tsx: any zh tag is zh,
+ // everything else — including an unavailable one — is en.
+ for (const tag of ["zh", "zh-CN", "zh-TW", "ZH-Hans"])
+ expect(resolveTrayLocale(tag)).toBe("zh");
+ for (const tag of ["en", "en-GB", "fr", "ja", "", undefined])
+ expect(resolveTrayLocale(tag)).toBe("en");
+ });
+});
diff --git a/packages/desktop/test/tray-prefs.test.ts b/packages/desktop/test/tray-prefs.test.ts
new file mode 100644
index 00000000..3ffe79f9
--- /dev/null
+++ b/packages/desktop/test/tray-prefs.test.ts
@@ -0,0 +1,167 @@
+/**
+ * The tray preferences: the two booleans in userData/tray.json, and the two frames that
+ * carry the Appearance switch between the shell and the page.
+ *
+ * Every ill-formed shape reads as ON for both. The shell starts before the window does,
+ * and a file it cannot make sense of must leave the app with an icon and a way back into
+ * it — never with neither.
+ */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import {
+ DEFAULT_TRAY_PREFS,
+ parseTrayCommand,
+ readTrayPrefs,
+ TRAY_PREFS_FILE,
+ trayPrefsPath,
+ trayStatusMessage,
+ updateTrayPrefs,
+ writeTrayPrefs,
+} from "../src/tray-prefs.js";
+
+describe("readTrayPrefs", () => {
+ let dir: string;
+
+ beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-tray-prefs-"));
+ });
+ afterEach(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+ it("defaults to a tray icon that keeps the app running when there is no file", () => {
+ expect(DEFAULT_TRAY_PREFS).toEqual({ showTrayIcon: true, closeToTray: true, locale: null });
+ expect(readTrayPrefs(dir)).toEqual({ showTrayIcon: true, closeToTray: true, locale: null });
+ });
+
+ it("defaults when the directory itself does not exist", () => {
+ expect(readTrayPrefs(path.join(dir, "never-created"))).toEqual({
+ showTrayIcon: true,
+ closeToTray: true,
+ locale: null,
+ });
+ });
+
+ it("reads back what was written", () => {
+ writeTrayPrefs(dir, { showTrayIcon: false, closeToTray: false, locale: null });
+ expect(readTrayPrefs(dir)).toEqual({ showTrayIcon: false, closeToTray: false, locale: null });
+ writeTrayPrefs(dir, { showTrayIcon: true, closeToTray: true, locale: null });
+ expect(readTrayPrefs(dir)).toEqual({ showTrayIcon: true, closeToTray: true, locale: null });
+ });
+
+ it("keeps a reported language, and treats anything else as none reported", () => {
+ writeTrayPrefs(dir, { showTrayIcon: true, closeToTray: true, locale: "zh" });
+ expect(readTrayPrefs(dir).locale).toBe("zh");
+ // A file written before the field existed, and a file with a language this build does not
+ // have, both mean the same thing: nothing has been reported, so the device decides.
+ for (const stored of [
+ '{"showTrayIcon":true,"closeToTray":true}',
+ '{"locale":"fr"}',
+ '{"locale":7}',
+ ]) {
+ fs.writeFileSync(trayPrefsPath(dir), stored);
+ expect(readTrayPrefs(dir).locale, stored).toBeNull();
+ }
+ });
+
+ it("writes tray.json into the userData directory, creating it if needed", () => {
+ const nested = path.join(dir, "userData");
+ writeTrayPrefs(nested, { showTrayIcon: true, closeToTray: false, locale: null });
+ expect(trayPrefsPath(nested)).toBe(path.join(nested, TRAY_PREFS_FILE));
+ expect(JSON.parse(fs.readFileSync(trayPrefsPath(nested), "utf8"))).toEqual({
+ showTrayIcon: true,
+ closeToTray: false,
+ locale: null,
+ });
+ });
+
+ it("defaults on malformed JSON", () => {
+ fs.writeFileSync(trayPrefsPath(dir), "{ closeToTray: ");
+ expect(readTrayPrefs(dir)).toEqual({ showTrayIcon: true, closeToTray: true, locale: null });
+ });
+
+ it("defaults per field: an ill-typed one does not take the other down with it", () => {
+ fs.writeFileSync(
+ trayPrefsPath(dir),
+ JSON.stringify({ closeToTray: "no", showTrayIcon: false }),
+ );
+ expect(readTrayPrefs(dir)).toEqual({ showTrayIcon: false, closeToTray: true, locale: null });
+ fs.writeFileSync(trayPrefsPath(dir), JSON.stringify({}));
+ expect(readTrayPrefs(dir)).toEqual({ showTrayIcon: true, closeToTray: true, locale: null });
+ fs.writeFileSync(trayPrefsPath(dir), JSON.stringify(null));
+ expect(readTrayPrefs(dir)).toEqual({ showTrayIcon: true, closeToTray: true, locale: null });
+ fs.writeFileSync(trayPrefsPath(dir), JSON.stringify(false));
+ expect(readTrayPrefs(dir)).toEqual({ showTrayIcon: true, closeToTray: true, locale: null });
+ });
+
+ it("leaves no staging file behind", () => {
+ writeTrayPrefs(dir, { showTrayIcon: true, closeToTray: false, locale: null });
+ expect(fs.readdirSync(dir)).toEqual([TRAY_PREFS_FILE]);
+ });
+});
+
+describe("updateTrayPrefs", () => {
+ let dir: string;
+
+ beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-tray-prefs-"));
+ });
+ afterEach(() => fs.rmSync(dir, { recursive: true, force: true }));
+
+ it("keeps the field it was not given", () => {
+ // The three writers hold snapshots taken at different moments — the tray menu's at
+ // install time, the Appearance switch's at click time, the page's language report at
+ // whatever moment it changes — so a whole-object write from any would revert the others.
+ writeTrayPrefs(dir, { showTrayIcon: true, closeToTray: false, locale: null });
+ expect(updateTrayPrefs(dir, { showTrayIcon: false })).toEqual({
+ showTrayIcon: false,
+ closeToTray: false,
+ locale: null,
+ });
+ expect(updateTrayPrefs(dir, { closeToTray: true })).toEqual({
+ showTrayIcon: false,
+ closeToTray: true,
+ locale: null,
+ });
+ expect(readTrayPrefs(dir)).toEqual({ showTrayIcon: false, closeToTray: true, locale: null });
+ // The language is the third writer and goes through the same door.
+ expect(updateTrayPrefs(dir, { locale: "zh" })).toEqual({
+ showTrayIcon: false,
+ closeToTray: true,
+ locale: "zh",
+ });
+ expect(updateTrayPrefs(dir, { showTrayIcon: true }).locale).toBe("zh");
+ });
+});
+
+describe("the Appearance switch on the wire", () => {
+ it("wraps the shown state for the push to the page", () => {
+ expect(trayStatusMessage(false, "zh")).toEqual({
+ type: "desktop-tray-status",
+ status: { showTrayIcon: false, locale: "zh" },
+ });
+ });
+
+ it("reads a command frame, and nothing else", () => {
+ expect(parseTrayCommand({ type: "desktop-tray-command", showTrayIcon: false })).toEqual({
+ showTrayIcon: false,
+ });
+ expect(parseTrayCommand({ type: "desktop-tray-command", locale: "zh" })).toEqual({
+ locale: "zh",
+ });
+ // One frame can carry both: the page sends the switch and the language separately, but
+ // nothing in the wire shape says it has to.
+ expect(
+ parseTrayCommand({ type: "desktop-tray-command", showTrayIcon: true, locale: "en" }),
+ ).toEqual({ showTrayIcon: true, locale: "en" });
+ // A field this build cannot read is dropped; the frame is still a tray command, and an
+ // empty patch simply changes nothing. Only a frame that is not one at all reads as null.
+ expect(parseTrayCommand({ type: "desktop-tray-command" })).toEqual({});
+ expect(parseTrayCommand({ type: "desktop-tray-command", showTrayIcon: "yes" })).toEqual({});
+ expect(parseTrayCommand({ type: "desktop-tray-command", locale: "fr" })).toEqual({});
+ // The same port carries the updater's frames; a tray reader must not answer to one.
+ expect(parseTrayCommand({ type: "desktop-updater-command", action: "check" })).toBeNull();
+ expect(parseTrayCommand(null)).toBeNull();
+ expect(parseTrayCommand("desktop-tray-command")).toBeNull();
+ });
+});
diff --git a/packages/desktop/test/util.test.ts b/packages/desktop/test/util.test.ts
index 9aa85f68..c11d8808 100644
--- a/packages/desktop/test/util.test.ts
+++ b/packages/desktop/test/util.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
import {
appOriginFor,
desktopLoginUrl,
+ hidesOnClose,
isAppUrl,
isLocalSurfaceUrl,
parsePortFile,
@@ -65,3 +66,29 @@ describe("restartDelayMs", () => {
expect([0, 1, 2, 3, 4].map(restartDelayMs)).toEqual([1000, 2000, 4000, 8000, 8000]);
});
});
+
+describe("hidesOnClose", () => {
+ const state = (over: Partial<Parameters<typeof hidesOnClose>[0]> = {}) => ({
+ quitting: false,
+ trayShown: true,
+ closeToTray: true,
+ ...over,
+ });
+
+ it("hides the window only while a tray icon can bring it back", () => {
+ expect(hidesOnClose(state())).toBe(true);
+ expect(hidesOnClose(state({ closeToTray: false }))).toBe(false);
+ });
+
+ it("lets the close through when there is no tray icon", () => {
+ // The Appearance switch turned it off, or the platform could not host one. A hidden
+ // window with nothing to restore it is a running app the user cannot reach: the close
+ // has to proceed instead, leaving the app in the Dock on macOS and quitting elsewhere.
+ expect(hidesOnClose(state({ trayShown: false }))).toBe(false);
+ expect(hidesOnClose(state({ trayShown: false, closeToTray: false }))).toBe(false);
+ });
+
+ it("never intercepts the close a quit runs", () => {
+ expect(hidesOnClose(state({ quitting: true }))).toBe(false);
+ });
+});
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index c175ab83..6d3bbf53 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -3504,6 +3504,68 @@ export interface DesktopUpdaterCommandMessage {
action: "check" | "download" | "install";
}
+// Desktop tray icon (desktop mode only)
+//
+// The shell keeps an icon in the system tray for as long as the app runs, and Settings ›
+// Appearance is where it is turned off and on. The switch rides the same utilityProcess
+// message channel as the client updater above: the shell pushes what it currently shows,
+// the page reads it at GET /api/desktop/tray and writes through PUT, which is relayed
+// back. The window stays a plain browser — no renderer IPC bridge.
+//
+// The page reports its UI language over the same route, so the tray menu reads in the
+// language the window does. The shell cannot see that preference itself: it lives in the
+// browser's localStorage, on the other side of a boundary this design keeps one-way.
+
+/** The two languages the Web App has; the shell's tray menu follows whichever is in use. */
+export type DesktopTrayLocale = "zh" | "en";
+
+/** What the shell is currently doing about its tray icon. */
+export interface DesktopTrayStatus {
+ /** Whether an icon is shown in the system tray while the app runs. */
+ showTrayIcon: boolean;
+ /**
+ * The language the tray menu is drawn in. Until a page reports one the shell uses the
+ * device language, so this can differ from the Web App's until the first report lands.
+ */
+ locale: DesktopTrayLocale;
+}
+
+/**
+ * What one PUT asks the shell to change. Every field is optional and a request must carry at
+ * least one: the switch and the language reach this route from different parts of the page.
+ */
+export interface DesktopTrayPatch {
+ showTrayIcon?: boolean;
+ locale?: DesktopTrayLocale;
+}
+
+/**
+ * GET / PUT /api/desktop/tray (desktop-shell sessions only): the tray preference.
+ * `status` is null until the shell's first push lands (a beat after server start); a
+ * client that finds null reads it as on, which is the shell's own default.
+ */
+export interface DesktopTrayStatusResponse {
+ status: DesktopTrayStatus | null;
+}
+
+/** Shell → server push over the utilityProcess message channel. */
+export interface DesktopTrayStatusMessage {
+ type: "desktop-tray-status";
+ status: DesktopTrayStatus;
+}
+
+/**
+ * Server → shell command over the utilityProcess message channel (relayed from PUT
+ * /api/desktop/tray). A patch, not a snapshot: the switch and the language are written by
+ * different parts of the page at different moments, and neither should have to restate the
+ * other's value to change its own.
+ */
+export interface DesktopTrayCommandMessage {
+ type: "desktop-tray-command";
+ showTrayIcon?: boolean;
+ locale?: DesktopTrayLocale;
+}
+
/**
* The outcome of one self-update run (`penguin update --yes` on the server host), carried
* by {@link UpdateJobStatus.result}. `unsupported` covers both a server not launched via
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index 841e3a2c..e28027b1 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -100,7 +100,7 @@ import { TitleGenerator, TitleNotifier } from "./runtime/title-generator.js";
import { AdminService } from "./services/admin-service.js";
import { DesktopService } from "./services/desktop-service.js";
import { LifecycleService } from "./services/lifecycle-service.js";
-import { desktopRoutes, desktopUpdateRoutes } from "./http/routes/desktop.js";
+import { desktopRoutes, desktopTrayRoutes, desktopUpdateRoutes } from "./http/routes/desktop.js";
import { AgentConfigService } from "./services/agent-config-service.js";
import { MemoryService } from "./services/memory-service.js";
import { AgentService } from "./services/agent-service.js";
@@ -492,6 +492,10 @@ export function createRuntimeApp(deps: AppDeps): Hono<AppEnv> {
app.use("/api/desktop/update", authMiddleware(deps.authService, deps.config.trustProxy));
app.use("/api/desktop/update/*", authMiddleware(deps.authService, deps.config.trustProxy));
app.route("/api/desktop/update", desktopUpdateRoutes(deps));
+ // The tray-icon preference rides the same relay and the same shell-window gate: it is
+ // the Settings › Appearance switch reaching the chrome around the window it runs in.
+ app.use("/api/desktop/tray", authMiddleware(deps.authService, deps.config.trustProxy));
+ app.route("/api/desktop/tray", desktopTrayRoutes(deps));
}
// Hot platform APIs run their own gate — the network gate, then the SAME auth middleware
// the routes below use (the boot's local API token as `Authorization: Bearer`, or an admin
diff --git a/packages/server/src/http/routes/desktop.ts b/packages/server/src/http/routes/desktop.ts
index 65be3be2..93e0db4a 100644
--- a/packages/server/src/http/routes/desktop.ts
+++ b/packages/server/src/http/routes/desktop.ts
@@ -1,18 +1,22 @@
/**
* Desktop-mode routes: POST /api/desktop/shutdown, the client-update relay under
- * /api/desktop/update, plus the shared desktop-mode guard that turns off multi-user
- * surfaces (see rejectInDesktopMode).
+ * /api/desktop/update, the tray-icon preference at /api/desktop/tray, plus the shared
+ * desktop-mode guard that turns off multi-user surfaces (see rejectInDesktopMode).
*
* The shutdown route is authenticated by the shell's Bearer token, not the cookie
* session (the shell holds no cookie), so it mounts OUTSIDE authMiddleware and only
* when desktop mode is enabled. Responds 202 first, then triggers the graceful
* shutdown a beat later so the response isn't cut off by the closing listener.
- * The update routes are called by the page instead, so they mount INSIDE authMiddleware
- * (see desktopUpdateRoutes).
+ * The other two are called by the page instead, so they mount INSIDE authMiddleware
+ * (see desktopUpdateRoutes and desktopTrayRoutes).
*/
import { Hono } from "hono";
import type { Context, MiddlewareHandler } from "hono";
-import type { DesktopUpdateStatusResponse } from "../../api/types.js";
+import type {
+ DesktopTrayPatch,
+ DesktopTrayStatusResponse,
+ DesktopUpdateStatusResponse,
+} from "../../api/types.js";
import { HttpError } from "../errors.js";
import type { AppEnv } from "../../auth/middleware.js";
import type { AppDeps } from "../../app.js";
@@ -59,6 +63,20 @@ export function desktopRoutes(deps: AppDeps): Hono {
return app;
}
+/**
+ * The shared gate for the two page-facing desktop surfaces: they exist only in desktop
+ * mode, and only for the shell's own window (`sessionVia === "desktop"`, the same
+ * two-field rule as the change-password gate, inverted). A browser signed into the same
+ * desktop-mode server must not read the machine's updater state, restart its GUI app, or
+ * reach into the chrome of a window it is not looking at.
+ */
+function shellSessionOf(deps: AppDeps, c: Context<AppEnv>, refusal: string): DesktopService {
+ const desktop = deps.desktop;
+ if (!desktop) throw new HttpError(404, "not_found", "Desktop mode is not enabled.");
+ if (c.var.sessionVia !== "desktop") throw new HttpError(403, "desktop_shell_only", refusal);
+ return desktop;
+}
+
/**
* Client-update relay routes (mounted INSIDE authMiddleware at /api/desktop/update, and
* only in desktop mode). Restricted to the shell's own window (`sessionVia === "desktop"`,
@@ -71,18 +89,8 @@ export function desktopRoutes(deps: AppDeps): Hono {
export function desktopUpdateRoutes(deps: AppDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
- const requireShellSession = (c: Context<AppEnv>): DesktopService => {
- const desktop = deps.desktop;
- if (!desktop) throw new HttpError(404, "not_found", "Desktop mode is not enabled.");
- if (c.var.sessionVia !== "desktop") {
- throw new HttpError(
- 403,
- "desktop_shell_only",
- "Client updates are managed from the desktop app's own window.",
- );
- }
- return desktop;
- };
+ const requireShellSession = (c: Context<AppEnv>): DesktopService =>
+ shellSessionOf(deps, c, "Client updates are managed from the desktop app's own window.");
app.get("/", (c) => {
const desktop = requireShellSession(c);
@@ -115,3 +123,51 @@ export function desktopUpdateRoutes(deps: AppDeps): Hono<AppEnv> {
return app;
}
+
+/**
+ * The tray-icon preference (mounted INSIDE authMiddleware at /api/desktop/tray, and only
+ * in desktop mode). GET reads what the shell last pushed — null until that first push,
+ * which the page reads as on, the shell's own default. PUT relays a patch — the switch, the
+ * page's UI language, or both; the shell applies it, persists it and pushes the new state
+ * straight back, so the answer here is an acknowledgement and the GET is what tells the truth.
+ */
+export function desktopTrayRoutes(deps: AppDeps): Hono<AppEnv> {
+ const app = new Hono<AppEnv>();
+ const refusal = "The tray icon is managed from the desktop app's own window.";
+
+ app.get("/", (c) => {
+ const desktop = shellSessionOf(deps, c, refusal);
+ return c.json({ status: desktop.getTrayStatus() } satisfies DesktopTrayStatusResponse);
+ });
+
+ app.put("/", async (c) => {
+ const desktop = shellSessionOf(deps, c, refusal);
+ const body = (await c.req.json().catch(() => null)) as {
+ showTrayIcon?: unknown;
+ locale?: unknown;
+ } | null;
+ const patch: DesktopTrayPatch = {};
+ if (body?.showTrayIcon !== undefined) {
+ if (typeof body.showTrayIcon !== "boolean") {
+ throw new HttpError(400, "invalid_show_tray_icon", "showTrayIcon must be a boolean.");
+ }
+ patch.showTrayIcon = body.showTrayIcon;
+ }
+ if (body?.locale !== undefined) {
+ if (body.locale !== "zh" && body.locale !== "en") {
+ throw new HttpError(400, "invalid_locale", 'locale must be "zh" or "en".');
+ }
+ patch.locale = body.locale;
+ }
+ // An empty patch is a caller bug, not a no-op worth relaying to the shell.
+ if (patch.showTrayIcon === undefined && patch.locale === undefined) {
+ throw new HttpError(400, "empty_tray_patch", "Pass showTrayIcon, locale, or both.");
+ }
+ if (!desktop.requestTrayCommand(patch)) {
+ throw new HttpError(503, "shell_unreachable", "The desktop shell is not listening.");
+ }
+ return c.body(null, 202);
+ });
+
+ return app;
+}
diff --git a/packages/server/src/services/desktop-service.ts b/packages/server/src/services/desktop-service.ts
index 0619569d..d5d3079e 100644
--- a/packages/server/src/services/desktop-service.ts
+++ b/packages/server/src/services/desktop-service.ts
@@ -13,14 +13,20 @@
*
* Comparisons hash both sides first so timingSafeEqual gets equal-length buffers.
*
- * The service is also the shell↔web relay for client updates: the shell pushes its
- * updater snapshot over the utilityProcess message channel (index.ts wires the port),
- * the web reads it at GET /api/desktop/update and posts check/download/install commands
- * that are forwarded back to the shell. The window itself stays a plain browser — every
- * capability flows through this HTTP surface, never a renderer IPC bridge.
+ * The service is also the shell↔web relay for two shell-owned surfaces: client updates
+ * and the tray icon. In both directions it is the same utilityProcess message channel
+ * (index.ts wires the port) — the shell pushes its current state, the web reads it at
+ * GET /api/desktop/update or /api/desktop/tray and writes back a command that is
+ * forwarded to the shell. The window itself stays a plain browser — every capability
+ * flows through this HTTP surface, never a renderer IPC bridge.
*/
import { createHash, timingSafeEqual } from "node:crypto";
-import type { DesktopUpdateStatus, DesktopUpdaterCommandMessage } from "../api/types.js";
+import type {
+ DesktopTrayPatch,
+ DesktopTrayStatus,
+ DesktopUpdateStatus,
+ DesktopUpdaterCommandMessage,
+} from "../api/types.js";
/** What the page may ask the shell's updater to do (the relayed command's `action`). */
export type UpdaterCommand = DesktopUpdaterCommandMessage["action"];
@@ -88,4 +94,31 @@ export class DesktopService {
this.updateCommandSender(action);
return true;
}
+
+ // --- tray-icon relay -------------------------------------------------------
+
+ private trayStatus: DesktopTrayStatus | null = null;
+ private trayCommandSender: ((patch: DesktopTrayPatch) => void) | null = null;
+
+ /** Latest shell push; null until the shell's first one lands (the page then reads it as on). */
+ getTrayStatus(): DesktopTrayStatus | null {
+ return this.trayStatus;
+ }
+
+ /** index.ts stores each shell push here (already validated at the message port). */
+ setTrayStatus(status: DesktopTrayStatus): void {
+ this.trayStatus = status;
+ }
+
+ /** index.ts registers the message-port sender; absent outside a shell-forked process. */
+ onTrayCommand(sender: (patch: DesktopTrayPatch) => void): void {
+ this.trayCommandSender = sender;
+ }
+
+ /** Invoked by the tray route; false when no shell port is wired (tests, plain runs). */
+ requestTrayCommand(patch: DesktopTrayPatch): boolean {
+ if (!this.trayCommandSender) return false;
+ this.trayCommandSender(patch);
+ return true;
+ }
}
diff --git a/packages/server/src/services/desktop-update-port.ts b/packages/server/src/services/desktop-update-port.ts
index 797b42db..44a34151 100644
--- a/packages/server/src/services/desktop-update-port.ts
+++ b/packages/server/src/services/desktop-update-port.ts
@@ -1,16 +1,20 @@
/**
- * Shell↔server message-port relay for client updates (desktop mode only).
+ * Shell↔server message-port relay (desktop mode only): client updates, and the tray icon.
*
* Under the desktop shell this server runs as an Electron utilityProcess, which injects
* `process.parentPort` — an EventEmitter-ish port to the shell. The shell pushes its
- * updater snapshot through it, and the update routes forward the page's
- * check/download/install commands back. Under a plain `penguin server|web` run the port does not exist and this
- * module wires nothing; the update routes then answer 503 `shell_unreachable`.
+ * updater snapshot and its tray state through it, and the routes forward the page's
+ * check/download/install commands and its tray switch back. Under a plain
+ * `penguin server|web` run the port does not exist and this module wires nothing; those
+ * routes then answer 503 `shell_unreachable`.
*
- * Wire shapes live in api/types.ts (DesktopUpdaterStatusMessage /
- * DesktopUpdaterCommandMessage) so the shell imports the same contract.
+ * Wire shapes live in api/types.ts (the two updater messages and the two tray ones) so
+ * the shell imports the same contract.
*/
import type {
+ DesktopTrayCommandMessage,
+ DesktopTrayStatus,
+ DesktopTrayStatusMessage,
DesktopUpdateStatus,
DesktopUpdaterCommandMessage,
DesktopUpdaterStatusMessage,
@@ -55,11 +59,30 @@ export function shellPortOf(proc: NodeJS.Process): ShellPort | null {
: null;
}
-/** Connects the port to the service: stores validated status pushes, registers the command sender. */
+/** Validates one shell tray push. Same rule as the updater's: strict on the discriminator, strict on every field it carries. */
+export function parseTrayStatusMessage(data: unknown): DesktopTrayStatus | null {
+ if (typeof data !== "object" || data === null) return null;
+ const msg = data as Partial<DesktopTrayStatusMessage>;
+ if (msg.type !== "desktop-tray-status") return null;
+ const status = msg.status as Partial<DesktopTrayStatus> | undefined;
+ if (typeof status !== "object" || status === null) return null;
+ if (typeof status.showTrayIcon !== "boolean") return null;
+ // An older shell against a newer server pushes no locale. Reading it as English rather
+ // than rejecting the whole push keeps the icon switch working across that pairing.
+ const locale = status.locale === "zh" || status.locale === "en" ? status.locale : "en";
+ return { showTrayIcon: status.showTrayIcon, locale };
+}
+
+/** Connects the port to the service: stores validated status pushes, registers the command senders. */
export function wireShellUpdatePort(desktop: DesktopService, port: ShellPort): void {
port.on("message", (e) => {
const status = parseUpdaterStatusMessage(e.data);
- if (status !== null) desktop.setUpdateStatus(status);
+ if (status !== null) {
+ desktop.setUpdateStatus(status);
+ return;
+ }
+ const tray = parseTrayStatusMessage(e.data);
+ if (tray !== null) desktop.setTrayStatus(tray);
});
desktop.onUpdateCommand((action) => {
port.postMessage({
@@ -67,4 +90,10 @@ export function wireShellUpdatePort(desktop: DesktopService, port: ShellPort): v
action,
} satisfies DesktopUpdaterCommandMessage);
});
+ desktop.onTrayCommand((patch) => {
+ port.postMessage({
+ type: "desktop-tray-command",
+ ...patch,
+ } satisfies DesktopTrayCommandMessage);
+ });
}
diff --git a/packages/server/test/desktop-tray.test.ts b/packages/server/test/desktop-tray.test.ts
new file mode 100644
index 00000000..d6483063
--- /dev/null
+++ b/packages/server/test/desktop-tray.test.ts
@@ -0,0 +1,201 @@
+/**
+ * The tray-icon preference relay: the /api/desktop/tray routes (shell-window sessions
+ * only), the DesktopService store/forward pair behind them, and the message-port glue.
+ *
+ * The session gate is pinned in both directions like the client update's next door: the
+ * shell's own window may read and write, a password-via session against the same
+ * desktop-mode server gets 403 — its holder may be on another machine and must not reach
+ * into the chrome of a window it is not looking at.
+ */
+import { describe, expect, it } from "vitest";
+import { createDesktopApp, createTestApp, desktopLoginCookie, loginAdmin } from "./helpers.js";
+import type { DesktopTrayPatch, DesktopTrayStatusResponse, ErrorBody } from "../src/api/types.js";
+import { DesktopService } from "../src/services/desktop-service.js";
+import {
+ parseTrayStatusMessage,
+ wireShellUpdatePort,
+} from "../src/services/desktop-update-port.js";
+import type { ShellPort } from "../src/services/desktop-update-port.js";
+
+const put = (cookie: string, body: string) => ({
+ method: "PUT",
+ headers: { cookie, "content-type": "application/json" },
+ body,
+});
+
+describe("GET /api/desktop/tray", () => {
+ it("serves null before the shell's first push, then the stored state", async () => {
+ const t = await createDesktopApp();
+ try {
+ const cookie = await desktopLoginCookie(t.app);
+ const before = await t.app.request("/api/desktop/tray", { headers: { cookie } });
+ expect(before.status).toBe(200);
+ expect((await before.json()) as DesktopTrayStatusResponse).toEqual({ status: null });
+
+ t.deps.desktop!.setTrayStatus({ showTrayIcon: false, locale: "en" });
+ const after = await t.app.request("/api/desktop/tray", { headers: { cookie } });
+ expect((await after.json()) as DesktopTrayStatusResponse).toEqual({
+ status: { showTrayIcon: false, locale: "en" },
+ });
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("answers 403 desktop_shell_only to a password-established session", async () => {
+ const t = await createDesktopApp();
+ try {
+ const admin = await loginAdmin(t.app);
+ const res = await t.app.request("/api/desktop/tray", { headers: { cookie: admin.cookie } });
+ expect(res.status).toBe(403);
+ expect(((await res.json()) as ErrorBody).error.code).toBe("desktop_shell_only");
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("does not exist outside desktop mode", async () => {
+ const t = await createTestApp();
+ try {
+ const admin = await loginAdmin(t.app);
+ const res = await t.app.request("/api/desktop/tray", { headers: { cookie: admin.cookie } });
+ expect(res.status).toBe(404);
+ } finally {
+ await t.cleanup();
+ }
+ });
+});
+
+describe("PUT /api/desktop/tray", () => {
+ it("forwards the switch to the registered shell sender and answers 202", async () => {
+ const t = await createDesktopApp();
+ try {
+ const cookie = await desktopLoginCookie(t.app);
+ const sent: DesktopTrayPatch[] = [];
+ t.deps.desktop!.onTrayCommand((patch) => sent.push(patch));
+
+ const off = await t.app.request("/api/desktop/tray", put(cookie, '{"showTrayIcon":false}'));
+ expect(off.status).toBe(202);
+ const on = await t.app.request("/api/desktop/tray", put(cookie, '{"showTrayIcon":true}'));
+ expect(on.status).toBe(202);
+ expect(sent).toEqual([{ showTrayIcon: false }, { showTrayIcon: true }]);
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("refuses a field it cannot read, and a request that asks for nothing", async () => {
+ const t = await createDesktopApp();
+ try {
+ const cookie = await desktopLoginCookie(t.app);
+ const sent: DesktopTrayPatch[] = [];
+ t.deps.desktop!.onTrayCommand((patch) => sent.push(patch));
+ const cases: Array<[string, string]> = [
+ ['{"showTrayIcon":"off"}', "invalid_show_tray_icon"],
+ ['{"showTrayIcon":0}', "invalid_show_tray_icon"],
+ ['{"locale":"fr"}', "invalid_locale"],
+ ['{"locale":true}', "invalid_locale"],
+ // Nothing to do is a caller bug, not a no-op worth waking the shell for. An
+ // unparseable body lands here too: it asks for nothing this route understands.
+ ["{}", "empty_tray_patch"],
+ ["not json", "empty_tray_patch"],
+ ];
+ for (const [body, code] of cases) {
+ const res = await t.app.request("/api/desktop/tray", put(cookie, body));
+ expect(res.status, body).toBe(400);
+ expect(((await res.json()) as ErrorBody).error.code, body).toBe(code);
+ }
+ expect(sent).toEqual([]);
+ } finally {
+ await t.cleanup();
+ }
+ });
+
+ it("refuses a password session, and answers 503 while no port is wired", async () => {
+ const t = await createDesktopApp();
+ try {
+ const admin = await loginAdmin(t.app);
+ const forbidden = await t.app.request(
+ "/api/desktop/tray",
+ put(admin.cookie, '{"showTrayIcon":false}'),
+ );
+ expect(forbidden.status).toBe(403);
+
+ const cookie = await desktopLoginCookie(t.app);
+ const unreachable = await t.app.request(
+ "/api/desktop/tray",
+ put(cookie, '{"showTrayIcon":false}'),
+ );
+ expect(unreachable.status).toBe(503);
+ expect(((await unreachable.json()) as ErrorBody).error.code).toBe("shell_unreachable");
+ } finally {
+ await t.cleanup();
+ }
+ });
+});
+
+describe("the tray half of the shell port", () => {
+ it("parses only well-formed tray status frames", () => {
+ expect(
+ parseTrayStatusMessage({
+ type: "desktop-tray-status",
+ status: { showTrayIcon: true, locale: "zh" },
+ }),
+ ).toEqual({ showTrayIcon: true, locale: "zh" });
+ // A shell older than this server pushes no language. Reading it as English keeps the
+ // icon switch working across that pairing rather than dropping the whole push.
+ expect(
+ parseTrayStatusMessage({ type: "desktop-tray-status", status: { showTrayIcon: true } }),
+ ).toEqual({ showTrayIcon: true, locale: "en" });
+ expect(
+ parseTrayStatusMessage({
+ type: "desktop-tray-status",
+ status: { showTrayIcon: true, locale: "fr" },
+ }),
+ ).toEqual({ showTrayIcon: true, locale: "en" });
+ for (const data of [
+ null,
+ "status",
+ {},
+ { type: "desktop-tray-status" },
+ { type: "desktop-tray-status", status: null },
+ { type: "desktop-tray-status", status: {} },
+ { type: "desktop-tray-status", status: { showTrayIcon: "yes" } },
+ // The updater's frames ride the same port and must not be read as tray ones.
+ { type: "desktop-updater-status", status: { appVersion: "1", state: "idle" } },
+ ]) {
+ expect(parseTrayStatusMessage(data)).toBeNull();
+ }
+ });
+
+ it("stores tray pushes and posts tray commands beside the updater's, on one port", () => {
+ const desktop = new DesktopService("t");
+ const posted: unknown[] = [];
+ let onMessage: ((e: { data: unknown }) => void) | undefined;
+ const port: ShellPort = {
+ on: (_event, listener) => {
+ onMessage = listener;
+ },
+ postMessage: (message) => posted.push(message),
+ };
+ wireShellUpdatePort(desktop, port);
+
+ onMessage!({
+ data: { type: "desktop-tray-status", status: { showTrayIcon: false, locale: "zh" } },
+ });
+ expect(desktop.getTrayStatus()).toEqual({ showTrayIcon: false, locale: "zh" });
+ // An updater frame on the same port leaves the tray state alone, and vice versa.
+ onMessage!({
+ data: { type: "desktop-updater-status", status: { appVersion: "1", state: "idle" } },
+ });
+ expect(desktop.getTrayStatus()).toEqual({ showTrayIcon: false, locale: "zh" });
+ expect(desktop.getUpdateStatus()).toEqual({ appVersion: "1", state: "idle" });
+
+ expect(desktop.requestTrayCommand({ showTrayIcon: true })).toBe(true);
+ expect(posted).toEqual([{ type: "desktop-tray-command", showTrayIcon: true }]);
+ });
+
+ it("reports no sender before a port is wired", () => {
+ expect(new DesktopService("t").requestTrayCommand({ showTrayIcon: false })).toBe(false);
+ });
+});
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 8ef88d12..77f799f4 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -135,6 +135,8 @@ import type {
UpdateCheckResponse,
UpdateJobStatus,
RestartResponse,
+ DesktopTrayPatch,
+ DesktopTrayStatusResponse,
DesktopUpdateStatusResponse,
HookArchiveInstallRequest,
UsageErrorKind,
@@ -1324,3 +1326,17 @@ export const desktopUpdateDownload = () =>
export const desktopUpdateInstall = () =>
apiFetch<void>("/api/desktop/update/install", { method: "POST", body: {} });
+
+// Desktop tray icon (desktop-shell sessions only) --------------------------------------
+
+/** What the shell last pushed; `status` is null until that first push, which reads as on. */
+export const getDesktopTray = () => apiFetch<DesktopTrayStatusResponse>("/api/desktop/tray");
+
+/**
+ * Relays a tray change to the shell, which applies it and pushes the new state back.
+ *
+ * A patch rather than a snapshot: Settings › Appearance writes the switch, and the locale
+ * provider writes the UI language whenever it changes, and neither knows the other's value.
+ */
+export const setDesktopTray = (patch: DesktopTrayPatch) =>
+ apiFetch<void>("/api/desktop/tray", { method: "PUT", body: patch });
diff --git a/packages/web/src/components/layout/app-layout.tsx b/packages/web/src/components/layout/app-layout.tsx
index 6696aa39..d9472911 100644
--- a/packages/web/src/components/layout/app-layout.tsx
+++ b/packages/web/src/components/layout/app-layout.tsx
@@ -14,6 +14,7 @@ import { useAuth } from "../../state/auth";
import { useProject } from "../../state/project";
import { useSessions } from "../../state/sessions";
import { useCompletionNotifications } from "../../state/use-completion-notifications";
+import { useTrayLocale } from "../../state/use-tray-locale";
import { Drawer } from "../ui/drawer";
import { GlyphIcon } from "../ui/glyph-icon";
import { Tooltip } from "../ui/tooltip";
@@ -267,6 +268,8 @@ export function AppLayout() {
// Desktop shell only (gated inside): system notification when a task finishes while
// the window is unfocused.
useCompletionNotifications();
+ // Desktop shell only: keeps the tray menu in the language this window is in.
+ useTrayLocale();
// The single eager owner of the update checks (use-update-badges.ts): one request per
// browser session, so a dot can be there on a fresh load instead of waiting for someone to
// open the sidebar menu. Every other anchor reads the same caches passively.
diff --git a/packages/web/src/features/settings/appearance-section.tsx b/packages/web/src/features/settings/appearance-section.tsx
index fda07cf8..43d612be 100644
--- a/packages/web/src/features/settings/appearance-section.tsx
+++ b/packages/web/src/features/settings/appearance-section.tsx
@@ -6,18 +6,23 @@
* TerminalThemeMode). The workbench launcher's row is here rather than with the chat's own
* settings because it is the same kind of choice: whether a piece of chrome is drawn. The
* tool short-name row is here for the same reason — it changes how a tool call is spelled
- * on screen, never what runs.
+ * on screen, never what runs. So is the tray-icon row, the one piece of chrome here that
+ * is not drawn by this page at all: it is the desktop shell's, and only the shell's own
+ * window may reach it (see isDesktopShellWindow), so the row is absent in a browser.
*/
-import { useSyncExternalStore } from "react";
+import { useEffect, useState, useSyncExternalStore } from "react";
import { S } from "../../lib/strings";
+import * as api from "../../api/endpoints";
import { Segmented } from "../../components/ui/segmented";
import { Switch } from "../../components/ui/switch";
+import { isDesktopShellWindow } from "../../lib/account-menu";
import {
launcherHiddenVersion,
readLauncherHidden,
subscribeLauncherHidden,
writeLauncherHidden,
} from "../dock/dock-launcher-state";
+import { useAuth } from "../../state/auth";
import { useTheme } from "../../state/theme";
import type { FontScale, TerminalThemeMode, ThemeMode } from "../../state/theme";
import { AccentPicker, PrefRow } from "./setting-row";
@@ -38,6 +43,31 @@ export function AppearanceSection() {
// The fan's "hide launcher" entry writes the same preference, so this row follows it.
useSyncExternalStore(subscribeLauncherHidden, launcherHiddenVersion);
const launcherShown = !readLauncherHidden();
+ const { desktopMode, sessionVia } = useAuth();
+ const offersTrayIcon = isDesktopShellWindow({ desktopMode, sessionVia });
+ // The shell owns this one, so it is fetched rather than read from a store. Anything the
+ // shell has not told us — no push yet, a request that failed — reads as on, the shell's
+ // own default, so the row never claims the icon is off while it is sitting in the tray.
+ const [trayIcon, setTrayIcon] = useState(true);
+ useEffect(() => {
+ if (!offersTrayIcon) return;
+ let live = true;
+ void api.getDesktopTray().then(
+ (res) => {
+ if (live) setTrayIcon(res.status?.showTrayIcon ?? true);
+ },
+ () => {},
+ );
+ return () => {
+ live = false;
+ };
+ }, [offersTrayIcon]);
+ // Optimistic: the switch answers the click, and a refused write snaps it back rather
+ // than leaving the row disagreeing with the icon the user is looking at.
+ const changeTrayIcon = (next: boolean): void => {
+ setTrayIcon(next);
+ void api.setDesktopTray({ showTrayIcon: next }).catch(() => setTrayIcon(!next));
+ };
const themeOptions: ReadonlyArray<{ value: ThemeMode; label: string }> = [
{ value: "light", label: S.settings.themeLight },
@@ -76,6 +106,11 @@ export function AppearanceSection() {
<PrefRow label={S.settings.toolAliases} info={S.settings.toolAliasesInfo}>
<Switch checked={toolAliases} onChange={setToolAliases} />
</PrefRow>
+ {offersTrayIcon && (
+ <PrefRow label={S.settings.trayIcon} info={S.settings.trayIconInfo}>
+ <Switch checked={trayIcon} onChange={changeTrayIcon} />
+ </PrefRow>
+ )}
</div>
);
}
diff --git a/packages/web/src/lib/account-menu.ts b/packages/web/src/lib/account-menu.ts
index 452f77c8..ff7372b0 100644
--- a/packages/web/src/lib/account-menu.ts
+++ b/packages/web/src/lib/account-menu.ts
@@ -16,6 +16,21 @@ export interface AccountMenuSession {
sessionVia: MeResponse["sessionVia"];
}
+/**
+ * Whether this page IS the desktop shell's own window — the one place a control may reach
+ * the app around the page: its updater, the chrome it is drawn in.
+ *
+ * BOTH halves are required. `desktopMode` alone would also match a browser signed in
+ * against the same desktop-mode server over loopback, which may be on another machine and
+ * must not drive this one's GUI app. `sessionVia` alone would match a stale desktop cookie
+ * replayed against a plain `penguin server` on the same data root, where no shell is
+ * listening at all. The server enforces the same pair on every route behind these
+ * controls.
+ */
+export function isDesktopShellWindow(session: AccountMenuSession): boolean {
+ return session.desktopMode && session.sessionVia === "desktop";
+}
+
/**
* Whether to offer a change-password entry at all.
*
@@ -35,7 +50,7 @@ export interface AccountMenuSession {
* root, where the server requires the old password like any other session.
*/
export function offersChangePassword(session: AccountMenuSession): boolean {
- return !(session.desktopMode && session.sessionVia === "desktop");
+ return !isDesktopShellWindow(session);
}
/**
diff --git a/packages/web/src/lib/desktop-update.ts b/packages/web/src/lib/desktop-update.ts
index c2b1514e..c2ee7bc6 100644
--- a/packages/web/src/lib/desktop-update.ts
+++ b/packages/web/src/lib/desktop-update.ts
@@ -5,18 +5,16 @@
* pure (vitest runs node-only here, so nothing renders — same split as account-menu.ts).
*/
import type { DesktopUpdateStatus } from "@prismshadow/penguin-server/api";
+import { isDesktopShellWindow } from "./account-menu";
import type { AccountMenuSession } from "./account-menu";
/**
- * Whether to offer the client-update row at all: only the shell's own window. Both
- * halves matter, mirroring offersChangePassword's reasoning inverted — `desktopMode`
- * alone would let a browser signed into the same desktop-mode server read this
- * machine's updater state and restart its GUI app; `sessionVia` alone would offer the
- * row to a stale desktop cookie replayed against a plain `penguin server`, where no
- * shell is listening. The server enforces the same pair on the routes.
+ * Whether to offer the client-update row at all: only the shell's own window, because
+ * only there is there an updater to drive — see isDesktopShellWindow for why both halves
+ * of that are required. The server enforces the same pair on the routes.
*/
export function offersClientUpdate(session: AccountMenuSession): boolean {
- return session.desktopMode && session.sessionVia === "desktop";
+ return isDesktopShellWindow(session);
}
/** How one row-initiated check ended, for exactly one report per outcome (in the modal when it is open, a toast otherwise). */
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 1453f96e..4e4391b9 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -221,6 +221,9 @@ export const en: Strings = {
notificationsDismissed:
"The permission prompt was closed without an answer, so notifications stay off. Turn this on again to ask once more.",
notificationsUnsupported: "This browser does not support system notifications.",
+ trayIcon: "Tray icon",
+ trayIconInfo:
+ "The desktop app keeps an icon in the system tray — the Windows notification area, the macOS menu bar, the Linux tray — for as long as it runs: click it to come back to the window, right-click it to start a session or quit. On by default; turning it off removes the icon at once, no restart, and closing the window then no longer hides it, so the app stays in the Dock on macOS and quits on Windows and Linux.",
currencyInfo: "Display currency for prices; storage is always USD.",
changePasswordInfo: "Change this account's sign-in password.",
accentNames: {
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 5b7e342a..ca4147bb 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -235,6 +235,10 @@ export const zh = {
notificationsDismissed:
"权限提示被关闭、没有给出答复,通知因此保持关闭。再次打开这个开关可以重新申请。",
notificationsUnsupported: "当前浏览器不支持系统通知。",
+ /** Desktop shell only: the system-tray icon. Absent in a browser. */
+ trayIcon: "托盘图标",
+ trayIconInfo:
+ "桌面应用运行期间在系统托盘(Windows 通知区、macOS 菜单栏、Linux 托盘)常驻一个图标,点击即可回到窗口,右键可开新会话或退出。默认开启;关掉后图标立即消失,无需重启,此时关闭窗口不再收进托盘:macOS 应用留在 Dock,Windows 与 Linux 关窗即退出。",
currencyInfo: "价格显示币种;存储始终为美元。",
changePasswordInfo: "更改当前账号的登录密码。",
accentNames: {
diff --git a/packages/web/src/state/use-tray-locale.ts b/packages/web/src/state/use-tray-locale.ts
new file mode 100644
index 00000000..71be019a
--- /dev/null
+++ b/packages/web/src/state/use-tray-locale.ts
@@ -0,0 +1,40 @@
+/**
+ * Tells the desktop shell which language the window is in, so its tray menu reads the same way.
+ *
+ * The shell cannot see this preference itself: it lives in this browser's localStorage, on the
+ * other side of a boundary the desktop design keeps deliberately one-way — the window is a
+ * plain browser with no IPC bridge into it. So the page reports, over the same
+ * `PUT /api/desktop/tray` the Appearance switch uses, and the shell persists what it hears and
+ * redraws its menu.
+ *
+ * Reports on mount as well as on change: the shell starts before any window loads and falls
+ * back to the device language until something tells it otherwise, which is the wrong answer for
+ * anyone who has picked a language that is not their device's.
+ *
+ * A failed report is dropped. There is no retry and no message: the tray is a convenience, the
+ * next language change (or the next launch of the app, which sends again on mount) will carry
+ * the value, and a toast about a menu the user may not even have open would be noise.
+ */
+import { useEffect } from "react";
+import * as api from "../api/endpoints";
+import { isDesktopShellWindow } from "../lib/account-menu";
+import { useAuth } from "./auth";
+import { useLocale } from "./locale";
+import type { Locale } from "./locale";
+import type { DesktopTrayLocale } from "@prismshadow/penguin-server/api";
+
+// The Web App's languages and the ones the tray route accepts are the same set, and a
+// divergence would otherwise show up as a 400 nobody looks at. Compile-time, no runtime cost.
+type LocalesAgree = Locale extends DesktopTrayLocale ? true : never;
+const _localesAgree: LocalesAgree = true;
+void _localesAgree;
+
+export function useTrayLocale(): void {
+ const { locale } = useLocale();
+ const { desktopMode, sessionVia } = useAuth();
+ const shell = isDesktopShellWindow({ desktopMode, sessionVia });
+ useEffect(() => {
+ if (!shell) return;
+ void api.setDesktopTray({ locale }).catch(() => {});
+ }, [shell, locale]);
+}
diff --git a/packages/web/test/account-menu.test.ts b/packages/web/test/account-menu.test.ts
index 5b1c2e5c..5703f7b0 100644
--- a/packages/web/test/account-menu.test.ts
+++ b/packages/web/test/account-menu.test.ts
@@ -16,7 +16,25 @@ import { readFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
-import { offersChangePassword, omitsOldPassword } from "../src/lib/account-menu";
+import {
+ isDesktopShellWindow,
+ offersChangePassword,
+ omitsOldPassword,
+} from "../src/lib/account-menu";
+
+describe("isDesktopShellWindow", () => {
+ it("is the shell's own window and nothing else", () => {
+ // The rule the shell-only controls share — the client-update row, and Appearance's
+ // tray switch, which reaches the chrome the page is drawn in. Both single-field
+ // simplifications are wrong: `desktopMode` alone lets a browser on another machine
+ // drive this one's GUI app, `sessionVia` alone matches a stale desktop cookie
+ // replayed against a plain `penguin server`, where no shell is listening.
+ expect(isDesktopShellWindow({ desktopMode: true, sessionVia: "desktop" })).toBe(true);
+ expect(isDesktopShellWindow({ desktopMode: true, sessionVia: "password" })).toBe(false);
+ expect(isDesktopShellWindow({ desktopMode: false, sessionVia: "desktop" })).toBe(false);
+ expect(isDesktopShellWindow({ desktopMode: false, sessionVia: "password" })).toBe(false);
+ });
+});
describe("offersChangePassword", () => {
it("hides it in the desktop shell's own window — no login form, seed password never shown", () => {