Skip to content

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

fix(server,web): scope browser-persisted UI state to the data root that produced it (#508)

Yaowei Zheng88cac057d758
diff --git a/changelog/unreleased/2026-08-26-install-scoped-local-state.md b/changelog/unreleased/2026-08-26-install-scoped-local-state.md
new file mode 100644
index 00000000..8a9bcec9
--- /dev/null
+++ b/changelog/unreleased/2026-08-26-install-scoped-local-state.md
@@ -0,0 +1,73 @@
+# Deleting the data root now also clears the browser-side UI state that belonged to it
+
+- **Date:** 2026-08-26
+- **Type:** fix
+- **Scope:** `server`, `web`, `docs`
+- **PR:** [#508](https://github.com/Prism-Shadow/penguin-harness/pull/508)
+
+[中文版](2026-08-26-install-scoped-local-state.zh.md)
+
+Deleting the data files and restarting brought the app back with the old Workspace still
+selected. Part of that state was never in the data root at all: the Web App keeps the
+new-chat draft, the sidebar's registered Workspaces, pinned Sessions, read markers and the
+last Project/Agent in `localStorage`, which in the desktop app lives in Electron's userData
+directory — deleting `PENGUIN_HOME` does not touch a byte of it. Every key named its user and
+Project with a compile-time constant (`admin`, `default_project`), so a wipe-and-restart
+re-provisioned the same ids, the keys lined up again, and the old state came back.
+
+The data root was given an identity, and the browser was made to scope that state to it.
+
+## Details
+
+- An opaque id was minted into `<root>/install-id` the first time a root was used, and
+ served from a new public `GET /api/install`. It was made an identity rather than a
+ credential — it authorizes nothing, carries no host name, user name or timestamp, and got
+ ordinary file permissions instead of `api-token`'s handling. Public, because the Web App
+ has to ask before it knows whether anyone is signed in, and a just-wiped root has nobody
+ signed in at all.
+- The Web App compared that id against the one it had recorded, before React mounted. A
+ different id cleared the keys that reference server-side entities; the same id — every
+ ordinary restart — cleared nothing.
+- One stored id plus a sweep, rather than the id embedded in every key name: key names were
+ left as they were, so nothing already on disk needed migrating, and orphaned keys left
+ behind by earlier roots were collected in the same pass instead of accumulating forever.
+- Browser preferences were kept: theme, language, accent, font scale, display currency,
+ terminal appearance, sidebar collapse, panel width, grouping/sorting mode, nav-group
+ collapse and the mid-run send mode. None of them names anything on the server, and wiping
+ a data root is not a request to reset someone's theme.
+- Cleared: chat drafts and parked drafts, the sidebar's Workspace registry, pinned Sessions,
+ session and group order, seen markers, collapsed and pinned sidebar groups, the last
+ Project and Agent, collapsed Memory scopes, the models page's group expansion and order,
+ the dock's per-conversation tab arrangement, and the standalone terminal page's attached
+ shell.
+- A boot that actually swept reloaded instead of rendering. Module evaluation of the whole
+ static import graph finishes before the entry point runs a statement, so a module that
+ read `localStorage` at module scope — the dock's per-conversation tab arrangement did —
+ was already holding a parsed copy of keys the sweep then removed, and its first scope
+ switch would have written the entire pre-wipe map back, under an id that matched by then
+ and would never be swept again. The reload re-evaluated every module against the cleaned
+ store, and the second pass reconciled to "unchanged" and rendered.
+- A tab left open across the wipe reloaded too. The sweep runs once per page load, so a tab
+ still open against the old root kept that state in memory and would have written it back
+ on the next pin, reorder or draft keystroke; the cross-tab `storage` event for the
+ recorded id became a sweep-and-reload in every other tab.
+- The route was mounted in the platform rather than the runtime shell. A hot update carries
+ platform, CLI and web bundle as one version and never the runtime, so the endpoint now
+ travels with the bundle that calls it — mounted in the runtime it would have been missing
+ on exactly the installations that received the new Web App by hot update, and the fix
+ would have been silently inert there until the next runtime install.
+- `penguin.chatRouteApplied.*` was left untouched: it is `sessionStorage`, scoped to one
+ tab's history, and cannot outlive a data root.
+- The classification table was made self-enforcing rather than self-reported: a test reads
+ the Web App source, collects every `penguin.*` key literal, and fails on any the table
+ does not cover, since a forgotten install-scoped key silently reintroduces this bug.
+- The second path a Workspace survives a wipe by was deliberately not touched: with `web.db`
+ deleted but the `default_project` directory kept, `ProjectService.provisionInitialProject`
+ adopts the existing directory and its `.project_config.toml`, including
+ `[default_chat].workspace`. That adoption is intended, and was left as it was.
+
+## Compatibility
+
+Nothing already on disk was migrated and nothing was destroyed on upgrade. The decision
+behind that, and the one thing a user who wiped a data root *before* this release has to do
+by hand, are in [backward compatibility](2026-08-27-backward-compatibility.md).
diff --git a/changelog/unreleased/2026-08-26-install-scoped-local-state.zh.md b/changelog/unreleased/2026-08-26-install-scoped-local-state.zh.md
new file mode 100644
index 00000000..b26663b3
--- /dev/null
+++ b/changelog/unreleased/2026-08-26-install-scoped-local-state.zh.md
@@ -0,0 +1,58 @@
+# 删除数据根后,浏览器侧属于它的 UI 状态也会一并清除
+
+- **Date:** 2026-08-26
+- **Type:** fix
+- **Scope:** `server`, `web`, `docs`
+- **PR:** [#508](https://github.com/Prism-Shadow/penguin-harness/pull/508)
+
+[English](2026-08-26-install-scoped-local-state.md)
+
+删掉数据文件重启后,应用回来时仍然选中着原来的 Workspace。其中一部分状态本就不在数据根里:Web App
+把新会话草稿、侧边栏登记的 Workspace、置顶的 Session、已读标记以及上次的 Project/Agent 存在
+`localStorage`——在桌面端它位于 Electron 的 userData 目录,删除 `PENGUIN_HOME` 一个字节也碰不到。
+而每个键里的用户与 Project 都是编译期常量(`admin`、`default_project`),于是清空重启后重新置备出
+同样的 id,键再次对上,旧状态就回来了。
+
+这次给数据根加上了一个身份标识,并让浏览器侧的状态按它划定作用域。
+
+## 细节
+
+- 在数据根首次被使用时,向 `<root>/install-id` 铸造了一个不透明 id,由新增的公开路由
+ `GET /api/install` 提供。它被定为**身份**而非凭据——不授权任何操作,不含主机名、用户名或时间戳,
+ 使用普通文件权限,而不是 `api-token` 那一套处理。之所以公开,是因为 Web App 必须在还不知道是否
+ 有人登录时就发问,而刚被清空的数据根根本没有任何人处于登录状态。
+- Web App 在 React 挂载之前,把该 id 与自己记录的值做了比较。不同则清除引用服务端实体的那些键;
+ 相同——也就是每一次普通重启——什么都不清。
+- 采用「存一个 id + 一次清扫」,而不是把 id 嵌进每个键名:键名保持原样,磁盘上已有的键无需迁移,
+ 早先数据根遗留的孤儿键也在同一趟里被回收,而不是永久堆积。
+- 保留了浏览器偏好:主题、语言、强调色、字号、显示币种、终端外观、侧边栏折叠、面板宽度、分组与排序
+ 方式、导航分组折叠,以及运行中发送模式。它们都不指向服务端的任何东西,清空数据根也不等于要求
+ 重置某人的主题。
+- 会被清除的:会话草稿与停放的草稿、侧边栏 Workspace 登记表、置顶 Session、会话与分组的手动顺序、
+ 已读标记、折叠与置顶的侧边栏分组、上次的 Project 与 Agent、折叠的 Memory 作用域、模型页分组的
+ 展开状态与顺序、Dock 按会话记录的标签布局,以及独立终端页所附着的 shell。
+- 真正发生清扫的那次启动改为重新加载页面,而不是继续渲染。整张静态 import 图的模块求值都发生在
+ 入口文件执行第一条语句之前,因此在模块作用域读过 `localStorage` 的模块——Dock 按会话记录的标签
+ 布局就是这样——手里已经握着清扫随后删掉的那份解析结果,它第一次切换作用域就会把整张清空前的表
+ 原样写回;而那时 id 已经对上,从此再也不会被清扫。重新加载让每个模块对着清扫后的存储重新求值,
+ 第二趟对账结果为「未变化」,正常渲染。
+- 跨过这次清空仍然开着的标签页也会重新加载。清扫每次页面加载只跑一趟,因此另一个仍对着旧数据根的
+ 标签页把那份状态留在内存里,下一次置顶、拖动排序或草稿输入就会把它写回去;现在记录 id 的跨标签
+ `storage` 事件会让其余每个标签页先清扫再重新加载。
+- 该路由挂在了 platform 上,而不是 runtime 外壳里。一次热更新把 platform、CLI 与 web 产物作为一个
+ 版本一起送达,且从不包含 runtime,因此这个端点现在与调用它的产物同行——挂在 runtime 里的话,恰恰
+ 是那些通过热更新拿到新 Web App 的安装会缺少它,本次修复在那里会一直静默失效,直到下一次安装新的
+ runtime。
+- `penguin.chatRouteApplied.*` 未被触及:它存在 `sessionStorage` 中,作用域限于一个标签页的历史,
+ 不可能活得比数据根更久。
+- 这张分类表从「靠自觉」改为「可强制」:新增的测试会读取 Web App 源码,收集其中每一个 `penguin.*`
+ 键字面量,只要有表里没覆盖到的就失败——遗漏一个 install 作用域的键,就会悄无声息地把这个 bug
+ 放回来。
+- Workspace 在清空后存活的另一条路径被有意保留:若删掉了 `web.db` 但没有删掉 `default_project`
+ 目录,`ProjectService.provisionInitialProject` 会沿用已有目录及其 `.project_config.toml`,
+ 其中包括 `[default_chat].workspace`。该沿用行为是有意为之,本次未做改动。
+
+## 兼容性
+
+磁盘上已有的数据没有做任何迁移,升级时也没有销毁任何东西。相应的决定,以及在本版本**之前**清空过
+数据根的用户唯一需要手动做的一件事,都记在[向后兼容](2026-08-27-backward-compatibility.zh.md)里。
diff --git a/changelog/unreleased/2026-08-27-backward-compatibility.md b/changelog/unreleased/2026-08-27-backward-compatibility.md
new file mode 100644
index 00000000..a05c5e12
--- /dev/null
+++ b/changelog/unreleased/2026-08-27-backward-compatibility.md
@@ -0,0 +1,75 @@
+# Backward compatibility: install-scoped browser state
+
+- **Date:** 2026-08-27
+- **Type:** process
+- **Scope:** `server`, `web`
+- **PR:** [#508](https://github.com/Prism-Shadow/penguin-harness/pull/508)
+
+[中文版](2026-08-27-backward-compatibility.zh.md)
+
+[Scoping browser-persisted UI state to its data root](2026-08-26-install-scoped-local-state.md)
+touched two things that outlive a release: a new file in the data root, `<root>/install-id`,
+and a new `localStorage` entry, `penguin.installId`. Only the browser side needed a decision;
+the file and the key are recorded here too, so a reader looking for "does my install need
+anything?" finds every answer in one place.
+
+(The batch dated 2026-08-26 has its own
+[backward compatibility](2026-08-26-backward-compatibility.md) entry, about `web.db` and the
+messaging bindings. The two are unrelated.)
+
+## The browser that has keys but no recorded id
+
+Every browser upgrading into this release holds the keys and has never recorded an install
+id. That is indistinguishable from a browser whose data root was wiped, so the sweep would
+have run on the first page load after the update, for everyone.
+
+Chosen: **adopt the current id, sweep nothing.** A first sight records the id and leaves the
+store exactly as it found it. Destroying legitimate state on upgrade — every user's draft,
+pins, Workspace registry and read markers, on an install nobody had touched — would have been
+a far worse defect than the one being fixed.
+
+**Nothing here has to be removed later, and nobody is on the hook to remove it.** The adopt
+branch is not a migration shim with an expiry: a browser with no recorded id is also a new
+profile, a new machine, a fresh private window and anyone who has cleared their site data.
+"First sight adopts" is the permanent rule of the comparison, and it reads the same in every
+release after this one.
+
+## What a user has to do, once
+
+The cost of adopting is that state which was **already** stale when this shipped stays stale.
+A user who wiped their data root before this release still sees the old Workspace, the old
+draft and the old pins, because this release records the current root's id over that state
+rather than clearing it.
+
+Clearing it is manual, and there is exactly one way: clear site data for the app's origin in
+the browser — in the desktop app, that state lives in Electron's userData directory rather
+than in `PENGUIN_HOME`, which is why deleting the data root never reached it. Doing so also
+resets the preferences the sweep is careful to keep: theme, language, accent, font scale,
+display currency, terminal appearance, sidebar collapse, panel width, grouping/sorting mode,
+nav-group collapse and the mid-run send mode.
+
+Wipes from this release onward need none of that: the next page load recognises the new root
+and clears the install-scoped keys by itself.
+
+## The new file in the data root
+
+`<root>/install-id` holds one line of printable ASCII and is written once, the first time a
+root is used. It is an identity, not a credential: it authorizes nothing, and it is served to
+unauthenticated callers on purpose.
+
+It needs no decision. A build from before this change never reads it and never writes it, so
+a downgrade ignores the file entirely and an upgrade back picks up the same id. Deleting the
+file by hand costs one sweep on the next page load — the root then looks new, which is
+exactly what it is claiming to be — and nothing else. A root that cannot be written reports
+no identity at all, and an unknown identity sweeps nothing.
+
+## The new `localStorage` key
+
+`penguin.installId` was added alongside the keys the Web App already kept, and it is the one
+key the sweep never removes: it is what the comparison reads. Builds from before this change
+do not know the key and leave it alone, so a downgrade is invisible in both directions.
+
+## Compatibility
+
+No action is required on upgrade or on downgrade. The single manual step, for a user who wiped
+a data root before this release, is above.
diff --git a/changelog/unreleased/2026-08-27-backward-compatibility.zh.md b/changelog/unreleased/2026-08-27-backward-compatibility.zh.md
new file mode 100644
index 00000000..21bc816a
--- /dev/null
+++ b/changelog/unreleased/2026-08-27-backward-compatibility.zh.md
@@ -0,0 +1,61 @@
+# 向后兼容:按数据根划定作用域的浏览器状态
+
+- **Date:** 2026-08-27
+- **Type:** process
+- **Scope:** `server`, `web`
+- **PR:** [#508](https://github.com/Prism-Shadow/penguin-harness/pull/508)
+
+[English](2026-08-27-backward-compatibility.md)
+
+[把浏览器持久化的 UI 状态按数据根划定作用域](2026-08-26-install-scoped-local-state.zh.md)动到了两样
+会跨越版本存活的东西:数据根里新增的文件 `<root>/install-id`,以及新增的 `localStorage` 条目
+`penguin.installId`。需要做决定的只有浏览器一侧;这个文件和这个键也一并记在这里,方便有人来查
+「我这套安装需要做什么吗?」时,在同一处找到全部答案。
+
+(2026-08-26 那一批有它自己的[向后兼容](2026-08-26-backward-compatibility.zh.md)条目,讲的是
+`web.db` 与消息绑定。两者互不相干。)
+
+## 有键、但从未记录过 id 的浏览器
+
+升级到本版本的每一个浏览器都存着这些键,且从未记录过 install id。这与数据根被清空过的浏览器无法
+区分,因此若不加处理,更新之后所有人的第一次页面加载都会触发清扫。
+
+选择:**沿用当前 id,不做任何清扫。** 首次见到时只记录 id,存储保持原样。升级时毁掉合法状态——每个
+用户的草稿、置顶、Workspace 登记表与已读标记,而这套安装其实谁也没动过——会是比正在修的这个严重得多
+的缺陷。
+
+**这里没有任何需要日后删除的东西,也没有人被挂上这笔账。** 沿用分支不是带有效期的迁移垫片:没有记录
+过 id 的浏览器,同时也意味着新的浏览器配置、新的机器、一个全新的隐私窗口,以及任何清除过站点数据的
+人。「首次见到即沿用」是这次比较的永久规则,本版本之后的每一个版本读起来都一样。
+
+## 用户需要手动做的一件事
+
+沿用的代价是:在本次发布时**已经**陈旧的状态会继续陈旧下去。在本版本之前清空过数据根的用户,仍会
+看到旧的 Workspace、旧的草稿和旧的置顶,因为本版本是把当前数据根的 id 记到那份状态之上,而不是把它
+清掉。
+
+清理只能手动进行,而且只有一种办法:在浏览器中清除该应用来源(origin)的站点数据——在桌面端,这份
+状态位于 Electron 的 userData 目录而不在 `PENGUIN_HOME` 里,这正是删除数据根始终碰不到它的原因。
+这样做同时也会重置清扫特意保留的那些偏好:主题、语言、强调色、字号、显示币种、终端外观、侧边栏折叠、
+面板宽度、分组与排序方式、导航分组折叠,以及运行中发送模式。
+
+从本版本起发生的清空则不需要这些:下一次页面加载会认出新的数据根,自行清除 install 作用域的键。
+
+## 数据根里新增的文件
+
+`<root>/install-id` 存放一行可打印 ASCII,在数据根首次被使用时写入一次。它是身份而非凭据:不授权
+任何操作,并且是有意提供给未登录调用方的。
+
+它不需要做决定。本次改动之前的构建既不会读它也不会写它,因此降级会完全忽略这个文件,再次升级回来
+也会拿到同一个 id。手动删掉这个文件的代价,是下一次页面加载会清扫一次——那时数据根看上去是新的,
+而它也正是这么声称的——除此之外没有别的影响。无法写入的数据根根本不会报出身份,而未知的身份不会
+清扫任何东西。
+
+## 新增的 `localStorage` 键
+
+`penguin.installId` 是在 Web App 原有那些键之外新增的一条,也是清扫唯一从不删除的键:它正是比较时
+读取的那一个。本次改动之前的构建不认识这个键,会原样放着,因此降级在两个方向上都不可察觉。
+
+## 兼容性
+
+升级与降级都不需要做任何操作。对在本版本之前清空过数据根的用户而言,唯一需要手动执行的一步在上文。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 7f0fe6a4..dbb97f91 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -68,6 +68,7 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
| --- | --- | --- |
| POST | /api/auth/login | Log in: `{userId, password}` → `{user}` |
| POST | /api/auth/logout | Log out, returns 204 |
+| GET | /api/install | Public: `{installId}` — an opaque id identifying the data root being served (`<root>/install-id`), minted the first time the root is used. The Web App compares it against the one it stored and clears the browser-side UI state that references server entities when it differs, so replacing the data root no longer leaves the old Workspace, drafts and pins in place. `null` means the server could not establish one; clients must then change nothing. |
| GET | /api/me | Current user info |
| PUT | /api/me/password | Change password: `{oldPassword, newPassword}` |
| GET | /api/me/prefs | Read UI preferences |
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index aa57e133..574eedeb 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -68,6 +68,7 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
| --- | --- | --- |
| POST | /api/auth/login | 登录:`{userId, password}` → `{user}` |
| POST | /api/auth/logout | 退出登录,返回 204 |
+| GET | /api/install | 公开:`{installId}`——标识当前所服务数据根的不透明 id(`<root>/install-id`),在该根首次被使用时铸造。Web App 将其与自己存下的值比较,不一致时清除浏览器侧那些引用服务端实体的 UI 状态,因此更换数据根后不会再留下旧的 Workspace、草稿与置顶。`null` 表示服务端无法确定该 id,此时客户端不应改动任何内容。 |
| GET | /api/me | 当前用户信息 |
| PUT | /api/me/password | 修改密码:`{oldPassword, newPassword}` |
| GET | /api/me/prefs | 读取 UI 偏好 |
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 63d193c3..195ee98e 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -67,6 +67,20 @@ export interface AuthResponse {
user: UserInfo;
}
+/**
+ * GET /api/install — the identity of the data root this server is serving (install-id.ts),
+ * read by the web app before it mounts so state persisted against a DIFFERENT root can be
+ * swept. Public, like the login route it sits next to.
+ */
+export interface InstallResponse {
+ /**
+ * Opaque per-data-root id, or null when the server could not establish one (an
+ * unreadable or unwritable root). Null means "unknown", and a client must change
+ * nothing on it — never treat it as a new install.
+ */
+ installId: string | null;
+}
+
export interface MeResponse {
user: UserInfo;
/**
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index 32b15ed8..4cf33408 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -59,9 +59,11 @@ import type { TerminalManager } from "./terminal/manager.js";
import type { AppEnv } from "./auth/middleware.js";
import { ADMIN_USER_ID, AuthService } from "./auth/service.js";
import { clearInitialAdminPassword } from "./initial-password.js";
+import { ensureInstallId } from "./install-id.js";
import { handleError, HttpError, errorBody } from "./http/errors.js";
import { attributedProjectId } from "./http/attribution.js";
import { authRoutes } from "./http/routes/auth.js";
+import { installRoutes } from "./http/routes/install.js";
import { ChannelHub } from "./runtime/channel.js";
import { ErrorRecorder } from "./runtime/error-recorder.js";
import {
@@ -291,6 +293,14 @@ export async function bootAppDeps(
storeApiToken(config.root, apiToken);
authService.setLocalApiToken(apiToken);
+ // Install identity: minted here so a root gets its name the first time it is used rather
+ // than on the first browser request, which keeps `<root>/install-id` alongside the other
+ // files a boot creates and makes the id observable to the CLI and to tests. The return
+ // value is deliberately unused — GET /api/install re-reads the file per request (see
+ // http/routes/install.ts); this call exists for the minting side effect. Nothing fails
+ // when it cannot be persisted: the browser then simply never sweeps.
+ ensureInstallId(config.root);
+
// The capability set buildAppDeps claims (see hmr/capabilities.ts) — every
// entry must be in place before ensure() below performs the first boot. The interface
// descriptor leads: it is what a bundle's handshake reads before trusting any of the rest.
@@ -912,6 +922,19 @@ export function createApp(
// GET is served, and the handler refuses the HEAD that Hono re-dispatches into it.
app.route("/api/projects/:projectId/model-oauth/callback", modelOAuthCallbackRoutes(deps));
+ // The data root's install identity, public: the web app compares it against what it holds
+ // in `localStorage` before React mounts, which is before it knows whether anyone is signed
+ // in — and a just-wiped root, the case the whole mechanism exists for, has nobody signed in
+ // at all. See http/routes/install.ts.
+ //
+ // Mounted in the PLATFORM rather than the runtime because a hot push carries platform + cli
+ // + web dist as ONE version and never the runtime (hmr/host.ts): the bundle that calls this
+ // route and the route itself then always move together, whereas a runtime mount would let a
+ // pushed web dist arrive on an installation whose runtime does not serve what it asks for.
+ // For that reason /api/install is deliberately absent from RUNTIME_PREFIXES above — the
+ // platform must serve it, not decline it.
+ app.route("/api/install", installRoutes(deps));
+
// Protected routes: cookie -> auth_session -> user, over the runtime's auth service.
app.use("/api/*", authMiddleware(deps.authService));
app.route("/api/me", meRoutes(deps));
diff --git a/packages/server/src/http/routes/install.ts b/packages/server/src/http/routes/install.ts
new file mode 100644
index 00000000..74223d8d
--- /dev/null
+++ b/packages/server/src/http/routes/install.ts
@@ -0,0 +1,36 @@
+/**
+ * Install-identity route: `GET /api/install -> { installId }`.
+ *
+ * PUBLIC (no login required), and that is a requirement rather than a convenience: the web
+ * app compares this id against the one in `localStorage` before React mounts, which is
+ * before it knows whether anyone is signed in — and the case this whole mechanism exists
+ * for, a wiped data root, is precisely the case where nobody is. See install-id.ts for why
+ * publishing the id discloses nothing.
+ *
+ * Mounted in the PLATFORM, above its auth gate (app.ts's createApp). A hot push carries
+ * platform + cli + web dist as one version and never the runtime, so putting the route where
+ * the platform is puts it where the web bundle that calls it is: the two can never arrive on
+ * an installation separately. The data root is still the runtime's — `deps.config.root` comes
+ * from the claimed capabilities either way — so ownership of the FILE and ownership of the
+ * route are simply different questions.
+ *
+ * The id is read per request rather than captured at boot. It is one small file and the
+ * request happens once per page load, and reading it live is what makes the answer follow
+ * the root: a root deleted out from under a running server reports a NEW id on the next
+ * load instead of a remembered one, so the browser sweeps without waiting for a restart.
+ */
+import { Hono } from "hono";
+import type { InstallResponse } from "../../api/types.js";
+import type { AppEnv } from "../../auth/middleware.js";
+import type { AppDeps } from "../../app.js";
+import { ensureInstallId } from "../../install-id.js";
+
+export function installRoutes(deps: AppDeps): Hono<AppEnv> {
+ const app = new Hono<AppEnv>();
+
+ app.get("/", (c) => {
+ return c.json({ installId: ensureInstallId(deps.config.root) } satisfies InstallResponse);
+ });
+
+ return app;
+}
diff --git a/packages/server/src/install-id.ts b/packages/server/src/install-id.ts
new file mode 100644
index 00000000..08b5a119
--- /dev/null
+++ b/packages/server/src/install-id.ts
@@ -0,0 +1,98 @@
+/**
+ * Install identity of a data root (`<root>/install-id`).
+ *
+ * The problem it exists for: the browser keeps UI state in `localStorage` — the new-chat
+ * draft with its Workspace, the sidebar's registered Workspaces, pinned Sessions, seen
+ * markers — and `localStorage` has no relationship whatsoever to the data root. In the
+ * desktop app it lives in Electron's userData directory, so deleting `PENGUIN_HOME` does
+ * not touch a byte of it. Both halves of every key are compile-time constants
+ * (`ADMIN_USER_ID`, `DEFAULT_PROJECT_ID`), so a wipe-and-restart re-provisions the same
+ * user and the same Project, the keys line up again, and the state the user thought they
+ * had deleted comes back. This file gives the ROOT a name the browser can compare against,
+ * so a root the user replaced is recognisable as a different one.
+ *
+ * It is an IDENTITY, not a credential. It authorizes nothing, so it gets none of the
+ * handling `api-token` gets: ordinary file permissions, no rotation, and it is served to
+ * unauthenticated callers (http/routes/install.ts) — the browser has to sweep before it
+ * knows whether anyone is signed in, and after a wipe nobody is. A `randomUUID` carries no
+ * host name, no user name and no timestamp, so publishing it discloses nothing beyond
+ * "this root has existed since some earlier boot".
+ *
+ * Lifecycle: minted the first time a root is used and never touched again. A restart on
+ * the same root reports the same id (nothing is swept); a root that was deleted and
+ * re-created has no file, so the next boot mints a new one (the browser sweeps).
+ */
+import { randomUUID } from "node:crypto";
+import fs from "node:fs";
+import path from "node:path";
+
+export function installIdPath(root: string): string {
+ return path.join(root, "install-id");
+}
+
+/** Printable ASCII, no spaces: the shape an id must have to be stored and compared safely. */
+const ID_SHAPE = /^[\x21-\x7e]+$/;
+
+/**
+ * The stored id, or null when the file holds nothing usable. Deliberately strict about
+ * shape — one line, printable, bounded length — because whatever comes back is compared
+ * against, and stored in, a browser's `localStorage`. A hand-written id is accepted as
+ * long as it is that shape; the format is not pinned to a UUID.
+ */
+function parseInstallId(raw: string): string | null {
+ const id = (raw.split("\n", 1)[0] ?? "").trim();
+ if (id === "" || id.length > 200 || !ID_SHAPE.test(id)) return null;
+ return id;
+}
+
+/**
+ * Mints and persists a fresh id. tmp + rename so a concurrent reader never sees a partial
+ * write. Returns null when it could not be persisted (a read-only root): an id we cannot
+ * store would be different on every boot, and handing that to the browser would sweep the
+ * user's UI state on every single load.
+ */
+function mintInstallId(root: string): string | null {
+ const id = randomUUID();
+ try {
+ fs.mkdirSync(root, { recursive: true });
+ const target = installIdPath(root);
+ const tmp = `${target}.${process.pid}.tmp`;
+ fs.writeFileSync(tmp, `${id}\n`);
+ fs.renameSync(tmp, target);
+ return id;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * This root's install id, minting one when the root has none yet. Null means "identity
+ * unknown", which every caller must treat as "change nothing": the browser skips its sweep
+ * rather than guess.
+ *
+ * Only an ABSENT file counts as a new root. Any other read failure — a permission problem,
+ * exhausted descriptors — returns null instead of minting, because minting over a root that
+ * still has its id would report a new identity for an unchanged root and destroy UI state
+ * that was never stale. A file that exists but holds junk is re-minted: tmp + rename means
+ * this writer cannot produce a torn one, so junk is external tampering with a file we own,
+ * and re-minting is the only outcome that leaves the root usable afterwards.
+ */
+export function ensureInstallId(root: string): string | null {
+ let raw: string;
+ try {
+ raw = fs.readFileSync(installIdPath(root), "utf8");
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") return null;
+ return mintInstallId(root);
+ }
+ return parseInstallId(raw) ?? mintInstallId(root);
+}
+
+/** The stored id without ever minting one; null when absent or unusable (tests, diagnostics). */
+export function readInstallId(root: string): string | null {
+ try {
+ return parseInstallId(fs.readFileSync(installIdPath(root), "utf8"));
+ } catch {
+ return null;
+ }
+}
diff --git a/packages/server/test/install-id.test.ts b/packages/server/test/install-id.test.ts
new file mode 100644
index 00000000..fe157a6a
--- /dev/null
+++ b/packages/server/test/install-id.test.ts
@@ -0,0 +1,182 @@
+/**
+ * Install identity of a data root: `<root>/install-id`, minted at boot and served publicly
+ * by `GET /api/install`.
+ *
+ * What the web app depends on and this pins: the id survives a restart on the same root
+ * (nothing gets swept on an ordinary restart), differs on a fresh root, and comes back new
+ * after the root is deleted — which is the reported bug's trigger. Plus the failure modes
+ * that must NOT read as "new root": a read error that is not ENOENT, and a root the id
+ * cannot be written to.
+ */
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import type { InstallResponse } from "../src/api/types.js";
+import { createApp } from "../src/app.js";
+import { HotResources } from "../src/hmr/resources.js";
+import { ensureInstallId, installIdPath, readInstallId } from "../src/install-id.js";
+import { TerminalManager } from "../src/terminal/manager.js";
+import { identityFrom } from "../src/terminal/identity.js";
+import { createTestApp, loginAdmin, makeTempRoot } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+describe("install id (file)", () => {
+ const roots: string[] = [];
+ const tempRoot = async (): Promise<string> => {
+ const root = await makeTempRoot();
+ roots.push(root);
+ return root;
+ };
+ afterEach(() => {
+ for (const root of roots.splice(0)) {
+ fs.rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
+ }
+ });
+
+ it("mints once and returns the same id on every later call (a restart sweeps nothing)", async () => {
+ const root = await tempRoot();
+ const first = ensureInstallId(root);
+ expect(first).not.toBeNull();
+ expect(ensureInstallId(root)).toBe(first);
+ expect(readInstallId(root)).toBe(first);
+ });
+
+ it("two roots never share an id", async () => {
+ expect(ensureInstallId(await tempRoot())).not.toBe(ensureInstallId(await tempRoot()));
+ });
+
+ it("deleting the root mints a new id — the wipe the browser has to notice", async () => {
+ const root = await tempRoot();
+ const before = ensureInstallId(root);
+ fs.rmSync(root, { recursive: true, force: true });
+
+ const after = ensureInstallId(root);
+ expect(after).not.toBeNull();
+ expect(after).not.toBe(before);
+ });
+
+ it("creates the root directory when it does not exist yet", async () => {
+ const parent = await tempRoot();
+ const root = path.join(parent, "not", "created", "yet");
+ expect(ensureInstallId(root)).not.toBeNull();
+ expect(fs.existsSync(installIdPath(root))).toBe(true);
+ });
+
+ it("a junk id file is replaced rather than left unusable", async () => {
+ const root = await tempRoot();
+ const original = ensureInstallId(root);
+ fs.writeFileSync(installIdPath(root), " \n");
+
+ const replaced = ensureInstallId(root);
+ expect(replaced).not.toBeNull();
+ expect(replaced).not.toBe(original);
+ expect(readInstallId(root)).toBe(replaced);
+ });
+
+ it("reads only the first line, trimmed (a hand-written id is honoured as-is)", async () => {
+ const root = await tempRoot();
+ fs.mkdirSync(root, { recursive: true });
+ fs.writeFileSync(installIdPath(root), "hand-written-id\ntrailing junk\n");
+ expect(ensureInstallId(root)).toBe("hand-written-id");
+ });
+
+ it("a read failure that is not ENOENT is unknown, never a new root", async () => {
+ const root = await tempRoot();
+ // A directory where the file should be: readFileSync fails with EISDIR/EPERM, which is
+ // not ENOENT. Minting here would report a new identity for a root nobody touched.
+ fs.mkdirSync(installIdPath(root), { recursive: true });
+ expect(ensureInstallId(root)).toBeNull();
+ });
+
+ it("a root that cannot be written is unknown, not a new id on every boot", async () => {
+ const parent = await tempRoot();
+ const file = path.join(parent, "a-file");
+ fs.writeFileSync(file, "not a directory");
+ // mkdir under a regular file fails (ENOTDIR), so the mint cannot be persisted.
+ expect(ensureInstallId(path.join(file, "root"))).toBeNull();
+ });
+
+ it("readInstallId never mints", async () => {
+ const root = path.join(os.tmpdir(), `penguin-install-id-absent-${process.pid}`);
+ expect(readInstallId(root)).toBeNull();
+ expect(fs.existsSync(installIdPath(root))).toBe(false);
+ });
+});
+
+describe("GET /api/install", () => {
+ let t: TestApp;
+
+ beforeEach(async () => {
+ t = await createTestApp();
+ });
+ afterEach(async () => {
+ await t.cleanup();
+ });
+
+ it("boot persists the id at <root>/install-id and the route reports it", async () => {
+ const stored = readInstallId(t.root);
+ expect(stored).not.toBeNull();
+
+ const res = await t.app.request("/api/install");
+ expect(res.status).toBe(200);
+ expect(((await res.json()) as InstallResponse).installId).toBe(stored);
+ });
+
+ it("answers without a session — the sweep runs before anyone is signed in", async () => {
+ // No cookie, no Bearer: a just-wiped root has nobody to sign in as, and the browser
+ // must still be able to recognise it as a different root.
+ const anonymous = await t.app.request("/api/install");
+ expect(anonymous.status).toBe(200);
+
+ const { cookie } = await loginAdmin(t.app);
+ const authed = await t.app.request("/api/install", { headers: { cookie } });
+ expect(((await authed.json()) as InstallResponse).installId).toBe(
+ ((await anonymous.json()) as InstallResponse).installId,
+ );
+ });
+
+ it("mounts in the PLATFORM, so a pushed web bundle can never outrun the route it calls", async () => {
+ // A hot push carries platform + cli + web dist as ONE version and never the runtime
+ // (hmr/host.ts), so the route the pushed bundle asks for has to travel with the platform.
+ // Mounted in the runtime it would be missing from exactly the installations that received
+ // the new web dist by push, and the platform's own auth gate would 401 a public route.
+ const platform = createApp(
+ t.deps,
+ new TerminalManager(new HotResources()),
+ identityFrom(t.deps.authService),
+ );
+
+ const res = await platform.request("/api/install");
+ expect(res.status).toBe(200);
+ expect(((await res.json()) as InstallResponse).installId).toBe(readInstallId(t.root));
+ });
+
+ it("hands overlapping callers on a fresh root the same id", async () => {
+ // Both requests are in flight before either resolves. A second, different id here would
+ // sweep the browser's UI state on a page load that changed nothing. Two SERVER PROCESSES
+ // cannot reach this: the root is locked (lock.ts) before either would mint.
+ fs.rmSync(installIdPath(t.root), { force: true });
+
+ const [first, second] = await Promise.all([
+ t.app.request("/api/install"),
+ t.app.request("/api/install"),
+ ]);
+ const idA = ((await first.json()) as InstallResponse).installId;
+ const idB = ((await second.json()) as InstallResponse).installId;
+
+ expect(idA).not.toBeNull();
+ expect(idB).toBe(idA);
+ expect(readInstallId(t.root)).toBe(idA);
+ });
+
+ it("follows the file: a root deleted under a running server reports a new id", async () => {
+ const before = readInstallId(t.root);
+ fs.rmSync(installIdPath(t.root), { force: true });
+
+ const res = await t.app.request("/api/install");
+ const after = ((await res.json()) as InstallResponse).installId;
+ expect(after).not.toBeNull();
+ expect(after).not.toBe(before);
+ });
+});
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 941455bc..7f6b496d 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -43,6 +43,7 @@ import type {
FilesStatRequest,
FilesStatResponse,
GoalResponse,
+ InstallResponse,
McpServerTestResponse,
MeResponse,
MemberAddRequest,
@@ -137,6 +138,12 @@ export const login = (body: AuthLoginRequest) =>
export const logout = () => apiFetch<void>("/api/auth/logout", { method: "POST", body: {} });
+/**
+ * The data root's install identity (public — no session needed, which is the point: the web
+ * app asks before it knows whether anyone is signed in). See lib/install-scope.ts.
+ */
+export const getInstall = () => apiFetch<InstallResponse>("/api/install");
+
export const getMe = () => apiFetch<MeResponse>("/api/me");
export const changePassword = (body: PasswordChangeRequest) =>
diff --git a/packages/web/src/lib/install-scope.ts b/packages/web/src/lib/install-scope.ts
new file mode 100644
index 00000000..95470cc3
--- /dev/null
+++ b/packages/web/src/lib/install-scope.ts
@@ -0,0 +1,487 @@
+/**
+ * Scoping browser-persisted UI state to the data root it was made against.
+ *
+ * The report this exists for: a user deleted their data files, restarted, and the app came
+ * back with the old Workspace still selected. `localStorage` has no relationship to the
+ * data root at all — in the desktop app it lives in Electron's userData directory, so no
+ * amount of deleting `PENGUIN_HOME` touches it — and every key that names an entity names
+ * it with a compile-time constant (`admin`, `default_project`). A wipe-and-restart
+ * re-provisions the same user and the same Project, the keys line up again, and the old
+ * draft, Workspace registry, pins and seen markers all come back.
+ *
+ * So the server names its root (`<root>/install-id`, served by `GET /api/install`) and this
+ * module compares that name against the one this browser last saw. A DIFFERENT name means
+ * the state here was made against a root that is gone, and the keys that reference server
+ * entities are cleared. Same name — including every ordinary restart — clears nothing.
+ *
+ * Why one stored id and a sweep, rather than putting the id into every key name:
+ * - key names stay as they are, so no module that builds a key changes and there is no
+ * migration for keys already on disk;
+ * - a key carrying a dead install id would be an orphan nothing ever reads or deletes,
+ * and each wipe would leave another full set behind. The sweep is the one place
+ * orphans are collected, and it collects them by walking the store;
+ * - the classification below stays readable as a table instead of being spread across
+ * twenty call sites.
+ *
+ * TWO THINGS THE SWEEP ALONE DOES NOT COVER, both of them a live copy of state the store no
+ * longer holds:
+ * - modules evaluated before the sweep ran (the whole static import graph finishes before
+ * main.tsx's first statement) — a swept boot RELOADS rather than renders, see
+ * bootInstallScope;
+ * - other tabs, still open against the root that is gone — see watchInstallScope.
+ *
+ * FIRST SIGHT (a browser with keys but no stored id — every user upgrading into this
+ * release) is indistinguishable from a wiped root, so it ADOPTS the current id and sweeps
+ * nothing. Destroying legitimate state on upgrade would be a far worse bug than the one
+ * being fixed. The practical consequence, which the changelog states plainly: state that is
+ * ALREADY stale when this ships stays stale; only wipes from here on are handled.
+ */
+import * as api from "../api/endpoints";
+
+/** Where this browser records the data root it last saw. Never swept — it IS the marker. */
+export const INSTALL_ID_KEY = "penguin.installId";
+
+/**
+ * What a stored key is tied to.
+ *
+ * - `install` — it references server-side entities (Session ids, Agent ids, Workspace
+ * paths, Project ids, terminal ids, provider group names) that a new data root does not
+ * have. Against a new root it is at best inert and at worst a lie, which is the bug.
+ * - `browser` — a display or input preference of this browser. It names nothing on the
+ * server, so a new root can honour it exactly as the old one did, and wiping a data root
+ * is not a request to reset someone's theme.
+ */
+export type KeyScope = "install" | "browser";
+
+/**
+ * One classification rule. `kind: "exact"` matches the key itself; `kind: "family"` matches
+ * a key prefix that ends in `.` and covers every id-suffixed key under it.
+ *
+ * Plain prefix matching would be wrong twice over, which is why the distinction exists:
+ * `penguin.sidebarCollapsed` (a preference) is a prefix of
+ * `penguin.sidebarCollapsedGroups.<projectId>` (install-scoped), and `penguin.terminal.`
+ * covers both `penguin.terminal.theme` (a preference) and `penguin.terminal.page.id`
+ * (a terminal id).
+ */
+export interface KeyRule {
+ kind: "exact" | "family";
+ key: string;
+ scope: KeyScope;
+ /** Why this scope — one line, kept next to the rule so the two cannot drift apart. */
+ why: string;
+}
+
+/**
+ * Every `penguin.*` key the web app persists in `localStorage`, classified.
+ *
+ * ADDING A KEY: add it here too. An unclassified key is left alone by the sweep (never
+ * deleting something we do not understand is the safe default), so a forgotten
+ * install-scoped key silently reintroduces the bug this module fixes. That is enforced
+ * rather than asked for: install-scope.test.ts scans `packages/web/src` for key literals and
+ * fails on any this table does not cover.
+ *
+ * Two `penguin.*` strings in the source are NOT here on purpose:
+ * - `penguin.chatRouteApplied.<field>` (features/chat/draft-view.tsx) is `sessionStorage`,
+ * not `localStorage`: it is scoped to one tab's history and dies with the tab, so it
+ * cannot outlive a data root.
+ * - `penguin.ooo` (lib/remark-autolink-boundary.ts) is the product's domain inside an
+ * example URL in a doc comment. It is not a storage key.
+ */
+export const KEY_RULES: readonly KeyRule[] = [
+ // ---------------------------------------------------------------- browser preferences
+ {
+ kind: "exact",
+ key: "penguin.theme",
+ scope: "browser",
+ why: "Colour-scheme choice for this browser; names nothing on the server.",
+ },
+ {
+ kind: "exact",
+ key: "penguin.fontScale",
+ scope: "browser",
+ why: "Root font size — a readability preference of this display.",
+ },
+ {
+ kind: "exact",
+ key: "penguin.accent",
+ scope: "browser",
+ why: "Accent colour; pure appearance.",
+ },
+ {
+ kind: "exact",
+ key: "penguin.currency",
+ scope: "browser",
+ why: "Display currency for prices; a formatting choice, prices are stored in USD either way.",
+ },
+ {
+ kind: "exact",
+ key: "penguin.terminal.theme",
+ scope: "browser",
+ why: "Terminal appearance pin (light/dark/follow-app); appearance only.",
+ },
+ {
+ kind: "exact",
+ key: "penguin.lang",
+ scope: "browser",
+ why: "UI language — the one preference a user would be most annoyed to lose.",
+ },
+ {
+ kind: "exact",
+ key: "penguin.sidebarCollapsed",
+ scope: "browser",
+ why: "Whether the sidebar is a narrow rail; chrome layout, holds no entity.",
+ },
+ {
+ kind: "exact",
+ key: "penguin.panelWidth",
+ scope: "browser",
+ why: "Side-panel width in px; its own module calls it a layout preference, not session data.",
+ },
+ {
+ kind: "exact",
+ key: "penguin.sidebarGroupMode",
+ scope: "browser",
+ why: "Group sessions by Workspace/Agent/time — the MODE, not the groups; valid against any root.",
+ },
+ {
+ kind: "exact",
+ key: "penguin.sidebarSortMode",
+ scope: "browser",
+ why: "Recent vs manual ordering — again the mode; the manual order itself is separate and install-scoped.",
+ },
+ {
+ kind: "exact",
+ key: "penguin.sidebarNavGroupCollapsed",
+ scope: "browser",
+ why: "Whether the static page-nav group is folded; the nav is built from a compile-time manifest.",
+ },
+ {
+ kind: "exact",
+ key: "penguin.steerMode",
+ scope: "browser",
+ why: "Steer vs queue-as-follow-up when sending mid-run; a per-user input habit.",
+ },
+
+ // --------------------------------------------------------------- install-scoped state
+ {
+ kind: "family",
+ key: "penguin.chatDraft.",
+ scope: "install",
+ why: "The new-chat and per-Session drafts: Workspace path, Agent id, model ref, Session id in the key. The reported bug.",
+ },
+ {
+ kind: "family",
+ key: "penguin.chatDrafts.",
+ scope: "install",
+ why: "Parked draft conversations — the same contents as an active draft, kept as a list.",
+ },
+ {
+ kind: "family",
+ key: "penguin.sidebarWorkspaces.",
+ scope: "install",
+ why: "Manually registered Workspace paths per Project; a new root has no such Project.",
+ },
+ {
+ kind: "family",
+ key: "penguin.pinnedSessions.",
+ scope: "install",
+ why: "Pinned Session ids.",
+ },
+ {
+ kind: "family",
+ key: "penguin.sessionOrder.",
+ scope: "install",
+ why: "Manual Session order — an array of Session ids.",
+ },
+ {
+ kind: "family",
+ key: "penguin.sessionSeen.",
+ scope: "install",
+ why: "Read markers keyed by Session id; against a new root every Session is new by definition.",
+ },
+ {
+ kind: "family",
+ key: "penguin.groupOrder.",
+ scope: "install",
+ why: "Manual group order — group keys are Agent ids and Workspace paths.",
+ },
+ {
+ kind: "family",
+ key: "penguin.sidebarCollapsedGroups.",
+ scope: "install",
+ why: "Collapsed sidebar groups, keyed by those same Agent ids and Workspace paths.",
+ },
+ {
+ kind: "family",
+ key: "penguin.sidebarPinnedGroups.",
+ scope: "install",
+ why: "Pinned sidebar groups, same key space.",
+ },
+ {
+ kind: "exact",
+ key: "penguin.lastProjectId",
+ scope: "install",
+ why: "The Project id last selected.",
+ },
+ {
+ kind: "family",
+ key: "penguin.lastAgentId.",
+ scope: "install",
+ why: "The Agent id last selected, per Project.",
+ },
+ {
+ kind: "family",
+ key: "penguin.memoryCollapsed.",
+ scope: "install",
+ why: "Collapsed Memory scopes, keyed by user x Project x Agent and holding scope keys.",
+ },
+ {
+ kind: "family",
+ key: "penguin.modelsExpandedGroups.",
+ scope: "install",
+ why: "Expanded provider groups of a Project's model table; includes user-defined group names that live in that Project's config.",
+ },
+ {
+ kind: "family",
+ key: "penguin.modelsGroupOrder.",
+ scope: "install",
+ why: "Manual order of those same per-Project provider groups.",
+ },
+ {
+ kind: "exact",
+ key: "penguin.dock.layout",
+ scope: "install",
+ why: "Dock tab arrangements keyed by conversation, holding Session ids and terminal ids.",
+ },
+ {
+ kind: "exact",
+ key: "penguin.terminal.page.id",
+ scope: "install",
+ why: "The terminal (shell) id the standalone terminal page reattaches to.",
+ },
+];
+
+/**
+ * The scope of a stored key, or null when no rule covers it. Exact rules are consulted
+ * first so a preference is never captured by a family it merely shares a stem with.
+ */
+export function scopeOfKey(key: string): KeyScope | null {
+ for (const rule of KEY_RULES) {
+ if (rule.kind === "exact" && rule.key === key) return rule.scope;
+ }
+ for (const rule of KEY_RULES) {
+ if (rule.kind === "family" && key.startsWith(rule.key)) return rule.scope;
+ }
+ return null;
+}
+
+/**
+ * The subset of `localStorage` this module uses. Enumeration (`length` + `key`) is what
+ * lets one rule cover every id-suffixed key under it and clean up orphans left by earlier
+ * roots. Tests inject an in-memory implementation — vitest runs in Node, with no DOM
+ * (the model-group-expansion.ts convention).
+ */
+export interface InstallScopeStorage {
+ readonly length: number;
+ key(index: number): string | null;
+ getItem(key: string): string | null;
+ setItem(key: string, value: string): void;
+ removeItem(key: string): void;
+}
+
+/**
+ * What one boot's comparison did.
+ *
+ * - `unknown` — no id to compare (the server could not establish one, or the request
+ * failed). Nothing read, nothing written, nothing removed.
+ * - `adopted` — this browser had no id recorded. First sight; the id is stored and nothing
+ * is swept.
+ * - `unchanged` — same root as last time. The ordinary case, including every restart.
+ * - `swept` — a different root. Install-scoped keys removed, preferences kept, and the new
+ * id recorded, so the next load is an ordinary `unchanged` one.
+ * - `swept-unrecorded` — the same removal, except the new id could not be written back
+ * (quota, blocked site data), so the next load compares and sweeps again. Split from
+ * `swept` for one reason: `swept` reloads the page (bootInstallScope) and this one must
+ * not, or every pass would sweep, fail to record, and reload again.
+ */
+export type InstallScopeResult = "unknown" | "adopted" | "unchanged" | "swept" | "swept-unrecorded";
+
+/** Reads one key, treating a throwing store as empty (blocked site data, partitioned iframe). */
+function read(storage: InstallScopeStorage, key: string): string | null {
+ try {
+ return storage.getItem(key);
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Removes every install-scoped key. Keys are collected before anything is removed:
+ * `removeItem` renumbers the store, so deleting during the walk would skip entries.
+ * Returns the keys removed (the caller logs the count; tests assert on it).
+ */
+function sweep(storage: InstallScopeStorage): string[] {
+ const doomed: string[] = [];
+ try {
+ for (let i = 0; i < storage.length; i += 1) {
+ const key = storage.key(i);
+ if (key !== null && scopeOfKey(key) === "install") doomed.push(key);
+ }
+ } catch {
+ return [];
+ }
+ const removed: string[] = [];
+ for (const key of doomed) {
+ try {
+ storage.removeItem(key);
+ removed.push(key);
+ } catch {
+ /* best-effort: a key that refuses to go is swept again on the next load */
+ }
+ }
+ return removed;
+}
+
+/**
+ * Compares the server's install id against the one this browser recorded, and acts on the
+ * difference. Pure with respect to everything but the store, so the whole decision table is
+ * testable without a DOM.
+ *
+ * `installId` of null means the server could not establish one; that is "unknown", never
+ * "new", so nothing is touched. The sweep runs BEFORE the id is stored: if the write fails
+ * (quota, private browsing) the next load repeats the comparison and sweeps again, which is
+ * idempotent — whereas recording an id we had not finished acting on would not be.
+ */
+export function reconcileInstallScope(
+ installId: string | null,
+ storage: InstallScopeStorage,
+): InstallScopeResult {
+ if (installId === null) return "unknown";
+ const stored = read(storage, INSTALL_ID_KEY);
+ if (stored === installId) return "unchanged";
+
+ const swept = stored !== null;
+ if (swept) sweep(storage);
+ try {
+ storage.setItem(INSTALL_ID_KEY, installId);
+ } catch {
+ /* best-effort: unrecorded means the next load compares again, which is harmless */
+ }
+ if (!swept) return "adopted";
+ // Read the marker BACK rather than trust the write: a swept boot reloads, and a sweep
+ // whose marker did not stick would sweep, fail to record and reload again on every pass.
+ return read(storage, INSTALL_ID_KEY) === installId ? "swept" : "swept-unrecorded";
+}
+
+/** How long to wait for the identity before rendering anyway — see syncInstallScope. */
+const INSTALL_ID_TIMEOUT_MS = 3000;
+
+/**
+ * Asks the server for this data root's identity and reconciles the browser's state against
+ * it. Never rejects and never throws: a boot step that can break the whole app is worse
+ * than the surprise it prevents.
+ *
+ * Bounded by a timeout because the caller renders nothing until this settles. The page's
+ * own HTML came from this same server milliseconds earlier, so an answer that takes longer
+ * than three seconds means something is badly wrong — and in that state showing the app
+ * with unswept state beats showing a blank page. Giving up resolves to `unknown`, which
+ * changes nothing; the next load tries again.
+ */
+export async function syncInstallScope(storage?: InstallScopeStorage): Promise<InstallScopeResult> {
+ let installId: string | null = null;
+ try {
+ const timeout = new Promise<null>((resolve) => {
+ setTimeout(() => resolve(null), INSTALL_ID_TIMEOUT_MS);
+ });
+ const answered = await Promise.race([api.getInstall().then((res) => res.installId), timeout]);
+ installId = answered;
+ } catch {
+ // A server that cannot answer is one we cannot identify: sweep nothing.
+ return "unknown";
+ }
+ try {
+ // `localStorage` is resolved INSIDE the try, never as a default parameter: merely
+ // touching it throws a SecurityError when site data is blocked (the convention every
+ // storage module here follows).
+ return reconcileInstallScope(installId, storage ?? localStorage);
+ } catch {
+ return "unknown";
+ }
+}
+
+/** What the boot does with the page once this browser's state has been reconciled. */
+export type BootAction = "mount" | "reload";
+
+/**
+ * The whole pre-mount step as one call: ask the server for the data root's identity,
+ * reconcile this browser's stored state against it, and say whether the page may render or
+ * has to start over.
+ *
+ * A RECORDED SWEEP RELOADS. ES module evaluation of the entire static import graph finishes
+ * before main.tsx's first statement runs, so a module that reads `localStorage` at module
+ * scope — features/dock/dock-state.ts parses `penguin.dock.layout` into module state there —
+ * is already holding a copy of keys the sweep then deletes, and its first write puts the
+ * whole map back. The id matches by then, so nothing ever sweeps it again and the
+ * resurrection is permanent. A reload re-evaluates every module against the cleaned store
+ * and the second pass reconciles to `unchanged`. Making that one module lazy would fix that
+ * one module and leave the class open for the next one; this holds however the import graph
+ * grows, and it costs one extra load only when the data root was actually replaced.
+ *
+ * `swept-unrecorded` deliberately mounts: reloading on a sweep whose marker did not stick
+ * would sweep, fail to record and reload again, forever.
+ */
+export async function bootInstallScope(storage?: InstallScopeStorage): Promise<BootAction> {
+ return (await syncInstallScope(storage)) === "swept" ? "reload" : "mount";
+}
+
+/** The `storage` event fields the cross-tab decision needs (tests pass a plain object). */
+export interface InstallIdChange {
+ key: string | null;
+ oldValue: string | null;
+ newValue: string | null;
+}
+
+/**
+ * What another tab's `storage` event means here, and whether this tab must reload.
+ *
+ * The sweep runs once per page load, so a tab that was ALREADY open when a second tab
+ * recognised the new root still holds the old root's state in module and component memory
+ * and writes it back on the next pin, reorder or draft keystroke — restoring keys the other
+ * tab removed, under an id that now matches and will never be swept again. A `storage` event
+ * fires in every OTHER tab of this origin, which is exactly the set that has to hear about
+ * it: sweep whatever this tab has already put back, and report that it must reload, so no
+ * live copy survives to write it a second time.
+ *
+ * Only an id REPLACED by a different id is a root that was wiped. A first recording
+ * (`oldValue` null) is that tab's adoption, which swept nothing; a removal (`newValue` null)
+ * is site data being cleared, which the next load adopts from scratch. Neither concerns the
+ * state held here.
+ */
+export function reactToInstallIdChange(
+ change: InstallIdChange,
+ storage: InstallScopeStorage,
+): boolean {
+ if (change.key !== INSTALL_ID_KEY) return false;
+ if (change.oldValue === null || change.newValue === null) return false;
+ if (change.oldValue === change.newValue) return false;
+ sweep(storage);
+ return true;
+}
+
+/**
+ * Wires reactToInstallIdChange to this browser's cross-tab `storage` events for the life of
+ * the page. A no-op where there is no window (tests, prerendering).
+ */
+export function watchInstallScope(storage?: InstallScopeStorage): void {
+ if (typeof window === "undefined") return;
+ window.addEventListener("storage", (event) => {
+ let stale = false;
+ try {
+ // `localStorage` is resolved INSIDE the try for the same reason syncInstallScope does.
+ stale = reactToInstallIdChange(event, storage ?? localStorage);
+ } catch {
+ return; // blocked site data: there was nothing readable to restore either
+ }
+ if (stale) location.reload();
+ });
+}
diff --git a/packages/web/src/main.tsx b/packages/web/src/main.tsx
index 76edf001..0ecf1f0b 100644
--- a/packages/web/src/main.tsx
+++ b/packages/web/src/main.tsx
@@ -1,10 +1,28 @@
/**
* Frontend entry point: mounts the React root component (the frontend SPA is only
* responsible for rendering and interaction).
+ *
+ * One thing happens before the mount: the browser's persisted UI state is reconciled
+ * against the data root the server is actually serving (lib/install-scope.ts). It has to be
+ * HERE and not in a provider, because the state it may clear is read from `useState`
+ * initializers scattered through the tree — the sidebar's pins and order, the composer's
+ * draft — and those run during the first render. A sweep that arrived one effect later
+ * would let a stale draft be read once and then deleted underneath the component holding
+ * it, which is worse than either doing nothing or doing it in time. Before `createRoot`
+ * there is provably no component to have read anything.
+ *
+ * It costs one same-origin request to the server this page was just served by, and it is
+ * bounded (see syncInstallScope): it can delay the first paint, it can never prevent it.
+ *
+ * A boot that actually swept RELOADS instead of mounting, and does not render at all on this
+ * pass — every module in the static import graph was evaluated before this file ran, so any
+ * that read the store at module scope is holding keys the sweep just removed. See
+ * bootInstallScope for why that is the remedy rather than making those modules lazy.
*/
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { App } from "./app";
+import { bootInstallScope, watchInstallScope } from "./lib/install-scope";
// KaTeX's stylesheet and its woff2 faces, resolved out of node_modules so Vite emits them as local
// assets: the desktop app has to render math with no network, and a CDN <link> would leave every
// formula as unstyled markup offline. Imported before styles.css so the app's own `.katex` rules
@@ -15,8 +33,21 @@ import "./styles.css";
const container = document.getElementById("root");
if (!container) throw new Error("#root mount point not found");
-createRoot(container).render(
- <StrictMode>
- <App />
- </StrictMode>,
-);
+function mount(): void {
+ createRoot(container!).render(
+ <StrictMode>
+ <App />
+ </StrictMode>,
+ );
+}
+
+// A second tab can recognise a replaced root while this one is open, leaving everything on
+// screen here pointing at a data root that is gone.
+watchInstallScope();
+
+// The rejection handler mounts too: bootInstallScope already swallows everything it can, and
+// the app must mount even if it somehow does not.
+void bootInstallScope().then((action) => {
+ if (action === "reload") location.reload();
+ else mount();
+}, mount);
diff --git a/packages/web/test/install-scope.test.ts b/packages/web/test/install-scope.test.ts
new file mode 100644
index 00000000..fb237f64
--- /dev/null
+++ b/packages/web/test/install-scope.test.ts
@@ -0,0 +1,620 @@
+/**
+ * install-scope.ts unit tests: reconciling browser-persisted UI state against the data root
+ * the server is actually serving.
+ *
+ * The decision table, in full — a changed install id sweeps the keys that reference server
+ * entities and leaves browser preferences alone; an unchanged id (every ordinary restart)
+ * touches nothing; a first sight with keys and no recorded id ADOPTS without sweeping, so
+ * upgrading into this release never destroys legitimate state; an unknown id changes
+ * nothing at all. Plus the two matching traps the classification exists to avoid
+ * (`penguin.sidebarCollapsed` under `penguin.sidebarCollapsedGroups.`,
+ * `penguin.terminal.theme` beside `penguin.terminal.page.id`), and storage that throws.
+ *
+ * The classification is also checked against the SOURCE rather than against a fixture: a key
+ * added to the app and forgotten here is the one way this module silently stops working.
+ */
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { setUnauthorizedHandler } from "../src/api/client";
+import {
+ bootInstallScope,
+ INSTALL_ID_KEY,
+ KEY_RULES,
+ reactToInstallIdChange,
+ reconcileInstallScope,
+ scopeOfKey,
+ syncInstallScope,
+} from "../src/lib/install-scope";
+import type { InstallScopeStorage } from "../src/lib/install-scope";
+
+/** In-memory storage (vitest runs in a Node environment, no localStorage; pinned-sessions.test.ts convention). */
+function memStorage(entries: Record<string, string> = {}): InstallScopeStorage & {
+ map: Map<string, string>;
+} {
+ const map = new Map<string, string>(Object.entries(entries));
+ return {
+ map,
+ get length() {
+ return map.size;
+ },
+ key: (i) => [...map.keys()][i] ?? null,
+ getItem: (k) => map.get(k) ?? null,
+ setItem: (k, v) => void map.set(k, v),
+ removeItem: (k) => void map.delete(k),
+ };
+}
+
+/** A representative populated store: install-scoped state on the left, preferences on the right. */
+function populated(): ReturnType<typeof memStorage> {
+ return memStorage({
+ "penguin.chatDraft.admin.default_project": '{"workspace":"/srv/app","agentId":"default_agent"}',
+ "penguin.chatDraft.session.admin.session-1": '{"text":"half a sentence"}',
+ "penguin.chatDrafts.admin.default_project": '[{"id":"draft-abcd1234"}]',
+ "penguin.sidebarWorkspaces.default_project": '[{"path":"/srv/app"}]',
+ "penguin.pinnedSessions.default_project": '["session-1"]',
+ "penguin.sessionOrder.default_project.workspace": '["session-1"]',
+ "penguin.sessionSeen.default_project": '{"session-1":"2026-08-26T00:00:00Z"}',
+ "penguin.groupOrder.default_project.workspace": '["/srv/app"]',
+ "penguin.sidebarCollapsedGroups.default_project": '["/srv/app"]',
+ "penguin.sidebarPinnedGroups.default_project": '["/srv/app"]',
+ "penguin.lastProjectId": "default_project",
+ "penguin.lastAgentId.default_project": "default_agent",
+ "penguin.memoryCollapsed.admin.default_project.default_agent": '["project"]',
+ "penguin.modelsExpandedGroups.default_project": '["anthropic"]',
+ "penguin.modelsGroupOrder.default_project": '["anthropic"]',
+ "penguin.dock.layout": '{"scopes":{"session-1":{}},"bottomRatio":0.4}',
+ "penguin.terminal.page.id": "term-1",
+
+ "penguin.theme": "dark",
+ "penguin.fontScale": "lg",
+ "penguin.accent": "violet",
+ "penguin.currency": "CNY",
+ "penguin.terminal.theme": "dark",
+ "penguin.lang": "en",
+ "penguin.sidebarCollapsed": "1",
+ "penguin.panelWidth": "420",
+ "penguin.sidebarGroupMode": "agent",
+ "penguin.sidebarSortMode": "manual",
+ "penguin.sidebarNavGroupCollapsed": "collapsed",
+ "penguin.steerMode": "followup",
+ });
+}
+
+/** Order-independent snapshot of a store, so assertions do not depend on Map insertion order. */
+function snap(map: Map<string, string>): [string, string][] {
+ return [...map.entries()].sort(([a], [b]) => a.localeCompare(b));
+}
+
+const PREFERENCE_KEYS = [
+ "penguin.theme",
+ "penguin.fontScale",
+ "penguin.accent",
+ "penguin.currency",
+ "penguin.terminal.theme",
+ "penguin.lang",
+ "penguin.sidebarCollapsed",
+ "penguin.panelWidth",
+ "penguin.sidebarGroupMode",
+ "penguin.sidebarSortMode",
+ "penguin.sidebarNavGroupCollapsed",
+ "penguin.steerMode",
+];
+
+const WEB_SRC = fileURLToPath(new URL("../src", import.meta.url));
+
+/**
+ * Keys the source contains that KEY_RULES deliberately does not classify, each with the
+ * reason. Anything else the scan finds has to be in the table: a key the sweep does not
+ * recognise is left alone, which is exactly how the bug this module fixes comes back.
+ */
+const UNCLASSIFIED_ON_PURPOSE: Record<string, string> = {
+ "penguin.installId": "the marker itself — it is what the comparison reads, never swept",
+ "penguin.chatRouteApplied.":
+ "sessionStorage: scoped to one tab's history, so it cannot outlive a data root",
+};
+
+/**
+ * Every `penguin.*` key literal in the web source, mapped to the file it was found in.
+ *
+ * Block comments are stripped first, and a match must follow a quote or backtick: prose
+ * names key PREFIXES (`penguin.terminal.`), a family without its dot, and the product's own
+ * domain in an example URL (`penguin.ooo`), and none of those is a storage key.
+ */
+function storageKeysInSource(): Map<string, string> {
+ const found = new Map<string, string>();
+ const walk = (dir: string): void => {
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ walk(full);
+ } else if (/\.tsx?$/.test(entry.name)) {
+ const code = fs.readFileSync(full, "utf8").replace(/\/\*[\s\S]*?\*\//g, "");
+ for (const match of code.matchAll(/["'`](penguin\.[A-Za-z0-9_.]*)/g)) {
+ const key = match[1]!;
+ if (!found.has(key)) found.set(key, path.relative(WEB_SRC, full));
+ }
+ }
+ }
+ };
+ walk(WEB_SRC);
+ return found;
+}
+
+describe("install-scope classification", () => {
+ it("classifies every penguin.* key the web source actually persists", () => {
+ const found = storageKeysInSource();
+ // A scan that finds nothing would pass every assertion below without checking anything.
+ expect(found.size).toBeGreaterThan(20);
+ for (const [key, file] of found) {
+ if (key in UNCLASSIFIED_ON_PURPOSE) continue;
+ expect(scopeOfKey(key), `${key} (src/${file}) is missing from KEY_RULES`).not.toBeNull();
+ }
+ });
+
+ it("keeps the deliberate exclusions honest: each is still a key the source contains", () => {
+ const found = storageKeysInSource();
+ for (const key of Object.keys(UNCLASSIFIED_ON_PURPOSE)) {
+ expect(found.has(key), `${key} is no longer in the source`).toBe(true);
+ }
+ });
+
+ it("covers every key the populated fixture holds, with no key both scopes", () => {
+ for (const key of populated().map.keys()) {
+ expect(scopeOfKey(key), key).not.toBeNull();
+ }
+ for (const key of PREFERENCE_KEYS) {
+ expect(scopeOfKey(key), key).toBe("browser");
+ }
+ });
+
+ it("an exact preference is not captured by a family that shares its stem", () => {
+ // The two traps plain prefix matching would fall into.
+ expect(scopeOfKey("penguin.sidebarCollapsed")).toBe("browser");
+ expect(scopeOfKey("penguin.sidebarCollapsedGroups.default_project")).toBe("install");
+ expect(scopeOfKey("penguin.terminal.theme")).toBe("browser");
+ expect(scopeOfKey("penguin.terminal.page.id")).toBe("install");
+ });
+
+ it("an unclassified key has no scope, so the sweep leaves it alone", () => {
+ expect(scopeOfKey("penguin.somethingAddedLater")).toBeNull();
+ expect(scopeOfKey("unrelated-app-key")).toBeNull();
+ expect(scopeOfKey(INSTALL_ID_KEY)).toBeNull();
+ });
+
+ it("rules are well formed: penguin-namespaced, families dotted, no duplicates", () => {
+ const seen = new Set<string>();
+ for (const rule of KEY_RULES) {
+ expect(rule.key.startsWith("penguin."), rule.key).toBe(true);
+ expect(rule.why.length, rule.key).toBeGreaterThan(0);
+ if (rule.kind === "family") expect(rule.key.endsWith("."), rule.key).toBe(true);
+ expect(seen.has(rule.key), rule.key).toBe(false);
+ seen.add(rule.key);
+ }
+ });
+});
+
+describe("reconcileInstallScope", () => {
+ it("a changed install id sweeps install-scoped keys and keeps preferences", () => {
+ const storage = populated();
+ storage.map.set(INSTALL_ID_KEY, "root-a");
+
+ expect(reconcileInstallScope("root-b", storage)).toBe("swept");
+
+ for (const key of storage.map.keys()) {
+ expect(scopeOfKey(key), `${key} survived the sweep`).not.toBe("install");
+ }
+ for (const key of PREFERENCE_KEYS) {
+ expect(storage.map.has(key), key).toBe(true);
+ }
+ expect(storage.map.get("penguin.theme")).toBe("dark");
+ expect(storage.map.get(INSTALL_ID_KEY)).toBe("root-b");
+ });
+
+ it("the sweep collects orphans from every earlier root, not just the last one", () => {
+ // Keys are id-suffixed, so a Project or Session that no longer exists leaves an entry
+ // nothing would ever read again. Walking the store is what reaches them.
+ const storage = memStorage({
+ [INSTALL_ID_KEY]: "root-a",
+ "penguin.chatDraft.admin.default_project": "{}",
+ "penguin.pinnedSessions.long_gone_project": '["session-9"]',
+ "penguin.sessionSeen.another_dead_project": "{}",
+ "penguin.theme": "dark",
+ });
+
+ expect(reconcileInstallScope("root-b", storage)).toBe("swept");
+ expect([...storage.map.keys()].sort()).toEqual([INSTALL_ID_KEY, "penguin.theme"]);
+ });
+
+ it("an unchanged install id sweeps nothing (the ordinary server restart)", () => {
+ const storage = populated();
+ storage.map.set(INSTALL_ID_KEY, "root-a");
+ const before = new Map(storage.map);
+
+ expect(reconcileInstallScope("root-a", storage)).toBe("unchanged");
+ expect(snap(storage.map)).toEqual(snap(before));
+ });
+
+ it("first sight — keys but no recorded id — adopts without sweeping", () => {
+ const storage = populated();
+ const before = new Map(storage.map);
+
+ expect(reconcileInstallScope("root-a", storage)).toBe("adopted");
+ expect(storage.map.get(INSTALL_ID_KEY)).toBe("root-a");
+ storage.map.delete(INSTALL_ID_KEY);
+ expect(snap(storage.map)).toEqual(snap(before));
+ });
+
+ it("an adopted id makes the very next boot an ordinary unchanged one", () => {
+ const storage = populated();
+ expect(reconcileInstallScope("root-a", storage)).toBe("adopted");
+ expect(reconcileInstallScope("root-a", storage)).toBe("unchanged");
+ expect(reconcileInstallScope("root-b", storage)).toBe("swept");
+ });
+
+ it("an unknown id (server could not establish one) changes nothing at all", () => {
+ const storage = populated();
+ const before = new Map(storage.map);
+
+ expect(reconcileInstallScope(null, storage)).toBe("unknown");
+ expect(snap(storage.map)).toEqual(snap(before));
+ });
+
+ it("a throwing store degrades instead of escaping", () => {
+ const throwing: InstallScopeStorage = {
+ get length(): number {
+ throw new Error("site data is blocked");
+ },
+ key: () => {
+ throw new Error("site data is blocked");
+ },
+ getItem: () => {
+ throw new Error("site data is blocked");
+ },
+ setItem: () => {
+ throw new Error("site data is blocked");
+ },
+ removeItem: () => {
+ throw new Error("site data is blocked");
+ },
+ };
+ // getItem throwing reads as "nothing recorded", so this is a first sight that adopts;
+ // the adopting write throws too and is swallowed.
+ expect(() => reconcileInstallScope("root-a", throwing)).not.toThrow();
+ expect(reconcileInstallScope("root-a", throwing)).toBe("adopted");
+ });
+
+ it("a sweep whose marker cannot be recorded is reported apart from one that stuck", () => {
+ const storage = populated();
+ storage.map.set(INSTALL_ID_KEY, "root-a");
+ const readOnlyMarker: InstallScopeStorage = {
+ ...storage,
+ get length(): number {
+ return storage.length;
+ },
+ key: (i) => storage.key(i),
+ setItem: () => {
+ throw new Error("quota exceeded");
+ },
+ };
+
+ // The keys still go; only the marker fails to land, so the next load compares again.
+ expect(reconcileInstallScope("root-b", readOnlyMarker)).toBe("swept-unrecorded");
+ expect(storage.map.has("penguin.chatDraft.admin.default_project")).toBe(false);
+ expect(storage.map.get(INSTALL_ID_KEY)).toBe("root-a");
+ expect(storage.map.get("penguin.theme")).toBe("dark");
+ });
+
+ it("a store that throws only on enumeration sweeps nothing rather than half of it", () => {
+ const storage = populated();
+ storage.map.set(INSTALL_ID_KEY, "root-a");
+ const before = new Map(storage.map);
+ const half: InstallScopeStorage = {
+ ...storage,
+ get length(): number {
+ throw new Error("site data is blocked");
+ },
+ setItem: (k, v) => storage.setItem(k, v),
+ };
+
+ expect(reconcileInstallScope("root-b", half)).toBe("swept");
+ before.set(INSTALL_ID_KEY, "root-b");
+ expect(snap(storage.map)).toEqual(snap(before));
+ });
+});
+
+describe("syncInstallScope", () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it("reconciles against the id the server reports", async () => {
+ vi.stubGlobal(
+ "fetch",
+ async () =>
+ new Response(JSON.stringify({ installId: "root-b" }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ const storage = populated();
+ storage.map.set(INSTALL_ID_KEY, "root-a");
+
+ expect(await syncInstallScope(storage)).toBe("swept");
+ expect(storage.map.has("penguin.chatDraft.admin.default_project")).toBe(false);
+ expect(storage.map.get("penguin.theme")).toBe("dark");
+ });
+
+ it("a server that cannot be reached sweeps nothing and never rejects", async () => {
+ vi.stubGlobal("fetch", async () => {
+ throw new Error("connection refused");
+ });
+ const storage = populated();
+ storage.map.set(INSTALL_ID_KEY, "root-a");
+ const before = new Map(storage.map);
+
+ await expect(syncInstallScope(storage)).resolves.toBe("unknown");
+ expect(snap(storage.map)).toEqual(snap(before));
+ });
+
+ it("a server reporting a null identity sweeps nothing", async () => {
+ vi.stubGlobal(
+ "fetch",
+ async () =>
+ new Response(JSON.stringify({ installId: null }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ const storage = populated();
+ storage.map.set(INSTALL_ID_KEY, "root-a");
+ const before = new Map(storage.map);
+
+ await expect(syncInstallScope(storage)).resolves.toBe("unknown");
+ expect(snap(storage.map)).toEqual(snap(before));
+ });
+
+ it("a storage that throws on every access still lets boot proceed", async () => {
+ vi.stubGlobal(
+ "fetch",
+ async () =>
+ new Response(JSON.stringify({ installId: "root-b" }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ const exploding = new Proxy({} as InstallScopeStorage, {
+ get() {
+ throw new Error("site data is blocked");
+ },
+ });
+
+ // Every read reads as empty, so this looks like a first sight and adopts — an adoption
+ // that stores nothing, because the write throws too. Nothing is destroyed and boot
+ // continues, which is the whole requirement.
+ await expect(syncInstallScope(exploding)).resolves.toBe("adopted");
+ });
+
+ it("a non-2xx answer sweeps nothing", async () => {
+ vi.stubGlobal(
+ "fetch",
+ async () =>
+ new Response(
+ JSON.stringify({ error: { code: "unauthorized", message: "Not signed in." } }),
+ { status: 401, headers: { "content-type": "application/json" } },
+ ),
+ );
+ // apiFetch takes a different branch from the network failure above: it parses the error
+ // body and, for a 401 outside /api/auth/, calls the global sign-out hook. Nothing is
+ // registered at this point in the boot — AuthProvider installs one during the first
+ // render, which has not happened — so the probe stays invisible; the spy pins that the
+ // hook is reached at all, since registering one EARLIER would then sign the user out.
+ const signedOut = vi.fn();
+ setUnauthorizedHandler(signedOut);
+ const storage = populated();
+ storage.map.set(INSTALL_ID_KEY, "root-a");
+ const before = new Map(storage.map);
+
+ try {
+ await expect(syncInstallScope(storage)).resolves.toBe("unknown");
+ expect(signedOut).toHaveBeenCalledTimes(1);
+ expect(snap(storage.map)).toEqual(snap(before));
+ } finally {
+ setUnauthorizedHandler(null);
+ }
+ });
+
+ it("gives up on a server that never answers, after three seconds, having swept nothing", async () => {
+ vi.useFakeTimers();
+ try {
+ // A request that never settles: the page renders nothing until this resolves, so the
+ // bound is the whole reason the timeout exists.
+ vi.stubGlobal("fetch", () => new Promise<Response>(() => {}));
+ const storage = populated();
+ storage.map.set(INSTALL_ID_KEY, "root-a");
+ const before = new Map(storage.map);
+
+ const pending = syncInstallScope(storage);
+ let settled = false;
+ void pending.then(() => {
+ settled = true;
+ });
+
+ await vi.advanceTimersByTimeAsync(2999);
+ expect(settled).toBe(false);
+ await vi.advanceTimersByTimeAsync(1);
+
+ await expect(pending).resolves.toBe("unknown");
+ expect(snap(storage.map)).toEqual(snap(before));
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
+/**
+ * The two-pass boot. dock-state.ts parses `penguin.dock.layout` into module state AT MODULE
+ * EVALUATION, which ES semantics put before main.tsx's first statement — so these tests
+ * install the storage global first and import that module dynamically, in the order a
+ * browser does it.
+ */
+describe("bootInstallScope", () => {
+ /** A bottom dock holding one terminal tab, arranged against the root that is about to go. */
+ const DOCK_FROM_ROOT_A = JSON.stringify({
+ scopes: {
+ "session-1": {
+ right: { tabs: [], active: null, open: false },
+ bottom: { tabs: ["terminal:term-abc"], active: "terminal:term-abc", open: true },
+ focus: "bottom",
+ },
+ },
+ bottomRatio: 0.4,
+ });
+
+ function installStorageGlobal(storage: InstallScopeStorage): void {
+ Object.defineProperty(globalThis, "localStorage", { configurable: true, value: storage });
+ }
+
+ function serverReports(installId: string | null): void {
+ vi.stubGlobal(
+ "fetch",
+ async () =>
+ new Response(JSON.stringify({ installId }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ }
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ Reflect.deleteProperty(globalThis, "localStorage");
+ vi.resetModules();
+ });
+
+ it("a swept boot reloads instead of rendering, and the second pass cannot resurrect the dock", async () => {
+ const storage = memStorage({
+ [INSTALL_ID_KEY]: "root-a",
+ "penguin.dock.layout": DOCK_FROM_ROOT_A,
+ "penguin.theme": "dark",
+ });
+ installStorageGlobal(storage);
+ serverReports("root-b");
+
+ // Pass one. Every module evaluates before main.tsx runs a statement, so dock-state is
+ // already holding the pre-wipe map — including a terminal tab whose shell died with the
+ // old root — and its first scope switch would write the whole thing back.
+ vi.resetModules();
+ await import("../src/features/dock/dock-state");
+
+ expect(await bootInstallScope()).toBe("reload");
+ expect(storage.map.has("penguin.dock.layout")).toBe(false);
+
+ // Pass two — the reload. Every module re-evaluates against the swept store.
+ vi.resetModules();
+ const dock = await import("../src/features/dock/dock-state");
+ expect(await bootInstallScope()).toBe("mount");
+
+ // The first route resolution's setDockScope is what persisted the old map; here it can
+ // only persist what the fresh evaluation read, which is nothing.
+ dock.setDockScope("new");
+ const persisted = storage.map.get("penguin.dock.layout") ?? "";
+ expect(persisted).not.toContain("term-abc");
+ expect(persisted).not.toContain("session-1");
+ expect(storage.map.get("penguin.theme")).toBe("dark");
+ });
+
+ it("mounts on every outcome that swept nothing, and on a sweep that could not be recorded", async () => {
+ const unchanged = memStorage({ [INSTALL_ID_KEY]: "root-a" });
+ installStorageGlobal(unchanged);
+ serverReports("root-a");
+ expect(await bootInstallScope()).toBe("mount");
+
+ const firstSight = memStorage({ "penguin.theme": "dark" });
+ installStorageGlobal(firstSight);
+ serverReports("root-a");
+ expect(await bootInstallScope()).toBe("mount");
+
+ const unknown = memStorage({ [INSTALL_ID_KEY]: "root-a" });
+ installStorageGlobal(unknown);
+ serverReports(null);
+ expect(await bootInstallScope()).toBe("mount");
+
+ // The reload would otherwise repeat forever: sweep, fail to record, reload, sweep again.
+ const backing = memStorage({ [INSTALL_ID_KEY]: "root-a", "penguin.lastProjectId": "p1" });
+ installStorageGlobal({
+ ...backing,
+ get length(): number {
+ return backing.length;
+ },
+ key: (i) => backing.key(i),
+ setItem: () => {
+ throw new Error("quota exceeded");
+ },
+ });
+ serverReports("root-b");
+ expect(await bootInstallScope()).toBe("mount");
+ expect(backing.map.has("penguin.lastProjectId")).toBe(false);
+ });
+});
+
+describe("a tab left open across the wipe", () => {
+ it("sweeps its own re-persisted state when another tab records a different root", () => {
+ const storage = populated();
+ storage.map.set(INSTALL_ID_KEY, "root-b"); // the other tab already recorded it
+
+ const stale = reactToInstallIdChange(
+ { key: INSTALL_ID_KEY, oldValue: "root-a", newValue: "root-b" },
+ storage,
+ );
+
+ expect(stale).toBe(true);
+ for (const key of storage.map.keys()) {
+ expect(scopeOfKey(key), `${key} survived the sweep`).not.toBe("install");
+ }
+ expect(storage.map.get("penguin.theme")).toBe("dark");
+ });
+
+ it("ignores the other tab's FIRST recording, which swept nothing itself", () => {
+ const storage = populated();
+ const before = new Map(storage.map);
+
+ expect(
+ reactToInstallIdChange({ key: INSTALL_ID_KEY, oldValue: null, newValue: "root-a" }, storage),
+ ).toBe(false);
+ expect(snap(storage.map)).toEqual(snap(before));
+ });
+
+ it("ignores site data being cleared, and a rewrite of the same id", () => {
+ const storage = populated();
+ const before = new Map(storage.map);
+
+ expect(
+ reactToInstallIdChange({ key: INSTALL_ID_KEY, oldValue: "root-a", newValue: null }, storage),
+ ).toBe(false);
+ expect(
+ reactToInstallIdChange(
+ { key: INSTALL_ID_KEY, oldValue: "root-a", newValue: "root-a" },
+ storage,
+ ),
+ ).toBe(false);
+ expect(snap(storage.map)).toEqual(snap(before));
+ });
+
+ it("ignores every other key, including the ones it would otherwise sweep", () => {
+ const storage = populated();
+ const before = new Map(storage.map);
+
+ expect(
+ reactToInstallIdChange(
+ { key: "penguin.pinnedSessions.default_project", oldValue: "[]", newValue: '["s1"]' },
+ storage,
+ ),
+ ).toBe(false);
+ expect(reactToInstallIdChange({ key: null, oldValue: null, newValue: null }, storage)).toBe(
+ false,
+ );
+ expect(snap(storage.map)).toEqual(snap(before));
+ });
+});