A local-first multi-agent app development platform, built on PenguinHarness
feat(desktop): 桌面端可以随 Windows 登录自己启动
lmliheng485dc3e3fdbc
diff --git a/changelog/unreleased/2026-11-01-windows-start-at-login.md b/changelog/unreleased/2026-11-01-windows-start-at-login.mdnew file mode 100644index 00000000..cca1443b--- /dev/null+++ b/changelog/unreleased/2026-11-01-windows-start-at-login.md@@ -0,0 +1,63 @@+# The desktop app can start with your Windows session, and waits in the tray++- **Date:** 2026-11-01+- **Type:** feature+- **Scope:** `desktop`, `server`, `web`+- **Breaking:** no++[中文](2026-11-01-windows-start-at-login.zh.md)++Settings › Appearance has a new row in the Windows desktop app — 「Start when you sign in」 — which+registers the installed app to start when that user signs in to Windows. It is off until it is+turned on, it applies at once, and the launch Windows itself starts opens no window: the app waits+in the tray, and the tray icon (or starting the app again, which comes to the same window) is how+the window appears. Nothing needs administrator rights and no service is installed — the entry is a+value in the current user's own startup list (`HKCU\Software\Microsoft\Windows\CurrentVersion\Run`),+and uninstalling removes it.++The row shows what Windows holds rather than a preference of our own, which is why it can also go+the other way: disable Adelie in Task Manager › Startup apps and the switch here reads off, because+that is what will happen at the next sign-in.++## Details++- `packages/desktop/src/login-item.ts` (new, pure, unit-tested): the argument the entry registers+ (`--started-at-login`), the write, the read and the frame parsers. Two decisions are recorded+ there: the value is registered under a name of the app's own (`Adelie`) so the uninstaller deletes+ exactly one value, and the reading therefore comes from `executableWillLaunchAtLogin` — Electron's+ `openAtLogin` compares the value named the AppUserModelId, which ours is not, while+ `executableWillLaunchAtLogin` answers the question the switch is asking: does any startup entry+ launch this executable and is it not disabled.+- The row is offered only where there is an entry to manage: the release build, on Windows. A dev+ shell draws nothing, because an unpackaged run would register the bare `electron.exe` from+ `node_modules`, and a `--dev` instance of an installed build would register a release launch under+ a dev-suffixed name — entries the user could not get rid of from the app. A browser signed into+ the same desktop-mode server draws nothing either, the rule the tray and the pet rows already use.+- The sign-in launch keeps the main window built and loaded but never shown, and only when a tray+ icon exists: a hidden app with no icon would be a window nothing can bring back. Closing the+ window, the tray menu, a second launch and the Dock all reach it through `showMainWindow`.+- `GET`/`PUT /api/desktop/login-item` (desktop-shell sessions only) read and write the switch over the+ same utilityProcess relay the tray icon uses: the status is what the shell last read from Windows,+ the patch is validated (`openAtLogin` must be a boolean; an empty patch is refused) and a PUT+ answers 503 when no shell is listening.+- `packages/desktop/build/installer.nsh` (new, hooked up by `nsis.include`) deletes both halves of the+ entry when the app is uninstalled — the startup value and Windows' record of whether it was+ enabled — so no dead row is left pointing at an executable that is gone.++## Tests++- `packages/desktop/test/login-item.test.ts` (new, 9 cases): the platform/profile support rule, the+ argument and its near misses, the write shape, the status mapping (a Task Manager disabled entry+ reads off, an unsupported shell reports `supported: false`), the command parser, and the+ uninstaller's literal matching the release identity's name.+- `packages/server/test/desktop-login-item.test.ts` (new, 8 cases): GET serving null before the+ shell's first push and the pushed status after it; 403 for a password session and 404 outside+ desktop mode; a PUT forwarded to the shell and answered 202; a non-boolean or empty field refused+ with 400 and never relayed; 503 with no shell wired; and only frames carrying both fields read as+ status pushes.+- Existing suites, unchanged: `desktop` 314 cases, `server` 3029, `web` 3374; `tsc` for the three+ packages; `oxlint` over the tree; `prettier --check .`.+- The Windows installer was built here under wine to prove the new NSIS include compiles into the+ uninstaller. The behaviour on a real machine — the entry appearing in Task Manager › Startup apps+ as enabled, a sign-out and sign-in starting the app into the tray with no window, the switch+ removing it, and an uninstall leaving nothing behind — needs a Windows machine.diff --git a/changelog/unreleased/2026-11-01-windows-start-at-login.zh.md b/changelog/unreleased/2026-11-01-windows-start-at-login.zh.mdnew file mode 100644index 00000000..13028d7e--- /dev/null+++ b/changelog/unreleased/2026-11-01-windows-start-at-login.zh.md@@ -0,0 +1,51 @@+# Windows 桌面端可以随登录启动,启动后在托盘待命++- **Date:** 2026-11-01+- **Type:** feature+- **Scope:** `desktop`, `server`, `web`+- **Breaking:** no++[English](2026-11-01-windows-start-at-login.md)++设置 › 外观 在 Windows 桌面端多了一行「开机自启动」:打开它,装好的 Adelie 就会在你登录这台机+时自己起来。默认关闭,打开即生效;Windows 拉起的这一次不弹窗口——应用在托盘里待命,点托盘图标+(或再启动一次应用,落到同一个窗口)就能把窗口调出来。不需要管理员权限,也不装任何服务:条目写+在当前用户自己的启动项里(`HKCU\Software\Microsoft\Windows\CurrentVersion\Run`),卸载时一并删掉。++这一行显示的是 Windows 那份登记本身,而不是我们另存的一份偏好,所以反过来也成立:在「任务管理器 ›+启动应用」里把 Adelie 禁用掉,这里的开关就会显示为关闭——因为下次登录它确实不会起。++## 细节++- `packages/desktop/src/login-item.ts`(新,纯函数,有用例):登录项注册用的参数+ (`--started-at-login`)、写入、读取与两个帧的解析。其中两个决定写在文件里:注册表值名用应用自己+ 的名字(`Adelie`),这样卸载脚本只删一个确定的值;因此读取走+ `executableWillLaunchAtLogin` 而不是 `openAtLogin`——后者比的是以 AppUserModelId 命名的那条值,+ 而我们写的不是那一条;前者回答的正是开关在问的问题:有没有哪条启动项会拉起这个可执行文件、且没被+ 停用。+- 只有在真有条目可管的地方才画这一行:Windows 上的正式安装版。开发态不画——未打包的运行会把+ `node_modules` 里那个裸 `electron.exe` 写进启动项,而正式安装版跑 `--dev` 又会把「正式版的启动」+ 注册在一个带 dev 后缀的名字下,两种条目用户都没法从应用里清掉。浏览器直连同一台桌面模式服务器时+ 也不画,判据与托盘、宠物那两行相同。+- 由登录项拉起的那一次,主窗口照样创建、照样加载,只是从不显示,而且仅在有托盘图标时才这样:既没有+ 窗口、又没有图标的进程没人能叫回来。关窗进托盘、托盘菜单、再次启动应用与 macOS 的 Dock 都走同一个+ `showMainWindow`。+- `GET`/`PUT /api/desktop/login-item`(仅限外壳自己的窗口)读写这个开关,走的是托盘图标已经在用的那+ 条 utilityProcess 通道:状态是外壳最后一次从 Windows 读到的结果,补丁会校验(`openAtLogin` 必须+ 是布尔;空补丁拒绝),没有外壳在听时 PUT 答 503。+- `packages/desktop/build/installer.nsh`(新,由 `nsis.include` 挂上)在卸载时把条目两半都删掉——启动+ 项那条值,以及 Windows 记着它「已启用/已禁用」的那条——不留一个指向已删可执行文件的死项。++## 测试++- `packages/desktop/test/login-item.test.ts`(新,9 条):平台与档位的支持判据、参数与近似参数的区+ 分、写入的形状、状态的换算(被任务管理器禁用的条目读作关闭、不支持的平台报 `supported: false`)、+ 命令帧的解析,以及卸载脚本里的值名与正式版身份名一致。+- `packages/server/test/desktop-login-item.test.ts`(新,8 条):外壳首次推送之前 GET 为 null、推送+ 之后读回;密码会话 403,非桌面模式 404;PUT 转发给外壳并答 202;非布尔或空字段 400 且不转发;没有+ 外壳端口时 503;只有两个字段都齐的帧才被当作状态推送。+- 既有用例未变:`desktop` 314 条、`server` 3029 条、`web` 3374 条;三个包的 `tsc`;整仓 `oxlint`;+ `prettier --check .`。+- 在本机用 wine 打了一次 Windows 安装包,确认新加的 NSIS include 能编进卸载器。真机行为——任务管理器+ › 启动应用里出现 Adelie 且为已启用、注销再登录后应用起在托盘且不弹窗、关掉开关后该条目消失、卸载+ 后不留死项——需要一台 Windows 机器来验。diff --git a/packages/desktop/build/installer.nsh b/packages/desktop/build/installer.nshnew file mode 100644index 00000000..5caeffef--- /dev/null+++ b/packages/desktop/build/installer.nsh@@ -0,0 +1,26 @@+# Custom NSIS hooks for Adelie's Windows installer. electron-builder.yml's `nsis.include` pulls+# this file in; electron-builder prepends what it was given to the generated script, so the macros+# below are defined before its own templates test for them (`!ifmacrodef customUnInstall` in+# templates/nsis/uninstaller.nsh).+#+# Why this exists: Settings › Appearance can register the app to start when the user signs in — a+# value under HKCU's Run key, written by Electron's app.setLoginItemSettings (see+# packages/desktop/src/login-item.ts). Left behind by an uninstall it points at an executable that+# is gone, so Task Manager › Startup apps keeps listing a dead entry that nothing in the product+# can remove any more. The uninstaller therefore deletes both halves of it.+#+# The value name is the app's own name as the shell sets it (app.name → "Adelie" for the release+# profile; see appIdentity in packages/desktop/src/app-identity.ts), because that literal is what+# the shell registers the entry under — the two have to stay equal. A per-machine install that+# another administrator uninstalls clears THAT account's HKCU entry rather than the one that turned+# the switch on; the entry lives in HKCU, so this is the most an uninstaller can honestly do.++!macro customUnInstall+ # The startup entry itself. Deleting a value that is not there is not an error in NSIS, which is+ # what makes this safe for the many installs that never turned the switch on.+ DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "Adelie"+ # The record Windows keeps of whether that entry is enabled or disabled (Task Manager › Startup+ # apps). Left behind, it would apply to whatever a later install registers under the same name —+ # an app that arrives already switched off in Task Manager.+ DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run" "Adelie"+!macroenddiff --git a/packages/desktop/electron-builder.yml b/packages/desktop/electron-builder.ymlindex 1fcffc8d..83e73d27 100644--- a/packages/desktop/electron-builder.yml+++ b/packages/desktop/electron-builder.yml@@ -158,6 +158,10 @@ nsis:# (uninstallerSidebar defaults to installerSidebar).installerSidebar: build/nsis/installerSidebar.bmpinstallerHeader: build/nsis/installerHeader.bmp+ # The installer's own NSIS hooks: `customUnInstall` removes the sign-in entry Settings ›+ # Appearance can register (HKCU's Run value and its StartupApproved half), which would otherwise+ # outlive the app as a dead row in Task Manager › Startup apps. See build/installer.nsh.+ include: build/installer.nshlinux:# Pre-rendered freedesktop icon set (scripts/render-icon.mjs): a directory of NxN.pngdiff --git a/packages/desktop/src/login-item.ts b/packages/desktop/src/login-item.tsnew file mode 100644index 00000000..a4be0baf--- /dev/null+++ b/packages/desktop/src/login-item.ts@@ -0,0 +1,145 @@+/**+ * The Windows login item — Windows' own record that Adelie starts when the user signs in. Pure+ * functions over Electron's arguments and settings, no Electron imports (unit-tested).+ *+ * WHERE THE STATE LIVES, AND WHY THERE IS NO FILE BESIDE IT. The tray's two booleans and the+ * pet's one live in `userData/*.json` because they are OUR preferences: nothing else can change+ * them, so we are their only writer. This one is the opposite — the entry is a value under+ * `HKCU\Software\Microsoft\Windows\CurrentVersion\Run`, and the user can disable it from+ * Task Manager › Startup apps without asking us. A copy of it in userData could therefore be+ * wrong the moment it is written, and a page reading a stale copy would draw a switch that lies.+ * So the shell reads the operating system's own record on every launch and after every write,+ * and reports that.+ *+ * WHY THE READ USES A DIFFERENT FIELD THAN THE WRITE. `setLoginItemSettings` writes the Run value+ * under `name`, and Electron's `getLoginItemSettings().openAtLogin` is documented as "true if the+ * app is set to open at login" — but on Windows it does not mean that. Its implementation reads+ * the single Run value named the AppUserModelId, ignores any custom `name`, and compares that+ * value's command line against `path` + `args`; since we pin a `name` of our own (the uninstaller+ * deletes exactly one value), reading `openAtLogin` would answer "no" for the very entry this+ * module had just written. `executableWillLaunchAtLogin` is the field that answers the question+ * the switch is asking: it is true when ANY Run entry — ours, or one the user added by hand —+ * launches this executable and is not disabled in Task Manager.+ *+ * THE FLAG, AND WHY ONE IS NEEDED. `wasOpenedAtLogin` exists only on macOS (Electron marks it+ * `@platform darwin`), so on Windows the one launch the login item itself starts is recognized by+ * an argument we write into the entry; main.ts then opens no visible window for it, and the tray+ * is where the app waits.+ *+ * A MOVED INSTALL, AND WHY NOTHING IS REWRITTEN BEHIND THE USER'S BACK. The entry holds an+ * absolute executable path, so installing to another directory leaves a value pointing at the old+ * one — invisible to the read above, which matches on the running executable. It reads as OFF+ * (truthfully: nothing will start), and the next time the switch is turned on the write lands on+ * the same value name and overwrites the dead entry, so it heals by itself in the one flow that+ * touches it. What is deliberately NOT done is rewriting the entry at startup to "fix" it: the+ * read cannot tell a wrong path from an absent entry, and an unconditional write would silently+ * re-enable an entry the user had switched off in Task Manager — a background app that comes back+ * against their wishes, which is worse than a dead value Windows already shows them.+ */+import type {+ DesktopLoginItemCommandMessage,+ DesktopLoginItemStatus,+ DesktopLoginItemStatusMessage,+} from "@adelie/server/api";+import type { Profile } from "./app-identity.js";++/** The argument the login item registers the app with, and the one a launch is recognized by. */+export const LOGIN_ITEM_FLAG = "--started-at-login";++/** The arguments to register with, and to write into the entry. */+export function loginItemArgs(): string[] {+ return [LOGIN_ITEM_FLAG];+}++/**+ * Whether this build has a login item to manage at all: the installed app, on Windows, and+ * nothing else.+ *+ * Windows-only because it is the only platform with a Run key (macOS would use the same API but+ * a different mechanism, and Linux would need a `~/.config/autostart` entry — neither is built).+ * Release-only because the entry records an absolute executable path and nothing else: an+ * unpackaged run would register the bare `electron.exe` from node_modules, which starts the+ * default Electron app rather than Adelie, and a `--dev` instance of an installed build would+ * register the release launch (our args carry the flag, not `--dev`) under a dev-suffixed name.+ * Both would be entries the user cannot get rid of from the app, so neither is offered: a dev+ * shell simply has no row.+ */+export function supportsLoginItem(opts: { platform: string; profile: Profile }): boolean {+ return opts.platform === "win32" && opts.profile === "release";+}++/** Whether Windows' login item is what started this process (see the flag above). */+export function startedAtLogin(argv: readonly string[]): boolean {+ return argv.includes(LOGIN_ITEM_FLAG);+}++/** The `Settings` object handed to `app.setLoginItemSettings`, structurally Electron's own. */+export interface LoginItemWrite {+ openAtLogin: boolean;+ path: string;+ args: string[];+ enabled: true;+ name: string;+}++/**+ * What to write for one switch flip. `openAtLogin: false` asks Electron to delete the entry —+ * both the Run value and the StartupApproved one — and every other field is then ignored.+ *+ * `path` is passed explicitly rather than left to Electron's default, so the entry names the+ * executable that is running. `enabled: true` is what makes turning the switch back on work: it+ * clears any "disabled" the user left in Task Manager, without which the entry would be written+ * again and still never start.+ */+export function loginItemWrite(opts: {+ name: string;+ execPath: string;+ openAtLogin: boolean;+}): LoginItemWrite {+ return {+ openAtLogin: opts.openAtLogin,+ path: opts.execPath,+ args: loginItemArgs(),+ enabled: true,+ name: opts.name,+ };+}++/**+ * What the page is told: whether this build has an entry to manage, and whether Windows will+ * actually use it. `supported: false` is reported for every platform and profile without one,+ * and the page draws no row for it rather than a switch that would write nothing.+ */+export function loginItemStatusOf(opts: {+ supported: boolean;+ executableWillLaunchAtLogin: boolean;+}): DesktopLoginItemStatus {+ if (!opts.supported) return { supported: false, openAtLogin: false };+ return { supported: true, openAtLogin: opts.executableWillLaunchAtLogin };+}++/** Wraps what Windows currently says for the port push. */+export function loginItemStatusMessage(+ status: DesktopLoginItemStatus,+): DesktopLoginItemStatusMessage {+ return { type: "desktop-login-item-status", status };+}++/**+ * Validates one server-relayed command off the port. Null when the frame is not one, and an+ * empty patch when it is one carrying nothing this build understands — the same distinction the+ * tray's parser draws, for the same reason.+ */+export function parseLoginItemCommand(data: unknown): LoginItemCommand | null {+ if (typeof data !== "object" || data === null) return null;+ const msg = data as Partial<DesktopLoginItemCommandMessage>;+ if (msg.type !== "desktop-login-item-command") return null;+ const patch: LoginItemCommand = {};+ if (typeof msg.openAtLogin === "boolean") patch.openAtLogin = msg.openAtLogin;+ return patch;+}++/** What one relayed command asks the shell to change; the route's patch is the same shape. */+export interface LoginItemCommand {+ openAtLogin?: boolean;+}diff --git a/packages/desktop/src/main.ts b/packages/desktop/src/main.tsindex f6cae370..507ebe25 100644--- a/packages/desktop/src/main.ts+++ b/packages/desktop/src/main.ts@@ -38,6 +38,14 @@* 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.*+ * Login item (Windows): Settings › Appearance can register the installed app to start when the+ * user signs in — off by default, and offered only where there is an entry to manage (see+ * login-item.ts). Windows keeps that record itself, in the user's own Run key: the shell reads it+ * back out of the operating system rather than storing it, and reports what it finds, so an entry+ * the user disabled in Task Manager shows here as off. The launch the entry itself starts carries+ * a flag, and that launch opens no visible window — it waits in the tray, which is where every+ * other path back to the app already is.+ ** 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,@@ -69,6 +77,7 @@ import path from "node:path";import { app, BrowserWindow, dialog, screen, session, shell } from "electron";import type { WindowOpenHandlerResponse } from "electron";import { resolveRoot } from "@adelie/core";+import type { DesktopLoginItemStatus } from "@adelie/server/api";import { mintApiToken } from "@adelie/server/auth-token";import { liveServerLock } from "@adelie/server/lock";import type { ServerLock } from "@adelie/server/lock";@@ -90,6 +99,14 @@ import { logLine, logServerOutput, startDesktopLog, stopDesktopLog } from "./desimport { handleFolderAccessFrame } from "./folder-access.js";import type { FolderAccessFrameDeps } from "./folder-access.js";import { applyLoginShellEnv } from "./login-shell-env.js";+import {+ loginItemStatusMessage,+ loginItemStatusOf,+ loginItemWrite,+ parseLoginItemCommand,+ startedAtLogin,+ supportsLoginItem,+} from "./login-item.js";import { installAppMenu } from "./menu.js";import { startEmbeddedServer, stopEmbeddedServer } from "./server-process.js";import type { EmbeddedServer } from "./server-process.js";@@ -153,6 +170,19 @@ let showPet = false;* own report arrives only once a window has loaded far enough to send it.*/let trayLocale: TrayLocale = "en";+/**+ * Whether this launch was started by Windows' own login item (see login-item.ts). Read from+ * process.argv rather than anywhere near Electron, for the same reason `profile` is.+ */+const launchedAtLogin = startedAtLogin(process.argv);+/**+ * Whether this launch keeps its window hidden: the login item started it AND there is a tray icon+ * to bring the window back from. A hidden app with no icon would be a window nobody can reopen+ * except by launching the app again, which is why the tray is part of the condition — the same+ * reasoning `hidesOnClose` (util.ts) applies to close-to-tray. Resolved before boot, once the+ * tray's own preference has been read and the install attempted.+ */+let startHidden = false;let server: EmbeddedServer | null = null;/** The live server child, for pushes that are not answers to one of its messages. */let relayChild: EmbeddedServer["child"] | null = null;@@ -231,7 +261,15 @@ function createWindow(url: string): void {},});builtinBrowser.host(win);- win.once("ready-to-show", () => win?.show());+ // Shown when it has painted — unless it was Windows' login item that started this launch, in+ // which case the window is built and loaded but stays hidden: the tray is where the app waits,+ // and every other way back to it (the tray menu, a second launch, the Dock) calls+ // showMainWindow. Built rather than skipped, because a launch with no window at all is a shape+ // nothing else in this file has: the pet waits on this window's first load, and the sign-in+ // token that a fresh launch redeems arrives with it.+ win.once("ready-to-show", () => {+ if (!startHidden) win?.show();+ });// Close-to-tray: the window goes away, the app and its embedded server stay, and the tray// icon is the way back. Every real exit — the tray's Quit, the app menu's, an OS logout —// passes through before-quit first, which is what `quitting` reports.@@ -662,13 +700,60 @@ function pushPetStatus(): void {relayChild?.postMessage(petStatusMessage(showPet));}+// --- the Windows login item -------------------------------------------------++/**+ * Whether this build has a sign-in entry to manage at all (see supportsLoginItem in+ * login-item.ts): the installed app, on Windows. Every other form answers the page with+ * `supported: false`, and the page draws no row for that rather than a switch that writes nothing.+ */+const loginItemSupported = supportsLoginItem({ platform: process.platform, profile });++/**+ * Reads Windows' own record of the sign-in entry, straight from the operating system. Nothing is+ * cached and nothing is stored: the user can disable the entry from Task Manager without the app+ * being told, so every push and every read is a fresh look (which is also why there is no+ * userData file beside the tray's and the pet's — see login-item.ts).+ */+function loginItemStatus(): DesktopLoginItemStatus {+ return loginItemStatusOf({+ supported: loginItemSupported,+ executableWillLaunchAtLogin:+ loginItemSupported && app.getLoginItemSettings().executableWillLaunchAtLogin,+ });+}++/**+ * Applies Settings › Appearance's sign-in switch: the Run entry is written or deleted now, and+ * what Windows says afterwards is pushed back to the page. `enabled: true` is what makes turning+ * the switch back on take effect after the entry was disabled in Task Manager (see+ * loginItemWrite).+ */+function setLoginItem(openAtLogin: boolean): void {+ if (loginItemSupported) {+ try {+ app.setLoginItemSettings(+ loginItemWrite({ name: identity.name, execPath: process.execPath, openAtLogin }),+ );+ } catch (err) {+ logLine(`[shell] the sign-in entry could not be written: ${String(err)}`);+ }+ }+ pushLoginItemStatus();+}++/** Tells the page what Windows says about starting at sign-in, which is what its row renders. */+function pushLoginItemStatus(): void {+ relayChild?.postMessage(loginItemStatusMessage(loginItemStatus()));+}+/*** 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 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.+ * frames to the updater, the Appearance switch's frames to the tray, to the pet window and to+ * Windows' login item, 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+ * four 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;@@ -688,6 +773,10 @@ function wireShellRelay(child: EmbeddedServer["child"]): void {}const pet = parsePetCommand(message);if (pet !== null && pet.showPet !== undefined) setShowPet(pet.showPet);+ const loginItem = parseLoginItemCommand(message);+ if (loginItem !== null && loginItem.openAtLogin !== undefined) {+ setLoginItem(loginItem.openAtLogin);+ }});const unsubscribe = onUpdaterStatus((status) => child.postMessage(updaterStatusMessage(status)));child.on("exit", () => {@@ -697,6 +786,7 @@ function wireShellRelay(child: EmbeddedServer["child"]): void {child.postMessage(updaterStatusMessage(getUpdaterStatus()));pushTrayStatus();pushPetStatus();+ pushLoginItemStatus();}/** Starts (or restarts) the embedded server and points the window at the claim link. */@@ -899,6 +989,12 @@ if (!app.requestSingleInstanceLock()) {// same rule the Web App applies to its own "follow the system" default.trayLocale = trayPrefs.locale ?? resolveTrayLocale(app.getLocale());openTray();+ // A launch Windows' own login item started waits in the tray instead of popping a window+ // over whatever the user just signed in to open — but only where there is a tray icon to+ // come back from (see startHidden). The attempt above is what decides that: a platform with+ // no tray leaves `tray` null, and this launch then behaves like any other.+ startHidden = launchedAtLogin && tray !== null;+ if (startHidden) logLine("[shell] started by the sign-in entry; waiting in the tray");// 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;diff --git a/packages/desktop/test/login-item.test.ts b/packages/desktop/test/login-item.test.tsnew file mode 100644index 00000000..6c4cea70--- /dev/null+++ b/packages/desktop/test/login-item.test.ts@@ -0,0 +1,154 @@+/**+ * The Windows login item: what the shell writes into the user's Run key, what it reads back out of+ * the operating system, and the two frames that carry the Appearance switch between the page and+ * the shell.+ *+ * The point of most of these cases is the pair of decisions login-item.ts explains at length: the+ * write pins a value name of our own (so the uninstaller can delete exactly one value), and the+ * read therefore cannot use Electron's `openAtLogin` — it uses `executableWillLaunchAtLogin`,+ * which is the "will Windows actually start this" answer.+ */+import { describe, expect, it } from "vitest";+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { appIdentity } from "../src/app-identity.js";+import {+ LOGIN_ITEM_FLAG,+ loginItemArgs,+ loginItemStatusMessage,+ loginItemStatusOf,+ loginItemWrite,+ parseLoginItemCommand,+ startedAtLogin,+ supportsLoginItem,+} from "../src/login-item.js";++describe("supportsLoginItem", () => {+ it("is the installed app on Windows, and nothing else", () => {+ expect(supportsLoginItem({ platform: "win32", profile: "release" })).toBe(true);+ // A dev shell has no entry to manage: an unpackaged run would register the bare electron.exe+ // from node_modules, and a `--dev` instance of an installed build would register the release+ // launch under a dev-suffixed name. Both are rows the user could not get rid of again.+ expect(supportsLoginItem({ platform: "win32", profile: "dev" })).toBe(false);+ expect(supportsLoginItem({ platform: "darwin", profile: "release" })).toBe(false);+ expect(supportsLoginItem({ platform: "linux", profile: "release" })).toBe(false);+ });+});++describe("startedAtLogin", () => {+ it("recognizes the argument the entry registers the app with", () => {+ expect(LOGIN_ITEM_FLAG).toBe("--started-at-login");+ expect(loginItemArgs()).toEqual([LOGIN_ITEM_FLAG]);+ // The main process's own argv shape: the executable first, the entry's arguments after it.+ // A second launch by hand carries neither.+ expect(startedAtLogin(["C:\\Adelie\\Adelie.exe", LOGIN_ITEM_FLAG])).toBe(true);+ expect(startedAtLogin(["C:\\Adelie\\Adelie.exe"])).toBe(false);+ expect(startedAtLogin([])).toBe(false);+ // Substrings and near misses are not the flag: the argument has to be the whole thing.+ expect(startedAtLogin(["--started-at-login=false"])).toBe(false);+ expect(startedAtLogin(["--started"])).toBe(false);+ });+});++describe("loginItemWrite", () => {+ it("registers the running executable, with the flag and its own value name", () => {+ const settings = loginItemWrite({+ name: "Adelie",+ execPath: "C:\\Users\\me\\AppData\\Local\\Programs\\Adelie\\Adelie.exe",+ openAtLogin: true,+ });+ expect(settings).toEqual({+ openAtLogin: true,+ path: "C:\\Users\\me\\AppData\\Local\\Programs\\Adelie\\Adelie.exe",+ args: ["--started-at-login"],+ enabled: true,+ name: "Adelie",+ });+ });++ it("clears a Task Manager 'disabled' even when turning the entry off", () => {+ // `enabled: true` is what removes the StartupApproved record; Electron ignores it when+ // openAtLogin is false (it deletes both values in that branch), but the field stays set so+ // the shape does not depend on which branch runs.+ expect(+ loginItemWrite({ name: "Adelie", execPath: "C:\\Adelie.exe", openAtLogin: false }),+ ).toEqual({+ openAtLogin: false,+ path: "C:\\Adelie.exe",+ args: ["--started-at-login"],+ enabled: true,+ name: "Adelie",+ });+ });+});++describe("loginItemStatusOf", () => {+ it("reports unsupported where there is no entry to manage, whatever the settings say", () => {+ expect(loginItemStatusOf({ supported: false, executableWillLaunchAtLogin: true })).toEqual({+ supported: false,+ openAtLogin: false,+ });+ });++ it("reports what Windows would really do", () => {+ expect(loginItemStatusOf({ supported: true, executableWillLaunchAtLogin: true })).toEqual({+ supported: true,+ openAtLogin: true,+ });+ // The user switched the entry off in Task Manager › Startup apps: enabled is false, so the+ // row shows off — which is the honest reading, the entry being registered notwithstanding.+ expect(loginItemStatusOf({ supported: true, executableWillLaunchAtLogin: false })).toEqual({+ supported: true,+ openAtLogin: false,+ });+ });+});++describe("the uninstaller", () => {+ it("deletes exactly the value the shell registers, both halves of it", () => {+ // The entry is written under the app's own name (loginItemWrite's `name`, which main.ts takes+ // from appIdentity), and the uninstaller deletes one literal — nothing at build time compares+ // the two, so a rename on either side would leave a dead row in Task Manager › Startup apps+ // that nothing in the product can remove.+ const nsh = fs.readFileSync(+ path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "build", "installer.nsh"),+ "utf8",+ );+ const name = appIdentity("release").name;+ expect(nsh).toContain(+ `DeleteRegValue HKCU "Software\\Microsoft\\Windows\\CurrentVersion\\Run" "${name}"`,+ );+ // The StartupApproved half too: left behind, it would apply to whatever a later install+ // registers under the same name.+ expect(nsh).toContain(`StartupApproved\\Run" "${name}"`);+ });+});++describe("the Appearance switch on the wire", () => {+ it("wraps the status for the push to the page", () => {+ expect(loginItemStatusMessage({ supported: true, openAtLogin: false })).toEqual({+ type: "desktop-login-item-status",+ status: { supported: true, openAtLogin: false },+ });+ });++ it("reads a command frame, and nothing else", () => {+ expect(+ parseLoginItemCommand({ type: "desktop-login-item-command", openAtLogin: true }),+ ).toEqual({ openAtLogin: true });+ expect(+ parseLoginItemCommand({ type: "desktop-login-item-command", openAtLogin: false }),+ ).toEqual({ openAtLogin: false });+ // A frame carrying nothing this build understands is still a login-item command, and an empty+ // patch changes nothing; only a frame that is not one at all reads as null.+ expect(parseLoginItemCommand({ type: "desktop-login-item-command" })).toEqual({});+ expect(+ parseLoginItemCommand({ type: "desktop-login-item-command", openAtLogin: "yes" }),+ ).toEqual({});+ // The same port carries the tray's and the pet's frames; this reader must not answer to one.+ expect(parseLoginItemCommand({ type: "desktop-tray-command", showTrayIcon: true })).toBeNull();+ expect(parseLoginItemCommand(null)).toBeNull();+ expect(parseLoginItemCommand("desktop-login-item-command")).toBeNull();+ });+});diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 927f706e..c621c5fe 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -5035,6 +5035,53 @@ export interface DesktopPetCommandMessage {showPet?: boolean;}+// Windows login item (desktop mode, Windows only)+//+// Whether Windows itself starts Adelie when the user signs in. The switch rides the same+// utilityProcess message channel as the tray icon above: the shell reports the state ITS OPERATING+// SYSTEM holds, the page reads it at GET /api/desktop/login-item and writes through PUT, which is+// relayed back.+//+// WHAT TRAVELS IS WINDOWS' OWN RECORD, not a preference of ours, and `supported` travels with it:+// the entry can be turned off from Task Manager › Startup apps and read back, and a shell that has+// no login item to manage (Linux today) says so rather than offering a switch that writes nothing.+// See the shell's src/login-item.ts for why there is no preference file beside it.++/** What the shell's operating system currently says about starting Adelie when the user signs in. */+export interface DesktopLoginItemStatus {+ /** This build has a login item to manage at all — the shell runs on Windows. */+ supported: boolean;+ /** The app is registered to start at sign-in, and that entry is not disabled. */+ openAtLogin: boolean;+}++/** What one PUT asks the shell to change; one optional field, the shape the tray patch beside it uses. */+export interface DesktopLoginItemPatch {+ openAtLogin?: boolean;+}++/**+ * GET / PUT /api/desktop/login-item (desktop-shell sessions only): the sign-in switch.+ * `status` is null until the shell's first push lands (a beat after server start). A page that+ * finds null — or a status with `supported: false` — draws no row, which is the honest rendering+ * for every platform this build cannot answer for.+ */+export interface DesktopLoginItemStatusResponse {+ status: DesktopLoginItemStatus | null;+}++/** Shell → server push over the utilityProcess message channel. */+export interface DesktopLoginItemStatusMessage {+ type: "desktop-login-item-status";+ status: DesktopLoginItemStatus;+}++/** Server → shell command over the utilityProcess message channel (relayed from the PUT above). */+export interface DesktopLoginItemCommandMessage {+ type: "desktop-login-item-command";+ openAtLogin?: 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 9aca2b5e..eeedaef0 100644--- a/packages/server/src/hmr/capabilities.ts+++ b/packages/server/src/hmr/capabilities.ts@@ -440,6 +440,10 @@ export type DesktopApi = Pick<| "setTrayStatus"| "onTrayCommand"| "requestTrayCommand"+ | "getLoginItemStatus"+ | "setLoginItemStatus"+ | "onLoginItemCommand"+ | "requestLoginItemCommand"| "getPetStatus"| "setPetStatus"| "onPetCommand"diff --git a/packages/server/src/http/routes/desktop.ts b/packages/server/src/http/routes/desktop.tsindex b1e7a33b..dba017b9 100644--- a/packages/server/src/http/routes/desktop.ts+++ b/packages/server/src/http/routes/desktop.ts@@ -1,7 +1,8 @@/*** Desktop-mode routes: POST /api/desktop/shutdown, the client-update relay under* /api/desktop/update, the tray-icon preference at /api/desktop/tray, the pet-window- * preference at /api/desktop/pet, the Privacy & Security pane at+ * preference at /api/desktop/pet, the Windows sign-in switch at /api/desktop/login-item, the+ * Privacy & Security pane at* /api/desktop/privacy-settings, plus the shared desktop-mode guard that turns off* multi-user surfaces (see rejectInDesktopMode).*@@ -9,14 +10,16 @@* 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, pet and privacy-settings routes are- * called by the page, so their groups sit behind the cookie gate and are further restricted+ * cut off by the closing listener. The update, tray, pet, login-item 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 {+ DesktopLoginItemPatch,+ DesktopLoginItemStatusResponse,DesktopPetPatch,DesktopPetStatusResponse,DesktopTrayPatch,@@ -215,6 +218,49 @@ export function desktopPetRoutes(deps: DesktopRouteDeps): Hono<AppEnv> {return app;}+/**+ * Starting Adelie when the user signs in to Windows. Unlike the switches above, the state this+ * reads is not one the shell keeps: it is what Windows itself has recorded, so the shell reads it+ * back out of the operating system on every launch and whenever the switch is thrown. GET returns+ * that reading — null only until the shell's first push, and `supported: false` wherever there is+ * no sign-in entry to manage (every non-Windows platform), which the page renders as no row at all.+ * PUT relays the patch; like the tray and the pet, it acknowledges and the push is what tells the+ * truth. A patch that is empty, or whose field is not a boolean, is a caller bug and never reaches+ * the shell. The members are optional on a layer older than this switch.+ */+export function desktopLoginItemRoutes(deps: DesktopRouteDeps): Hono<AppEnv> {+ const app = new Hono<AppEnv>();+ const refusal = "Starting at sign-in is managed from the desktop app's own window.";++ app.get("/", (c) => {+ const desktop = shellSessionOf(deps, c, refusal);+ const status = desktop.getLoginItemStatus?.() ?? null;+ return c.json({ status } satisfies DesktopLoginItemStatusResponse);+ });++ app.put("/", async (c) => {+ const desktop = shellSessionOf(deps, c, refusal);+ const body = (await c.req.json().catch(() => null)) as { openAtLogin?: unknown } | null;+ const patch: DesktopLoginItemPatch = {};+ if (body?.openAtLogin !== undefined) {+ if (typeof body.openAtLogin !== "boolean") {+ throw new HttpError(400, "invalid_open_at_login", "openAtLogin must be a boolean.");+ }+ patch.openAtLogin = body.openAtLogin;+ }+ // An empty patch is a caller bug, not a no-op worth relaying to the shell.+ if (patch.openAtLogin === undefined) {+ throw new HttpError(400, "empty_login_item_patch", "Pass openAtLogin.");+ }+ if (!desktop.requestLoginItemCommand?.(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@@ -304,6 +350,26 @@ export class DesktopPetRoutes {}}+@Component({+ contributes: {+ "HttpModule.routes": [+ {+ id: "DesktopLoginItemRoutes.routes",+ prefix: "/api/desktop/login-item",+ auth: "user",+ order: 10,+ },+ ],+ },+})+export class DesktopLoginItemRoutes {+ @Use() private readonly desktop!: Desktop;+ @Bind("DesktopLoginItemRoutes.routes") routes!: Hono<AppEnv>;+ setup() {+ this.routes = desktopLoginItemRoutes({ desktop: this.desktop.current() });+ }+}+@Component({contributes: {"HttpModule.routes": [diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.tsindex a6dc7077..b1a73073 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 {+ DesktopLoginItemRoutes,DesktopPetRoutes,DesktopPrivacySettingsRoutes,DesktopRoutes,@@ -467,6 +468,7 @@ export class CompanyModule {}DesktopUpdateRoutes,DesktopTrayRoutes,DesktopPetRoutes,+ DesktopLoginItemRoutes,DesktopPrivacySettingsRoutes,PluginRoutes,PluginRegistryRoutes,diff --git a/packages/server/src/services/desktop-service.ts b/packages/server/src/services/desktop-service.tsindex 21158f41..f5b628c5 100644--- a/packages/server/src/services/desktop-service.ts+++ b/packages/server/src/services/desktop-service.ts@@ -15,9 +15,10 @@* Comparisons hash both sides first so timingSafeEqual gets equal-length buffers.** 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, /api/desktop/tray or /api/desktop/pet and writes back a command that+ * tray icon, the pet window and the Windows login item. 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, /api/desktop/tray, /api/desktop/pet or+ * /api/desktop/login-item 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.*@@ -28,6 +29,8 @@import { createHash, timingSafeEqual } from "node:crypto";import type {DesktopFolderAccessResult,+ DesktopLoginItemPatch,+ DesktopLoginItemStatus,DesktopPetPatch,DesktopPetStatus,DesktopPrivacyPane,@@ -158,6 +161,39 @@ export class DesktopService {return true;}+ // --- login-item relay (Windows) --------------------------------------------++ private loginItemStatus: DesktopLoginItemStatus | null = null;+ private loginItemCommandSender: ((patch: DesktopLoginItemPatch) => void) | null = null;++ /**+ * What Windows currently says about starting the app when the user signs in; null until the+ * shell's first push lands. Where the tray and the pet fall back to their own defaults, this one+ * has none to fall back to and does not invent one: the state belongs to the operating system,+ * and the page draws its row only for a status a shell has actually confirmed `supported`. An+ * absent status is therefore rendered as no row at all rather than as a wrong switch.+ */+ getLoginItemStatus(): DesktopLoginItemStatus | null {+ return this.loginItemStatus;+ }++ /** index.ts stores each shell push here (already validated at the message port). */+ setLoginItemStatus(status: DesktopLoginItemStatus): void {+ this.loginItemStatus = status;+ }++ /** index.ts registers the message-port sender; absent outside a shell-forked process. */+ onLoginItemCommand(sender: (patch: DesktopLoginItemPatch) => void): void {+ this.loginItemCommandSender = sender;+ }++ /** Invoked by the login-item route; false when no shell port is wired (tests, plain runs). */+ requestLoginItemCommand(patch: DesktopLoginItemPatch): boolean {+ if (!this.loginItemCommandSender) return false;+ this.loginItemCommandSender(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 38e70aca..30557857 100644--- a/packages/server/src/services/desktop-update-port.ts+++ b/packages/server/src/services/desktop-update-port.ts@@ -1,23 +1,27 @@/**- * Shell↔server message-port relay (desktop mode only): client updates, the tray icon, and the- * Workspace picker's macOS folder access.+ * Shell↔server message-port relay (desktop mode only): client updates, the tray icon, the desktop+ * pet, the Windows login item, and the Workspace picker's macOS folder access.** Under the desktop shell this server runs as an Electron utilityProcess, which injects* `process.parentPort` — an EventEmitter-ish port to the shell. The shell pushes its- * updater snapshot and its tray state through it, and the routes forward the page's- * check/download/install commands and its tray switch back. Folder access is the one+ * updater snapshot, its tray state, its pet state and what Windows says about starting the app at+ * sign-in through it, and the routes forward the page's check/download/install commands, its tray+ * and pet switches and its sign-in switch back. Folder access is the one* request that is answered: the shell reads the folder and replies under the request's id.* Under a plain `penguin server|web` run the port does not exist and this module wires* nothing; those routes then answer 503 `shell_unreachable`.*- * Wire shapes live in api/types.ts (the updater, tray and folder-access messages) so the- * shell imports the same contract.+ * Wire shapes live in api/types.ts (the updater, tray, pet, login-item and folder-access messages)+ * so the shell imports the same contract.*/import { randomUUID } from "node:crypto";import type {DesktopFolderAccessMessage,DesktopFolderAccessResult,DesktopFolderAccessResultMessage,+ DesktopLoginItemCommandMessage,+ DesktopLoginItemStatus,+ DesktopLoginItemStatusMessage,DesktopOpenPrivacySettingsMessage,DesktopPetCommandMessage,DesktopPetStatus,@@ -100,6 +104,19 @@ export function parsePetStatusMessage(data: unknown): DesktopPetStatus | null {return { showPet: status.showPet };}+/** Validates one shell login-item push. Same rule as the tray's: strict on the discriminator and on every field it carries. */+export function parseLoginItemStatusMessage(data: unknown): DesktopLoginItemStatus | null {+ if (typeof data !== "object" || data === null) return null;+ const msg = data as Partial<DesktopLoginItemStatusMessage>;+ if (msg.type !== "desktop-login-item-status") return null;+ const status = msg.status as Partial<DesktopLoginItemStatus> | undefined;+ if (typeof status !== "object" || status === null) return null;+ // Both fields, with no default for either: a push that cannot say whether the platform is even+ // supported would have the page draw a switch it cannot promise anything about.+ if (typeof status.supported !== "boolean" || typeof status.openAtLogin !== "boolean") return null;+ return { supported: status.supported, openAtLogin: status.openAtLogin };+}+/** Validates one shell reply to a folder-access request; null when the frame is not one. */export function parseFolderAccessResultMessage(data: unknown,@@ -143,6 +160,11 @@ export function wireShellUpdatePort(desktop: DesktopService, port: ShellPort): vdesktop.setPetStatus(pet);return;}+ const loginItem = parseLoginItemStatusMessage(e.data);+ if (loginItem !== null) {+ desktop.setLoginItemStatus(loginItem);+ 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);@@ -168,6 +190,12 @@ export function wireShellUpdatePort(desktop: DesktopService, port: ShellPort): v...patch,} satisfies DesktopPetCommandMessage);});+ desktop.onLoginItemCommand((patch) => {+ port.postMessage({+ type: "desktop-login-item-command",+ ...patch,+ } satisfies DesktopLoginItemCommandMessage);+ });desktop.onFolderAccessRequest((path) =>new Promise<DesktopFolderAccessResult | null>((resolve) => {diff --git a/packages/server/test/desktop-login-item.test.ts b/packages/server/test/desktop-login-item.test.tsnew file mode 100644index 00000000..16662830--- /dev/null+++ b/packages/server/test/desktop-login-item.test.ts@@ -0,0 +1,214 @@+/**+ * The sign-in entry relay: the /api/desktop/login-item routes (the shell window's sessions only),+ * and the shell port they ride.+ *+ * - The status reads as null before the shell's first push, then as what it pushed — including the+ * `supported: false` a non-Windows shell reports, which is not the same thing as silence.+ * - 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 status frame is read, and the two fields are both required: this switch is+ * the operating system's record, so a frame that cannot say whether it is even supported is+ * dropped rather than half-read.+ */+import { describe, expect, it } from "vitest";+import { createDesktopApp, createTestApp, desktopLoginCookie, loginAdmin } from "./helpers.js";+import type {+ DesktopLoginItemPatch,+ DesktopLoginItemStatusResponse,+ ErrorBody,+} from "../src/api/types.js";+import { DesktopService } from "../src/services/desktop-service.js";+import {+ parseLoginItemStatusMessage,+ 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/login-item", () => {+ it("serves null before the shell's first push, then the stored status", async () => {+ const t = await createDesktopApp();+ try {+ const cookie = await desktopLoginCookie(t.app);+ const before = await t.app.request("/api/desktop/login-item", { headers: { cookie } });+ expect(before.status).toBe(200);+ expect((await before.json()) as DesktopLoginItemStatusResponse).toEqual({ status: null });++ t.deps.desktop!.setLoginItemStatus({ supported: true, openAtLogin: true });+ const after = await t.app.request("/api/desktop/login-item", { headers: { cookie } });+ expect((await after.json()) as DesktopLoginItemStatusResponse).toEqual({+ status: { supported: true, openAtLogin: true },+ });++ // A Linux or macOS shell answers with `supported: false` rather than by staying quiet: the+ // page draws no row for either, and the two are the same to it, but the difference is what+ // a person reading the API (or a future platform) needs.+ t.deps.desktop!.setLoginItemStatus({ supported: false, openAtLogin: false });+ const elsewhere = await t.app.request("/api/desktop/login-item", { headers: { cookie } });+ expect((await elsewhere.json()) as DesktopLoginItemStatusResponse).toEqual({+ status: { supported: false, openAtLogin: false },+ });+ } 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/login-item", {+ 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/login-item", {+ headers: { cookie: admin.cookie },+ });+ expect(res.status).toBe(404);+ } finally {+ await t.cleanup();+ }+ });+});++describe("PUT /api/desktop/login-item", () => {+ 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: DesktopLoginItemPatch[] = [];+ t.deps.desktop!.onLoginItemCommand((patch) => sent.push(patch));++ const on = await t.app.request(+ "/api/desktop/login-item",+ put(cookie, '{"openAtLogin":true}'),+ );+ expect(on.status).toBe(202);+ const off = await t.app.request(+ "/api/desktop/login-item",+ put(cookie, '{"openAtLogin":false}'),+ );+ expect(off.status).toBe(202);+ expect(sent).toEqual([{ openAtLogin: true }, { openAtLogin: 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: DesktopLoginItemPatch[] = [];+ t.deps.desktop!.onLoginItemCommand((patch) => sent.push(patch));+ const cases: Array<[string, string]> = [+ ['{"openAtLogin":"on"}', "invalid_open_at_login"],+ ['{"openAtLogin":1}', "invalid_open_at_login"],+ ['{"openAtLogin":null}', "invalid_open_at_login"],+ // 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_login_item_patch"],+ ["not json", "empty_login_item_patch"],+ ];+ for (const [body, code] of cases) {+ const res = await t.app.request("/api/desktop/login-item", 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/login-item",+ put(admin.cookie, '{"openAtLogin":true}'),+ );+ expect(forbidden.status).toBe(403);++ const cookie = await desktopLoginCookie(t.app);+ const unreachable = await t.app.request(+ "/api/desktop/login-item",+ put(cookie, '{"openAtLogin":true}'),+ );+ expect(unreachable.status).toBe(503);+ expect(((await unreachable.json()) as ErrorBody).error.code).toBe("shell_unreachable");+ } finally {+ await t.cleanup();+ }+ });+});++describe("the login-item half of the shell port", () => {+ it("parses only well-formed status frames, with both fields present", () => {+ expect(+ parseLoginItemStatusMessage({+ type: "desktop-login-item-status",+ status: { supported: true, openAtLogin: false },+ }),+ ).toEqual({ supported: true, openAtLogin: false });+ expect(+ parseLoginItemStatusMessage({+ type: "desktop-login-item-status",+ status: { supported: false, openAtLogin: false },+ }),+ ).toEqual({ supported: false, openAtLogin: false });+ for (const data of [+ null,+ "status",+ {},+ { type: "desktop-login-item-status" },+ { type: "desktop-login-item-status", status: null },+ { type: "desktop-login-item-status", status: {} },+ { type: "desktop-login-item-status", status: { supported: true } },+ { type: "desktop-login-item-status", status: { openAtLogin: true } },+ { type: "desktop-login-item-status", status: { supported: true, openAtLogin: "yes" } },+ // The tray's frames ride the same port and must not be read as login-item ones.+ { type: "desktop-tray-status", status: { showTrayIcon: true, locale: "en" } },+ ]) {+ expect(parseLoginItemStatusMessage(data)).toBeNull();+ }+ });++ it("stores login-item pushes and posts its commands beside the others, on one port", () => {+ const desktop = new DesktopService("t");+ const port = new FakePort();+ wireShellUpdatePort(desktop, port);++ expect(desktop.getLoginItemStatus()).toBeNull();+ port.emit({+ type: "desktop-login-item-status",+ status: { supported: true, openAtLogin: true },+ });+ expect(desktop.getLoginItemStatus()).toEqual({ supported: true, openAtLogin: true });+ // A tray frame on the same port leaves the sign-in state alone, and vice versa.+ port.emit({ type: "desktop-tray-status", status: { showTrayIcon: false, locale: "zh" } });+ expect(desktop.getLoginItemStatus()).toEqual({ supported: true, openAtLogin: true });+ expect(desktop.getTrayStatus()).toEqual({ showTrayIcon: false, locale: "zh" });++ expect(desktop.requestLoginItemCommand({ openAtLogin: false })).toBe(true);+ expect(port.sent).toEqual([{ type: "desktop-login-item-command", openAtLogin: false }]);+ });+});diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 97b5f942..608786b4 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -228,6 +228,8 @@ import type {UpdateJobStatus,UpdateProfileRequest,UpdateProfileResponse,+ DesktopLoginItemPatch,+ DesktopLoginItemStatusResponse,DesktopPetPatch,DesktopPetStatusResponse,DesktopTrayPatch,@@ -2566,6 +2568,22 @@ export const getDesktopPet = () => apiFetch<DesktopPetStatusResponse>("/api/deskexport const setDesktopPet = (patch: DesktopPetPatch) =>apiFetch<void>("/api/desktop/pet", { method: "PUT", body: patch });+// Desktop sign-in entry (desktop-shell sessions only, Windows) --------------------------++/**+ * What Windows itself says about starting the app when the user signs in, as the shell last read+ * it. `status` is null until that first read lands, and `status.supported` is false wherever there+ * is no entry to manage (every non-Windows platform, and a dev shell) — both of which the+ * Appearance page renders as no row at all, because there is no honest default for a switch that+ * is really a registry value.+ */+export const getDesktopLoginItem = () =>+ apiFetch<DesktopLoginItemStatusResponse>("/api/desktop/login-item");++/** Relays the sign-in switch to the shell, which writes the entry and pushes back what Windows says. */+export const setDesktopLoginItem = (patch: DesktopLoginItemPatch) =>+ apiFetch<void>("/api/desktop/login-item", { 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/settings/appearance-section.tsx b/packages/web/src/features/settings/appearance-section.tsxindex 1e434b8f..cd8f1236 100644--- a/packages/web/src/features/settings/appearance-section.tsx+++ b/packages/web/src/features/settings/appearance-section.tsx@@ -327,6 +327,41 @@ export function AppearanceSection() {void api.setDesktopPet({ showPet: next }).catch(() => setShowPet(!next));};+ // Starting at sign-in. This one has no default to fall back on, so `null` — nothing read yet,+ // or a request that failed — draws no row at all, and neither does a shell that answers+ // `supported: false` (a non-Windows platform, or a dev shell). The state is Windows' own record+ // rather than a preference of ours: the shell reads it back out of the operating system, so a+ // switch the user turned off in Task Manager › Startup apps arrives here as off.+ const [startAtLogin, setStartAtLogin] = useState<boolean | null>(null);+ useEffect(() => {+ if (!offersShellChrome) return;+ let live = true;+ void api.getDesktopLoginItem().then(+ (res) => {+ if (live) setStartAtLogin(res.status?.supported === true ? res.status.openAtLogin : null);+ },+ () => {},+ );+ return () => {+ live = false;+ };+ }, [offersShellChrome]);+ // Optimistic like the two above, but re-read afterwards: the reply to the write is only an+ // acknowledgement, and Windows' record is what this row is meant to show — the entry can be+ // refused by policy, and a locked-down machine can leave it disabled however often we ask.+ const changeStartAtLogin = (next: boolean): void => {+ setStartAtLogin(next);+ void api.setDesktopLoginItem({ openAtLogin: next }).then(+ () => {+ void api.getDesktopLoginItem().then(+ (res) => setStartAtLogin(res.status?.supported === true ? res.status.openAtLogin : null),+ () => {},+ );+ },+ () => setStartAtLogin(!next),+ );+ };+const themeOptions: ReadonlyArray<{ value: ThemeMode; label: string }> = [{ value: "light", label: S.settings.themeLight },{ value: "dark", label: S.settings.themeDark },@@ -431,6 +466,14 @@ export function AppearanceSection() {onChange={changeTrayIcon}/>)}+ {offersShellChrome && startAtLogin !== null && (+ <ToggleRow+ label={S.settings.startAtLogin}+ info={S.settings.startAtLoginInfo}+ checked={startAtLogin}+ onChange={changeStartAtLogin}+ />+ )}{offersShellChrome && (<ToggleRowlabel={S.settings.showPet}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex e9ece75c..889b3759 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -853,6 +853,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 (Windows): the sign-in entry; drawn only where the shell answers `supported`. */+ startAtLogin: "Start when you sign in",+ startAtLoginInfo:+ "Starts Adelie when you sign in to Windows, waiting in the tray without opening a window — click the tray icon to open it. Off by default. The entry is registered for the current user (the Run key under HKCU), so it needs no administrator rights and installs no service. Disable it in Task Manager › Startup apps and this switch shows off to match; uninstalling removes it.",/** Desktop shell only: the companion window at /pet. */showPet: "Desktop pet",showPetInfo:diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 87feccdd..88f33698 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -908,6 +908,13 @@ export const zh = {trayIcon: "托盘图标",trayIconInfo:"桌面应用运行期间在系统托盘(Windows 通知区、macOS 菜单栏、Linux 托盘)常驻一个图标,点击即可回到窗口,右键可开新会话或退出。默认开启;关掉后图标立即消失,无需重启,此时关闭窗口不再收进托盘:macOS 应用留在 Dock,Windows 与 Linux 关窗即退出。",+ /**+ * Desktop shell only (Windows): the sign-in entry. The row is drawn only for a shell that+ * answers `supported`, and its value is what Windows itself holds — see the switch's note.+ */+ startAtLogin: "开机自启动",+ startAtLoginInfo:+ "登录 Windows 后自动启动 Adelie,开机那一次只在托盘待命、不弹窗,点托盘图标就能打开窗口。默认关闭;这条登记写在当前用户的启动项里(HKCU 的 Run 键),不需要管理员权限,不上系统服务。你在「任务管理器 › 启动应用」里禁用它,这里也会如实显示成关闭;卸载时会一并删掉。",/** Desktop shell only: the companion window at /pet. */showPet: "桌面宠物",showPetInfo: