A local-first multi-agent app development platform, built on PenguinHarness
feat: 给桌面版加一只桌宠,会报通知、新版本和模型余额
lmlihenge9a24c2a46c7
diff --git a/changelog/unreleased/2026-10-20-desktop-pet.md b/changelog/unreleased/2026-10-20-desktop-pet.mdnew file mode 100644index 00000000..3e2cd52b--- /dev/null+++ b/changelog/unreleased/2026-10-20-desktop-pet.md@@ -0,0 +1,59 @@+# The desktop app can keep a pet on screen: a small penguin for notices, updates and balance++- **Date:** 2026-10-20+- **Type:** feature+- **Scope:** `desktop`, `server`, `web`+- **Breaking:** no++[中文版](2026-10-20-desktop-pet.zh.md)++The desktop app has a companion window: a small Adelie penguin in the bottom-right corner of the+screen the main window is on, above other windows, drawn on a transparent background so it floats+on the desktop instead of sitting in a box. Settings › Appearance gained a "Show desktop pet"+switch beside the tray-icon one, and the pet's own panel carries a way to hide it again; both write+the same preference, so the two cannot disagree. It is **off by default** — the tray icon is chrome+inside a window the user already opened, while the pet is a window of its own floating over other+apps, so it appears when it is asked for and not before. The shell remembers the choice in+`pet.json` under its user data and reopens the window on start when it is on.++What the pet is for: it says one thing at a time in a bubble above the penguin — a schedule that+fired, by name; how many tool calls are waiting for a person ("有 N 个工具调用在等你批准"); a+colleague's spend nearing or passing its budget — and keeps the last five in the panel behind a+click. The panel also carries the account's pinned group balance with a refresh action, the+client-update state with the one action that state offers (check, download, restart to install),+and the newest notice.++## Details++- The pet window is a second window of the same app origin showing a route of the Web App itself+ (`/pet`): no preload, no IPC bridge, no separately served page. It is frameless, transparent,+ non-resizable, kept off the taskbar and always on top; the page paints the penguin and marks the+ rest of the window draggable, so the pet is moved by dragging anywhere on it that is not a control.+- Everything it shows comes over the same HTTP surface every other page reads: the user-level event+ stream for what happened while nobody was looking, the shell's update snapshot, and the pinned+ model balance. Because that stream is the user-level one, a schedule firing in any Session, an+ approval waiting in any Session and a budget warning all reach the pet.+- Turning it on and off crosses the same relay the tray switch uses: `GET`/`PUT /api/desktop/pet` on+ the server, restricted to the shell's own windows and refused anywhere else, then a+ `desktop-pet-command` frame over the utilityProcess channel to the shell, which writes `pet.json`+ and opens or closes the window. A missing `showPet` and a non-boolean one are rejected at the+ route instead of being relayed.+- The window is 260×248, 24px off the bottom-right corner of the main window's working area. It is+ not click-through — a transparent pixel still swallows the click that lands on it — so the size is+ kept as tight as the bubble and the penguin together need.+- The penguin is an inline SVG in the Web App with fixed colours and no external asset, and it bobs+ gently unless the system asks for reduced motion.+- The pet's page re-reads the update snapshot once a minute and speaks only when the announced state+ actually changes: the shell pushes that snapshot to the server, so polling is what turns it into+ something the pet can say.+- `/pet` is an ordinary route. In a plain browser tab the penguin still draws and the notices still+ arrive; the two readings that belong to the shell say so rather than failing, and the pet's own+ hide action is not offered where there is no pet window to hide.+- The desktop shell's smoke run now reports the pet window's URL and title, and screenshots it+ beside the main window's when a screenshot was asked for.++## Compatibility++- Nothing existing changed: this adds a route, a preference file and a window. `showPet` defaults to+ off, so an install that had no pet keeps having none until the switch is turned on, and the shell+ members the pet's relay adds are optional, so a shell without them is not required to answer.diff --git a/changelog/unreleased/2026-10-20-desktop-pet.zh.md b/changelog/unreleased/2026-10-20-desktop-pet.zh.mdnew file mode 100644index 00000000..f973d006--- /dev/null+++ b/changelog/unreleased/2026-10-20-desktop-pet.zh.md@@ -0,0 +1,43 @@+# 桌面版能养一只桌宠了:通知、新版本和模型余额都落在企鹅身上++- **Date:** 2026-10-20+- **Type:** feature+- **Scope:** `desktop`, `server`, `web`+- **Breaking:** no++[English](2026-10-20-desktop-pet.md)++桌面版多了一个伴随窗口:主窗口所在屏幕的右下角蹲着一只阿德利企鹅,压在其他窗口之上,背景是透明的 ——+它浮在桌面上,而不是待在一个框里。设置 › 外观在托盘图标开关旁边多了一个「显示桌宠」,桌宠自己的面板+里也有一个把它收起来的入口,两者写的是同一份偏好,不会互相矛盾。它**默认关闭** —— 托盘图标是用户已经+打开的那个窗口里的装饰,桌宠则是自己的一扇窗、会盖住别的应用,所以它只在该出现的时候出现。壳把选择记在+用户数据目录的 `pet.json` 里,开着的时候下次启动就把窗口开出来。++桌宠要说的话:一次一句,出现在企鹅上方的气泡里 —— 定时任务触发了(带任务名)、有 N 个工具调用在等批准、+同事的花费接近或超过预算 —— 最近五条留在点开的面板里。面板里还有账号上固定住的分组余额与刷新动作、+客户端更新状态连同那个状态唯一能做的动作(检查 / 下载 / 重启安装),以及最新一条通知。++## 细节++- 桌宠窗口是同一个应用来源的第二个窗口,加载的是 Web 应用自己的一条路由(`/pet`):没有 preload、+ 没有 IPC 桥、也没有单独托管的页面。它无边框、透明、不可缩放、不进任务栏、始终置顶;页面画出企鹅,+ 并把窗口其余部分标成可拖动区,所以在企鹅之外的任何地方按住它都能拖动。+- 它显示的一切都走其他页面读的同一套 HTTP 面:用户级事件流回答「没人看着的时候发生了什么」,壳的更新+ 快照,以及固定住的模型余额。走的是用户级事件流,所以任何会话里定时任务触发、任何会话里有工具调用在等+ 批准、任何员工预算告警,都能传到桌宠这里。+- 开关走的是托盘开关同一条中继:服务端 `GET`/`PUT /api/desktop/pet`,只对壳自己的窗口开放、别处一律+ 拒绝,然后一帧 `desktop-pet-command` 经 utilityProcess 通道送到壳,由壳写 `pet.json` 并开关窗口。+ 缺少 `showPet`、或者它不是布尔值,在路由处就被拒掉,不会转发给壳。+- 窗口 260×248,贴在主窗口所在显示器工作区的右下角、距边 24px。它不是穿点击的 —— 透明的像素也会吃掉+ 落在上面的那一次点击 —— 所以尺寸只留气泡和企鹅一起需要的那点空间。+- 企鹅是 Web 应用里的内联 SVG,固定配色、不依赖外部资源;系统要求减少动效时它就不轻轻摇晃。+- 桌宠页面每分钟重读一次更新快照,只有播报过的状态真的变了才开口:壳把快照推给服务端,所以是这次轮询+ 让它变成桌宠能说出口的话。+- `/pet` 是一条普通路由。在浏览器标签里打开,企鹅照样画出来、通知照样到达;两项属于壳的读数会说清+ 「只在桌面应用里能读」而不是报错,而没有桌宠窗口可藏的地方就不提供「隐藏桌宠」。+- 桌面壳的冒烟运行现在会报告桌宠窗口的地址与标题,在被要求截图时还会把它一并截下来,名字挨着主窗口那张。++## 兼容性++- 没有改动任何已有的东西:本轮只是多了路由、偏好文件和窗口。`showPet` 默认关闭,所以此前没有桌宠的+ 安装升级后依旧没有,直到打开那个开关;桌宠中继新增的壳成员都是可选的,没有它们的壳不需要应答。diff --git a/packages/desktop/src/main.ts b/packages/desktop/src/main.tsindex f413feea..f6cae370 100644--- a/packages/desktop/src/main.ts+++ b/packages/desktop/src/main.ts@@ -30,6 +30,14 @@* stop). Settings › Appearance turns the icon off and on, reaching the shell over the same* utilityProcess relay the client updater uses.*+ * Desktop pet: a small frameless, transparent, always-on-top window showing the Web App's own+ * `/pet` route — the Adelie penguin, which announces schedule firings, tool calls waiting for+ * approval and budget warnings, and reports the model balance and the client-update state when+ * clicked (see pet-window.ts and pet-prefs.ts; the preference lives in userData/pet.json and+ * defaults to off). Settings › Appearance turns it on and off over that same relay. Being a page+ * of this same origin, it is a plain browser with no IPC bridge of its own — the whole reason it+ * can be delivered by the platform rather than the shell.+ ** Built-in browser: the main window (and no other) may host <webview> guests in the* `persist:penguin-browser` partition, and builtin-browser.ts relays raw CDP and cookie writes* for them over that same port. That relay is the only part of the browser the shell carries,@@ -58,7 +66,7 @@import fs from "node:fs";import os from "node:os";import path from "node:path";-import { app, BrowserWindow, dialog, session, shell } from "electron";+import { app, BrowserWindow, dialog, screen, session, shell } from "electron";import type { WindowOpenHandlerResponse } from "electron";import { resolveRoot } from "@adelie/core";import { mintApiToken } from "@adelie/server/auth-token";@@ -95,6 +103,8 @@ import {trayStatusMessage,updateTrayPrefs,} from "./tray-prefs.js";+import { parsePetCommand, petStatusMessage, readPetPrefs, updatePetPrefs } from "./pet-prefs.js";+import { PET_WINDOW_OPTIONS, petShotPath, petWindowPosition, petWindowUrl } from "./pet-window.js";import { getUpdaterStatus, handleUpdaterCommand, initUpdater, onUpdaterStatus } from "./updater.js";import { parseUpdaterCommand, updaterStatusMessage } from "./updater-status.js";import {@@ -131,6 +141,12 @@ 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 pet window, and the Appearance switch's value for it. The window exists exactly while the+ * preference is on and the app origin is known (see openPet).+ */+let petWin: BrowserWindow | null = null;+let showPet = false;/*** 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@@ -231,7 +247,16 @@ function createWindow(url: string): void {});win.on("closed", () => {win = null;+ // The pet is chrome of this app, and chrome does not keep it alive: `window-all-closed` is+ // what quits on Windows and Linux, and a floating penguin that held that back would leave a+ // running server behind a window nobody can get back to. Only where closing the last window+ // really does end the app — macOS keeps it in the Dock, and keeps the pet with it.+ if (process.platform !== "darwin") closePet();});+ // The pet window waits for this: its page signs in with the same cookie this load is what+ // establishes (see openPet). Idempotent, and it re-checks the preference, so a later load of+ // the main window is where a pet that was switched on before boot finally appears.+ win.webContents.on("did-finish-load", () => openPet());// New windows, from this window and from every window it opens, go through one rule// (classifyWindowOpen): only the Workspace preview hand-off, a preview page and a detached// terminal get a window of this app; other sites go to the system browser; anything else@@ -557,13 +582,93 @@ function setTrayLocale(next: TrayLocale): void {pushTrayStatus();}+// --- the desktop pet -------------------------------------------------------++/**+ * Creates the pet window if the preference asks for one, the app origin is known and there is+ * none. Idempotent, and called from three places: app boot has finished, the main window has+ * finished a load (its cookie is what the pet page signs in with — see below), and the+ * Appearance switch has just been turned on.+ *+ * The window is a second plain browser on this app's own origin, showing `/pet`, so it needs+ * nothing the main window does not already have: no preload, no IPC bridge, no separately served+ * page. That is also why it waits for the main window's first load — the session cookie arrives+ * with it, and a pet page that asked too early would render its "not signed in" nothing and never+ * ask again.+ */+function openPet(): void {+ if (quitting || !showPet || petWin !== null || appOrigin === null) return;+ const origin = appOrigin;+ // On the display the app window is on, beside its bottom-right corner: the pet is a companion+ // to the window the user is working in, not to whichever monitor the cursor happens to be on.+ const display =+ win !== null && !win.isDestroyed()+ ? screen.getDisplayMatching(win.getBounds())+ : screen.getPrimaryDisplay();+ const pet = new BrowserWindow({+ ...PET_WINDOW_OPTIONS,+ ...petWindowPosition(display.workArea),+ });+ petWin = pet;+ // Chrome, not a browsing surface: it opens no window, and a navigation that leaves the app+ // goes to the system browser like any other (the pet page itself has no links).+ pet.webContents.setWindowOpenHandler(() => ({ action: "deny" }));+ pet.webContents.on("will-navigate", (event, target) => {+ if (!isAppUrl(target, appOrigin)) {+ event.preventDefault();+ openInSystem(target);+ }+ });+ // Shown only once it has painted: a transparent window that has drawn nothing is a flash of+ // the desktop showing through. showInactive, because the pet appearing must not take the focus+ // away from whatever the user is typing into.+ pet.once("ready-to-show", () => {+ if (!pet.isDestroyed()) pet.showInactive();+ });+ pet.on("closed", () => {+ petWin = null;+ });+ void pet.loadURL(petWindowUrl(origin));+}++/**+ * Closes the pet window, now. `destroy` rather than `close`: switching the pet off is a decision+ * about chrome, nothing in it can be unsaved, and a renderer that is wedged must not be able to+ * keep a window on screen after the user asked for it to go.+ */+function closePet(): void {+ petWin?.destroy();+ petWin = null;+}++/**+ * Applies Settings › Appearance's pet switch (or the pet's own "hide me" row, which writes the+ * same field through the same route): the window appears or goes at once, no restart.+ */+function setShowPet(next: boolean): void {+ showPet = next;+ try {+ updatePetPrefs(app.getPath("userData"), { showPet: next });+ } catch (err) {+ logLine(`[shell] the pet preference could not be saved: ${String(err)}`);+ }+ if (next) openPet();+ else closePet();+ pushPetStatus();+}++/** Tells the page what the pet window is actually doing, which is what its switch renders. */+function pushPetStatus(): void {+ relayChild?.postMessage(petStatusMessage(showPet));+}+/*** Shell relay over the utilityProcess port: forward the account-menu row's check/install- * frames to the updater, the Appearance switch's frames to the tray, the built-in browser's- * commands to its guests and the Workspace picker's folder-access requests to folder-access.ts,- * 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.+ * frames to the updater, the Appearance switch's frames to the tray and to the pet window, the+ * built-in browser's commands to its guests and the Workspace picker's folder-access requests to+ * folder-access.ts, push every updater status fold back, and push all three 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;@@ -579,7 +684,10 @@ function wireShellRelay(child: EmbeddedServer["child"]): void {if (command !== null) {if (command.locale !== undefined) setTrayLocale(command.locale);if (command.showTrayIcon !== undefined) setShowTrayIcon(command.showTrayIcon);+ return;}+ const pet = parsePetCommand(message);+ if (pet !== null && pet.showPet !== undefined) setShowPet(pet.showPet);});const unsubscribe = onUpdaterStatus((status) => child.postMessage(updaterStatusMessage(status)));child.on("exit", () => {@@ -588,6 +696,7 @@ function wireShellRelay(child: EmbeddedServer["child"]): void {});child.postMessage(updaterStatusMessage(getUpdaterStatus()));pushTrayStatus();+ pushPetStatus();}/** Starts (or restarts) the embedded server and points the window at the claim link. */@@ -790,6 +899,9 @@ if (!app.requestSingleInstanceLock()) {// same rule the Web App applies to its own "follow the system" default.trayLocale = trayPrefs.locale ?? resolveTrayLocale(app.getLocale());openTray();+ // The pet's preference, read before boot for the same reason: the window it decides about+ // is opened by the main window's first load, which boot is what starts.+ showPet = readPetPrefs(app.getPath("userData")).showPet;initUpdater(() => win);await boot();// Install or repair the bundled 'penguin' command. Runs every launch: that is what@@ -815,17 +927,31 @@ function armSmokeProbe(target: BrowserWindow): void {setTimeout(() => {void (async () => {try {+ const pet = petWin;const result = {title: target.webContents.getTitle(),url: target.webContents.getURL(),origin: appOrigin,embedded: server !== null,+ // Whether the pet window is up, and what it is showing. Null is the honest answer for+ // a run whose preference is off, so the probe reports it rather than only the cases+ // where the window exists.+ pet:+ pet === null || pet.isDestroyed()+ ? null+ : { url: pet.webContents.getURL(), title: pet.webContents.getTitle() },};const shot = process.env.PENGUIN_DESKTOP_SMOKE_SHOT;if (shot) {- const image = await target.webContents.capturePage();const { writeFileSync } = await import("node:fs");+ const image = await target.webContents.capturePage();writeFileSync(shot, image.toPNG());+ // The pet is a window of its own, and its pixels are the only way to check that what+ // it draws is the penguin and not a blank transparent rectangle: its shot lands beside+ // the main window's when a run has one.+ if (pet !== null && !pet.isDestroyed()) {+ writeFileSync(petShotPath(shot), (await pet.webContents.capturePage()).toPNG());+ }}process.stdout.write(`DESKTOP-SMOKE-RESULT ${JSON.stringify(result)}\n`);} catch (err) {diff --git a/packages/desktop/src/pet-prefs.ts b/packages/desktop/src/pet-prefs.tsnew file mode 100644index 00000000..4c30ff19--- /dev/null+++ b/packages/desktop/src/pet-prefs.ts@@ -0,0 +1,100 @@+/**+ * The desktop pet's preference — on disk, and on the wire. Pure path, file and frame logic, no+ * Electron imports (unit-tested).+ *+ * One boolean lives in `userData/pet.json`:+ *+ * - `showPet` — whether the shell keeps its small companion window on screen. It is the Web+ * App's Settings › Appearance switch, relayed to the shell over the utilityProcess message+ * channel the client updater and the tray icon already use (see main.ts and the server's+ * services/desktop-update-port.ts). The pet window's own "hide me" row writes the same field+ * through the same route, so the two ways of turning it off cannot disagree.+ *+ * Unlike the tray's two booleans, this one defaults to OFF: the tray icon is chrome inside a+ * window the user already opened, while the pet is a window of its own that floats over+ * everything else. It appears when it is asked for and not before.+ *+ * The preference is a convenience, never a reason for the shell to fail to start — a missing or+ * malformed file reads as the default, and a failed write is the caller's line in the log.+ */+import fs from "node:fs";+import path from "node:path";+import type { DesktopPetCommandMessage, DesktopPetStatusMessage } from "@adelie/server/api";++/** Preference file name, inside the app's userData directory. */+export const PET_PREFS_FILE = "pet.json";++export interface PetPrefs {+ /** The pet window is on screen for as long as the app runs and the preference stays on. */+ showPet: boolean;+}++export const DEFAULT_PET_PREFS: PetPrefs = {+ showPet: false,+};++/** Location of the preference file for a userData directory. */+export function petPrefsPath(userDataDir: string): string {+ return path.join(userDataDir, PET_PREFS_FILE);+}++/** Reads the preference; anything unreadable, unparsable or ill-typed reads as the default. */+export function readPetPrefs(userDataDir: string): PetPrefs {+ let parsed: unknown;+ try {+ parsed = JSON.parse(fs.readFileSync(petPrefsPath(userDataDir), "utf8"));+ } catch {+ return { ...DEFAULT_PET_PREFS };+ }+ if (typeof parsed !== "object" || parsed === null) return { ...DEFAULT_PET_PREFS };+ const value = (parsed as Partial<Record<keyof PetPrefs, unknown>>).showPet;+ return { showPet: typeof value === "boolean" ? value : DEFAULT_PET_PREFS.showPet };+}++/** Writes the preference. Throws on failure: the caller decides how to report it. */+export function writePetPrefs(userDataDir: string, prefs: PetPrefs): void {+ fs.mkdirSync(userDataDir, { recursive: true });+ const file = petPrefsPath(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 pet's own row)+ * go through this, so neither can clobber the other's value with a snapshot it read before the+ * other wrote.+ */+export function updatePetPrefs(userDataDir: string, patch: Partial<PetPrefs>): PetPrefs {+ const next = { ...readPetPrefs(userDataDir), ...patch };+ writePetPrefs(userDataDir, next);+ return next;+}++// --- the wire, to and from the Web App's Appearance settings -----------------++/** Wraps what the pet window is currently doing for the port push. */+export function petStatusMessage(showPet: boolean): DesktopPetStatusMessage {+ return { type: "desktop-pet-status", status: { showPet } };+}++/**+ * Validates one server-relayed pet 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 pet push.+ */+export function parsePetCommand(data: unknown): PetCommand | null {+ if (typeof data !== "object" || data === null) return null;+ const msg = data as Partial<DesktopPetCommandMessage>;+ if (msg.type !== "desktop-pet-command") return null;+ const patch: PetCommand = {};+ if (typeof msg.showPet === "boolean") patch.showPet = msg.showPet;+ return patch;+}++/** What one relayed command asks the shell to change; every field optional, as the route's patch is. */+export interface PetCommand {+ showPet?: boolean;+}diff --git a/packages/desktop/src/pet-window.ts b/packages/desktop/src/pet-window.tsnew file mode 100644index 00000000..84835529--- /dev/null+++ b/packages/desktop/src/pet-window.ts@@ -0,0 +1,105 @@+/**+ * The desktop pet's window: which page it shows, how big it is, where it sits, and what it is+ * allowed to be. Pure — no Electron imports — so every decision here is unit-tested and main.ts+ * only has to create the window from it.+ *+ * The pet is a second window of the SAME app origin, showing a route of the Web App itself+ * (`/pet`). That is the whole reason it needs no preload, no IPC bridge and no separately served+ * page: the window is a plain browser like the main one, signed in by the same cookie, and it+ * learns everything it says over the same HTTP surface every other page reads.+ *+ * It is frameless, transparent and always on top, so the penguin appears to float on the desktop+ * rather than sit in a box; the page draws the fill and marks itself draggable. The window is NOT+ * click-through: its transparent corners still swallow a click that lands on them, which is why+ * the size below is kept as tight as the bubble and the pet together need. Drag from anywhere the+ * pet is not — the page opts its own controls out of the drag region.+ */+import path from "node:path";++/** The Web App route the pet window loads (see the Web App's router). */+export const PET_PAGE_PATH = "/pet";++/** The pet page's URL on a given app origin. */+export function petWindowUrl(origin: string): string {+ return `${origin}${PET_PAGE_PATH}`;+}++/**+ * Where the smoke run's screenshot of the pet window goes, given the one it was asked for: beside+ * the main window's, with `-pet` before the extension ("smoke.png" → "smoke-pet.png"). Parsed+ * rather than searched for a dot, so a directory in the path that has one (or a dotfile name) is+ * left alone — and the main window's shot is never the file that gets overwritten.+ */+export function petShotPath(mainShotPath: string): string {+ const { dir, name } = path.parse(mainShotPath);+ return path.join(dir, `${name}-pet.png`);+}++/**+ * The window's size. Small: the pet is a corner companion, and every pixel here is a pixel of+ * desktop it covers (see the click-through note above). Wide enough for the panel's longest line,+ * tall enough for that panel — three stacked rows and the hide action — with the penguin under it,+ * which is what the page is laid out to.+ */+export const PET_WINDOW_SIZE = { width: 260, height: 248 } as const;++/** A display's work area, in Electron's shape (excludes the taskbar/dock). */+export interface WorkArea {+ x: number;+ y: number;+ width: number;+ height: number;+}++/** Gap between the pet and the corner of the work area. */+export const PET_WINDOW_MARGIN = 24;++/**+ * Where a fresh pet window opens: the bottom-right corner of the work area, inset by+ * {@link PET_WINDOW_MARGIN}. The bottom right is where a desktop companion sits on every platform+ * — beside the clock, out of the way of the window a person is actually working in. It is a+ * starting position, not a policy: the window is movable and the shell puts it back here only+ * when the preference is switched on again during the same run.+ */+export function petWindowPosition(workArea: WorkArea): { x: number; y: number } {+ return {+ x: Math.round(workArea.x + workArea.width - PET_WINDOW_SIZE.width - PET_WINDOW_MARGIN),+ y: Math.round(workArea.y + workArea.height - PET_WINDOW_SIZE.height - PET_WINDOW_MARGIN),+ };+}++/**+ * What the pet window is, whatever anything else may want.+ *+ * - `frame: false` + `transparent: true` + `backgroundColor: "#00000000"` — the penguin floats;+ * the page draws what fills the window, and the rest is empty desktop.+ * - `alwaysOnTop` — it is a companion, and one that hides behind the window you are working in+ * would only be seen when it is useless.+ * - `skipTaskbar` — it is not a peer of the main window in the task list or the Dock, and+ * `showInactive` keeps it from taking the focus when it appears.+ * - Not resizable, minimizable, maximizable or fullscreenable: it has one size and one purpose.+ * - The same webPreferences hardening as the main window and as every window this app opens: a+ * plain browser, no Node, no preload, sandboxed. The pet page is ordinary app code, so it gets+ * nothing the main window does not — including <webview>, which stays the main window's alone.+ */+export const PET_WINDOW_OPTIONS = {+ ...PET_WINDOW_SIZE,+ show: false,+ frame: false,+ transparent: true,+ backgroundColor: "#00000000",+ hasShadow: false,+ resizable: false,+ movable: true,+ minimizable: false,+ maximizable: false,+ fullscreenable: false,+ skipTaskbar: true,+ alwaysOnTop: true,+ autoHideMenuBar: true,+ webPreferences: {+ contextIsolation: true,+ nodeIntegration: false,+ sandbox: true,+ },+} as const;diff --git a/packages/desktop/test/main-window-open.test.ts b/packages/desktop/test/main-window-open.test.tsindex 76d21cd5..ad96b641 100644--- a/packages/desktop/test/main-window-open.test.ts+++ b/packages/desktop/test/main-window-open.test.ts@@ -33,12 +33,15 @@ describe("main.ts window-open handling", () => {});it("answers every window's requests through openWindowFor — the main window's too", () => {- // One handler for the main window, one for each window it opens (guardOpenedWindow).- // Both delegate; neither decides anything of its own first.- expect(count(/setWindowOpenHandler\(/)).toBe(2);+ // One delegating handler for the main window, one for each window it opens+ // (guardOpenedWindow), and the pet window's, which denies everything: that window is chrome+ // with no links in it, so it has nothing to classify — and a denial is not the exception this+ // guards against (the count of `action: "allow"` above is what catches a second one).+ expect(count(/setWindowOpenHandler\(/)).toBe(3);expect(count(/setWindowOpenHandler\(\(\{ url: target \}\) => openWindowFor\(target, iconPath\)\)/),).toBe(2);+ expect(count(/setWindowOpenHandler\(\(\) => \(\{ action: "deny" \}\)\)/)).toBe(1);});it("pins the page-controllable window options in the one allow", () => {diff --git a/packages/desktop/test/pet-prefs.test.ts b/packages/desktop/test/pet-prefs.test.tsnew file mode 100644index 00000000..950f6267--- /dev/null+++ b/packages/desktop/test/pet-prefs.test.ts@@ -0,0 +1,124 @@+/**+ * The desktop pet's preference: the one boolean in userData/pet.json, and the two frames that+ * carry the Appearance switch between the shell and the page.+ *+ * Every ill-formed shape reads as OFF, the shell's own default: a file it cannot make sense of+ * must never be the reason a window appears over everything the user is doing.+ */+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_PET_PREFS,+ PET_PREFS_FILE,+ parsePetCommand,+ petPrefsPath,+ petStatusMessage,+ readPetPrefs,+ updatePetPrefs,+ writePetPrefs,+} from "../src/pet-prefs.js";++describe("readPetPrefs", () => {+ let dir: string;++ beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-pet-prefs-"));+ });+ afterEach(() => fs.rmSync(dir, { recursive: true, force: true }));++ it("defaults to no pet when there is no file", () => {+ expect(DEFAULT_PET_PREFS).toEqual({ showPet: false });+ expect(readPetPrefs(dir)).toEqual({ showPet: false });+ });++ it("defaults when the directory itself does not exist", () => {+ expect(readPetPrefs(path.join(dir, "never-created"))).toEqual({ showPet: false });+ });++ it("defaults on anything ill-typed rather than trusting it", () => {+ const cases: Array<[unknown, { showPet: boolean }]> = [+ [null, { showPet: false }],+ ["on", { showPet: false }],+ [42, { showPet: false }],+ [[], { showPet: false }],+ [{}, { showPet: false }],+ [{ showPet: "true" }, { showPet: false }],+ [{ showPet: 1 }, { showPet: false }],+ // A stray field is not a reason to distrust the one this build reads.+ [{ showPet: true, size: "big" }, { showPet: true }],+ ];+ for (const [value, expected] of cases) {+ fs.writeFileSync(path.join(dir, PET_PREFS_FILE), JSON.stringify(value));+ expect(readPetPrefs(dir), JSON.stringify(value)).toEqual(expected);+ }+ });++ it("defaults on a file that is not JSON at all", () => {+ fs.writeFileSync(path.join(dir, PET_PREFS_FILE), "{ not json");+ expect(readPetPrefs(dir)).toEqual({ showPet: false });+ });++ it("reads what was written", () => {+ writePetPrefs(dir, { showPet: true });+ expect(readPetPrefs(dir)).toEqual({ showPet: true });+ expect(petPrefsPath(dir)).toBe(path.join(dir, PET_PREFS_FILE));+ });+});++describe("updatePetPrefs", () => {+ let dir: string;++ beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), "penguin-pet-prefs-"));+ });+ afterEach(() => fs.rmSync(dir, { recursive: true, force: true }));++ it("patches one field without losing the others, and writes the file it reads", () => {+ const first = updatePetPrefs(dir, { showPet: true });+ expect(first).toEqual({ showPet: true });+ // The old value is irrelevant to the type today, and the read-modify-write still has to go+ // through the file: that is what makes two writers safe.+ fs.writeFileSync(+ petPrefsPath(dir),+ `${JSON.stringify({ showPet: true, size: 200 }, null, 2)}\n`,+ );+ expect(updatePetPrefs(dir, {})).toEqual({ showPet: true });+ expect(JSON.parse(fs.readFileSync(petPrefsPath(dir), "utf8"))).toEqual({ showPet: true });+ });++ it("creates the userData directory when it does not exist yet", () => {+ const nested = path.join(dir, "a", "b");+ writePetPrefs(nested, { showPet: true });+ expect(fs.existsSync(petPrefsPath(nested))).toBe(true);+ });+});++describe("the pet frame on the port", () => {+ it("wraps the state for the push", () => {+ expect(petStatusMessage(true)).toEqual({+ type: "desktop-pet-status",+ status: { showPet: true },+ });+ });++ it("parses only well-formed pet commands", () => {+ expect(parsePetCommand({ type: "desktop-pet-command", showPet: false })).toEqual({+ showPet: false,+ });+ // A frame of this build's own kind that carries nothing is an empty patch, not a non-frame:+ // the caller needs to tell those apart.+ expect(parsePetCommand({ type: "desktop-pet-command" })).toEqual({});+ expect(parsePetCommand({ type: "desktop-pet-command", showPet: "yes" })).toEqual({});+ for (const data of [+ null,+ "pet",+ {},+ { type: "desktop-tray-command", showTrayIcon: true },+ { type: "desktop-updater-command", action: "check" },+ ]) {+ expect(parsePetCommand(data)).toBeNull();+ }+ });+});diff --git a/packages/desktop/test/pet-window.test.ts b/packages/desktop/test/pet-window.test.tsnew file mode 100644index 00000000..0357e003--- /dev/null+++ b/packages/desktop/test/pet-window.test.ts@@ -0,0 +1,84 @@+/**+ * The desktop pet's window: the page it loads, the size it takes, the corner it opens in and+ * the options it is created with.+ *+ * The assertions on the options are the point of the file: each of them is a hole the pet window+ * must not have — a frame around a floating penguin, a window that can be resized into a corner+ * pixel, one that steals the taskbar slot of the app, or one that hands the page Node.+ */+import { describe, expect, it } from "vitest";+import {+ PET_PAGE_PATH,+ PET_WINDOW_MARGIN,+ PET_WINDOW_OPTIONS,+ PET_WINDOW_SIZE,+ petShotPath,+ petWindowPosition,+ petWindowUrl,+} from "../src/pet-window.js";++describe("petWindowUrl", () => {+ it("points at the pet route on the app's own origin", () => {+ expect(petWindowUrl("http://localhost:4000")).toBe(`http://localhost:4000${PET_PAGE_PATH}`);+ expect(PET_PAGE_PATH).toBe("/pet");+ });+});++describe("petShotPath", () => {+ it("puts the pet's screenshot beside the main window's, never over it", () => {+ expect(petShotPath("/tmp/smoke.png")).toBe("/tmp/smoke-pet.png");+ expect(petShotPath("smoke.jpeg")).toBe("smoke-pet.png");+ // No extension, a dot that is only part of a directory name, and a dotfile: the suffix still+ // lands on the file's own name, and the main window's shot is never the one that gets+ // clobbered.+ expect(petShotPath("/tmp/a.b/smoke")).toBe("/tmp/a.b/smoke-pet.png");+ expect(petShotPath("/tmp/rel-0.5.1.png")).toBe("/tmp/rel-0.5.1-pet.png");+ expect(petShotPath("/tmp/.hidden")).toBe("/tmp/.hidden-pet.png");+ });+});++describe("petWindowPosition", () => {+ it("sits in the bottom-right corner of the work area, inset by the margin", () => {+ expect(petWindowPosition({ x: 0, y: 0, width: 1920, height: 1080 })).toEqual({+ x: 1920 - PET_WINDOW_SIZE.width - PET_WINDOW_MARGIN,+ y: 1080 - PET_WINDOW_SIZE.height - PET_WINDOW_MARGIN,+ });+ });++ it("follows a work area that does not start at the origin (a second display, a top panel)", () => {+ expect(petWindowPosition({ x: 1920, y: 24, width: 1280, height: 720 })).toEqual({+ x: 1920 + 1280 - PET_WINDOW_SIZE.width - PET_WINDOW_MARGIN,+ y: 24 + 720 - PET_WINDOW_SIZE.height - PET_WINDOW_MARGIN,+ });+ });+});++describe("PET_WINDOW_OPTIONS", () => {+ it("is transparent, frameless, on top, out of the task list, and fixed in size", () => {+ expect(PET_WINDOW_OPTIONS.frame).toBe(false);+ expect(PET_WINDOW_OPTIONS.transparent).toBe(true);+ expect(PET_WINDOW_OPTIONS.backgroundColor).toBe("#00000000");+ expect(PET_WINDOW_OPTIONS.hasShadow).toBe(false);+ expect(PET_WINDOW_OPTIONS.alwaysOnTop).toBe(true);+ expect(PET_WINDOW_OPTIONS.skipTaskbar).toBe(true);+ expect(PET_WINDOW_OPTIONS.resizable).toBe(false);+ expect(PET_WINDOW_OPTIONS.minimizable).toBe(false);+ expect(PET_WINDOW_OPTIONS.maximizable).toBe(false);+ expect(PET_WINDOW_OPTIONS.fullscreenable).toBe(false);+ // Draggable, unlike the size: the page owns where it ends up on screen.+ expect(PET_WINDOW_OPTIONS.movable).toBe(true);+ // Shown only once the page has rendered — a transparent window that paints nothing is a+ // flash of the desktop behind it.+ expect(PET_WINDOW_OPTIONS.show).toBe(false);+ expect(PET_WINDOW_OPTIONS.width).toBe(PET_WINDOW_SIZE.width);+ expect(PET_WINDOW_OPTIONS.height).toBe(PET_WINDOW_SIZE.height);+ });++ it("gives the page a plain browser, like every other window of this app", () => {+ expect(PET_WINDOW_OPTIONS.webPreferences).toEqual({+ contextIsolation: true,+ nodeIntegration: false,+ sandbox: true,+ });+ });+});diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex a49b8a5c..d6a49576 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -4789,6 +4789,54 @@ export interface DesktopTrayCommandMessage {locale?: DesktopTrayLocale;}+// Desktop pet (desktop mode only)+//+// A small always-on-top companion window the shell draws beside the app — the Adelie penguin,+// which speaks up when something happens (a schedule fired, tool calls waiting for approval, a+// budget warning) and, when clicked, reports the model balance and the client-update state.+//+// The switch rides the same utilityProcess message channel as the tray icon above: the shell+// pushes what it currently shows, the page reads it at GET /api/desktop/pet and writes through+// PUT, which is relayed back. The pet window itself is a second plain-browser window on this+// same origin, so it is signed in by the same cookie and reads everything the page reads —+// there is no renderer IPC bridge, and no separately-served page.++/** What the shell is currently doing about its pet window. */+export interface DesktopPetStatus {+ /** The pet window is on screen (or about to be) while the shell runs. */+ showPet: boolean;+}++/**+ * What one PUT asks the shell to change. One field today, and optional all the same: the request+ * shape follows the tray patch beside it, and the pet window's own "hide me" writes the same+ * field the Settings switch does.+ */+export interface DesktopPetPatch {+ showPet?: boolean;+}++/**+ * GET / PUT /api/desktop/pet (desktop-shell sessions only): the pet preference.+ * `status` is null until the shell's first push lands (a beat after server start); a client+ * that finds null reads it as off, which is the shell's own default.+ */+export interface DesktopPetStatusResponse {+ status: DesktopPetStatus | null;+}++/** Shell → server push over the utilityProcess message channel. */+export interface DesktopPetStatusMessage {+ type: "desktop-pet-status";+ status: DesktopPetStatus;+}++/** Server → shell command over the utilityProcess message channel (relayed from PUT /api/desktop/pet). */+export interface DesktopPetCommandMessage {+ type: "desktop-pet-command";+ showPet?: boolean;+}+// Desktop folder access (desktop mode, macOS)//// macOS privacy protection (TCC) guards Desktop, Documents, Downloads and removable and networkdiff --git a/packages/server/src/hmr/capabilities.ts b/packages/server/src/hmr/capabilities.tsindex 808e8cfb..6cbaed1b 100644--- a/packages/server/src/hmr/capabilities.ts+++ b/packages/server/src/hmr/capabilities.ts@@ -436,6 +436,10 @@ export type DesktopApi = Pick<| "setTrayStatus"| "onTrayCommand"| "requestTrayCommand"+ | "getPetStatus"+ | "setPetStatus"+ | "onPetCommand"+ | "requestPetCommand"| "onFolderAccessRequest"| "requestFolderAccess"| "onPrivacySettingsCommand"diff --git a/packages/server/src/http/routes/desktop.ts b/packages/server/src/http/routes/desktop.tsindex 4cad00d1..b1e7a33b 100644--- a/packages/server/src/http/routes/desktop.ts+++ b/packages/server/src/http/routes/desktop.ts@@ -1,21 +1,24 @@/*** Desktop-mode routes: POST /api/desktop/shutdown, the client-update relay under- * /api/desktop/update, the tray-icon preference at /api/desktop/tray, the Privacy & Security- * pane at /api/desktop/privacy-settings, plus the shared desktop-mode guard that turns off+ * /api/desktop/update, the tray-icon preference at /api/desktop/tray, the pet-window+ * preference at /api/desktop/pet, the Privacy & Security pane at+ * /api/desktop/privacy-settings, plus the shared desktop-mode guard that turns off* multi-user surfaces (see rejectInDesktopMode).** Platform code, all of it: what the shell's window may ask of the shell is policy. The* shutdown route is authenticated by the shell's Bearer token, not the cookie session (the* shell holds no cookie), so its group is unauthenticated and checks the token itself; it* answers 202 first, then triggers the graceful shutdown a beat later so the response is not- * cut off by the closing listener. The update, tray and privacy-settings routes are called by- * the page, so their groups sit behind the cookie gate and are further restricted to the- * shell's own window.+ * cut off by the closing listener. The update, tray, pet and privacy-settings routes are+ * called by the page, so their groups sit behind the cookie gate and are further restricted+ * to the shell's own windows.*/import { Hono } from "hono";import type { Context, MiddlewareHandler } from "hono";import { Bind, Component, Use } from "@adelie/core/kernel";import type {+ DesktopPetPatch,+ DesktopPetStatusResponse,DesktopTrayPatch,DesktopTrayStatusResponse,DesktopUpdateStatusResponse,@@ -171,6 +174,47 @@ export function desktopTrayRoutes(deps: DesktopRouteDeps): Hono<AppEnv> {return app;}+/**+ * The pet-window preference. GET reads what the shell last pushed — null until that first push,+ * which the page reads as off, the shell's own default. PUT relays a patch: the Settings switch,+ * or the pet window hiding itself, both of which mean the same thing to the shell. It 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. Like the relays above, the members are optional on a layer+ * older than the pet.+ */+export function desktopPetRoutes(deps: DesktopRouteDeps): Hono<AppEnv> {+ const app = new Hono<AppEnv>();+ const refusal = "The desktop pet is managed from the desktop app's own window.";++ app.get("/", (c) => {+ const desktop = shellSessionOf(deps, c, refusal);+ const status = desktop.getPetStatus?.() ?? null;+ return c.json({ status } satisfies DesktopPetStatusResponse);+ });++ app.put("/", async (c) => {+ const desktop = shellSessionOf(deps, c, refusal);+ const body = (await c.req.json().catch(() => null)) as { showPet?: unknown } | null;+ const patch: DesktopPetPatch = {};+ if (body?.showPet !== undefined) {+ if (typeof body.showPet !== "boolean") {+ throw new HttpError(400, "invalid_show_pet", "showPet must be a boolean.");+ }+ patch.showPet = body.showPet;+ }+ // An empty patch is a caller bug, not a no-op worth relaying to the shell.+ if (patch.showPet === undefined) {+ throw new HttpError(400, "empty_pet_patch", "Pass showPet.");+ }+ if (!desktop.requestPetCommand?.(patch)) {+ throw new HttpError(503, "shell_unreachable", "The desktop shell is not listening.");+ }+ return c.body(null, 202);+ });++ return app;+}+/*** Opens System Settings at a Privacy & Security pane — Files and Folders, or Full Disk Access —* for the Workspace picker's box about a folder macOS refused. The shell opens it (on macOS@@ -245,6 +289,21 @@ export class DesktopTrayRoutes {}}+@Component({+ contributes: {+ "HttpModule.routes": [+ { id: "DesktopPetRoutes.routes", prefix: "/api/desktop/pet", auth: "user", order: 10 },+ ],+ },+})+export class DesktopPetRoutes {+ @Use() private readonly desktop!: Desktop;+ @Bind("DesktopPetRoutes.routes") routes!: Hono<AppEnv>;+ setup() {+ this.routes = desktopPetRoutes({ desktop: this.desktop.current() });+ }+}+@Component({contributes: {"HttpModule.routes": [diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.tsindex a8d9f883..0fbb15cd 100644--- a/packages/server/src/platform.ts+++ b/packages/server/src/platform.ts@@ -125,6 +125,7 @@ import { MeRoutes } from "./http/routes/me.js";import { UserVaultRoutes } from "./http/routes/user-vault.js";import { AuthRoutes } from "./http/routes/auth.js";import {+ DesktopPetRoutes,DesktopPrivacySettingsRoutes,DesktopRoutes,DesktopTrayRoutes,@@ -464,6 +465,7 @@ export class CompanyModule {}DesktopRoutes,DesktopUpdateRoutes,DesktopTrayRoutes,+ DesktopPetRoutes,DesktopPrivacySettingsRoutes,PluginRoutes,PluginRegistryRoutes,diff --git a/packages/server/src/services/desktop-service.ts b/packages/server/src/services/desktop-service.tsindex 834d90a4..21158f41 100644--- a/packages/server/src/services/desktop-service.ts+++ b/packages/server/src/services/desktop-service.ts@@ -14,12 +14,12 @@** Comparisons hash both sides first so timingSafeEqual gets equal-length buffers.*- * 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+ * The service is also the shell↔web relay for the surfaces the shell owns: client updates, the+ * tray icon and the pet window. 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.+ * GET /api/desktop/update, /api/desktop/tray or /api/desktop/pet 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.** The same channel carries the Workspace picker's macOS folder access: a request the shell* answers (its main process reads a folder in the app's own name), and a command that opens@@ -28,6 +28,8 @@import { createHash, timingSafeEqual } from "node:crypto";import type {DesktopFolderAccessResult,+ DesktopPetPatch,+ DesktopPetStatus,DesktopPrivacyPane,DesktopTrayPatch,DesktopTrayStatus,@@ -129,6 +131,33 @@ export class DesktopService {return true;}+ // --- pet-window relay ------------------------------------------------------++ private petStatus: DesktopPetStatus | null = null;+ private petCommandSender: ((patch: DesktopPetPatch) => void) | null = null;++ /** Latest shell push; null until the shell's first one lands (the page then reads it as off). */+ getPetStatus(): DesktopPetStatus | null {+ return this.petStatus;+ }++ /** index.ts stores each shell push here (already validated at the message port). */+ setPetStatus(status: DesktopPetStatus): void {+ this.petStatus = status;+ }++ /** index.ts registers the message-port sender; absent outside a shell-forked process. */+ onPetCommand(sender: (patch: DesktopPetPatch) => void): void {+ this.petCommandSender = sender;+ }++ /** Invoked by the pet route; false when no shell port is wired (tests, plain runs). */+ requestPetCommand(patch: DesktopPetPatch): boolean {+ if (!this.petCommandSender) return false;+ this.petCommandSender(patch);+ return true;+ }+// --- macOS folder-access relay ----------------------------------------------private folderAccessSender: FolderAccessSender | null = null;diff --git a/packages/server/src/services/desktop-update-port.ts b/packages/server/src/services/desktop-update-port.tsindex f6b4a6ea..38e70aca 100644--- a/packages/server/src/services/desktop-update-port.ts+++ b/packages/server/src/services/desktop-update-port.ts@@ -19,6 +19,9 @@ import type {DesktopFolderAccessResult,DesktopFolderAccessResultMessage,DesktopOpenPrivacySettingsMessage,+ DesktopPetCommandMessage,+ DesktopPetStatus,+ DesktopPetStatusMessage,DesktopTrayCommandMessage,DesktopTrayStatus,DesktopTrayStatusMessage,@@ -86,6 +89,17 @@ export function parseTrayStatusMessage(data: unknown): DesktopTrayStatus | nullreturn { showTrayIcon: status.showTrayIcon, locale };}+/** Validates one shell pet push. Same rule as the tray's: strict on the discriminator and on the field it carries. */+export function parsePetStatusMessage(data: unknown): DesktopPetStatus | null {+ if (typeof data !== "object" || data === null) return null;+ const msg = data as Partial<DesktopPetStatusMessage>;+ if (msg.type !== "desktop-pet-status") return null;+ const status = msg.status as Partial<DesktopPetStatus> | undefined;+ if (typeof status !== "object" || status === null) return null;+ if (typeof status.showPet !== "boolean") return null;+ return { showPet: status.showPet };+}+/** Validates one shell reply to a folder-access request; null when the frame is not one. */export function parseFolderAccessResultMessage(data: unknown,@@ -124,6 +138,11 @@ export function wireShellUpdatePort(desktop: DesktopService, port: ShellPort): vdesktop.setTrayStatus(tray);return;}+ const pet = parsePetStatusMessage(e.data);+ if (pet !== null) {+ desktop.setPetStatus(pet);+ return;+ }// A reply nobody waits for any more (its request timed out) is dropped.const access = parseFolderAccessResultMessage(e.data);if (access !== null) awaiting.get(access.id)?.(access);@@ -143,6 +162,12 @@ export function wireShellUpdatePort(desktop: DesktopService, port: ShellPort): v...patch,} satisfies DesktopTrayCommandMessage);});+ desktop.onPetCommand((patch) => {+ port.postMessage({+ type: "desktop-pet-command",+ ...patch,+ } satisfies DesktopPetCommandMessage);+ });desktop.onFolderAccessRequest((path) =>new Promise<DesktopFolderAccessResult | null>((resolve) => {diff --git a/packages/server/test/desktop-pet.test.ts b/packages/server/test/desktop-pet.test.tsnew file mode 100644index 00000000..336fe06a--- /dev/null+++ b/packages/server/test/desktop-pet.test.ts@@ -0,0 +1,178 @@+/**+ * The pet-window preference relay: the /api/desktop/pet routes (the shell window's sessions+ * only), and the shell port they ride.+ *+ * - The pet state reads as null before the shell's first push, then as what it pushed.+ * - A PUT forwards the switch to the shell and answers 202; a field it cannot read, or a+ * request that asks for nothing, is refused and reaches no shell.+ * - A password session against the same desktop server gets 403; with no shell wired the PUT+ * answers 503; a plain server has no such route.+ * - Only a well-formed pet frame is read; the updater's and the tray's frames on the same port+ * are not pet frames.+ * - Pet pushes and pet commands share one port with the other two relays, none disturbing the+ * others.+ */+import { describe, expect, it } from "vitest";+import { createDesktopApp, createTestApp, desktopLoginCookie, loginAdmin } from "./helpers.js";+import type { DesktopPetPatch, DesktopPetStatusResponse, ErrorBody } from "../src/api/types.js";+import { DesktopService } from "../src/services/desktop-service.js";+import { parsePetStatusMessage, wireShellUpdatePort } from "../src/services/desktop-update-port.js";+import { FakePort } from "./builtin-browser/fake-shell.js";++const put = (cookie: string, body: string) => ({+ method: "PUT",+ headers: { cookie, "content-type": "application/json" },+ body,+});++describe("GET /api/desktop/pet", () => {+ 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/pet", { headers: { cookie } });+ expect(before.status).toBe(200);+ expect((await before.json()) as DesktopPetStatusResponse).toEqual({ status: null });++ t.deps.desktop!.setPetStatus({ showPet: true });+ const after = await t.app.request("/api/desktop/pet", { headers: { cookie } });+ expect((await after.json()) as DesktopPetStatusResponse).toEqual({+ status: { showPet: true },+ });+ } 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/pet", { 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/pet", { headers: { cookie: admin.cookie } });+ expect(res.status).toBe(404);+ } finally {+ await t.cleanup();+ }+ });+});++describe("PUT /api/desktop/pet", () => {+ 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: DesktopPetPatch[] = [];+ t.deps.desktop!.onPetCommand((patch) => sent.push(patch));++ const on = await t.app.request("/api/desktop/pet", put(cookie, '{"showPet":true}'));+ expect(on.status).toBe(202);+ // The pet window's own "hide me" writes the same field the Settings switch does.+ const off = await t.app.request("/api/desktop/pet", put(cookie, '{"showPet":false}'));+ expect(off.status).toBe(202);+ expect(sent).toEqual([{ showPet: true }, { showPet: false }]);+ } 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: DesktopPetPatch[] = [];+ t.deps.desktop!.onPetCommand((patch) => sent.push(patch));+ const cases: Array<[string, string]> = [+ ['{"showPet":"yes"}', "invalid_show_pet"],+ ['{"showPet":1}', "invalid_show_pet"],+ // 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_pet_patch"],+ ["not json", "empty_pet_patch"],+ ];+ for (const [body, code] of cases) {+ const res = await t.app.request("/api/desktop/pet", 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/pet",+ put(admin.cookie, '{"showPet":true}'),+ );+ expect(forbidden.status).toBe(403);++ const cookie = await desktopLoginCookie(t.app);+ const unreachable = await t.app.request("/api/desktop/pet", put(cookie, '{"showPet":true}'));+ expect(unreachable.status).toBe(503);+ expect(((await unreachable.json()) as ErrorBody).error.code).toBe("shell_unreachable");+ } finally {+ await t.cleanup();+ }+ });+});++describe("the pet half of the shell port", () => {+ it("parses only well-formed pet status frames", () => {+ expect(+ parsePetStatusMessage({ type: "desktop-pet-status", status: { showPet: true } }),+ ).toEqual({ showPet: true });+ // A push carrying more than this build knows about still reads as what it says.+ expect(+ parsePetStatusMessage({+ type: "desktop-pet-status",+ status: { showPet: false, size: 200 },+ }),+ ).toEqual({ showPet: false });+ for (const data of [+ null,+ "status",+ {},+ { type: "desktop-pet-status" },+ { type: "desktop-pet-status", status: null },+ { type: "desktop-pet-status", status: {} },+ { type: "desktop-pet-status", status: { showPet: "yes" } },+ // The other two relays ride the same port and must not be read as pet ones.+ { type: "desktop-updater-status", status: { appVersion: "1", state: "idle" } },+ { type: "desktop-tray-status", status: { showTrayIcon: true, locale: "zh" } },+ ]) {+ expect(parsePetStatusMessage(data)).toBeNull();+ }+ });++ it("stores pet pushes and posts pet commands beside the other relays, on one port", () => {+ const desktop = new DesktopService("t");+ const port = new FakePort();+ wireShellUpdatePort(desktop, port);++ port.emit({ type: "desktop-pet-status", status: { showPet: true } });+ expect(desktop.getPetStatus()).toEqual({ showPet: true });+ // A tray frame on the same port leaves the pet state alone, and vice versa.+ port.emit({ type: "desktop-tray-status", status: { showTrayIcon: false, locale: "zh" } });+ expect(desktop.getPetStatus()).toEqual({ showPet: true });+ expect(desktop.getTrayStatus()).toEqual({ showTrayIcon: false, locale: "zh" });++ expect(desktop.requestPetCommand({ showPet: false })).toBe(true);+ expect(port.sent).toEqual([{ type: "desktop-pet-command", showPet: false }]);+ });+});diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.tsindex 67b457a5..c4ef701b 100644--- a/packages/ui-gallery/src/app/mock/routes.ts+++ b/packages/ui-gallery/src/app/mock/routes.ts@@ -39,6 +39,7 @@ import type {ChatDefaultsDto,CommandPolicyDto,DefaultModelResponse,+ DesktopPetStatusResponse,DesktopTrayStatusResponse,DesktopUpdateStatusResponse,DirectorySkillsResponse,@@ -2617,6 +2618,10 @@ router.post("/api/desktop/update/install", () => notFound("Desktop updater")).get("/api/desktop/tray", (): DesktopTrayStatusResponse => ({ status: null })).put("/api/desktop/tray", () => empty())+ // The pet window, like the tray: a shell-owned preference with no shell here, so the read is+ // "unknown" (null, which the page and the Appearance switch read as off) and the write lands.+ .get("/api/desktop/pet", (): DesktopPetStatusResponse => ({ status: null }))+ .put("/api/desktop/pet", () => empty()).post("/api/desktop/privacy-settings", () => notFound("Desktop mode"));// ---------------------------------------------------------------------------------------------diff --git a/packages/web/e2e/pet.spec.mjs b/packages/web/e2e/pet.spec.mjsnew file mode 100644index 00000000..8c5df4a4--- /dev/null+++ b/packages/web/e2e/pet.spec.mjs@@ -0,0 +1,93 @@+/**+ * The desktop pet's page, end to end in the real app: /pet is the whole content of the shell's+ * companion window (main.ts loads it there), so what is asserted here is what a person sees on+ * their desktop — the penguin, the panel behind it, and a notice arriving on its own.+ *+ * The shell itself is not part of this suite (Playwright drives a browser), which is exactly the+ * point of the design: everything the pet shows it reads over HTTP, so a browser tab can be held+ * to the same behavior. The two readings that belong to the shell — the model balance's route and+ * the update snapshot — therefore assert their desktop-only wording here; the desktop half is+ * verified by the shell's own smoke run.+ *+ * The notice is the real thing, not a stub: a Session under `always-ask` is sent a Prompt that+ * makes the mock model call a tool, the runtime escalates that call, and the user-channel event+ * about it (session_approvals) is what the pet turns into a bubble.+ */+import { test, expect } from "@playwright/test";+import { provisionAndLogin } from "./auth.mjs";++const BASE = process.env.BASE_URL;+const MOCK = process.env.MOCK_URL;+const U = "petuser";+const P = "password123";++// The penguin bobs — an infinite CSS animation — and Playwright refuses to click an element whose+// box never settles. Reduced motion is the app's own answer to that preference (the global rule in+// styles.css turns every animation off), so the spec emulates it per page; that also pins the pet+// as clickable with animations disabled.++test("the pet shows its readings, and speaks up when a call needs the user", async ({ page }) => {+ await provisionAndLogin(page.request, U, P);++ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();+ const projectId = projects.projects[0].projectId;+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {+ data: {+ defaultModel: { provider: "custom", modelId: "claude-4-8" },+ models: [+ {+ provider: "custom",+ modelId: "claude-4-8",+ apiKey: "sk-mock",+ baseUrl: MOCK,+ contextWindow: 200000,+ pricing: { cacheRead: 1, cacheWrite: 5, output: 10 },+ },+ ],+ },+ });+ expect(put.ok(), "put models").toBeTruthy();++ await page.goto(`${BASE}/pet`);+ await page.emulateMedia({ reducedMotion: "reduce" });+ const penguin = page.getByRole("button", { name: "点我:余额、新版本和通知" });+ await penguin.waitFor();+ // Nothing else of the app is drawn: this window is 260×240 of chrome, and the app shell+ // (sidebar, chat) must not be in it.+ await expect(page.getByPlaceholder(/输入消息/)).toHaveCount(0);++ // --- the panel behind a click ---+ await penguin.click();+ await expect(page.getByText("模型余额", { exact: true })).toBeVisible();+ await expect(page.getByText("客户端更新", { exact: true })).toBeVisible();+ await expect(page.getByText("通知", { exact: true })).toBeVisible();+ // Both shell-owned readings say so rather than failing, and the pet's own hide action is not+ // offered where there is no pet window to hide.+ await expect(page.getByText("余额只在桌面应用里能读。", { exact: true })).toBeVisible();+ await expect(page.getByText("客户端更新只在桌面应用里能读。", { exact: true })).toBeVisible();+ await expect(page.getByText("暂时没有新通知。", { exact: true })).toBeVisible();+ await expect(page.getByText("隐藏桌宠")).toHaveCount(0);++ // Back to just the penguin, so the bubble below is what is on screen.+ await penguin.click();+ await expect(page.getByText("模型余额", { exact: true })).toHaveCount(0);++ // --- a call that needs the user, announced without anyone touching the app ---+ const sess = await (+ await page.request.post(`${BASE}/api/projects/${projectId}/agents/default_agent/sessions`, {+ data: { provider: "custom", modelId: "claude-4-8", approvalMode: "always-ask" },+ })+ ).json();+ const sessionId = sess.session.sessionId;+ const task = await page.request.post(`${BASE}/api/sessions/${sessionId}/tasks`, {+ data: { input: [{ type: "text", text: "Help me set up @theme" }] },+ });+ expect(task.ok(), "post task").toBeTruthy();++ const bubble = page.getByRole("status");+ await expect(bubble).toContainText("有 1 个工具调用在等你批准", { timeout: 30_000 });++ // The bubble fades on its own; what it said stays in the panel.+ await penguin.click();+ await expect(page.getByText("有 1 个工具调用在等你批准", { exact: true })).toBeVisible();+});diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 735f5800..e8ef7ec8 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -220,6 +220,8 @@ import type {UpdateJobStatus,UpdateProfileRequest,UpdateProfileResponse,+ DesktopPetPatch,+ DesktopPetStatusResponse,DesktopTrayPatch,DesktopTrayStatusResponse,HookArchiveInstallRequest,@@ -2510,6 +2512,19 @@ export const openPrivacySettings = (pane: DesktopPrivacyPane) =>server: null,});+// Desktop pet (desktop-shell sessions only) --------------------------------------------++/** What the shell last pushed; `status` is null until that first push, which reads as off. */+export const getDesktopPet = () => apiFetch<DesktopPetStatusResponse>("/api/desktop/pet");++/**+ * Relays the pet switch to the shell, which opens or closes the window at once and pushes the+ * new state back. Settings › Appearance writes it, and so does the pet window's own "hide me"+ * row — the same field through the same route, so the two can never disagree.+ */+export const setDesktopPet = (patch: DesktopPetPatch) =>+ apiFetch<void>("/api/desktop/pet", { method: "PUT", body: patch });+// ---- Workflows (an Agent's own extension packages, served as tabs beside the chat) ----const workflowsBase = (projectId: string, agentId: string) =>`/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/workflows`;diff --git a/packages/web/src/features/pet/penguin.tsx b/packages/web/src/features/pet/penguin.tsxnew file mode 100644index 00000000..ad4bdc62--- /dev/null+++ b/packages/web/src/features/pet/penguin.tsx@@ -0,0 +1,42 @@+/**+ * The pet itself: an Adelie penguin, drawn as one inline SVG.+ *+ * Inline rather than an image file on purpose — it has to be crisp at any size, follow the+ * window's shape without a canvas, and cost no request in a window whose whole job is to be+ * cheap. Fixed colours, not theme tokens: a penguin is black, white and orange in either theme,+ * and the light belly is what makes it read against a dark desktop too.+ *+ * The bob is a CSS animation (styles.css, `.pet-bob`), so the global reduced-motion rule turns it+ * off with every other animation in the app and leaves a still penguin standing.+ */+export function Penguin({ className }: { className?: string }) {+ return (+ <svg+ viewBox="0 0 100 108"+ role="img"+ aria-hidden="true"+ focusable="false"+ className={className}+ >+ {/* Head, back and flippers: one black silhouette. */}+ <path+ d="M50 2c17 0 29 13 29 31 0 6-1 11-3 16 6 5 10 13 12 23 2 11 2 22 0 29-1 4-5 6-9 5-6-2-12-3-18-3h-22c-6 0-12 1-18 3-4 1-8-1-9-5-2-7-2-18 0-29 2-10 6-18 12-23-2-5-3-10-3-16C21 15 33 2 50 2Z"+ fill="#1f2937"+ />+ {/* Belly. */}+ <path+ d="M50 22c11 0 19 9 19 24 0 14-1 26-3 38-1 6-8 9-16 9s-15-3-16-9c-2-12-3-24-3-38 0-15 8-24 19-24Z"+ fill="#f8fafc"+ />+ {/* The white eye-ring is the Adelie's own marking: the one detail that says which penguin. */}+ <circle cx="40" cy="24" r="5.5" fill="#f8fafc" />+ <circle cx="60" cy="24" r="5.5" fill="#f8fafc" />+ <circle cx="40" cy="24" r="2.6" fill="#0f172a" />+ <circle cx="60" cy="24" r="2.6" fill="#0f172a" />+ {/* Beak and feet. */}+ <path d="M50 30l7 5-7 5-7-5 7-5Z" fill="#f59e0b" />+ <path d="M33 99h16l-3 7H34l-1-7Z" fill="#f59e0b" />+ <path d="M51 99h16l1 7H52l-1-7Z" fill="#f59e0b" />+ </svg>+ );+}diff --git a/packages/web/src/features/pet/pet-notice.ts b/packages/web/src/features/pet/pet-notice.tsnew file mode 100644index 00000000..f2ec3854--- /dev/null+++ b/packages/web/src/features/pet/pet-notice.ts@@ -0,0 +1,163 @@+/**+ * What the desktop pet says, and when it says it: the user-channel events it reacts to, the+ * client-update snapshots it speaks about, and the wording of both.+ *+ * Pure — no React, no fetch — so the rules live in one place: the page that draws the pet renders+ * exactly what these functions return, and the tests pin which events are worth a bubble and+ * which are not. The events are the user-level stream `GET /api/events` (see api/sse.ts), which is+ * already the cross-Session channel: a tab that is looking at one conversation is told here about+ * a schedule that fired somewhere else.+ *+ * Three things are worth speaking up about, chosen for the same reason — the person is looking at+ * the desktop, not at the app, and cannot see the row that changed:+ *+ * - a schedule fired (it ran something on its own),+ * - tool calls are waiting for approval (the agent is stopped until someone answers),+ * - a company budget warned or paused an employee (money, and the run stops).+ *+ * Everything else on that stream is either something the app's own chrome already shows (a+ * session's run state, its title, a tab count) or noise at this size (every channel message). The+ * app's task-completion notification is its own, deliberately separate feature: it is a system+ * notification for a window you are not looking at, and this is a bubble on the desktop.+ */+import type { DesktopUpdateStatus, ServerEvent } from "@adelie/server/api";+import type { Strings } from "../../lib/strings";++/** One thing the pet has to say. Small enough to be a union, so the wording is exhaustive. */+export type PetNotice =+ /** A schedule fired and sent its Prompt. */+ | { kind: "schedule"; name: string }+ /** Tool calls are waiting for a person to answer them (the count is the Session row's). */+ | { kind: "approval"; count: number }+ /** The organization's scheduler warned about, or paused, an employee's budget. */+ | { kind: "budget"; state: "warned" | "paused" }+ /** A newer client build is offered (`ready` false) or downloaded and waiting for a restart. */+ | { kind: "update"; version: string; ready: boolean };++/**+ * The notice one user-channel event earns, or null for the many that earn none. Exhaustive over+ * the events the pet knows and open-ended for the rest: the stream grows, and a new event type+ * must not be a compile error in a feature that only wants to be told about a few of them.+ */+export function noticeForEvent(event: ServerEvent): PetNotice | null {+ switch (event.type) {+ case "schedule_fired":+ return { kind: "schedule", name: event.name };+ // Only calls that are still waiting: the same event with a zero count is the last one being+ // answered, which is the opposite of something to speak about.+ case "session_approvals":+ return event.count > 0 ? { kind: "approval", count: event.count } : null;+ case "org_budget":+ // "resumed" is good news, and the least urgent thing on this stream.+ return event.state === "resumed" ? null : { kind: "budget", state: event.state };+ default:+ return null;+ }+}++/**+ * The notice one client-update snapshot earns, or null when there is nothing to announce. Only+ * the two states that ask the user to do something — an update to fetch, or a downloaded build to+ * restart into. Progress and failures belong in the panel behind the penguin, where they can be+ * read at leisure; a bubble is for the moment the pet has something to say.+ *+ * A snapshot that has not changed earns nothing either, which the caller decides: this reads one+ * snapshot on its own, and the page remembers what it has already announced (see noticeKey).+ */+export function noticeForUpdate(status: DesktopUpdateStatus | null): PetNotice | null {+ if (status === null || status.version === undefined) return null;+ if (status.state === "available")+ return { kind: "update", version: status.version, ready: false };+ if (status.state === "downloaded") {+ return { kind: "update", version: status.version, ready: true };+ }+ return null;+}++/**+ * A stable identity for one notice: what the page compares against the last one it announced, so+ * a poll that keeps returning the same state does not repeat itself, and what React keys a list+ * of them by. Two sentences with the same key read the same.+ */+export function noticeKey(notice: PetNotice): string {+ switch (notice.kind) {+ case "schedule":+ return `schedule:${notice.name}`;+ case "approval":+ return `approval:${notice.count}`;+ case "budget":+ return `budget:${notice.state}`;+ case "update":+ return `update:${notice.version}:${notice.ready ? "ready" : "offered"}`;+ }+}++/** One notice as the bubble says it. */+export function noticeText(notice: PetNotice, pet: Strings["pet"]): string {+ switch (notice.kind) {+ case "schedule":+ return pet.scheduleFired(notice.name);+ case "approval":+ return pet.approvalsWaiting(notice.count);+ case "budget":+ return notice.state === "paused" ? pet.budgetPaused : pet.budgetWarned;+ case "update":+ return notice.ready+ ? pet.updateDownloaded(notice.version)+ : pet.updateAvailable(notice.version);+ }+}++/**+ * What the panel's update row reads: the state the shell is in, in one line. A null snapshot is+ * "no check has run yet" — the shell pushes one a beat after the server starts — and the page+ * substitutes the desktop-only wording itself when it is not the shell's own window.+ */+export function updateText(status: DesktopUpdateStatus | null, pet: Strings["pet"]): string {+ if (status === null) return pet.updateIdle;+ switch (status.state) {+ case "idle":+ return pet.updateIdle;+ case "checking":+ return pet.updateChecking;+ case "up-to-date":+ return pet.updateUpToDate(status.appVersion);+ case "available":+ return status.version !== undefined ? pet.updateAvailable(status.version) : pet.updateIdle;+ case "downloading":+ return pet.updateDownloading(status.percent ?? 0);+ case "downloaded":+ return status.version !== undefined ? pet.updateDownloaded(status.version) : pet.updateIdle;+ case "unsupported":+ return pet.updateUnsupported;+ case "error":+ return pet.updateError(status.message ?? "");+ }+}++/**+ * What the panel's update row offers to DO, given the state: fetch the release the shell has+ * offered, restart into the one it has downloaded, ask for a check, or nothing at all. The three+ * commands are the ones the main window's update modal sends (POST /api/desktop/update/…), and+ * clicking here is the same consent it collects there.+ */+export function updateCommand(+ status: DesktopUpdateStatus | null,+): "check" | "download" | "install" | null {+ switch (status?.state) {+ case undefined:+ case "idle":+ case "unsupported":+ case "up-to-date":+ case "error":+ return "check";+ case "available":+ return "download";+ case "downloaded":+ return "install";+ // A check or a download already under way has nothing to click.+ case "checking":+ case "downloading":+ return null;+ }+}diff --git a/packages/web/src/features/pet/pet-page.tsx b/packages/web/src/features/pet/pet-page.tsxnew file mode 100644index 00000000..39ff8913--- /dev/null+++ b/packages/web/src/features/pet/pet-page.tsx@@ -0,0 +1,281 @@+/**+ * The desktop pet's page: the entire content of the shell's companion window (main.ts creates it+ * at /pet; pet-notice.ts decides what it says).+ *+ * It is a page of this app on the app's own origin, so it is signed in by the same cookie the main+ * window is, and every fact it shows comes over the HTTP surface every other page uses — the+ * user-level event stream for what happened while nobody was looking, the shell's update snapshot,+ * and the account's pinned model balance. Nothing here talks to the shell directly.+ *+ * Three things, in the order they are useful:+ *+ * - A bubble above the penguin when something happens (see pet-notice.ts), which fades on its own:+ * the pet speaks, it does not stack up a notification center.+ * - The panel behind a click: the pinned balance, the client-update state with the one action that+ * state offers, the last notice, and the way to hide the pet again.+ * - The window itself, which drags: the page paints the penguin and marks the rest of the window+ * draggable (`.pet-drag` / `.pet-no-drag` in styles.css — `-webkit-app-region` is Electron's and+ * has no React type of its own).+ *+ * In a plain browser tab (anyone can open /pet) the penguin still draws and the notices still+ * arrive, and the two desktop-only readings say so instead of failing: everything about the shell+ * is gated on being the shell's own window, exactly as the update modal and the tray switch are.+ */+import { useCallback, useEffect, useRef, useState } from "react";+import type { ReactNode } from "react";+import type { DesktopUpdateStatus } from "@adelie/server/api";+import { providerInfo } from "@adelie/core/model-catalog";+import * as api from "../../api/endpoints";+import { openUserEvents } from "../../api/sse";+import { S } from "../../lib/strings";+import { isDesktopShellWindow } from "../../lib/account-menu";+import { useAuth } from "../../state/auth";+import { useTheme } from "../../state/theme";+import { useBalance, usePinnedBalance, requestBalance } from "../models/balance";+import { PINNED_BALANCE_REFRESH_MS, balanceView } from "../models/group-balance";+import {+ noticeForEvent,+ noticeForUpdate,+ noticeKey,+ noticeText,+ updateCommand,+ updateText,+} from "./pet-notice";+import type { PetNotice } from "./pet-notice";+import { Penguin } from "./penguin";++/** How long a bubble stays up before the pet stops talking. */+const BUBBLE_MS = 8_000;+/** How many notices the panel keeps, newest first. */+const NOTICE_KEEP = 5;+/**+ * How often the update snapshot is re-read. The shell pushes it to the server whenever its updater+ * moves, but nothing tells this page — the push direction is shell → server — so a slow poll is+ * what turns that into a bubble. Once a minute, on a route that answers from memory.+ */+const UPDATE_POLL_MS = 60_000;++/**+ * One line of the panel: a muted label with its optional action on the first line, and the value+ * under it. Stacked rather than side by side because the window is 260px wide — a label column+ * wide enough for "客户端更新" leaves the value an ellipsis, and these values (a balance reading,+ * a notice, the state of an update) are the whole point of the row.+ */+function Row({+ label,+ children,+ action,+}: {+ label: string;+ children: ReactNode;+ action?: ReactNode;+}) {+ return (+ <div>+ <div className="flex items-center justify-between gap-1.5">+ <span className="text-xs leading-tight text-gray-500 dark:text-gray-400">{label}</span>+ {action}+ </div>+ <div className="text-xs leading-tight break-words text-gray-800 dark:text-gray-100">+ {children}+ </div>+ </div>+ );+}++/** The small text button the panel's rows carry. */+function PetButton({ label, onClick }: { label: string; onClick: () => void }) {+ return (+ <button+ type="button"+ onClick={onClick}+ className="shrink-0 rounded border border-gray-200 px-1.5 py-0.5 text-xs whitespace-nowrap text-gray-600 hover:bg-gray-100 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800"+ >+ {label}+ </button>+ );+}++/**+ * The pinned balance as the pet shows it — the same store the models page and the sidebar read+ * (features/models/balance.ts), so a refresh anywhere is a refresh here, and the same wording+ * (balanceView), so the amount reads identically wherever the user sees it.+ */+function usePetBalance(inShell: boolean): { text: string; title: string; refresh: () => void } {+ const pin = usePinnedBalance();+ const { currency } = useTheme();+ const projectId = pin?.projectId ?? null;+ const provider = pin?.provider ?? "";+ const state = useBalance(projectId, provider);+ useEffect(() => {+ if (projectId === null) return;+ void requestBalance(projectId, provider);+ const timer = window.setInterval(+ () => void requestBalance(projectId, provider),+ PINNED_BALANCE_REFRESH_MS,+ );+ return () => window.clearInterval(timer);+ }, [projectId, provider]);+ const refresh = useCallback(() => {+ if (projectId !== null) void requestBalance(projectId, provider, true);+ }, [projectId, provider]);+ if (!inShell) return { text: S.pet.balanceUnavailable, title: "", refresh };+ if (pin === null) return { text: S.pet.balanceMissing, title: "", refresh };+ const view = balanceView(state, providerInfo(provider)?.label ?? provider, currency);+ return { ...view, refresh };+}++export function PetPage() {+ const { desktopMode, sessionVia } = useAuth();+ const inShell = isDesktopShellWindow({ desktopMode, sessionVia });+ const [notices, setNotices] = useState<readonly PetNotice[]>([]);+ const [bubble, setBubble] = useState<PetNotice | null>(null);+ const [panelOpen, setPanelOpen] = useState(false);+ const [update, setUpdate] = useState<DesktopUpdateStatus | null>(null);+ const balance = usePetBalance(inShell);++ // The window is transparent where the page paints nothing (styles.css): the app's own windows+ // get a canvas background from the shared theme, and this is the one window that must not.+ useEffect(() => {+ document.body.classList.add("pet-body");+ return () => document.body.classList.remove("pet-body");+ }, []);++ /** Says one thing: it goes to the top of the panel's list and up into the bubble. */+ const speak = useCallback((notice: PetNotice) => {+ setNotices((prev) => [notice, ...prev].slice(0, NOTICE_KEEP));+ setBubble(notice);+ }, []);++ // What happened while nobody was looking: the user-level stream, which is this app's+ // cross-Session channel (schedules, approvals waiting, budget warnings).+ useEffect(() => {+ const connection = openUserEvents({+ onOmniMessage: () => {},+ onServerEvent: (event) => {+ const notice = noticeForEvent(event);+ if (notice !== null) speak(notice);+ },+ });+ return () => connection.close();+ }, [speak]);++ /** The last update state this page has announced, so a poll that changes nothing stays quiet. */+ const announcedUpdate = useRef<string | null>(null);+ const readUpdate = useCallback(() => {+ void api.getDesktopUpdate().then(+ (res) => {+ setUpdate(res.status);+ const notice = noticeForUpdate(res.status);+ if (notice === null) return;+ const key = noticeKey(notice);+ if (key === announcedUpdate.current) return;+ announcedUpdate.current = key;+ speak(notice);+ },+ // Not the shell's window, or the shell is not listening: the row says so on its own.+ () => setUpdate(null),+ );+ }, [speak]);+ useEffect(() => {+ if (!inShell) return;+ readUpdate();+ const timer = window.setInterval(readUpdate, UPDATE_POLL_MS);+ return () => window.clearInterval(timer);+ }, [inShell, readUpdate]);++ useEffect(() => {+ if (bubble === null) return;+ const timer = window.setTimeout(() => setBubble(null), BUBBLE_MS);+ return () => window.clearTimeout(timer);+ }, [bubble]);++ const command = updateCommand(update);+ const latest = notices[0];+ const updateLabel =+ command === null+ ? null+ : command === "download"+ ? S.pet.download+ : command === "install"+ ? S.pet.install+ : S.pet.check;+ // The three commands the main window's update modal sends, from the same routes.+ const runCommand = (which: "check" | "download" | "install"): void => {+ const call =+ which === "download"+ ? api.desktopUpdateDownload+ : which === "install"+ ? api.desktopUpdateInstall+ : api.desktopUpdateCheck;+ void call().catch(() => {});+ };++ return (+ <div className="pet-drag flex h-screen w-screen flex-col items-center justify-end gap-1 overflow-hidden bg-transparent p-1">+ {panelOpen && (+ <div className="pet-no-drag w-full space-y-1 rounded-lg border border-gray-200 bg-white/95 p-2 shadow-lg dark:border-gray-700 dark:bg-gray-900/95">+ <Row+ label={S.pet.balance}+ action={<PetButton label={S.pet.refresh} onClick={balance.refresh} />}+ >+ {/* The vendor's own figures and the read time, the same sentence the models page and+ the sidebar put behind their balance. Only when there is one: an empty hint would+ open an empty panel. */}+ <span {...(balance.title === "" ? {} : { "data-tooltip": balance.title })}>+ {balance.text}+ </span>+ </Row>+ <Row+ label={S.pet.update}+ action={+ updateLabel === null ? undefined : (+ <PetButton+ label={updateLabel}+ onClick={() => {+ if (command !== null) runCommand(command);+ }}+ />+ )+ }+ >+ {inShell ? updateText(update, S.pet) : S.pet.updateUnavailable}+ </Row>+ <Row label={S.pet.notices}>+ {latest === undefined ? S.pet.noNotices : noticeText(latest, S.pet)}+ </Row>+ {inShell && (+ <div className="flex justify-end pt-0.5">+ <button+ type="button"+ onClick={() => void api.setDesktopPet({ showPet: false }).catch(() => {})}+ className="rounded px-1 py-0.5 text-xs text-gray-500 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-800"+ >+ {S.pet.hide}+ </button>+ </div>+ )}+ </div>+ )}+ {/* The bubble is above the penguin and drags with the window: it holds no control. */}+ {!panelOpen && bubble !== null && (+ <div+ role="status"+ aria-live="polite"+ className="w-full rounded-lg border border-gray-200 bg-white/95 px-2 py-1 text-xs leading-snug text-gray-800 shadow-lg dark:border-gray-700 dark:bg-gray-900/95 dark:text-gray-100"+ >+ {noticeText(bubble, S.pet)}+ </div>+ )}+ <button+ type="button"+ aria-label={S.pet.open}+ data-tooltip={S.pet.open}+ onClick={() => setPanelOpen((open) => !open)}+ className="pet-no-drag pet-bob block h-[72px] w-[72px] shrink-0 outline-none"+ >+ <Penguin className="h-full w-full" />+ </button>+ </div>+ );+}diff --git a/packages/web/src/features/settings/appearance-section.tsx b/packages/web/src/features/settings/appearance-section.tsxindex ca99e247..1aed84a9 100644--- a/packages/web/src/features/settings/appearance-section.tsx+++ b/packages/web/src/features/settings/appearance-section.tsx@@ -6,10 +6,10 @@* the app unless pinned (see 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. 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.+ * tool call is spelled on screen, never what runs. So are the last two rows, the only chrome here+ * that is not drawn by this page at all: the desktop shell's tray icon and its pet window. Both+ * belong to the shell, only the shell's own window may reach them (see isDesktopShellWindow), so+ * both rows are absent in a browser.*/import { useEffect, useState, useSyncExternalStore } from "react";import { PrefRow, Segmented, Select, SwatchPicker, THEME_IDS, ToggleRow } from "@adelie/ui";@@ -119,13 +119,13 @@ export function AppearanceSection() {useSyncExternalStore(subscribeLauncherHidden, launcherHiddenVersion);const launcherShown = !readLauncherHidden();const { desktopMode, sessionVia } = useAuth();- const offersTrayIcon = isDesktopShellWindow({ desktopMode, sessionVia });+ const offersShellChrome = 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;+ if (!offersShellChrome) return;let live = true;void api.getDesktopTray().then((res) => {@@ -136,7 +136,7 @@ export function AppearanceSection() {return () => {live = false;};- }, [offersTrayIcon]);+ }, [offersShellChrome]);// 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 => {@@ -144,6 +144,28 @@ export function AppearanceSection() {void api.setDesktopTray({ showTrayIcon: next }).catch(() => setTrayIcon(!next));};+ // The pet window, read the same way and from the shell's own default the other way round: the+ // pet is off unless something says otherwise, so an answer that has not arrived yet reads as+ // off — the row must not claim a penguin is on the desktop when there is none.+ const [showPet, setShowPet] = useState(false);+ useEffect(() => {+ if (!offersShellChrome) return;+ let live = true;+ void api.getDesktopPet().then(+ (res) => {+ if (live) setShowPet(res.status?.showPet ?? false);+ },+ () => {},+ );+ return () => {+ live = false;+ };+ }, [offersShellChrome]);+ const changeShowPet = (next: boolean): void => {+ setShowPet(next);+ void api.setDesktopPet({ showPet: next }).catch(() => setShowPet(!next));+ };+const themeOptions: ReadonlyArray<{ value: ThemeMode; label: string }> = [{ value: "light", label: S.settings.themeLight },{ value: "dark", label: S.settings.themeDark },@@ -220,7 +242,7 @@ export function AppearanceSection() {checked={toolAliases}onChange={setToolAliases}/>- {offersTrayIcon && (+ {offersShellChrome && (<ToggleRowlabel={S.settings.trayIcon}info={S.settings.trayIconInfo}@@ -228,6 +250,14 @@ export function AppearanceSection() {onChange={changeTrayIcon}/>)}+ {offersShellChrome && (+ <ToggleRow+ label={S.settings.showPet}+ info={S.settings.showPetInfo}+ checked={showPet}+ onChange={changeShowPet}+ />+ )}</div>);}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 712edb69..29bca9aa 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -780,6 +780,10 @@ export const en: Strings = {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.",+ /** Desktop shell only: the companion window at /pet. */+ showPet: "Desktop pet",+ showPetInfo:+ "A small penguin sits in the bottom-right corner of the desktop: it speaks up when a schedule fires, when tool calls are waiting for your approval, or when a company budget is nearly spent, and clicking it shows the model balance and the client-update state — and hides it again from there. Off by default; either way it takes effect at once and never touches the window you are working in.",currencyInfo: "Display currency for prices; storage is always USD.",changePasswordInfo: "Change this account's sign-in password.",/** Personal company-mode switch (general page) and the admin master switch (its own server page). */@@ -1049,6 +1053,52 @@ export const en: Strings = {taskCompleteBody: (session: string): string => `"${session}" has finished — click to view`,},+ /**+ * The desktop pet (its own window at /pet; the desktop app only). Its bubble and the panel+ * behind the penguin are the whole surface, and they answer the three questions a person asks+ * while they are looking at the desktop rather than at the app: did anything need me, how much+ * model credit is left, and is there a new build.+ */+ pet: {+ /** The penguin's tooltip and accessible name: what a click opens. */+ open: "Click for the balance, new versions and notices",+ /** The panel's footer action, which writes the same preference the Appearance switch does. */+ hide: "Hide the pet",+ refresh: "Refresh",+ balance: "Model balance",+ /** No balance is pinned to the account (see features/models/balance.ts). */+ balanceMissing: "Nothing pinned yet: pin a group's balance from the Models page.",+ /** The balance route is the shell's server's; a plain browser tab cannot read it. */+ balanceUnavailable: "The balance is available in the desktop app only.",+ update: "Client update",+ updateChecking: "Checking for a new version…",+ updateIdle: "No check has run yet.",+ /** `version` is the installed shell version. */+ updateUpToDate: (version: string): string => `Up to date (${version})`,+ /** `version` is the newer release. */+ updateAvailable: (version: string): string => `Version ${version} is available`,+ updateDownloading: (percent: number): string => `Downloading the new version — ${percent}%`,+ updateDownloaded: (version: string): string =>+ `Version ${version} is ready — restart to install it`,+ updateUnsupported: "This installation is updated by the system or by the dev workflow.",+ updateError: (message: string): string => `The update check failed: ${message}`,+ updateUnavailable: "Client updates are visible in the desktop app only.",+ download: "Download",+ install: "Restart and install",+ check: "Check for updates",+ notices: "Notices",+ noNotices: "Nothing new right now.",+ /** `name` is the schedule's name. */+ scheduleFired: (name: string): string => `Schedule "${name}" fired`,+ /** `count` is how many tool calls are waiting for a person (see session_approvals). */+ approvalsWaiting: (count: number): string =>+ count === 1+ ? "A tool call is waiting for your approval"+ : `${count} tool calls are waiting for your approval`,+ budgetWarned: "An employee is close to their budget",+ budgetPaused: "An employee was paused on budget",+ },+common: {save: "Save",cancel: "Cancel",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 086b87d7..4e2ea820 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -837,6 +837,10 @@ export const zh = {trayIcon: "托盘图标",trayIconInfo:"桌面应用运行期间在系统托盘(Windows 通知区、macOS 菜单栏、Linux 托盘)常驻一个图标,点击即可回到窗口,右键可开新会话或退出。默认开启;关掉后图标立即消失,无需重启,此时关闭窗口不再收进托盘:macOS 应用留在 Dock,Windows 与 Linux 关窗即退出。",+ /** Desktop shell only: the companion window at /pet. */+ showPet: "桌面宠物",+ showPetInfo:+ "桌面右下角常驻一只小企鹅:定时任务触发、有工具调用等你批准、公司预算告警时它会冒个气泡,点它可以看模型余额和客户端更新,也能在那里隐藏它。默认关闭;打开或关掉都立即生效,不会碰你正在用的窗口。",currencyInfo: "价格显示币种;存储始终为美元。",changePasswordInfo: "更改当前账号的登录密码。",/** Personal company-mode switch (general page) and the admin master switch (its own server page). */@@ -1102,6 +1106,48 @@ export const zh = {taskCompleteBody: (session: string): string => `「${session}」已完成,点击查看`,},+ /**+ * The desktop pet (its own window at /pet; the desktop app only). Its bubble and the panel+ * behind the penguin are the whole surface, and they answer the three questions a person asks+ * while they are looking at the desktop rather than at the app: did anything need me, how much+ * model credit is left, and is there a new build.+ */+ pet: {+ /** The penguin's tooltip and accessible name: what a click opens. */+ open: "点我:余额、新版本和通知",+ /** The panel's footer action, which writes the same preference the Appearance switch does. */+ hide: "隐藏桌宠",+ refresh: "刷新",+ balance: "模型余额",+ /** No balance is pinned to the account (see features/models/balance.ts). */+ balanceMissing: "还没固定余额:在「模型」页点分组余额旁的图钉固定一个。",+ /** The balance route is the shell's server's; a plain browser tab cannot read it. */+ balanceUnavailable: "余额只在桌面应用里能读。",+ update: "客户端更新",+ updateChecking: "正在检查新版本…",+ updateIdle: "还没检查过新版本。",+ /** `version` is the installed shell version. */+ updateUpToDate: (version: string): string => `已是最新(${version})`,+ /** `version` is the newer release. */+ updateAvailable: (version: string): string => `有新版本 ${version}`,+ updateDownloading: (percent: number): string => `正在下载新版本 ${percent}%`,+ updateDownloaded: (version: string): string => `新版本 ${version} 已就绪,重启即可安装`,+ updateUnsupported: "这个安装形式由系统或开发流程管更新。",+ updateError: (message: string): string => `检查新版本失败:${message}`,+ updateUnavailable: "客户端更新只在桌面应用里能读。",+ download: "下载新版本",+ install: "重启安装",+ check: "检查新版本",+ notices: "通知",+ noNotices: "暂时没有新通知。",+ /** `name` is the schedule's name. */+ scheduleFired: (name: string): string => `定时任务「${name}」已触发`,+ /** `count` is how many tool calls are waiting for a person (see session_approvals). */+ approvalsWaiting: (count: number): string => `有 ${count} 个工具调用在等你批准`,+ budgetWarned: "有员工的花费接近预算上限了",+ budgetPaused: "有员工因预算被暂停了",+ },+common: {save: "保存",cancel: "取消",diff --git a/packages/web/src/router.tsx b/packages/web/src/router.tsxindex aa90956b..c03a2637 100644--- a/packages/web/src/router.tsx+++ b/packages/web/src/router.tsx@@ -36,6 +36,7 @@ import { ChannelView } from "./features/company/channel-view";import { HandbookPage } from "./features/company/handbook-page";import { MachinesPage } from "./features/machines/machines-page";import { WorkflowAppPage } from "./features/workflows/workflow-app-page";+import { PetPage } from "./features/pet/pet-page";import { PAGES } from "./lib/pages";import type { PageEntry } from "./lib/pages";@@ -95,6 +96,20 @@ function RequireAuthBare({ children }: { children: React.ReactNode }) {return <>{children}</>;}+/**+ * The desktop pet window's route (see features/pet/pet-page.tsx; the shell's main.ts loads it).+ *+ * Outside the app shell like the terminal, and without its redirect: this window is 260×240 of+ * transparent chrome, and a sign-in form inside it would be absurd. Not signed in — which only+ * happens in a browser tab that opens /pet — renders nothing at all. The pet window itself never+ * lands here: the shell opens it after the main window's first load, by which time the session+ * cookie exists.+ */+function PetRoute() {+ const { user } = useAuth();+ return user ? <PetPage /> : null;+}+/** When already logged in, visiting /login redirects straight to the chat page. */function LoginRoute() {const { user } = useAuth();@@ -114,6 +129,8 @@ export function AppRouter({ initialPath }: { initialPath?: string } = {}) {</RequireAuthBare>}/>+ {/* The desktop pet window's page (see PetRoute). */}+ <Route path="/pet" element={<PetRoute />} />{/* One workflow's page as the whole app: outside the shell, like the terminal; thecommand palette it mounts is the way back. */}{["/app/:projectId/:agentId/:workflowId", "/app/:projectId/:agentId/:workflowId/:tabKey"].map(diff --git a/packages/web/src/styles.css b/packages/web/src/styles.cssindex c91cbc11..b9c44a01 100644--- a/packages/web/src/styles.css+++ b/packages/web/src/styles.css@@ -457,3 +457,43 @@/* The company channel's bubble (`.channel-bubble`: the deeper inline-code chip and table rulesinside it) lives in the shared UI package too, beside its component:packages/ui/src/components/chat/channel-bubble/channel-bubble.css. */++/* ---------- The desktop pet window ---------- */++/* The pet is a frameless, transparent Electron window showing the app's /pet route+ (features/pet/pet-page.tsx; the shell's main.ts creates it). Three things are the app's own+ here, in plain CSS rather than utilities: the drag regions, because `-webkit-app-region` has no+ place in csstype's React style types, and the window's transparency, which has to override the+ shared theme's canvas background on <body>. All of it is inert in a browser tab. */++/* The whole window drags the pet around; the penguin and the panel opt out so they stay+ clickable. Everything else — the margins around the penguin, the bubble — is the grab handle. */+.pet-drag {+ -webkit-app-region: drag;+}+.pet-no-drag {+ -webkit-app-region: no-drag;+}++/* The desktop shows through wherever the page paints nothing. The page marks the body for as+ long as it is mounted, so no other route is affected. */+body.pet-body,+body.pet-body #root {+ background: transparent;+}++/* The pet's idle bob: a slow breathe in place, so it reads as alive rather than as an icon.+ `prefers-reduced-motion` switches it off with everything else (the global block above), which+ leaves the penguin standing still. */+@keyframes pet-bob {+ 0%,+ 100% {+ transform: translateY(0) scale(1);+ }+ 50% {+ transform: translateY(-3px) scale(1.02);+ }+}+.pet-bob {+ animation: pet-bob 3.6s ease-in-out infinite;+}diff --git a/packages/web/test/icon-registry.test.ts b/packages/web/test/icon-registry.test.tsindex 047c6beb..5320b633 100644--- a/packages/web/test/icon-registry.test.ts+++ b/packages/web/test/icon-registry.test.ts@@ -42,6 +42,10 @@ const ALLOWLIST: Readonly<Record<string, readonly [number, string]>> = {"features/company/handbook-explorer.tsx": [1, "W4"],"features/company/shared.tsx": [2, "W4"],"features/models/models-page.tsx": [4, "W4"],+ // The desktop pet itself (features/pet/penguin.tsx): an illustration, not a glyph — one Adelie+ // penguin drawn for one window, with no registry entry to share a look with, and nothing else in+ // the app draws it. Listed like the rest so a path that moves or multiplies still shows up here.+ "features/pet/penguin.tsx": [5, "W10"],"features/plugins/plugins-page.tsx": [2, "W4"],"features/schedules/schedule-row.tsx": [3, "W4"],"features/schedules/schedule-suggestions.tsx": [3, "W4"],diff --git a/packages/web/test/pet-notice.test.ts b/packages/web/test/pet-notice.test.tsnew file mode 100644index 00000000..7d4677b5--- /dev/null+++ b/packages/web/test/pet-notice.test.ts@@ -0,0 +1,184 @@+/**+ * What the desktop pet says: which user-channel events are worth a bubble, what an update+ * snapshot does and does not announce, and the wording of both.+ *+ * The point of pinning this here is that the stream is broad and the pet is small: every test+ * below that expects null is the feature saying "this is not why a penguin should interrupt you".+ */+import { describe, expect, it } from "vitest";+import type { DesktopUpdateStatus, ServerEvent } from "@adelie/server/api";+import {+ noticeForEvent,+ noticeForUpdate,+ noticeKey,+ noticeText,+ updateCommand,+ updateText,+} from "../src/features/pet/pet-notice.js";+import { S } from "../src/lib/strings.js";+import { en } from "../src/lib/strings-en.js";++const status = (state: DesktopUpdateStatus["state"], rest: Partial<DesktopUpdateStatus> = {}) =>+ ({ appVersion: "0.5.1", state, ...rest }) as DesktopUpdateStatus;++describe("noticeForEvent", () => {+ it("speaks when a schedule fired", () => {+ const event = {+ type: "schedule_fired",+ projectId: "p",+ agentId: "a",+ name: "每日进度",+ sessionId: "s",+ } as ServerEvent;+ expect(noticeForEvent(event)).toEqual({ kind: "schedule", name: "每日进度" });+ });++ it("speaks about tool calls that are still waiting, and stays quiet once none are", () => {+ expect(noticeForEvent({ type: "session_approvals", sessionId: "s", count: 2 })).toEqual({+ kind: "approval",+ count: 2,+ });+ // The same event with a zero count is the last call being answered.+ expect(noticeForEvent({ type: "session_approvals", sessionId: "s", count: 0 })).toBeNull();+ });++ it("speaks about a budget warning or pause, not about a resume", () => {+ const base = { projectId: "p", orgId: "o", agentId: "a", ratio: 0.9 };+ expect(noticeForEvent({ ...base, type: "org_budget", state: "warned" })).toEqual({+ kind: "budget",+ state: "warned",+ });+ expect(noticeForEvent({ ...base, type: "org_budget", state: "paused" })).toEqual({+ kind: "budget",+ state: "paused",+ });+ expect(noticeForEvent({ ...base, type: "org_budget", state: "resumed" })).toBeNull();+ });++ it("stays quiet for everything the app's own chrome already shows", () => {+ const quiet: ServerEvent[] = [+ { type: "hello" },+ { type: "task_state", state: "idle" },+ { type: "session_title", sessionId: "s", title: "t" },+ {+ type: "session_state",+ sessionId: "s",+ projectId: "p",+ state: "idle",+ lastActiveAt: "2026-10-20T00:00:00Z",+ hasTrace: true,+ },+ { type: "session_background", sessionId: "s", processes: 1, subagents: 0 },+ { type: "credentials_updated" },+ { type: "resync_required" },+ ];+ for (const event of quiet) expect(noticeForEvent(event), event.type).toBeNull();+ });+});++describe("noticeForUpdate", () => {+ it("announces only the two states that ask the user to do something", () => {+ expect(noticeForUpdate(status("available", { version: "0.6.0" }))).toEqual({+ kind: "update",+ version: "0.6.0",+ ready: false,+ });+ expect(noticeForUpdate(status("downloaded", { version: "0.6.0" }))).toEqual({+ kind: "update",+ version: "0.6.0",+ ready: true,+ });+ // Progress, failures and the steady states belong in the panel, which the user opens.+ for (const state of [+ "idle",+ "checking",+ "downloading",+ "up-to-date",+ "error",+ "unsupported",+ ] as const) {+ expect(noticeForUpdate(status(state)), state).toBeNull();+ }+ expect(noticeForUpdate(null)).toBeNull();+ // An offer with no version in it is nothing to click.+ expect(noticeForUpdate(status("available"))).toBeNull();+ });+});++describe("noticeKey", () => {+ it("tells apart exactly what reads differently", () => {+ expect(noticeKey({ kind: "schedule", name: "a" })).not.toBe(+ noticeKey({ kind: "schedule", name: "b" }),+ );+ // The same state announced twice is one key, which is what keeps a poll from repeating itself.+ expect(noticeKey({ kind: "update", version: "1", ready: false })).toBe(+ noticeKey({ kind: "update", version: "1", ready: false }),+ );+ expect(noticeKey({ kind: "update", version: "1", ready: false })).not.toBe(+ noticeKey({ kind: "update", version: "1", ready: true }),+ );+ });+});++describe("noticeText", () => {+ it("words every notice, in both languages", () => {+ expect(noticeText({ kind: "schedule", name: "日报" }, S.pet)).toContain("日报");+ expect(noticeText({ kind: "approval", count: 3 }, S.pet)).toContain("3");+ expect(noticeText({ kind: "budget", state: "warned" }, S.pet)).toBe(S.pet.budgetWarned);+ expect(noticeText({ kind: "budget", state: "paused" }, S.pet)).toBe(S.pet.budgetPaused);+ expect(noticeText({ kind: "update", version: "0.6.0", ready: false }, S.pet)).toContain(+ "0.6.0",+ );+ expect(noticeText({ kind: "update", version: "0.6.0", ready: true }, S.pet)).toContain("0.6.0");+ // The English dictionary answers the same call — the shape is shared, not the words.+ expect(noticeText({ kind: "schedule", name: "Daily" }, en.pet)).toContain("Daily");+ expect(noticeText({ kind: "budget", state: "paused" }, en.pet)).toBe(en.pet.budgetPaused);+ });+});++describe("updateText", () => {+ it("reads every state the shell can be in", () => {+ expect(updateText(null, S.pet)).toBe(S.pet.updateIdle);+ expect(updateText(status("idle"), S.pet)).toBe(S.pet.updateIdle);+ expect(updateText(status("checking"), S.pet)).toBe(S.pet.updateChecking);+ expect(updateText(status("up-to-date"), S.pet)).toBe(S.pet.updateUpToDate("0.5.1"));+ expect(updateText(status("available", { version: "0.6.0" }), S.pet)).toBe(+ S.pet.updateAvailable("0.6.0"),+ );+ expect(updateText(status("downloading", { version: "0.6.0", percent: 42 }), S.pet)).toBe(+ S.pet.updateDownloading(42),+ );+ expect(updateText(status("downloaded", { version: "0.6.0" }), S.pet)).toBe(+ S.pet.updateDownloaded("0.6.0"),+ );+ expect(updateText(status("unsupported", { reason: "dev" }), S.pet)).toBe(+ S.pet.updateUnsupported,+ );+ expect(updateText(status("error", { message: "offline" }), S.pet)).toBe(+ S.pet.updateError("offline"),+ );+ });++ it("falls back to a quiet line when a state arrives without the field it needs", () => {+ expect(updateText(status("available"), S.pet)).toBe(S.pet.updateIdle);+ expect(updateText(status("downloaded"), S.pet)).toBe(S.pet.updateIdle);+ // A download with no percentage reported is 0%, not NaN.+ expect(updateText(status("downloading", { version: "0.6.0" }), S.pet)).toBe(+ S.pet.updateDownloading(0),+ );+ });+});++describe("updateCommand", () => {+ it("offers the one action each state is waiting for, and none while one is under way", () => {+ expect(updateCommand(null)).toBe("check");+ expect(updateCommand(status("idle"))).toBe("check");+ expect(updateCommand(status("up-to-date"))).toBe("check");+ expect(updateCommand(status("error"))).toBe("check");+ expect(updateCommand(status("unsupported"))).toBe("check");+ expect(updateCommand(status("available", { version: "0.6.0" }))).toBe("download");+ expect(updateCommand(status("downloaded", { version: "0.6.0" }))).toBe("install");+ expect(updateCommand(status("checking"))).toBeNull();+ expect(updateCommand(status("downloading", { version: "0.6.0" }))).toBeNull();+ });+});