A local-first multi-agent app development platform, built on PenguinHarness
fix(desktop,server,web): the desktop window signs itself in instead of asking for a password (#811)
Yaowei Zheng610577f0e4a5
diff --git a/changelog/unreleased/2026-09-20-desktop-attach-sign-in.md b/changelog/unreleased/2026-09-20-desktop-attach-sign-in.mdnew file mode 100644index 00000000..74b08d6c--- /dev/null+++ b/changelog/unreleased/2026-09-20-desktop-attach-sign-in.md@@ -0,0 +1,26 @@+# The desktop app signs its own window in when another server holds the data root++- **Date:** 2026-09-20+- **Type:** fix+- **Scope:** `desktop`, `server`, `web`, `docs`+- **PR:** [#811](https://github.com/Prism-Shadow/penguin-harness/pull/811)++[中文版](2026-09-20-desktop-attach-sign-in.zh.md)++A desktop app that found another server already holding its data root — a `penguin web` or `penguin server` instance, or an older copy of the app still running — attached to that instance and left the window on the App's sign-in page. The password that page asks for does not exist: the desktop seeds its admin with a random value that is hashed and discarded unseen, so the only way on was `penguin server reset-admin-password` from a terminal. The shell now signs the window in itself, by minting a session in the data root it owns and setting the cookie for it, and answers any later arrival at the sign-in page the same way.++## Details++- `attach-session.ts` plans the sign-in: it calls the server package's `mintApiToken` on the data root and returns either the cookie to set or a failure to show. The minter is a parameter, so the module stays pure and every outcome is covered by tests.+- The minted session lasts thirty days, the same span an ordinary browser sign-in gets. Shorter sessions never reach the server's renewal window, so they expire on schedule however much the window is used.+- Attach mode sets the cookie before the window opens, then loads the app root. The same attempt runs from the main window's navigation events, so an expired session and a failed claim land signed in again instead of on the sign-in page. One attempt per arrival, re-armed only by reaching a page the App serves to a signed-in window.+- Signing out stands. The shell watches the App's request to end the session and leaves the sign-in page it leads to alone, until something signs in again or the app is launched again — every other arrival there is still answered.+- `mintApiToken` took a `via` option for the session's kind, defaulting to `cli` so `penguin auth token` is unchanged; the desktop mints `desktop`, which is what the App reads back to leave the current-password field out of its change-password form.+- The change-password form now decides whether to ask for the current password by the same pair the server's gate reads — a `desktop` session on a server started in desktop mode — so the field stops disappearing where the server still requires it.+- When minting fails — a `web.db` owned by another OS account, one written by another release, or a data root with no `web.db` at all — a dialog names the data root, the port and pid of the server holding it, the reason the minter gave, and the `penguin server reset-admin-password` rescue, then continues to the sign-in page.+- A child window sent to the sign-in page by a dying session closes instead of showing it, which returns a detached terminal's tab to the dock in the main window rather than stranding it behind a form it cannot use.+- The session cookie's name is a copy of the server's `SESSION_COOKIE`, pinned to that declaration by a test.+- The desktop quickstart gained a paragraph on what happens when another server owns the data root, and on what to do if a window still shows the login page.+- The initial-password trail keeps quiet in any window the shell signed in: it asks its reader to+ change a password they hold, and a shell-minted session holds none and cannot set one on a server it+ only attached to. The terminal that started that server saw the same notice at startup.diff --git a/changelog/unreleased/2026-09-20-desktop-attach-sign-in.zh.md b/changelog/unreleased/2026-09-20-desktop-attach-sign-in.zh.mdnew file mode 100644index 00000000..d8121bf0--- /dev/null+++ b/changelog/unreleased/2026-09-20-desktop-attach-sign-in.zh.md@@ -0,0 +1,24 @@+# 数据目录被别的服务端占用时,桌面应用自己完成窗口登录++- **Date:** 2026-09-20+- **Type:** fix+- **Scope:** `desktop`, `server`, `web`, `docs`+- **PR:** [#811](https://github.com/Prism-Shadow/penguin-harness/pull/811)++[English](2026-09-20-desktop-attach-sign-in.md)++桌面应用发现数据目录已被另一个服务端占用时——`penguin web` 或 `penguin server` 实例,或仍在运行的旧版应用——会附着到那个实例,并把窗口留在 App 的登录页上。而那个页面要的密码根本不存在:桌面端为 admin 生成的是一个随机值,哈希后即丢弃,从不显示,于是唯一的出路是去终端跑 `penguin server reset-admin-password`。现在壳自己完成登录:在它所拥有的数据目录里签发一个会话,并为窗口设置对应的 Cookie;此后窗口每次再落到登录页,也照此处理。++## 细节++- `attach-session.ts` 负责规划这次登录:它对数据目录调用 server 包的 `mintApiToken`,返回要设置的 Cookie,或一份可供展示的失败说明。签发函数是参数传入的,模块因此保持纯粹,每种结果都由测试覆盖。+- 签发的会话有效期为三十天,与普通浏览器登录相同。更短的会话够不到服务端的续期窗口,无论窗口怎么使用都会按时过期。+- 附着模式在开窗之前设置 Cookie,然后加载应用根地址。同一套尝试也挂在主窗口的导航事件上,因此会话过期与 claim 失败都会重新变成已登录状态,而不是停在登录页。每次抵达登录页只尝试一次,只有窗口到达 App 只对已登录窗口提供的页面时才重新武装。+- 退出登录的效果予以保留。壳会观察 App 结束会话的那个请求,并放任随之而来的登录页不管,直到再次有人登录、或应用重新启动为止——其余各种抵达登录页的情形照常处理。+- `mintApiToken` 新增 `via` 选项标记会话的种类,默认仍为 `cli`,`penguin auth token` 的行为不变;桌面端签发 `desktop`,App 据此在修改密码表单里省去当前密码一栏。+- 修改密码表单是否索取当前密码,改用与服务端判定相同的组合条件——会话为 `desktop`,且服务端以桌面模式启动——于是在服务端仍要求旧密码的场合,这一栏不会再消失。+- 签发失败时——`web.db` 属于另一个操作系统账号、由另一个版本写入,或数据目录里根本没有 `web.db`——弹窗会给出数据目录、占用它的服务端的端口与 pid、签发失败的原因,以及 `penguin server reset-admin-password` 这条补救命令,然后继续前往登录页。+- 会话失效把子窗口送去登录页时,子窗口直接关闭而不再显示登录页:分离出去的终端标签因此回到主窗口的停靠面板,而不是被困在一张用不了的表单后面。+- 会话 Cookie 的名字是服务端 `SESSION_COOKIE` 的一份副本,由一条测试把两者钉在一起。+- 桌面端快速开始文档新增一段,说明数据目录被别的服务端占用时会发生什么,以及窗口仍然出现登录页时该怎么做。+- 初始密码提示条在壳签进来的窗口里不再出现:它提醒的是握有那个密码的人,而壳自签的会话既没有那个密码、也改不了它;该提醒的人在起那台 server 的终端里已经看到了开机提示。diff --git a/packages/desktop/src/attach-session.ts b/packages/desktop/src/attach-session.tsnew file mode 100644index 00000000..2143a7d7--- /dev/null+++ b/packages/desktop/src/attach-session.ts@@ -0,0 +1,265 @@+/**+ * Signing the shell's own window in, for a server the shell did not spawn.+ *+ * The one-shot PENGUIN_DESKTOP_TOKEN means something only to the server this shell started,+ * so a window pointed at any other instance — attach mode, where another server already+ * holds the data root's lock — landed on the App's sign-in page. That page is a dead end+ * here: the desktop seeds its admin with a random password that is hashed and discarded+ * unseen, so there is nothing to type and nothing to look up.+ *+ * The way out is the authorization the shell already holds. Being able to read and write a+ * data root is this product's authorization boundary — that directory holds every credential+ * a session could reach — so the shell mints a session row in the root's own web.db and hands+ * the window the cookie for it, the same move `penguin auth token` makes for a script. A root+ * it cannot mint in says so in one of a few recognizable ways, and each of them is something+ * the person at the keyboard can act on, so the failures come back as text for a dialog+ * rather than as an exception.+ *+ * Pure, and free of Electron: the minter is a parameter, so the tests drive every outcome.+ */+import type { MintedVia, MintTokenResult } from "@prismshadow/penguin-server/auth-token";+import { isAppUrl } from "./util.js";++/**+ * The session cookie's name. Duplicated from the server's SESSION_COOKIE rather than+ * imported: the shell mints through the one server module that deliberately needs no running+ * server, and re-exporting the name from it would drag the HTTP layer the name belongs to+ * into this bundle and the CLI's. A test pins the two values together instead.+ */+export const SESSION_COOKIE = "penguin_session";++/**+ * How long a minted session lives: thirty days, which is both what the server gives an+ * ordinary browser sign-in (config.ts, authSessionTtlMs) and the ceiling the minter enforces+ * (CLI_TOKEN_MAX_TTL_MS). The minter's own default of one hour (CLI_TOKEN_TTL_MS) is right+ * for a token in a file and wrong here, for a reason that is easy to miss: the server slides+ * a session's expiry only when the session's whole span reaches the renewal window+ * (authenticateWithMeta against authSessionRenewMs, a day under the TTL), so a one-hour row+ * expires on the hour however much the window is used. This cookie backs a window someone+ * leaves open for weeks. At thirty days the row renews in place once it is a day old, exactly+ * as a browser session does; at anything shorter the window would drop back to the sign-in+ * page on a timer and be rescued again, leaving a dead row behind each time.+ */+export const ATTACH_SESSION_TTL_MS = 30 * 24 * 60 * 60_000;++/** What this module needs of `mintApiToken`, so a test can be the minter. */+export type SessionMinter = (+ root: string,+ opts: { ttlMs: number; via: MintedVia },+) => MintTokenResult;++/**+ * A cookie in the shape Electron's `cookies.set` takes. `expirationDate` (seconds since the+ * epoch) comes from the minted row: the row carries the authoritative expiry, and a cookie+ * outliving it would leave the window holding a credential the server has already dropped.+ */+export interface SessionCookie {+ url: string;+ name: string;+ value: string;+ path: string;+ httpOnly: boolean;+ sameSite: "lax";+ expirationDate?: number;+}++/** Why the shell could not sign itself in. `detail` is prose, ready for a dialog. */+export interface SignInFailure {+ /** `no_server`: the root holds no web.db. `failed`: the mint itself refused, with a reason. */+ reason: "no_server" | "failed";+ detail: string;+}++/** What the shell should do about the window: set this cookie, or show this failure. */+export type SignInPlan =+ { outcome: "cookie"; cookie: SessionCookie } | { outcome: "failed"; failure: SignInFailure };++/**+ * Plans a sign-in on `origin` for the server keeping its data in `root`. The origin decides+ * only where the cookie goes; the authorization comes entirely from the root, which is why+ * this works against a server the shell has no other relationship with.+ */+export function planSignIn(opts: {+ root: string;+ origin: string;+ mint: SessionMinter;+}): SignInPlan {+ // `desktop`, not the minter's default `cli`: the row records what this session actually is,+ // the desktop shell's own window, which is what the App reads back to leave the current+ // password out of its change-password form — an account the shell created has a password+ // nobody has ever seen.+ const minted = opts.mint(opts.root, { ttlMs: ATTACH_SESSION_TTL_MS, via: "desktop" });+ if (minted.outcome === "no_server") {+ return {+ outcome: "failed",+ failure: {+ reason: "no_server",+ detail:+ `There is no web.db in ${opts.root}, so that data root holds no account to sign in ` ++ `as. The server this window is talking to keeps its data elsewhere — PENGUIN_HOME ` ++ `or PENGUIN_WEB_DB points it somewhere this app is not looking.`,+ },+ };+ }+ if (minted.outcome === "failed") {+ // The minter's own explanation: a database owned by another OS account, or one an older+ // release wrote. Passed through whole, because it already names the file and the fix.+ return { outcome: "failed", failure: { reason: "failed", detail: minted.detail } };+ }+ const expiresAt = Date.parse(minted.expiresAt);+ return {+ outcome: "cookie",+ cookie: {+ url: `${opts.origin}/`,+ name: SESSION_COOKIE,+ value: minted.token,+ path: "/",+ httpOnly: true,+ sameSite: "lax",+ // An unreadable expiry would be a server bug, and a cookie without one lasts only as+ // long as the window — which fails towards asking again, not towards never expiring.+ ...(Number.isFinite(expiresAt) ? { expirationDate: Math.floor(expiresAt / 1000) } : {}),+ },+ };+}++/** The server holding the data root, as its lock records it. */+export interface OtherServer {+ pid: number;+ port: number;+}++/** A message box, in the parts Electron's dialog takes. */+export interface SignInDialog {+ message: string;+ detail: string;+ buttons: string[];+}++/**+ * The dialog raised when the shell could not sign its own window in. It has to answer three+ * questions at once, because the person seeing it did nothing to provoke it: which data root+ * and which process this is about, why the automatic sign-in did not happen, and what to do+ * about a sign-in page whose password was never shown to anyone. The single button is the+ * honest set of choices — the window is going to the sign-in page either way.+ */+export function signInFailureDialog(opts: {+ dataRoot: string;+ other: OtherServer | null;+ failure: SignInFailure;+}): SignInDialog {+ const lines = [+ `Data root: ${opts.dataRoot}`,+ ...(opts.other !== null+ ? [`Server using it: port ${opts.other.port}, process ${opts.other.pid}`]+ : []),+ "",+ opts.failure.detail,+ "",+ "This app normally signs its own window in by writing a session into that data root, so " ++ "it never asks for a password — the one it created for itself is random and was never " ++ "shown. This window will fall back to the sign-in page, where that password is of no use.",+ "",+ "To get a password you can use, stop the server above and run:",+ "",+ " penguin server reset-admin-password",+ ];+ return {+ message:+ opts.other !== null+ ? "Another server is using this data root, and the window could not sign itself in."+ : "The window could not sign itself in.",+ detail: lines.join("\n"),+ buttons: ["Continue to the sign-in page"],+ };+}++/**+ * The App's sign-in page. Everything that fails to authenticate arrives here: the App's own+ * route guard replaces the URL with it whenever /api/me says nobody is signed in, and the+ * server redirects a failed claim to it. Watching for the path is therefore a catch-all, and+ * costs one comparison per navigation.+ */+const LOGIN_PATH = "/login";++/**+ * Whether a navigation put the window on the sign-in page. The query string is ignored — the+ * server appends `?claimFailed=…` on its way here, and the App strips it a moment later — but+ * the path is matched whole, so a page merely named after it is not mistaken for it.+ */+export function isLoginPageUrl(url: string, origin: string | null): boolean {+ if (!isAppUrl(url, origin)) return false;+ const { pathname } = new URL(url);+ return pathname === LOGIN_PATH || pathname === `${LOGIN_PATH}/`;+}++/** What to do about the page the window has landed on. */+export type SignInMove = "rescue" | "leave";++/**+ * Decides which arrivals at the sign-in page the shell answers with a session.+ *+ * Two things must not happen, and they pull in opposite directions, which is why this is a+ * state machine and not a condition:+ *+ * - A data root that cannot mint must not loop. One attempt answers a stay on the sign-in+ * page; it is re-armed only by the window reaching a page the App serves to a signed-in+ * window, since that is the only evidence the last attempt took. The URL the shell loads+ * itself after an attempt is not such evidence, so it is excluded by name.+ * - **A sign-out must stick.** It is the one arrival at the sign-in page that is a decision+ * rather than a failure, and from outside the page it looks exactly like an expired+ * session — so the shell is told about it separately, by watching the request the App+ * makes to end the session. Do not delete this branch on the grounds that the rescue+ * ought to cover every route to the sign-in page: cover this one and Sign out becomes a+ * no-op, with no way to hand the machine to someone else. The suppression lasts until+ * something signs in again, or until the next launch, which is where this state begins.+ */+export interface SignInGuard {+ /** Reports where the window has landed, and gets the move for it. */+ arrived(url: string, origin: string | null): SignInMove;+ /**+ * Records an attempt the shell has made, and the URL it is loading next (null when it+ * loads nothing, because the window is already on the page it would land on).+ */+ tried(landingUrl: string | null): void;+ /** Records that the App has ended the session on purpose. */+ signedOut(): void;+}++/** A guard with no history: one launch of the app, one fresh start for all of the above. */+export function createSignInGuard(): SignInGuard {+ /** An attempt has answered the window's current stay on the sign-in page. */+ let attempted = false;+ /** The session was ended on purpose, and nothing has signed in since. */+ let signOutRequested = false;+ /** A URL the shell is loading of its own accord; arriving there is not the App's doing. */+ let shellLoad: string | null = null;+ return {+ arrived(url, origin) {+ if (isLoginPageUrl(url, origin)) {+ if (signOutRequested || attempted) return "leave";+ // Marked here as well as in `tried`, so a caller that never reports back still gets+ // one attempt rather than one per navigation.+ attempted = true;+ return "rescue";+ }+ if (url === shellLoad) {+ shellLoad = null;+ return "leave";+ }+ // Any other page of the App is served to signed-in windows only, so the window is in:+ // the next arrival at the sign-in page is a new situation, and a sign-out that was+ // honored is over.+ attempted = false;+ signOutRequested = false;+ return "leave";+ },+ tried(landingUrl) {+ attempted = true;+ shellLoad = landingUrl;+ },+ signedOut() {+ signOutRequested = true;+ },+ };+}diff --git a/packages/desktop/src/main.ts b/packages/desktop/src/main.tsindex 7599d7f6..048719d7 100644--- a/packages/desktop/src/main.ts+++ b/packages/desktop/src/main.ts@@ -17,7 +17,12 @@* no node integration); every capability flows through the server's HTTP API.** Attach mode: when a live server (e.g. `penguin web`) already owns the data root, the- * window loads that instance instead — normal login page, deliberate degradation.+ * window loads that instance instead. The one-shot token buys nothing there, so the shell+ * signs the window in the other way it is entitled to — a session minted straight into the+ * data root it owns (see attach-session.ts) — and the same move answers any later arrival at+ * the sign-in page, which has no password anyone could type. Signing out is the exception:+ * it is a decision rather than a failure, so it is left to stand until the next sign-in or+ * the next launch.** Tray: a system-tray icon is shown for as long as the app runs, and by default closing the* window only hides it, so the server and its background tasks keep running (see tray.ts;@@ -47,11 +52,20 @@import fs from "node:fs";import os from "node:os";import path from "node:path";-import { app, BrowserWindow, dialog, shell } from "electron";+import { app, BrowserWindow, dialog, session, shell } from "electron";import type { WindowOpenHandlerResponse } from "electron";import { resolveRoot } from "@prismshadow/penguin-core";+import { mintApiToken } from "@prismshadow/penguin-server/auth-token";import { liveServerLock } from "@prismshadow/penguin-server/lock";+import type { ServerLock } from "@prismshadow/penguin-server/lock";import { appIdentity, desktopDataRoot, resolveProfile } from "./app-identity.js";+import {+ createSignInGuard,+ isLoginPageUrl,+ planSignIn,+ signInFailureDialog,+} from "./attach-session.js";+import type { SignInFailure } from "./attach-session.js";import { embeddedCliEntry } from "./launcher.js";import { webDistEntry, webDistFor } from "./web-dist.js";import { resolveTrayIcon, resolveWindowIcon } from "./app-icon.js";@@ -218,6 +232,16 @@ function createWindow(url: string): void {openInSystem(target);}});+ // The catch-all for every route to the sign-in page — an attached instance that never saw+ // this shell's token, a session that lapsed, a claim that failed. The page asks for a+ // password this installation does not have, so the shell answers it the way it answers+ // attach mode (see signInFromDataRoot). Both events are needed: the App routes to the+ // sign-in page within the loaded page, and the server redirects to it across a load.+ win.webContents.on("did-navigate", (_event, url) => onMainWindowNavigated(url));+ win.webContents.on("did-navigate-in-page", (_event, url, isMainFrame) => {+ if (isMainFrame) onMainWindowNavigated(url);+ });+ watchForSignOut(win);// The page's renderer died (the app-level handler below logs why): reload it, after a pause// that grows while it keeps dying, so a page that crashes as it loads cannot spin.const target = win;@@ -303,6 +327,20 @@ function guardOpenedWindow(): void {child.webContents.setWindowOpenHandler(({ url: target }) => openWindowFor(target, iconPath));child.webContents.on("did-create-window", (next) => guardOpenedWindow(next, iconPath, false));+ // A session that dies while a child window is open sends that window to the sign-in page+ // too — the App's guard redirects on the first 401, wherever it is rendered. A sign-in form+ // is of no use in a subordinate surface: there is no password to type, and signing back in+ // is the main window's business, which it now does by itself. So the child closes instead,+ // which for a detached terminal returns its tab to the dock in the main window rather than+ // stranding it behind a form. A preview window never reaches this page: an unauthorized+ // preview hand-off answers with an API error, not the App.+ const closeOnSignInPage = (url: string): void => {+ if (isLoginPageUrl(url, appOrigin)) child.close();+ };+ child.webContents.on("did-navigate", (_event, url) => closeOnSignInPage(url));+ child.webContents.on("did-navigate-in-page", (_event, url, isMainFrame) => {+ if (isMainFrame) closeOnSignInPage(url);+ });child.webContents.on("will-navigate", (event, target) => {if (!isLocalSurfaceUrl(target, appOrigin)) {event.preventDefault();@@ -356,6 +394,89 @@ function navigateMainWindow(target: string): void {void win.loadURL(url);}+// --- signing the window in -------------------------------------------------++/** The data root this shell owns; null until boot resolves it. */+let shellDataRoot: string | null = null;+/**+ * The lock of the server this shell attached to instead of starting its own, so a failure+ * can name the process holding the data root; null while the server is this shell's.+ */+let attachedServer: ServerLock | null = null;+/**+ * Which arrivals at the sign-in page the shell answers with a session — one attempt per+ * stay, and none at all after a sign-out. It starts fresh with the process, which is what+ * makes a launch the way back in after signing out (see attach-session.ts).+ */+const signInGuard = createSignInGuard();++/**+ * Puts a session cookie for the current origin into the window's cookie store, by minting a+ * session row in the data root this shell owns. False means it could not and the dialog+ * explaining that is up; the caller then lets the window reach the sign-in page, which is at+ * least a page with an explanation behind it rather than a dead end.+ */+async function signInFromDataRoot(): Promise<boolean> {+ const root = shellDataRoot;+ if (root === null || appOrigin === null) return false;+ const plan = planSignIn({ root, origin: appOrigin, mint: mintApiToken });+ if (plan.outcome === "failed") {+ showSignInFailure(root, plan.failure);+ return false;+ }+ try {+ await session.defaultSession.cookies.set(plan.cookie);+ return true;+ } catch (err) {+ // The row exists and the cookie store refused it. Rare enough to have no handling of its+ // own, and identical from where the user sits, so it takes the same explanation.+ showSignInFailure(root, { reason: "failed", detail: String(err) });+ return false;+ }+}++/** Reports a failed sign-in: one line in the log, and the dialog the user acts on. */+function showSignInFailure(dataRoot: string, failure: SignInFailure): void {+ logLine(`[shell] the window could not be signed in: ${failure.detail}`);+ const opts = {+ type: "warning" as const,+ title: app.name,+ ...signInFailureDialog({ dataRoot, other: attachedServer, failure }),+ };+ void (win !== null ? dialog.showMessageBox(win, opts) : dialog.showMessageBox(opts));+}++/** The App's sign-out, as a request pattern: the one intent a navigation cannot express. */+const SIGN_OUT_REQUEST = "*://*/api/auth/logout";++/**+ * Watches for the App ending the session on purpose, which the catch-all must not undo.+ * A sign-out leads to the same page as an expired session and needs the opposite answer, and+ * the page never tells the shell which it is — so the intent is read off the request the App+ * makes to end the session. The listener belongs to the session rather than to one window, so+ * a sign-out from any window of this app counts, and registering it again replaces it.+ */+function watchForSignOut(target: BrowserWindow): void {+ target.webContents.session.webRequest.onCompleted({ urls: [SIGN_OUT_REQUEST] }, (details) => {+ // A refused sign-out leaves the session alive, so the window never reaches the sign-in+ // page, and there is nothing to suppress.+ if (details.statusCode < 400 && isAppUrl(details.url, appOrigin)) signInGuard.signedOut();+ });+}++/** Runs the guard's decision for wherever the main window has just landed. */+function onMainWindowNavigated(url: string): void {+ if (signInGuard.arrived(url, appOrigin) !== "rescue") return;+ void signInFromDataRoot().then((signedIn) => {+ // The app root, not a reload: the page underneath IS the sign-in page, and reloading it+ // shows it for a beat before the App redirects a signed-in window away from it. A failed+ // attempt loads nothing — the window is already going where it would be sent.+ const landing = signedIn && appOrigin !== null ? `${appOrigin}/` : null;+ signInGuard.tried(landing);+ if (landing !== null) void win?.loadURL(landing);+ });+}+// --- tray -----------------------------------------------------------------/**@@ -531,16 +652,26 @@ async function boot(): Promise<void> {homedir: os.homedir(),releaseRoot: resolveRoot,});+ shellDataRoot = dataRoot;if (profile === "dev") {logLine(`[shell] dev instance '${app.name}' on data root ${dataRoot}`);}const existing = await liveServerLock(dataRoot);if (existing !== null) {- // Attach mode: the one-shot token only works against a server this shell spawned,- // so the window goes through the normal login page of the existing instance.+ // Attach mode: another server — a `penguin web` run, an older app still up — holds this+ // data root, and the one-shot token only works against a server this shell spawned. The+ // window is signed in the other way the product recognizes instead: a session minted+ // straight into the root this shell owns, which is the same authority the CLI mints on.+ attachedServer = existing;appOrigin = `http://localhost:${existing.port}`;- logLine(`[shell] attaching to the running server at ${appOrigin}`);- createWindow(`${appOrigin}/`);+ logLine(`[shell] attaching to the running server at ${appOrigin} (pid ${existing.pid})`);+ await signInFromDataRoot();+ // Either way the window opens on the app root: signed in it goes straight into the App,+ // and otherwise the App sends it to the sign-in page the dialog has just explained. The+ // attempt is recorded with that URL, so arriving there does not buy a second one.+ const landing = `${appOrigin}/`;+ signInGuard.tried(landing);+ createWindow(landing);return;}await startServerAndWindow(dataRoot);diff --git a/packages/desktop/test/attach-session.test.ts b/packages/desktop/test/attach-session.test.tsnew file mode 100644index 00000000..708e32d7--- /dev/null+++ b/packages/desktop/test/attach-session.test.ts@@ -0,0 +1,223 @@+/**+ * The shell signing its own window in: what it plans for each outcome the minter can return,+ * how long the session it asks for lives, what it tells the user when it cannot sign in, and+ * which pages count as the sign-in page.+ */+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";+import type { MintedVia, MintTokenResult } from "@prismshadow/penguin-server/auth-token";+import {+ ATTACH_SESSION_TTL_MS,+ createSignInGuard,+ isLoginPageUrl,+ planSignIn,+ SESSION_COOKIE,+ signInFailureDialog,+} from "../src/attach-session.js";+import type { SessionMinter } from "../src/attach-session.js";++const ORIGIN = "http://localhost:53187";+const ROOT = "/home/someone/.penguin/data";++const EXPIRES_AT = "2026-10-20T08:00:00.000Z";+const MINTED: MintTokenResult = {+ outcome: "minted",+ token: "s3cr3t-token",+ userId: "admin",+ expiresAt: EXPIRES_AT,+};++/** A minter with one canned answer, which records what it was asked for. */+function minter(result: MintTokenResult): {+ mint: SessionMinter;+ calls: Array<{ root: string; ttlMs: number; via: MintedVia }>;+} {+ const calls: Array<{ root: string; ttlMs: number; via: MintedVia }> = [];+ return {+ calls,+ mint: (root, opts) => {+ calls.push({ root, ttlMs: opts.ttlMs, via: opts.via });+ return result;+ },+ };+}++describe("planSignIn", () => {+ it("turns a minted session into the cookie the window needs", () => {+ const { mint, calls } = minter(MINTED);+ const plan = planSignIn({ root: ROOT, origin: ORIGIN, mint });+ // `desktop`, not `cli`: the window this signs in IS the desktop shell's, and the App reads+ // that back to leave the current-password field out of its change-password form.+ expect(calls).toEqual([{ root: ROOT, ttlMs: ATTACH_SESSION_TTL_MS, via: "desktop" }]);+ expect(plan).toEqual({+ outcome: "cookie",+ cookie: {+ url: `${ORIGIN}/`,+ name: SESSION_COOKIE,+ value: "s3cr3t-token",+ path: "/",+ httpOnly: true,+ sameSite: "lax",+ expirationDate: Date.parse(EXPIRES_AT) / 1000,+ },+ });+ });++ it("leaves the cookie without an expiry when the row's cannot be read as a date", () => {+ const { mint } = minter({+ outcome: "minted",+ token: "s3cr3t-token",+ userId: "admin",+ expiresAt: "whenever",+ });+ const plan = planSignIn({ root: ROOT, origin: ORIGIN, mint });+ expect(plan.outcome).toBe("cookie");+ if (plan.outcome !== "cookie") return;+ expect(plan.cookie.expirationDate).toBeUndefined();+ });++ it("reports a root with no web.db as a root that holds no account", () => {+ const { mint } = minter({ outcome: "no_server" });+ const plan = planSignIn({ root: ROOT, origin: ORIGIN, mint });+ expect(plan.outcome).toBe("failed");+ if (plan.outcome !== "failed") return;+ expect(plan.failure.reason).toBe("no_server");+ expect(plan.failure.detail).toContain(ROOT);+ });++ it("passes the minter's own explanation through untouched", () => {+ const detail = "cannot open /root/web.db — minting needs the data root's own OS account";+ const { mint } = minter({ outcome: "failed", detail });+ const plan = planSignIn({ root: ROOT, origin: ORIGIN, mint });+ expect(plan).toEqual({ outcome: "failed", failure: { reason: "failed", detail } });+ });+});++describe("the minted session's lifetime", () => {+ /**+ * Thirty days is what the server gives a browser sign-in, and the only span that renews in+ * place: a shorter session never reaches the renewal window, so it would expire on schedule+ * however much the window is used and drop it back on the sign-in page.+ */+ it("is the thirty days an ordinary browser session gets", () => {+ expect(ATTACH_SESSION_TTL_MS).toBe(30 * 24 * 60 * 60 * 1000);+ });+});++/**+ * The cookie name is a copy of the server's, so it is pinned to the declaration it copies:+ * the two are read by different processes and nothing else would notice them drifting apart.+ */+describe("the session cookie's name", () => {+ it("is the name the server reads sessions from", () => {+ const middleware = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ "../../server/src/auth/middleware.ts",+ );+ const declared = /export const SESSION_COOKIE = "([^"]+)"/.exec(+ fs.readFileSync(middleware, "utf8"),+ )?.[1];+ expect(declared).toBe(SESSION_COOKIE);+ });+});++describe("signInFailureDialog", () => {+ it("names the data root, the server holding it, the reason and the way out", () => {+ const box = signInFailureDialog({+ dataRoot: ROOT,+ other: { pid: 4242, port: 7364 },+ failure: { reason: "failed", detail: "the database belongs to another account" },+ });+ expect(box.message).toContain("could not sign itself in");+ expect(box.detail).toContain(ROOT);+ expect(box.detail).toContain("7364");+ expect(box.detail).toContain("4242");+ expect(box.detail).toContain("the database belongs to another account");+ expect(box.detail).toContain("penguin server reset-admin-password");+ expect(box.buttons).toEqual(["Continue to the sign-in page"]);+ });++ it("claims no other server when the shell started its own", () => {+ const box = signInFailureDialog({+ dataRoot: ROOT,+ other: null,+ failure: { reason: "no_server", detail: "there is no web.db" },+ });+ expect(box.detail).not.toContain("Server using it");+ expect(box.detail).toContain(ROOT);+ expect(box.detail).toContain("penguin server reset-admin-password");+ });+});++describe("isLoginPageUrl", () => {+ it.each<[string, boolean]>([+ [`${ORIGIN}/login`, true],+ [`${ORIGIN}/login/`, true],+ // The server appends this on a failed claim, and the App strips it a moment later.+ [`${ORIGIN}/login?claimFailed=desktop`, true],+ [`${ORIGIN}/login-help`, false],+ [`${ORIGIN}/logins`, false],+ [`${ORIGIN}/chat`, false],+ [`${ORIGIN}/`, false],+ // Another instance on this machine, and the preview host, which is not the App.+ ["http://localhost:9999/login", false],+ ["http://127.0.0.1:53187/login", false],+ ["not a url", false],+ ])("%s is the sign-in page: %s", (url, expected) => {+ expect(isLoginPageUrl(url, ORIGIN)).toBe(expected);+ });++ it("is false before boot has resolved an origin", () => {+ expect(isLoginPageUrl(`${ORIGIN}/login`, null)).toBe(false);+ });+});++describe("createSignInGuard", () => {+ const LOGIN = `${ORIGIN}/login`;++ it("answers the first arrival at the sign-in page, and only that one", () => {+ const guard = createSignInGuard();+ expect(guard.arrived(LOGIN, ORIGIN)).toBe("rescue");+ expect(guard.arrived(LOGIN, ORIGIN)).toBe("leave");+ });++ it("counts an attempt that loaded nothing", () => {+ const guard = createSignInGuard();+ guard.tried(null);+ expect(guard.arrived(LOGIN, ORIGIN)).toBe("leave");+ });++ it("does not read the page the shell loads itself as a window that got in", () => {+ const guard = createSignInGuard();+ expect(guard.arrived(LOGIN, ORIGIN)).toBe("rescue");+ guard.tried(`${ORIGIN}/`);+ expect(guard.arrived(`${ORIGIN}/`, ORIGIN)).toBe("leave");+ // Straight back to the sign-in page: the session just minted is not working, and a+ // second attempt would be the first turn of a loop.+ expect(guard.arrived(LOGIN, ORIGIN)).toBe("leave");+ });++ it("answers again once the window has reached a page of the App", () => {+ const guard = createSignInGuard();+ expect(guard.arrived(LOGIN, ORIGIN)).toBe("rescue");+ guard.tried(`${ORIGIN}/`);+ expect(guard.arrived(`${ORIGIN}/`, ORIGIN)).toBe("leave");+ expect(guard.arrived(`${ORIGIN}/chat`, ORIGIN)).toBe("leave");+ expect(guard.arrived(LOGIN, ORIGIN)).toBe("rescue");+ });++ it("leaves a deliberate sign-out alone until something signs in again", () => {+ const guard = createSignInGuard();+ expect(guard.arrived(`${ORIGIN}/chat`, ORIGIN)).toBe("leave");+ guard.signedOut();+ expect(guard.arrived(LOGIN, ORIGIN)).toBe("leave");+ // However the window comes back to the page, the sign-out still holds.+ expect(guard.arrived(`${ORIGIN}/login?claimFailed=desktop`, ORIGIN)).toBe("leave");+ // Signed in with a password: a later trip to the sign-in page is a failure again, not a+ // decision, so the shell answers it.+ expect(guard.arrived(`${ORIGIN}/chat`, ORIGIN)).toBe("leave");+ expect(guard.arrived(LOGIN, ORIGIN)).toBe("rescue");+ });+});diff --git a/packages/docs/content/quickstart-desktop.en.md b/packages/docs/content/quickstart-desktop.en.mdindex 8dadf689..565e6c03 100644--- a/packages/docs/content/quickstart-desktop.en.md+++ b/packages/docs/content/quickstart-desktop.en.md@@ -79,6 +79,8 @@ On macOS, the app does not install the command while it runs from the mounted dmThe desktop app uses the same data root as a [CLI install](/quickstart-cli), so you can use the two side by side.+Only one server can use a data root at a time. If one is already running on yours — a `penguin web` or `penguin server` instance, or an older copy of the app that is still open — the app attaches to that server instead of starting a second one, and signs its own window in against it, so the window still opens with no login page. Being able to read the data root is what lets it do that, so a root it cannot read leaves the window on the login page instead, behind a dialog naming the data root and the server that holds it. The window signs itself in but cannot set a password on a server it only attached to: for a password you can type, such as for a browser reaching that same server, stop the server and run `penguin server reset-admin-password`.+If you later serve that data root over the network with `penguin server`, first give its `admin` a password you can use, because the desktop app deliberately seeds one that nobody can read. Stop the server, then run:```bash@@ -87,6 +89,8 @@ penguin server reset-admin-passwordThe `admin` account returns to the unclaimed state. When you start the server again, it prints a first-login link where you set the new password.+That command is also the way out if a window ever does show the login page: the password the desktop app created for itself is random and was never shown, so there is nothing to type there.+## Next steps- [Web App](/web-app): find your way around the interface.diff --git a/packages/docs/content/quickstart-desktop.zh.md b/packages/docs/content/quickstart-desktop.zh.mdindex e5235cbc..fbee51ea 100644--- a/packages/docs/content/quickstart-desktop.zh.md+++ b/packages/docs/content/quickstart-desktop.zh.md@@ -79,6 +79,8 @@ PenguinHarness 不内置任何模型凭据。为要使用的模型配置 API Key桌面应用与 [CLI 安装](/quickstart-cli)使用同一个数据目录,两者可以搭配使用。+一个数据目录同一时间只能由一个服务端使用。如果你的数据目录上已经有服务端在运行——`penguin web` 或 `penguin server` 实例,或是仍然开着的旧版应用——应用不会再起一个,而是附着到那个服务端,并自己完成窗口的登录,窗口照样不出现登录页。它能这样做,靠的是能读取数据目录;因此遇到读不了的数据目录时,窗口会停在登录页,并先弹窗说明数据目录和占用它的服务端。窗口能自己登录,却不能给这个只是附着上去的服务端设置密码:要拿到一个可以手动输入的密码(例如给访问同一个服务端的浏览器用),先停掉该服务端,再运行 `penguin server reset-admin-password`。+如果之后要用 `penguin server` 把这个数据目录开放到网络上,要先给 `admin` 设置一个你能用的密码,因为桌面应用刻意生成了一个谁也读不到的密码。先停止服务端,再运行:```bash@@ -87,6 +89,8 @@ penguin server reset-admin-password`admin` 账号会回到未认领状态。再次启动服务端时,它会打印一条首次登录链接,打开链接即可设置新密码。+窗口万一真的出现了登录页,出路也是这条命令:桌面应用给自己生成的密码是随机的,从未显示过,页面上没有可输入的内容。+## 下一步- [Web App](/web-app):熟悉界面。diff --git a/packages/server/src/auth-token.ts b/packages/server/src/auth-token.tsindex 8a162b67..03f9e887 100644--- a/packages/server/src/auth-token.ts+++ b/packages/server/src/auth-token.ts@@ -8,6 +8,7 @@ import path from "node:path";import fs from "node:fs";import { openExistingDatabase } from "./db/database.js";import { AuthSessionsRepo } from "./db/repos/auth-sessions.js";+import type { SessionViaValue } from "./db/repos/auth-sessions.js";import { UsersRepo } from "./db/repos/users.js";import { wire } from "@prismshadow/penguin-core/kernel";@@ -20,6 +21,23 @@ export const CLI_TOKEN_TTL_MS = 60 * 60_000;*/export const CLI_TOKEN_MAX_TTL_MS = 30 * 24 * 60 * 60_000;+/**+ * What a minted row records about how its session was established.+ *+ * `cli` is the default and what `penguin auth token` writes: a session that behaves like a+ * password one in every way. `desktop` is for the desktop shell signing its own window in+ * against a server it did not spawn, and says the same thing its one-shot claim token says —+ * with as much backing, since only an account that can write this file can mint at all.+ *+ * The distinction is not cosmetic: a desktop session may set a password without supplying the+ * current one, because the account the shell created has a password that was generated,+ * hashed and discarded unseen — there is nothing to supply, and whoever can write to this+ * data root can already reset that password offline (`penguin server reset-admin-password`).+ * That allowance is granted by a server running in desktop mode; against any other server the+ * value records what the session is without widening what it may do (routes/me.ts).+ */+export type MintedVia = Extract<SessionViaValue, "cli" | "desktop">;+export type MintTokenResult =| { outcome: "minted"; token: string; userId: string; expiresAt: string }/** No web.db on this root — the server has never run here, so there is no account to mint for. */@@ -48,7 +66,14 @@ function explain(err: unknown, dbPath: string): string {/** Issues an API session token for the data root at `root`. */export function mintApiToken(root: string,- opts: { userId?: string; ttlMs?: number; dbPath?: string; now?: Date } = {},+ opts: {+ userId?: string;+ ttlMs?: number;+ dbPath?: string;+ now?: Date;+ /** How the session records its own establishment; `cli` unless told otherwise. */+ via?: MintedVia;+ } = {},): MintTokenResult {const userId = opts.userId ?? "admin";const dbPath = opts.dbPath ?? path.join(root, "web.db");@@ -66,7 +91,7 @@ export function mintApiToken(// row cannot drift from one the server issues itself.const { token, expiresAt } = wire(AuthSessionsRepo, { db: db }).issue({userId,- via: "cli",+ via: opts.via ?? "cli",now: opts.now ?? new Date(),ttlMs: opts.ttlMs ?? CLI_TOKEN_TTL_MS,maxTtlMs: CLI_TOKEN_MAX_TTL_MS,diff --git a/packages/server/test/auth-token.test.ts b/packages/server/test/auth-token.test.tsindex a24b3ac8..6d6aec6f 100644--- a/packages/server/test/auth-token.test.ts+++ b/packages/server/test/auth-token.test.ts@@ -4,7 +4,8 @@* A session is a row in web.db, so minting opens the database and inserts one — no running* server, no owner token, no loopback. Reading the root already reaches every credential the* token could, so the write adds no authority; the row is a `cli` session the server honors- * on its next request.+ * on its next request, or a `desktop` one when the caller is the shell signing its own window+ * in.*/import path from "node:path";import { describe, expect, it } from "vitest";@@ -86,6 +87,34 @@ describe("minting an API session", () => {}});+ /**+ * The desktop shell mints with `via: "desktop"` when it signs its own window in against a+ * server it did not spawn, and the session has to read back as that kind — it is what the+ * App reads to leave the current-password field out of a form whose account has a password+ * nobody was ever shown. A `cli` mint must keep reading back as an ordinary password+ * session, which is what `penguin auth token` has always produced.+ */+ it("records how the session was established, defaulting to cli", async () => {+ const root = await makeTempRoot();+ const dbPath = path.join(root, "web.db");+ const t = await createTestApp({ config: { root, dbPath } });+ try {+ const asCli = mintApiToken(root, { dbPath });+ const asDesktop = mintApiToken(root, { dbPath, via: "desktop" });+ expect(asCli.outcome).toBe("minted");+ expect(asDesktop.outcome).toBe("minted");+ if (asCli.outcome !== "minted" || asDesktop.outcome !== "minted") return;+ const viaOf = async (token: string) => {+ const res = await apiClient(t.app, `${SESSION_COOKIE}=${token}`).get("/api/me");+ return ((await res.json()) as { sessionVia: string }).sessionVia;+ };+ expect(await viaOf(asCli.token)).toBe("password");+ expect(await viaOf(asDesktop.token)).toBe("desktop");+ } finally {+ await t.cleanup();+ }+ });+it("refuses an account that does not exist", async () => {const root = await makeTempRoot();const dbPath = path.join(root, "web.db");diff --git a/packages/web/src/components/account/change-password-dialog.tsx b/packages/web/src/components/account/change-password-dialog.tsxindex 25db2315..1f9373c4 100644--- a/packages/web/src/components/account/change-password-dialog.tsx+++ b/packages/web/src/components/account/change-password-dialog.tsx@@ -15,12 +15,12 @@ import { PasswordInput } from "../ui/password-input";import { Modal } from "../ui/modal";export function ChangePasswordDialog({ open, onClose }: { open: boolean; onClose: () => void }) {- const { refresh, sessionVia } = useAuth();- // Desktop and first-login sessions set the password without the old one — for them the- // current password is random and was never shown (see omitsOldPassword). Keyed on the- // session's origin, not desktopMode: a browser signed into the same server with a password- // must still prove it.- const noOldPassword = omitsOldPassword(sessionVia);+ const { refresh, desktopMode, sessionVia } = useAuth();+ // The shell's own window and a first-login session set the password without the old one —+ // for them the current password is random and was never shown (see omitsOldPassword). Both+ // fields are needed, not the session's origin alone: they are what the server's own gate+ // reads, and a field it wants but the form leaves out fails the request.+ const noOldPassword = omitsOldPassword({ desktopMode, sessionVia });const [oldPassword, setOldPassword] = useState("");const [newPassword, setNewPassword] = useState("");const [confirmPassword, setConfirmPassword] = useState("");diff --git a/packages/web/src/components/layout/app-layout.tsx b/packages/web/src/components/layout/app-layout.tsxindex e48c5b79..d228489a 100644--- a/packages/web/src/components/layout/app-layout.tsx+++ b/packages/web/src/components/layout/app-layout.tsx@@ -7,6 +7,7 @@import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import { NavLink, Outlet, useLocation, useMatch, useNavigate } from "react-router";import * as api from "../../api/endpoints";+import { nagsAboutInitialPassword } from "../../lib/account-menu";import { S } from "../../lib/strings";import { latestConversation, withoutOrgSessions } from "../../lib/session-grouping";import { navNoteFor, useUpdateBadges } from "../../lib/use-update-badges";@@ -353,7 +354,7 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {}export function AppLayout() {- const { user, desktopMode } = useAuth();+ const { user, desktopMode, sessionVia } = useAuth();// The docks belong to the conversation they were arranged in, so switching Sessions// switches the arrangement with it (dock-state.ts). The draft page's route id ("new" /// a parked draft id) is a scope of its own, handed to the Session the first send@@ -385,7 +386,8 @@ export function AppLayout() {// dismissed banner never flashes before disappearing. Hydration only runs when the banner// would show at all; unreachable prefs fail open (treated as not dismissed, banner shows).const [passwordBannerDismissed, setPasswordBannerDismissed] = useState<boolean | null>(null);- const passwordBannerRelevant = Boolean(user?.passwordIsInitial) && !desktopMode;+ const passwordBannerRelevant =+ Boolean(user?.passwordIsInitial) && nagsAboutInitialPassword({ desktopMode, sessionVia });useEffect(() => {if (!passwordBannerRelevant) return;let cancelled = false;diff --git a/packages/web/src/lib/account-menu.ts b/packages/web/src/lib/account-menu.tsindex ff7372b0..d0eabcc4 100644--- a/packages/web/src/lib/account-menu.ts+++ b/packages/web/src/lib/account-menu.ts@@ -60,7 +60,31 @@ export function offersChangePassword(session: AccountMenuSession): boolean {* `routes/me.ts`: the desktop shell's own window, and a session claimed through a first-login* link. In both, the account's current password is a random value that was hashed and* discarded unseen — demanding it would dead-end the one flow the session exists for.+ *+ * The desktop half is the two-field rule, not `sessionVia` alone, because the server is the+ * authority and its gate reads `deps.desktop !== null && sessionVia === "desktop"`. The two+ * used to be indistinguishable — a `desktop` session existed only where a shell had spawned+ * the server — but the shell now mints one for itself against a server it merely attached to,+ * and there the server still requires the old password. Keeping the shorter test would hide a+ * field the request must carry, and the submit would fail on a form that looked complete.+ * That window has no way to set a password in the UI, which is the point: the account's+ * password is recovered from the machine with `penguin server reset-admin-password`.+ */+/**+ * Whether to nag that the account still runs on its initial password.+ *+ * The trail is advice for an operator who HAS that password — the one a server prints, or the+ * first-login link it frames — and whose account is therefore claimable by anyone who reaches+ * it. A session the desktop shell minted has neither half: the shell seeds a random password it+ * never shows, and the window cannot set one (`omitsOldPassword` follows the server, which asks+ * for the old password unless the server is the shell's own). Nagging there is a prompt with no+ * way to act on it, so it is left to the terminal that started the server — the notice it framed+ * at startup says the same thing to the person who can act.*/-export function omitsOldPassword(sessionVia: MeResponse["sessionVia"]): boolean {- return sessionVia === "desktop" || sessionVia === "setup";+export function nagsAboutInitialPassword(session: AccountMenuSession): boolean {+ return !session.desktopMode && session.sessionVia !== "desktop";+}++export function omitsOldPassword(session: AccountMenuSession): boolean {+ return isDesktopShellWindow(session) || session.sessionVia === "setup";}diff --git a/packages/web/test/account-menu.test.ts b/packages/web/test/account-menu.test.tsindex 445d89d2..018405d3 100644--- a/packages/web/test/account-menu.test.ts+++ b/packages/web/test/account-menu.test.ts@@ -19,6 +19,7 @@ import { describe, expect, it } from "vitest";import {isDesktopShellWindow,offersChangePassword,+ nagsAboutInitialPassword,omitsOldPassword,} from "../src/lib/account-menu";@@ -58,15 +59,37 @@ describe("offersChangePassword", () => {});});+describe("nagsAboutInitialPassword", () => {+ it("keeps quiet in any window the desktop shell signed in", () => {+ // The trail asks its reader to change a password they hold; a shell-minted session holds+ // none, and cannot set one on a server it only attached to. Both desktop cases are+ // therefore silent, while a password session on either kind of server hears it.+ expect(nagsAboutInitialPassword({ desktopMode: true, sessionVia: "desktop" })).toBe(false);+ expect(nagsAboutInitialPassword({ desktopMode: false, sessionVia: "desktop" })).toBe(false);+ expect(nagsAboutInitialPassword({ desktopMode: false, sessionVia: "password" })).toBe(true);+ expect(nagsAboutInitialPassword({ desktopMode: false, sessionVia: "setup" })).toBe(true);+ });+});+describe("omitsOldPassword", () => {- it("omits the current-password field for desktop and first-login sessions only", () => {+ it("omits the current-password field for the shell's own window and first-login sessions", () => {// For both, the account's current password was hashed and discarded unseen — demanding// it would dead-end the flow: a first-login claimer would face a field nobody on earth// can fill. A password session must still prove the current password, mirroring// routes/me.ts.- expect(omitsOldPassword("desktop")).toBe(true);- expect(omitsOldPassword("setup")).toBe(true);- expect(omitsOldPassword("password")).toBe(false);+ expect(omitsOldPassword({ desktopMode: true, sessionVia: "desktop" })).toBe(true);+ expect(omitsOldPassword({ desktopMode: true, sessionVia: "setup" })).toBe(true);+ expect(omitsOldPassword({ desktopMode: false, sessionVia: "setup" })).toBe(true);+ expect(omitsOldPassword({ desktopMode: true, sessionVia: "password" })).toBe(false);+ });++ it("keeps the field for a desktop session against a server no shell spawned", () => {+ // The shell mints one of these for itself when it attaches to a server it did not start+ // (a `penguin web` instance on the same data root). The server's gate is the pair, so it+ // still demands the old password there; a form that dropped the field would submit a+ // request the server refuses. That account's password is recovered with `penguin server+ // reset-admin-password`, not from this form.+ expect(omitsOldPassword({ desktopMode: false, sessionVia: "desktop" })).toBe(false);});it("is hidden in exactly one of the four states", () => {