A local-first multi-agent app development platform, built on PenguinHarness
feat(web,server): 主题文件放进数据根就能导入,外观页里可选
lmlihengcc06123b3fc8
diff --git a/changelog/unreleased/2026-10-23-imported-themes.md b/changelog/unreleased/2026-10-23-imported-themes.mdnew file mode 100644index 00000000..94fd6733--- /dev/null+++ b/changelog/unreleased/2026-10-23-imported-themes.md@@ -0,0 +1,58 @@+# A theme can live in your data root now, and the appearance page offers it++- **Date:** 2026-10-23+- **Type:** feat+- **Scope:** `core`, `server`, `ui`, `web`+- **Breaking:** no++[中文](2026-10-23-imported-themes.zh.md)++A theme has always been one thing: a set of values for the UI's token names. Every component reads+those names and not one of them asks which theme is active, so a theme that arrives as data repaints+the whole app — no rebuild, no plugin, no code that runs. Drop a JSON file in `<data root>/themes/`+and the next page load offers it in **Settings › Appearance**, beside the three that ship.++The appearance page also says where to put a file (the exact directory the server read), what a file+got wrong, and which accent presets the chosen theme offers — including a theme's own, taken from the+same file.++`examples/themes/warm-paper.json` is a theme to start from: warm paper surfaces, a terracotta accent,+three presets.++## Details++- **Format.** `{ "schemaVersion": 1, "id", "name", "nameZh"?, "light": {"--ui-…": value}, "dark"?: {…},+ "accents"?: [{ "id", "light", "dark"? }] }`, at most 400 names and 12 presets per file. `light` is+ the base both modes start from, `dark` changes only what differs, and each preset is scoped to its+ own theme. A value is one line, at most 120 characters, and may not contain `;` `{` `}` `<` `\` `@`+ or a newline, nor fetch anything (`url(`, `image-set(`): an imported theme is confined to token+ values, so it cannot add a rule, hide an element or call home.+- **The server** (`server/src/http/routes/themes.ts`): `GET /api/themes` lists what read plus the+ files that did not, behind the login; `GET /api/themes.css` is the same files as one stylesheet and+ is public, because `index.html` links it in `<head>` and the sign-in page is a page like any other.+ Every request re-reads the directory — no restart, no cache — and one broken file costs nobody else:+ it is named with its reason and left out of the sheet. Two files claiming one id reject the later+ one.+- **The rules** (`core/src/internal/external-theme.ts`, so both ends share one reading) are emitted in+ the named layers `ui-theme` and `ui-accent`, on `:root[data-theme="…"]` with the base rule reaching+ both modes — an unlayered rule would beat the user's own font pairing, and the two-selector base+ rule needs no promise about which sheet the browser read first.+- **The app** (`web/src/state/external-themes.ts`) makes the judgement the other two cannot: the token+ names are the UI package's contract, so a name the contract has never heard of is reported (it paints+ nothing) while a name a file leaves out is only listed (it keeps the default theme's value). The+ readers in `state/theme-prefs.ts` — and the pre-paint script in `index.html` — now accept any+ well-formed id instead of a fixed list, so an imported theme's id survives a reload even while its+ file is being read; a malformed one, and an absent value, still read as the default theme.+- Tests: `core/test/external-theme.test.ts` (shape and safety), `server/test/themes.test.ts` (the two+ routes, a broken file, a duplicate id, an edit that lands on the next read), `web/test/external-themes.test.ts`+ (the contract judgement, the swatches, the read), and the updated `web/test/theme-prefs.test.ts` /+ `ui/test/boot-script.test.ts` for the open id space.++## Compatibility++- Nothing stored, wired or built changes: an installation with no `themes/` directory gets one comment+ from the sheet and the same three themes as before. The stylesheet link is a no-op request for it.+- The file format is versioned (`schemaVersion`); an unknown version is refused with the reason rather+ than half-read.+- No dependency change. The three shipped themes are untouched — an imported theme can only paint+ under its own id.diff --git a/changelog/unreleased/2026-10-23-imported-themes.zh.md b/changelog/unreleased/2026-10-23-imported-themes.zh.mdnew file mode 100644index 00000000..fa67d929--- /dev/null+++ b/changelog/unreleased/2026-10-23-imported-themes.zh.md@@ -0,0 +1,46 @@+# 主题可以放在数据根里自己导入,外观页会把它列出来++- **Date:** 2026-10-23+- **Type:** feat+- **Scope:** `core`, `server`, `ui`, `web`+- **Breaking:** no++[English](2026-10-23-imported-themes.md)++主题一直只有一件事:给 UI 的那些令牌名一组取值。每个组件都只读这些名字、从不问现在是哪个主题,所以以数据+形式来的主题能重画整个应用——不用重新构建、不用插件、没有会跑起来的代码。把一个 JSON 文件放进+`<数据根>/themes/`,下一次刷新页面它就会出现在**设置 › 外观**的主题列表里,和自带的三套并列。++外观页还会写出文件该放哪儿(服务端真正读的那个目录)、某个文件哪里写错了,以及当前这套主题提供哪几个强调色+——包括主题自己的那个,也是从同一个文件里读的。++`examples/themes/warm-paper.json` 可以直接拿来改:暖色纸张底、陶土强调色,外加三个预设。++## 细节++- **格式**:`{ "schemaVersion": 1, "id", "name", "nameZh"?, "light": {"--ui-…": 值}, "dark"?: {…},+ "accents"?: [{ "id", "light", "dark"? }] }`,一个文件最多 400 个名字、12 个预设。`light` 是两种模式共同的+ 底,`dark` 只写明暗不同的部分,每个预设只在自己那套主题下生效。一个值只写一行、最长 120 字符,不能含+ `;` `{` `}` `<` `\` `@` 和换行,也不能去取外部资源(`url(`、`image-set(`):外置主题只能改这些令牌的取值,+ 不能加规则、藏元素或往外发请求。+- **服务端**(`server/src/http/routes/themes.ts`):`GET /api/themes` 给出读到的主题与读不了的文件,要登录;+ `GET /api/themes.css` 是同一批文件拼成的一张样式表,**不需要登录**——`index.html` 在 `<head>` 里就链接了它,+ 而登录页也是一张页面。每次请求都重读目录(不用重启、没有缓存),一个坏文件也不耽误别人:它带着原因被列出来,+ 只是不进样式表。两个文件抢同一个主题名时,后一个被拒。+- **规则**(`core/src/internal/external-theme.ts`,两端共用一份读法)写在具名的 `ui-theme` 与 `ui-accent` 层+ 里,选择器是 `:root[data-theme="…"]` 且基础规则同时覆盖明暗两种模式——不分层会压过用户自选的字体搭配,而+ 一次覆盖两种模式的选择器就不需要假定浏览器先读了哪张表。+- **应用侧**(`web/src/state/external-themes.ts`)做另外两处做不了的判断:令牌名是 UI 包的契约,所以这边不认识+ 的名字会被列出来(它不会生效),而某个名字没写只作为提示(它沿用默认主题的值)。`state/theme-prefs.ts` 的+ 读取与 `index.html` 里的预绘制脚本都改成按格式校验,不再对着固定列表:外置主题的 id 在文件还没读回来之前也+ 能扛过一次刷新;格式不对的、以及没存过的值,仍然读作默认主题。+- 测试:`core/test/external-theme.test.ts`(形状与安全)、`server/test/themes.test.ts`(两条路由、坏文件、+ 重名、改完下一次请求即生效)、`web/test/external-themes.test.ts`(契约判断、色卡、读取),以及跟着开放 id+ 空间更新的 `web/test/theme-prefs.test.ts` 与 `ui/test/boot-script.test.ts`。++## 兼容性++- 已存数据、接口与构建产物都没有变化:没有 `themes/` 目录时,那张样式表只是一句注释,主题仍是原来那三套;对+ 它来说这个链接是一次空请求。+- 文件格式带版本(`schemaVersion`):不认识的版本会被连原因一起拒掉,不会读一半。+- 没有依赖变化。自带的三套主题没动——外置主题只能在它自己的 id 下上色。diff --git a/docs/FORK-PROGRESS.md b/docs/FORK-PROGRESS.mdindex d32b24f2..dccec609 100644--- a/docs/FORK-PROGRESS.md+++ b/docs/FORK-PROGRESS.md@@ -14256,3 +14256,79 @@ setDeleting(null); // 被拒也关`imap.csu.edu.cn:993` 两个端口也都是超时(202.197.0.0/16 那个老问题),于是照第一百零九轮以来的做法改由飞书送达(`message_id=om_x100b629da80218a0c0cd9c045e9cdcf`,收件人即已绑定的那个私聊),正文同时留在 scratchpad 的`r114/report.md`。下一轮开工先再试一次 `mail.py check`,通了再把积压的补发到 `[email protected]`。++## 第一百一十五轮:主题可以放进数据根自己导入,外观页列得出来、也能换(2026-10-23,用户点单)++### 为什么是这一条++用户在会话里问「能不能外置主题,我可以导入主题插件,进而改变页面 UI」。可行性的根据是既有的那条约束:+主题只是一组令牌取值,组件只读 `--ui-*`、从不问当前是哪个主题(`packages/ui/test/no-theme-reads.test.ts`+钉着这条),所以外置主题能重画整个应用而**不需要重新构建前端**。我给了方案并提了三个要拍板的问题,用户回了+「3」—— 先做样例:运行时加载 + 校验 + 外观页能切换 + 一个样例主题。另外两条问没答,按我自己的推荐默认推进:+只收令牌数据(不收整段 CSS),来源是数据根里的 `themes/*.json` 目录(日后可以包成插件)。++落点分三处,理由是两端都不能互相 import:模型、安全校验与 CSS 生成放 `@adelie/core`(server 依赖 core,+不依赖 ui;ui 也不依赖 core),契约判断(不认识的名字、没写的名字)放 web(web 同时依赖 core 与 ui)。++### 改了什么(6 处源码 + 4 个测试 + 样例 + 文档)++- `packages/core/src/internal/external-theme.ts`(新):文件形状与安全校验(值禁 `; { } < \ @` 换行,+ 禁 `url(`/`image-set(`/`expression(`;最多 400 个名字、12 个预设;id 走 `^[a-z][a-z0-9-]{0,31}$`),+ 以及「一条主题 = 一段 CSS」。规则写在具名的 `@layer ui-theme` / `@layer ui-accent` 里、选择器是+ `:root[data-theme="…"]` 且基础规则同时覆盖 `.dark`:不分层会压过用户自选的字体搭配(`ui-font`),+ 一次覆盖两种模式的选择器则不需要假定浏览器先读了哪张表。导出经 `core/src/index.ts`。+- `packages/server/src/http/routes/themes.ts`(新):`GET /api/themes`(auth user,order 66)读目录并+ 报出读不了的文件;`GET /api/themes.css`(auth none,order 5,`text/css`,`no-cache`)把同一批文件拼成+ 一张样式表。**每次请求都重读目录**(不用重启、没有缓存),单文件坏不影响其它,重名的后一个进 rejected。+ `api/types.ts` 加 `ImportedTheme` / `ImportedThemesResponse`,`platform.ts` 把两个类挂进 `ApiModule`。+- `packages/ui/src/tokens.ts` + `boot.ts`:id 空间改成开放的(`THEME_ID_PATTERN`、`isThemeId`、+ `isBuiltinTheme`、`themeAccentPresets`、`themeOwnAccent`),预绘制脚本改成按格式校验,**并且只对字符串+ 校验** —— store 里没有值时 `getItem` 给 null,`RegExp.test(null)` 会把四个字母的 "null" 认成一个合法 id+ (boot-script 的逐组合比对当场抓到了这一条)。`packages/web/index.html` 里那份内联副本逐字重贴,并在+ `<title>` 后加了 `<link rel="stylesheet" href="/api/themes.css">`(早于首帧,没主题时返回一句注释,+ 不是失败请求)。+- `packages/web/src/state/external-themes.ts`(新):拉 `/api/themes` 并做 core 与 ui 各自做不了的那个判断+ ——不认识的名字报出来(不生效),没写的名字只列出来(沿用默认主题的值);同时给出每套主题的强调色色卡+ (预设取文件里的 `--ui-accent`,预设没写就退回主题自己的)与「随主题」那个颜色。模块级缓存 + 一次请求+ 共享,另有「重新读取」。+- `packages/web/src/state/theme-prefs.ts`、`theme.tsx`、`features/settings/appearance-section.tsx`、+ `lib/strings{,-en}.ts`、`api/endpoints.ts`:主题 id 与强调色改按格式校验(与预绘制脚本一致,外置主题+ 的 id 在文件读回来之前也能扛过一次刷新),主题行列出内置三套加导入的(未提供文件的那个 id 也留在选项里,+ 否则分段控件没有选中项),主题行下面那块写出:目录路径、放文件的方法、「重新读取」、每个写错的文件的+ 原因、每套导入主题的不认识 / 没写提示。色卡与「随主题」的颜色都从文件数据来。+- 测试:`core/test/external-theme.test.ts`(11 条,形状与安全)、`server/test/themes.test.ts`(6 条:两条+ 路由、坏文件、重名、改完下一次请求即生效)、`web/test/external-themes.test.ts`(8 条:契约判断、色卡、+ 读取)、`ui/test/boot-script.test.ts`(把 provider 模型改成按格式校验,并加一条专门盯「格式对但列表里+ 没有的 id」与 "null" 的用例)、`web/test/theme-prefs.test.ts`(跟着开放 id 空间更新)。+- 样例:`examples/themes/warm-paper.json`(暖纸:暖白底 + 陶土强调色 + 三个预设)与一对 README。+- 文档:changelog 一对 `changelog/unreleased/2026-10-23-imported-themes{,.zh}.md` + 本节。++### 验证(都不是推测)++- 逐包 test 全绿:ui **130 文件 / 1053 通过**(+1)、core **69 文件 / 1410 通过 / 6 跳过**、+ web **264 文件 / 3239 通过 / 2 跳过**(+15)、server `themes.test.ts` **6 / 6**。+- **真服务 + 真浏览器**(一次性数据根 `/tmp/theme-probe-data-*`,里面放了 `warm-paper.json` 与一个坏+ `broken.json`;服务 8955、`packages/{server,web}/dist` 都是本轮新构建的产物):`curl /api/themes.css`+ 直接返回 `:root[data-theme="warm-paper"]…`;Playwright 单条用例通过,断言的是**浏览器算出来的值**而不是+ 样式表里的字面量:默认主题 `--ui-canvas` = `#fff`(浏览器会归一化 `#ffffff`)→ 选「暖纸」→ `#f6f1e7`、+ `body` 背景 `rgb(246, 241, 231)` → 切深色 → `#17140f` → 点 terracotta 色卡 → `data-accent="terracotta"`、+ `--ui-accent` = `#d9834f` → 刷新后仍在(预绘制脚本)→ 切回「通用」→ 属性消失、`#fff`。+- 外观页真看一眼(截图在 scratchpad `theme-probe/theme-light.png`、`theme-dark-accent.png`):主题行里+ 通用 / 白领 / 极客 / 暖纸 四选一、暖纸选中;下面写着「主题目录 /tmp/theme-probe-data-auUj/themes」、+ 放文件的说明、「203 个令牌这个主题没写(…等 198 个),它们沿用「通用」主题的值」以及+ 「broken.json:不是合法的 JSON…」。探针脚本与截图都在 scratchpad(`theme-probe/theme-probe.spec.mjs`),+ **不提交**(跑完已从 `packages/web/e2e/` 删掉,`packages/web/test-results/` 也删了)。+- 端口 8955(探针自己的),跑完已停;3003 / 4000 / 7364 / 7372 一个没碰;数据只落在 `mktemp` 的一次性根。++### 没做 / 还差什么++- 主题形态仍是我推荐的默认:**只收令牌值**,不收整段 CSS,也不做设置页粘贴。用户日后想要任意 CSS,就得+ 另立一条(那要处理它与用户自选字体、与冲突规则的关系)。+- 来源是目录。包成插件(`.adelie-plugin` 带一份 `themes/*.json` 当载荷)留到用户点单时再说。+- 主题文件里没有预设的显示名(强调色色卡的名字就是 id)—— 格式要加字段才谈得上。+- 没有把示例主题拷进现网数据根:改 `/root/.penguin/data` 属于用户的环境,等他说要。++### 汇报++- 先按 `csu-mail` 技能试 `mail.py check`(中南网段自 2026-10-08 起不通,约定一轮只试一次),失败改飞书;+ 正文留在 scratchpad 的 `r115/report.md`。diff --git a/examples/themes/README.md b/examples/themes/README.mdnew file mode 100644index 00000000..6ea3ab04--- /dev/null+++ b/examples/themes/README.md@@ -0,0 +1,35 @@+<!-- English | [简体中文](README.zh.md) -->++# Example: a theme an installation imports++`warm-paper.json` is a theme in the format the app reads: warm paper surfaces, a terracotta accent+and three accent presets.++```bash+cp examples/themes/warm-paper.json "<data root>/themes/"+```++It then appears in **Settings › Appearance**, in the theme list, on the next page load — and the+page prints the exact directory it read, so there is nothing to guess. A default installation's data+root is `~/.penguin/data`. There is no restart and no cache: the server reads the directory on every+request, so a file edited, added or deleted is what the next page load shows.++## What a theme may say++A theme is **values for the UI's token names**, and nothing else — no components, no layout, no code+that runs. That is why importing one needs no build: every component reads those names, and none of+them asks which theme is active, so the same files that paint a shipped theme paint an imported one.++- The names are the contract in `packages/ui/src/tokens.ts`. The three shipped themes+ (`packages/ui/src/themes/*.css`) each set **every** name in both modes; a name your file leaves out+ keeps the shipped default's value, so a half-filled theme still paints.+- `light` is the base both modes start from, `dark` changes only what differs, and `accents`+ (optional, at most 12) are the presets the accent row offers — each scoped to this theme, so a+ preset of another theme's does not paint here.+- Values are one line each, bounded to 120 characters. They may not contain `;`, `{`, `}`, `<`, `\`,+ `@` or a newline, and may not fetch anything (`url(`, `image-set(`): an imported theme is confined+ to the token names, so it cannot add a rule, hide an element or call home.++The appearance page reports what a file got wrong: a name the contract does not know paints nothing+and is listed as unknown, while a file that does not read at all is listed with the reason and+paints nothing.diff --git a/examples/themes/README.zh.md b/examples/themes/README.zh.mdnew file mode 100644index 00000000..367ae1a0--- /dev/null+++ b/examples/themes/README.zh.md@@ -0,0 +1,29 @@+<!-- [English](README.md) | 简体中文 -->++# 示例:放在数据根里的主题++`warm-paper.json` 是一份应用能读的主题:暖色纸张底、陶土强调色,另带三个强调色预设。++```bash+cp examples/themes/warm-paper.json "<数据根>/themes/"+```++刷新页面,它就会出现在**设置 › 外观**的主题列表里——页面上会写出读的那个目录,不用猜。默认安装+的数据根是 `~/.penguin/data`。不用重启,也没有缓存:服务端每次请求都会读一遍目录,所以改过、加过、+删过的文件,下一次刷新页面就是结果。++## 主题能写什么++主题只是**一组 UI 令牌名的取值**,别的都不是——没有组件、没有布局、没有会跑起来的代码。正因为+每个组件都只读这些名字、从不问当前是哪个主题,所以外置主题不需要重新构建前端。++- 这些名字是 `packages/ui/src/tokens.ts` 里的契约。三个自带主题(`packages/ui/src/themes/*.css`)+ 在明暗两种模式下把每个名字都写满;你的文件漏掉的名字,沿用自带默认主题的值,所以只写一半也照样+ 能画出来。+- `light` 是两种模式共同的底,`dark` 只写明暗不同的部分,`accents`(可选,最多 12 个)是强调色行+ 给出的预设,各自只在自己的主题下生效——别的主题的预设到这里不会上色。+- 每个值只写一行、最长 120 个字符,不能含 `;`、`{`、`}`、`<`、`\`、`@` 和换行,也不能去取外部资源+ (`url(`、`image-set(`):外置主题只能改这些令牌的取值,不能加规则、藏元素或往外发请求。++外观页会把文件写错的地方列出来:这边不认识的令牌名不会生效,会作为警告列出;完全读不了的文件会连+原因一起列出,并且一点颜色都不会画。diff --git a/examples/themes/warm-paper.json b/examples/themes/warm-paper.jsonnew file mode 100644index 00000000..d4cfe74f--- /dev/null+++ b/examples/themes/warm-paper.json@@ -0,0 +1,91 @@+{+ "schemaVersion": 1,+ "id": "warm-paper",+ "name": "Warm Paper",+ "nameZh": "暖纸",+ "light": {+ "--ui-canvas": "#f6f1e7",+ "--ui-surface": "#fffdf7",+ "--ui-surface-muted": "#efe8da",+ "--ui-fill-neutral": "#e7dfcf",+ "--ui-inset": "#f1ebdf",+ "--ui-overlay": "#fffdf7",+ "--ui-overlay-backdrop": "rgba(60,50,40,0.32)",+ "--ui-fg": "#2e2a24",+ "--ui-fg-emphasis": "#1c1915",+ "--ui-fg-muted": "#5c554a",+ "--ui-fg-subtle": "#7d7568",+ "--ui-fg-link": "#9a4a24",+ "--ui-fg-link-hover": "#7f3a1b",+ "--ui-line": "#e2d9c8",+ "--ui-line-muted": "#ede5d6",+ "--ui-line-emphasis": "#cbbfa9",+ "--ui-divider": "#e2d9c8",+ "--ui-accent": "#b4552d",+ "--ui-accent-hover": "#9c4926",+ "--ui-accent-active": "#833d1f",+ "--ui-accent-fg": "#fffaf3",+ "--ui-accent-muted": "#f0e2d7",+ "--ui-accent-line": "#e0c6b4",+ "--ui-code-bg": "#efe8da",+ "--ui-code-line": "#e2d9c8",+ "--ui-code-gutter": "#7d7568",+ "--ui-code-selection": "rgba(180,85,45,0.18)",+ "--ui-selection-bg": "rgba(180,85,45,0.18)",+ "--ui-focus-ring": "#b4552d",+ "--ui-focus-ring-offset": "#fffdf7",+ "--ui-focus-ring-input": "#b4552d",+ "--ui-radius-control": "6px",+ "--ui-radius-md": "8px"+ },+ "dark": {+ "--ui-canvas": "#17140f",+ "--ui-surface": "#1e1a14",+ "--ui-surface-muted": "#241f18",+ "--ui-fill-neutral": "#2b251c",+ "--ui-inset": "#211c15",+ "--ui-overlay": "#221d16",+ "--ui-overlay-backdrop": "rgba(0,0,0,0.5)",+ "--ui-fg": "#e8e1d4",+ "--ui-fg-emphasis": "#f7f3ea",+ "--ui-fg-muted": "#b3a996",+ "--ui-fg-subtle": "#8c8271",+ "--ui-fg-link": "#e09a6c",+ "--ui-fg-link-hover": "#efb48c",+ "--ui-line": "#2f2920",+ "--ui-line-muted": "#282218",+ "--ui-line-emphasis": "#443b2d",+ "--ui-divider": "#2f2920",+ "--ui-accent": "#d9834f",+ "--ui-accent-hover": "#e39a6d",+ "--ui-accent-active": "#c67140",+ "--ui-accent-fg": "#2a1b10",+ "--ui-accent-muted": "#33251b",+ "--ui-accent-line": "#4a3527",+ "--ui-code-bg": "#211c15",+ "--ui-code-line": "#2f2920",+ "--ui-code-gutter": "#8c8271",+ "--ui-code-selection": "rgba(217,131,79,0.22)",+ "--ui-selection-bg": "rgba(217,131,79,0.22)",+ "--ui-focus-ring": "#d9834f",+ "--ui-focus-ring-offset": "#17140f",+ "--ui-focus-ring-input": "#d9834f"+ },+ "accents": [+ {+ "id": "terracotta",+ "light": { "--ui-accent": "#b4552d", "--ui-accent-fg": "#fffaf3" },+ "dark": { "--ui-accent": "#d9834f", "--ui-accent-fg": "#2a1b10" }+ },+ {+ "id": "slate-blue",+ "light": { "--ui-accent": "#2f4a52", "--ui-accent-fg": "#f6fbfb" },+ "dark": { "--ui-accent": "#9fc3cb", "--ui-accent-fg": "#16232a" }+ },+ {+ "id": "olive",+ "light": { "--ui-accent": "#5c6a2f", "--ui-accent-fg": "#fbfcef" },+ "dark": { "--ui-accent": "#b6c47a", "--ui-accent-fg": "#22290f" }+ }+ ]+}diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 40970948..c2267959 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -80,6 +80,22 @@ export { modelVisiblePath } from "./internal/model-visible-path.js";// same way.export { atomicWriteFile } from "./internal/atomic-write.js";export type { AtomicWriteOptions } from "./internal/atomic-write.js";+// Imported themes: the file format an installation drops in its data root's `themes/`, and the+// CSS it becomes. The server reads the files and serves the sheet; the app reads them back as+// data. Both ends need it and neither may import the other, so it is here.+export {+ EXTERNAL_THEME_SCHEMA_VERSION,+ THEME_ID_PATTERN,+ isThemeId,+ readExternalTheme,+ externalThemeCss,+ externalThemesCss,+} from "./internal/external-theme.js";+export type {+ ExternalTheme,+ ExternalThemeAccent,+ ExternalThemeRead,+} from "./internal/external-theme.js";// `metaMaxTokens` is the output cap every out-of-band meta request shares — a small budget,// tightened by the entry's pinned per-model cap. Exported so a host running its own one-off// requests on a Project's model sizes them the way the SDK sizes its own.diff --git a/packages/core/src/internal/external-theme.ts b/packages/core/src/internal/external-theme.tsnew file mode 100644index 00000000..23fb7b79--- /dev/null+++ b/packages/core/src/internal/external-theme.ts@@ -0,0 +1,274 @@+/**+ * Themes an installation imported, rather than the three the UI package ships.+ *+ * A theme is nothing but VALUES for the token contract (`@adelie/ui`'s tokens.ts) — every+ * component reads those names and none of them asks which theme is active, so a theme that+ * arrives as data repaints the whole app with no rebuild and no component knowing. What a shipped+ * theme declares in `themes/<id>.css` an imported one declares in a JSON file, and this module+ * turns that file into the CSS the browser would otherwise have been built with:+ *+ * :root[data-theme="warm-paper"] { --ui-canvas: … } ← the theme's light values+ * :root[data-theme="warm-paper"].dark { … } ← only what dark changes+ *+ * It lives in core, not in the UI package, because BOTH ends need it and they may not import each+ * other: the server reads the files and serves the stylesheet (it has no React and must not gain+ * one), and the app reads the same files back as data. The token NAMES are the UI package's —+ * they are a contract about components — so what is checked here is the shape and the safety of a+ * value, never whether a name exists; the app adds that judgement where the contract lives.+ *+ * THE BASE RULE REACHES BOTH MODES (`:root[data-theme="x"], :root[data-theme="x"].dark`) so the+ * cascade needs no promise about which sheet came first: a name the theme declares and dark does+ * not change keeps the theme's value in dark mode, exactly as a shipped theme's base rule beats+ * Primer's `.dark` rule. Everything the theme leaves out falls through to the default theme, whose+ * base rule is the bare `:root` — which is why a half-filled theme warns rather than fails: it+ * paints, it is just more Primer than its author meant.+ *+ * THE LAYERS ARE NAMED (`@layer ui-theme`, `@layer ui-accent`) for the same reason: an unlayered+ * rule beats every layered one, so an imported theme that declared `--ui-font-sans` unlayered+ * would override the user's own font pairing, which lives in `ui-font`, last of the three.+ *+ * A VALUE IS A VALUE. Nothing here is echoed into the sheet without passing {@link SAFE_VALUE},+ * which refuses the characters that would let an imported file leave its declaration — `;`, `{`,+ * `}`, `\`, `<`, a newline, `@` — and the two functions that fetch something (`url(`,+ * `image-set(`). An imported theme is therefore confined to the token names: it cannot add rules,+ * hide an element or call home. That is the whole trade — no new components, no new layout, one+ * set of values per mode.+ */++/** The file shape this module reads. A later shape bumps it rather than half-reading an old file. */+export const EXTERNAL_THEME_SCHEMA_VERSION = 1;++/**+ * The id space of a theme, open: an installation imports themes besides the three the UI package+ * ships, and one pattern covers both — the shipped ids are just short ones. The UI package carries+ * the same pattern for the pre-paint script (`@adelie/ui`'s THEME_ID_PATTERN), and a test in the+ * web app holds the two equal.+ */+export const THEME_ID_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;++/** Whether a stored theme or accent id is one the app may put in a `data-*` attribute. */+export function isThemeId(value: unknown): value is string {+ return typeof value === "string" && THEME_ID_PATTERN.test(value);+}++/** The user-facing names are copy, so they are only bounded — not patterns. */+const NAME = /^[\s\S]{1,60}$/;++/**+ * What a declared value may look like. Length-bounded, one line, and free of the characters that+ * end a declaration, open a block, escape, or — with `url(`/`image-set(` — fetch something.+ */+const SAFE_VALUE = /^[^;{}<>\\@\n\r]{1,120}$/;+const FETCHES = /url\s*\(|image-set\s*\(|expression\s*\(/i;++/** A cap that keeps a runaway file from becoming a megabyte of stylesheet on every page load. */+const MAX_TOKENS = 400;+const MAX_ACCENTS = 12;++/** One accent preset an imported theme lists, shaped like the shipped themes' own. */+export interface ExternalThemeAccent {+ readonly id: string;+ /** The `--ui-accent` (and anything else the author wants) for light mode. */+ readonly light: Readonly<Record<string, string>>;+ /** Only what dark changes; absent means the light values hold in both modes. */+ readonly dark?: Readonly<Record<string, string>>;+}++/** A theme file, read and validated. */+export interface ExternalTheme {+ readonly id: string;+ /** Its name in the interface. `nameZh` is what a Chinese UI shows; absent falls back to `name`. */+ readonly name: string;+ readonly nameZh?: string;+ /** Every token the theme sets for light — the base both modes start from. */+ readonly light: Readonly<Record<string, string>>;+ readonly dark?: Readonly<Record<string, string>>;+ readonly accents?: readonly ExternalThemeAccent[];+}++export type ExternalThemeRead =+ | { readonly ok: true; readonly theme: ExternalTheme }+ | { readonly ok: false; readonly errors: readonly string[] };++function isPlainObject(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++/** One token map: `--ui-*` names only, values as above, within {@link MAX_TOKENS}. */+function readTokens(+ value: unknown,+ where: string,+ errors: string[],+): Record<string, string> | null {+ if (!isPlainObject(value)) {+ errors.push(`${where}: 必须是一个对象(名字 → 值)`);+ return null;+ }+ const entries = Object.entries(value);+ if (entries.length === 0) {+ errors.push(`${where}: 一个名字都没有`);+ return null;+ }+ if (entries.length > MAX_TOKENS) {+ errors.push(`${where}: ${entries.length} 个名字,超过上限 ${MAX_TOKENS}`);+ return null;+ }+ const out: Record<string, string> = {};+ for (const [name, raw] of entries) {+ if (!/^--[a-z0-9-]+$/.test(name)) {+ errors.push(`${where}: 「${name}」不是合法的令牌名(要 --小写-连字符)`);+ continue;+ }+ if (typeof raw !== "string" || !SAFE_VALUE.test(raw) || FETCHES.test(raw)) {+ errors.push(`${where}: 「${name}」的值不能用(不能有 ; { } < \\ @ 换行,也不能 url()`);+ continue;+ }+ out[name] = raw;+ }+ return Object.keys(out).length === 0 ? null : out;+}++function readAccents(value: unknown, errors: string[]): readonly ExternalThemeAccent[] | undefined {+ if (value === undefined) return undefined;+ if (!Array.isArray(value)) {+ errors.push("accents: 要是一个数组");+ return undefined;+ }+ if (value.length > MAX_ACCENTS) {+ errors.push(`accents: ${value.length} 个预设,超过上限 ${MAX_ACCENTS}`);+ return undefined;+ }+ const out: ExternalThemeAccent[] = [];+ const seen = new Set<string>();+ for (const [index, entry] of value.entries()) {+ const where = `accents[${index}]`;+ if (!isPlainObject(entry)) {+ errors.push(`${where}: 要是一个对象`);+ continue;+ }+ const id = entry.id;+ // `neutral` is the absence of a preset, so it can never be one.+ if (typeof id !== "string" || !THEME_ID_PATTERN.test(id) || id === "neutral") {+ errors.push(+ `${where}.id: 「${String(id)}」不是合法的预设名(要小写连字符,且不能叫 neutral)`,+ );+ continue;+ }+ if (seen.has(id)) {+ errors.push(`${where}.id: 「${id}」出现了两次`);+ continue;+ }+ const light = readTokens(entry.light, `${where}.light`, errors);+ if (light === null) continue;+ const dark = entry.dark === undefined ? null : readTokens(entry.dark, `${where}.dark`, errors);+ if (entry.dark !== undefined && dark === null) continue;+ seen.add(id);+ out.push({ id, light, ...(dark === null ? {} : { dark }) });+ }+ return out.length === 0 ? undefined : out;+}++/**+ * Reads a theme file. Errors are collected rather than thrown on the first one: whoever wrote the+ * file gets the whole list, and a file refused here never reaches a stylesheet. The shipped ids+ * are not refused here (this module does not know them); an imported theme can only ever paint+ * under its own `data-theme`, so a file that names a shipped theme simply never matches.+ */+export function readExternalTheme(value: unknown): ExternalThemeRead {+ if (!isPlainObject(value)) return { ok: false, errors: ["顶层必须是一个对象"] };+ const errors: string[] = [];++ const schema = value.schemaVersion;+ if (schema !== undefined && schema !== EXTERNAL_THEME_SCHEMA_VERSION) {+ errors.push(+ `schemaVersion: ${String(schema)} 不是本版本认识的 ${EXTERNAL_THEME_SCHEMA_VERSION}`,+ );+ }+ const id = value.id;+ if (typeof id !== "string" || !THEME_ID_PATTERN.test(id)) {+ errors.push(+ `id: 「${String(id)}」不是合法的主题名(要小写字母开头、小写字母数字连字符,最长 32)`,+ );+ }+ const name = value.name;+ if (typeof name !== "string" || !NAME.test(name)) {+ errors.push("name: 要有 1–60 个字的显示名");+ }+ const nameZh = value.nameZh;+ if (nameZh !== undefined && (typeof nameZh !== "string" || !NAME.test(nameZh))) {+ errors.push("nameZh: 要有 1–60 个字(不写就用 name)");+ }+ const light = readTokens(value.light, "light", errors);+ const dark = value.dark === undefined ? null : readTokens(value.dark, "dark", errors);+ if (value.dark !== undefined && dark === null && errors.length === 0) {+ errors.push("dark: 没有可用的值");+ }+ const accents = readAccents(value.accents, errors);++ if (+ errors.length > 0 ||+ light === null ||+ typeof id !== "string" ||+ typeof name !== "string" ||+ !THEME_ID_PATTERN.test(id)+ ) {+ return { ok: false, errors: errors.length > 0 ? errors : ["文件读不出一个主题"] };+ }+ return {+ ok: true,+ theme: {+ id,+ name,+ ...(typeof nameZh === "string" ? { nameZh } : {}),+ light,+ ...(dark === null ? {} : { dark }),+ ...(accents === undefined ? {} : { accents }),+ },+ };+}++function declarations(tokens: Readonly<Record<string, string>>): string {+ return Object.entries(tokens)+ .map(([name, value]) => `${name}:${value}`)+ .join(";");+}++/** The two selectors a theme's base rule matches: the attribute, and itself under `.dark`. */+function roots(id: string, accent: string | null): [string, string] {+ const root =+ accent === null+ ? `:root[data-theme="${id}"]`+ : `:root[data-theme="${id}"][data-accent="${accent}"]`;+ return [root, `${root}.dark`];+}++/** One theme's rules, ready to be concatenated with the others into one stylesheet. */+export function externalThemeCss(theme: ExternalTheme): string {+ const out: string[] = [`/* ${theme.id} — ${theme.name} */`];+ const [base, baseDark] = roots(theme.id, null);+ out.push("@layer ui-theme{");+ out.push(`${base},${baseDark}{${declarations(theme.light)}}`);+ if (theme.dark !== undefined && Object.keys(theme.dark).length > 0) {+ out.push(`${baseDark}{${declarations(theme.dark)}}`);+ }+ out.push("}");+ const accents = theme.accents ?? [];+ if (accents.length > 0) {+ out.push("@layer ui-accent{");+ for (const accent of accents) {+ const [light, dark] = roots(theme.id, accent.id);+ out.push(`${light},${dark}{${declarations(accent.light)}}`);+ if (accent.dark !== undefined && Object.keys(accent.dark).length > 0) {+ out.push(`${dark}{${declarations(accent.dark)}}`);+ }+ }+ out.push("}");+ }+ return out.join("\n");+}++/** Every imported theme's rules in one stylesheet; the shipped themes are not repeated here. */+export function externalThemesCss(themes: readonly ExternalTheme[]): string {+ if (themes.length === 0) return "/* no imported themes */\n";+ return themes.map(externalThemeCss).join("\n") + "\n";+}diff --git a/packages/core/test/external-theme.test.ts b/packages/core/test/external-theme.test.tsnew file mode 100644index 00000000..db0b966d--- /dev/null+++ b/packages/core/test/external-theme.test.ts@@ -0,0 +1,180 @@+/**+ * Imported themes (src/internal/external-theme.ts).+ *+ * Two things break without a test here and neither shows up on the machine that wrote the file: a+ * value that escapes its declaration (the file becomes CSS once it is served, so `red} body{…`+ * would repaint — or unhide — anything), and a base rule that does not reach dark mode (the+ * theme's own value would lose to Primer's `.dark` rule, which is the one thing an imported theme+ * is allowed to assume it beats).+ */+import { describe, expect, it } from "vitest";+import {+ THEME_ID_PATTERN,+ externalThemeCss,+ externalThemesCss,+ isThemeId,+ readExternalTheme,+} from "../src/internal/external-theme.js";++const VALID = {+ schemaVersion: 1,+ id: "warm-paper",+ name: "Warm paper",+ nameZh: "暖纸",+ light: { "--ui-canvas": "#f7f2e8", "--ui-accent": "#a4471f", "--ui-fg": "#2b2620" },+ dark: { "--ui-canvas": "#1a1713", "--ui-fg": "#ece6dc" },+ accents: [+ { id: "clay", light: { "--ui-accent": "#b8552f" }, dark: { "--ui-accent": "#d9906c" } },+ ],+};++function read(value: unknown) {+ const result = readExternalTheme(value);+ if (!result.ok) throw new Error(`expected ok, got: ${result.errors.join(" / ")}`);+ return result.theme;+}++describe("readExternalTheme", () => {+ it("reads a whole file, keeping the optional parts", () => {+ const theme = read(VALID);+ expect(theme.id).toBe("warm-paper");+ expect(theme.nameZh).toBe("暖纸");+ expect(theme.dark?.["--ui-canvas"]).toBe("#1a1713");+ expect(theme.accents?.[0]?.id).toBe("clay");+ });++ it("reads a file that only sets light values", () => {+ const theme = read({ id: "bare", name: "Bare", light: { "--ui-canvas": "#ffffff" } });+ expect(theme.dark).toBeUndefined();+ // One rule, whose selector list already reaches dark mode: no second `.dark` rule.+ expect(externalThemeCss(theme).match(/\.dark\{/g)).toHaveLength(1);+ });++ it("refuses a value that would leave its declaration", () => {+ for (const value of [+ "#fff; } body { display: none",+ "url(https://example.com/x.png)",+ "image-set(url(a.png) 1x)",+ "@import 'x.css'",+ "red}",+ "back\\slash",+ "<script>",+ "#fff\n--ui-accent: red",+ ]) {+ const result = readExternalTheme({+ id: "escape",+ name: "Escape",+ light: { "--ui-canvas": value },+ });+ expect(result.ok, value).toBe(false);+ }+ });++ it("refuses names that are not spelled like a token", () => {+ const result = readExternalTheme({ id: "x", name: "X", light: { "ui-canvas": "#fff" } });+ expect(result.ok).toBe(false);+ if (!result.ok) expect(result.errors[0]).toContain("ui-canvas");+ });++ it("refuses ids that are not ids", () => {+ for (const id of ["Warm", "9lives", "-lead", "a".repeat(33), ""]) {+ const result = readExternalTheme({ ...VALID, id });+ expect(result.ok, id).toBe(false);+ }+ // The shipped ids are legal ids (the module has no list of its own): an imported theme that+ // takes one simply never matches, because its rules are scoped to its own data-theme.+ expect(readExternalTheme({ ...VALID, id: "github" }).ok).toBe(true);+ });++ it("refuses a file with no light values, no name, or an unknown schemaVersion", () => {+ expect(readExternalTheme({ ...VALID, light: {} }).ok).toBe(false);+ expect(readExternalTheme({ ...VALID, name: "" }).ok).toBe(false);+ expect(readExternalTheme({ ...VALID, schemaVersion: 2 }).ok).toBe(false);+ expect(readExternalTheme([]).ok).toBe(false);+ expect(readExternalTheme("hi").ok).toBe(false);+ });++ it("refuses `neutral`, duplicate and malformed accents", () => {+ const result = readExternalTheme({+ ...VALID,+ accents: [+ { id: "neutral", light: { "--ui-accent": "#111111" } },+ { id: "clay", light: { "--ui-accent": "#b8552f" } },+ { id: "clay", light: { "--ui-accent": "#999999" } },+ { id: "Slate", light: { "--ui-accent": "#5c6470" } },+ { id: "honey", light: {} },+ ],+ });+ expect(result.ok).toBe(false);+ if (!result.ok) {+ const all = result.errors.join("\n");+ expect(all).toContain("neutral");+ expect(all).toContain("两次");+ expect(all).toContain("Slate");+ }+ });++ it("caps a runaway file instead of turning it into a stylesheet", () => {+ const many = Object.fromEntries(+ Array.from({ length: 401 }, (_v, i) => [`--ui-token-${i}`, "#ffffff"]),+ );+ expect(readExternalTheme({ id: "huge", name: "Huge", light: many }).ok).toBe(false);+ const thirteen = Array.from({ length: 13 }, (_v, i) => ({+ id: `accent-${i}`,+ light: { "--ui-accent": "#ffffff" },+ }));+ expect(readExternalTheme({ ...VALID, accents: thirteen }).ok).toBe(false);+ });+});++describe("externalThemeCss", () => {+ it("writes the base rule for both modes and the accent presets into their layers", () => {+ const css = externalThemeCss(read(VALID));+ expect(css).toContain("@layer ui-theme{");+ expect(css).toContain("@layer ui-accent{");+ // The base rule reaches dark mode by itself: :root[data-theme="warm-paper"].dark is in the+ // SAME selector list as the light one, so a name dark does not change keeps the theme's value+ // rather than falling back to Primer's `.dark` rule.+ expect(css).toContain(+ ':root[data-theme="warm-paper"],:root[data-theme="warm-paper"].dark{--ui-canvas:#f7f2e8;--ui-accent:#a4471f;--ui-fg:#2b2620}',+ );+ expect(css).toContain(+ ':root[data-theme="warm-paper"].dark{--ui-canvas:#1a1713;--ui-fg:#ece6dc}',+ );+ expect(css).toContain(+ ':root[data-theme="warm-paper"][data-accent="clay"],:root[data-theme="warm-paper"][data-accent="clay"].dark{--ui-accent:#b8552f}',+ );+ expect(css).toContain(+ ':root[data-theme="warm-paper"][data-accent="clay"].dark{--ui-accent:#d9906c}',+ );+ // Nothing is emitted outside a layer: an unlayered rule would beat `ui-font`, where the user's+ // own font pairing lives.+ let depth = 0;+ const outside: string[] = [];+ for (const line of css.split("\n")) {+ if (depth === 0 && line !== "" && !line.startsWith("/*") && !line.startsWith("@layer ")) {+ outside.push(line);+ }+ depth += (line.match(/\{/g) ?? []).length - (line.match(/\}/g) ?? []).length;+ }+ expect(outside).toEqual([]);+ expect(depth).toBe(0);+ });++ it("says so when there is nothing to serve", () => {+ expect(externalThemesCss([])).toContain("no imported themes");+ expect(externalThemesCss([read(VALID)])).toContain('data-theme="warm-paper"');+ });+});++describe("the id pattern", () => {+ it("accepts the shipped ids and what an author would plausibly write, refusing the rest", () => {+ for (const id of ["github", "modern", "geek", "warm-paper", "a", "x-9-9"]) {+ expect(isThemeId(id), id).toBe(true);+ }+ for (const id of ["", "-a", "A", "a b", "a_b", "a.b", "a".repeat(33), 7, null, undefined]) {+ expect(isThemeId(id), String(id)).toBe(false);+ }+ expect(THEME_ID_PATTERN.source).toBe("^[a-z][a-z0-9-]{0,31}$");+ });+});diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex d6a49576..a420d2e5 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -25,7 +25,7 @@ import type {ToolDefinitionConfig,} from "@adelie/core/interfaces";// Build/harness identity is not an interface contract — it ships from the barrel (core's version-info.ts).-import type { HarnessInfo, VersionReport, HarnessHistory } from "@adelie/core";+import type { HarnessInfo, VersionReport, HarnessHistory, ExternalTheme } from "@adelie/core";import type { IfacesDiff } from "@adelie/hmr";import type { WorkflowInfo } from "../mechanisms/workflows.js";@@ -2204,6 +2204,22 @@ export interface DirectorySkillsResponse {skills: DirectorySkillItem[];}+/** One theme file under the data root's `themes/`, read and validated (core reads it). */+export interface ImportedTheme {+ /** The file it came from, relative to the themes directory — what the page names it by. */+ file: string;+ /** The theme as data. The app turns it into swatches and warnings; the server serves its CSS. */+ theme: ExternalTheme;+}++export interface ImportedThemesResponse {+ /** The directory that was read, for the page that says where to put a file. */+ dir: string;+ themes: ImportedTheme[];+ /** Files that are not a theme, with the reason — one bad file never hides the good ones. */+ rejected: Array<{ file: string; errors: string[] }>;+}+export interface SessionCreateRequest {/** Upstream id of the session's model; always sent together with provider. Omit both for the Project's default Model. */modelId?: string;diff --git a/packages/server/src/http/routes/themes.ts b/packages/server/src/http/routes/themes.tsnew file mode 100644index 00000000..e3b9f964--- /dev/null+++ b/packages/server/src/http/routes/themes.ts@@ -0,0 +1,165 @@+/**+ * Imported themes: what an installation put in `<data root>/themes/`.+ *+ * GET /api/themes the list, for the appearance page (auth: user)+ * GET /api/themes.css the same files as one stylesheet (auth: none)+ *+ * WHY A DIRECTORY AND NOT A PLUGIN. A theme is values for the UI package's token contract, nothing+ * else (core's internal/external-theme.ts), so installing one needs no code to run, no build and+ * no trust: dropping a JSON file in a folder is the whole install, and the same file can travel as+ * a plugin's payload later. The folder is the data root's `themes/`, beside the installation's own+ * things — replacing the app (`penguin update`) replaces `bin lib web node` and leaves it alone.+ *+ * WHY THE STYLESHEET IS PUBLIC. The web app links it from `<head>` (packages/web/index.html), and+ * the sign-in page is a page like any other: a reader who imported a theme should see it before+ * they log in. It discloses the theme ids and colours of this installation to whoever can already+ * reach its port, which is the machine's own owner. The JSON list stays behind the login, because+ * it is the app's data rather than its paint.+ *+ * NOTHING IS CACHED. A request reads the directory, so a theme added, edited or deleted shows up+ * on the next page load of the machine that owns the folder — no restart, no cache to bust. A file+ * that does not read is reported in the JSON list and skipped in the sheet rather than failing the+ * response: one broken theme must not take the other one down, and whoever wrote it gets the+ * reason.+ */+import { readdir, readFile } from "node:fs/promises";+import { join } from "node:path";+import { Hono } from "hono";+import { externalThemesCss, readExternalTheme } from "@adelie/core";+import type { ExternalTheme } from "@adelie/core";+import { Bind, Component, Use } from "@adelie/core/kernel";+import type { AppEnv } from "../../auth/middleware.js";+import type { ImportedThemesResponse } from "../../api/types.js";+import { Config } from "../../hmr/capabilities.js";++/** Where an installation's themes live, under the data root. */+export const THEMES_DIR = "themes";++/** A body-bounded reader: a theme file is values, and values are small. */+const MAX_FILE_BYTES = 256 * 1024;++/** One theme that read, with the file it came from. */+export interface ReadTheme {+ readonly file: string;+ readonly theme: ExternalTheme;+}++export interface ReadThemes {+ /** The directory that was read, whether or not it exists — the page shows it to the reader. */+ readonly dir: string;+ readonly themes: readonly ReadTheme[];+ readonly rejected: ReadonlyArray<{ file: string; errors: readonly string[] }>;+}++/**+ * Reads every `*.json` in the themes directory. Files are visited in name order so two requests+ * agree about which of two files owns an id, and a directory that does not exist is not an error —+ * a fresh installation has none.+ */+export async function readImportedThemes(root: string): Promise<ReadThemes> {+ const dir = join(root, THEMES_DIR);+ let names: string[];+ try {+ names = (await readdir(dir)).filter((name) => name.endsWith(".json")).sort();+ } catch {+ return { dir, themes: [], rejected: [] };+ }+ const themes: ReadTheme[] = [];+ const rejected: Array<{ file: string; errors: readonly string[] }> = [];+ for (const file of names) {+ let text: string;+ try {+ text = await readFile(join(dir, file), "utf8");+ } catch (error) {+ rejected.push({ file, errors: [`读不了这个文件:${(error as Error).message}`] });+ continue;+ }+ if (text.length > MAX_FILE_BYTES) {+ rejected.push({ file, errors: [`文件超过 ${MAX_FILE_BYTES} 字节`] });+ continue;+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(text);+ } catch (error) {+ rejected.push({ file, errors: [`不是合法的 JSON:${(error as Error).message}`] });+ continue;+ }+ const read = readExternalTheme(parsed);+ if (!read.ok) {+ rejected.push({ file, errors: read.errors });+ continue;+ }+ // A theme whose id another file already claimed is refused rather than silently dropped: the+ // person who wrote it should see that their file is the one not painting.+ //+ // An id a shipped theme owns is deliberately NOT refused here — the server does not carry the+ // list of shipped ids (they are the UI package's). Such a file is inert instead: its rules are+ // scoped to its own `data-theme`, which the app never writes for a shipped id.+ if (themes.some((entry) => entry.theme.id === read.theme.id)) {+ rejected.push({ file, errors: [`主题名「${read.theme.id}」已被另一个文件用了`] });+ continue;+ }+ themes.push({ file, theme: read.theme });+ }+ return { dir, themes, rejected };+}++export function themesRoutes(deps: { root: string }): Hono<AppEnv> {+ const routes = new Hono<AppEnv>();+ routes.get("/", async (c) => {+ const { dir, themes, rejected } = await readImportedThemes(deps.root);+ return c.json({+ dir,+ themes: themes.map(({ file, theme }) => ({ file, theme })),+ rejected: rejected.map(({ file, errors }) => ({ file, errors: [...errors] })),+ } satisfies ImportedThemesResponse);+ });+ return routes;+}++export function themeStylesheetRoutes(deps: { root: string }): Hono<AppEnv> {+ const routes = new Hono<AppEnv>();+ routes.get("/", async (c) => {+ const { themes } = await readImportedThemes(deps.root);+ return c.body(externalThemesCss(themes.map((entry) => entry.theme)), 200, {+ "Content-Type": "text/css; charset=utf-8",+ // Derived from files: revalidate per load, so editing a file and reloading the page is the+ // whole edit-test loop.+ "Cache-Control": "no-cache",+ });+ });+ return routes;+}++/** The appearance page's list: what this installation imported, and what would not read. */+@Component({+ contributes: {+ "HttpModule.routes": [+ { id: "ThemesRoutes.routes", prefix: "/api/themes", auth: "user", order: 66 },+ ],+ },+})+export class ThemesRoutes {+ @Use() private readonly config!: Config;+ @Bind("ThemesRoutes.routes") routes!: Hono<AppEnv>;+ setup() {+ this.routes = themesRoutes({ root: this.config.root });+ }+}++/** The stylesheet the app links from `<head>`, before anyone has logged in. */+@Component({+ contributes: {+ "HttpModule.routes": [+ { id: "ThemeStylesheetRoutes.routes", prefix: "/api/themes.css", auth: "none", order: 5 },+ ],+ },+})+export class ThemeStylesheetRoutes {+ @Use() private readonly config!: Config;+ @Bind("ThemeStylesheetRoutes.routes") routes!: Hono<AppEnv>;+ setup() {+ this.routes = themeStylesheetRoutes({ root: this.config.root });+ }+}diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.tsindex 0fbb15cd..a6dc7077 100644--- a/packages/server/src/platform.ts+++ b/packages/server/src/platform.ts@@ -132,6 +132,7 @@ import {DesktopUpdateRoutes,} from "./http/routes/desktop.js";import { InstallRoutes } from "./http/routes/install.js";+import { ThemesRoutes, ThemeStylesheetRoutes } from "./http/routes/themes.js";import { HmrRoutes } from "./hmr/routes.js";import { EventsRoutes } from "./http/routes/events.js";import { PluginRegistryRoutes, PluginRoutes } from "./http/routes/plugins.js";@@ -471,6 +472,8 @@ export class CompanyModule {}PluginRegistryRoutes,InstalledPluginRoutes,SuggestIdRoutes,+ ThemesRoutes,+ ThemeStylesheetRoutes,],exports: [Http, WebShell, UpdateCheck],})diff --git a/packages/server/test/themes.test.ts b/packages/server/test/themes.test.tsnew file mode 100644index 00000000..da691122--- /dev/null+++ b/packages/server/test/themes.test.ts@@ -0,0 +1,186 @@+/**+ * Imported themes over HTTP: the appearance page's list (`GET /api/themes`) and the stylesheet the+ * app links from `<head>` (`GET /api/themes.css`).+ *+ * - The directory is a data root's `themes/`: a file dropped in it needs no restart, because every+ * request reads the directory — an installation with no such directory answers with an empty list+ * and a sheet that is one comment, not a failed request.+ * - A file that does not read costs nobody else: it is named with its reason in the list and left+ * out of the sheet, and the good themes beside it are still served. Two files claiming one id+ * reject the later one, so which file paints is not decided by the filesystem's mood.+ * - The list is the app's data and stays behind the login; the sheet is the app's paint and is read+ * before anyone signs in (the sign-in page renders under the theme too), so it is public.+ * - What the sheet says is the theme's own values, scoped to its own `data-theme` and its layers —+ * the shape core's external-theme.test.ts pins; here it is the HTTP answer that is under test.+ */+import fs from "node:fs/promises";+import path from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import type { ImportedThemesResponse } from "../src/api/types.js";+import { apiClient, createTestApp, provisionUser } from "./helpers.js";+import type { TestApp } from "./helpers.js";++/** A theme file that reads: everything the format allows. */+const WARM_PAPER = {+ schemaVersion: 1,+ id: "warm-paper",+ name: "Warm Paper",+ nameZh: "暖纸",+ light: { "--ui-canvas": "#f7f3ec", "--ui-surface": "#fffdf8" },+ dark: { "--ui-canvas": "#16130f" },+ accents: [{ id: "terracotta", light: { "--ui-accent": "#b4552d" } }],+};++let live: TestApp[] = [];++/** An app whose data root already holds these files in `themes/` — an installation's own state. */+async function appWithThemes(files: Record<string, string | object> = {}): Promise<TestApp> {+ const t = await createTestApp({+ beforeSeed: async (root) => {+ const names = Object.keys(files);+ if (names.length === 0) return;+ const dir = path.join(root, "themes");+ await fs.mkdir(dir, { recursive: true });+ for (const name of names) {+ const body = files[name]!;+ await fs.writeFile(+ path.join(dir, name),+ typeof body === "string" ? body : JSON.stringify(body),+ "utf8",+ );+ }+ },+ });+ live.push(t);+ return t;+}++afterEach(async () => {+ const open = live;+ live = [];+ await Promise.all(open.map((t) => t.cleanup()));+});++async function listThemes(t: TestApp, cookie?: string): Promise<Response> {+ return t.app.request("/api/themes", cookie ? { headers: { cookie } } : {});+}++describe("imported themes", () => {+ it("没有 themes 目录时:列表是空的,样式表只有一句注释", async () => {+ const t = await appWithThemes();+ const { cookie } = await provisionUser(t.app, "theme_reader");++ const list = await listThemes(t, cookie);+ expect(list.status).toBe(200);+ const body = (await list.json()) as ImportedThemesResponse;+ expect(body.dir).toBe(path.join(t.root, "themes"));+ expect(body.themes).toEqual([]);+ expect(body.rejected).toEqual([]);++ const sheet = await t.app.request("/api/themes.css");+ expect(sheet.status).toBe(200);+ expect(sheet.headers.get("content-type")).toBe("text/css; charset=utf-8");+ expect(await sheet.text()).toBe("/* no imported themes */\n");+ });++ it("列表要登录,样式表不用——首屏在登录之前就要上色", async () => {+ const t = await appWithThemes({ "warm-paper.json": WARM_PAPER });++ const anonymous = await listThemes(t);+ expect(anonymous.status).toBe(401);++ const sheet = await t.app.request("/api/themes.css");+ expect(sheet.status).toBe(200);+ expect(sheet.headers.get("cache-control")).toBe("no-cache");+ expect(await sheet.text()).toContain(':root[data-theme="warm-paper"]');+ });++ it("放进去一份好主题:列表里认得出它,样式表里就是它自己的值", async () => {+ const t = await appWithThemes({ "warm-paper.json": WARM_PAPER });+ const { cookie } = await provisionUser(t.app, "theme_reader");++ const body = (await (await listThemes(t, cookie)).json()) as ImportedThemesResponse;+ expect(body.rejected).toEqual([]);+ expect(body.themes.map((entry) => entry.file)).toEqual(["warm-paper.json"]);+ const theme = body.themes[0]!.theme;+ expect(theme.id).toBe("warm-paper");+ expect(theme.nameZh).toBe("暖纸");+ expect(theme.light["--ui-canvas"]).toBe("#f7f3ec");++ const css = await (await t.app.request("/api/themes.css")).text();+ // Light first and both modes in one base rule, dark only what it changes — so the sheet needs+ // no promise about which stylesheet the browser read first.+ expect(css).toContain(+ '@layer ui-theme{\n:root[data-theme="warm-paper"],:root[data-theme="warm-paper"].dark{--ui-canvas:#f7f3ec;--ui-surface:#fffdf8}\n:root[data-theme="warm-paper"].dark{--ui-canvas:#16130f}\n}',+ );+ // A preset is scoped to its own theme as well: it paints only under the theme that lists it.+ expect(css).toContain(+ '@layer ui-accent{\n:root[data-theme="warm-paper"][data-accent="terracotta"],:root[data-theme="warm-paper"][data-accent="terracotta"].dark{--ui-accent:#b4552d}\n}',+ );+ });++ it("读不了的文件只坑自己:好主题照旧上色,坏文件连原因一起报出来", async () => {+ const t = await appWithThemes({+ "warm-paper.json": WARM_PAPER,+ "broken.json": "{ this is not json",+ "risky.json": {+ schemaVersion: 1,+ id: "risky",+ name: "Risky",+ light: { "--ui-canvas": "red;background:url(http://example.test/x.png)" },+ },+ "notes.txt": "not a theme, not even read",+ });+ const { cookie } = await provisionUser(t.app, "theme_reader");++ const body = (await (await listThemes(t, cookie)).json()) as ImportedThemesResponse;+ expect(body.themes.map((entry) => entry.theme.id)).toEqual(["warm-paper"]);+ // Only the `.json` names are read at all, and each refusal carries the reason.+ expect(body.rejected.map((entry) => entry.file).sort()).toEqual(["broken.json", "risky.json"]);+ expect(body.rejected.find((entry) => entry.file === "broken.json")!.errors[0]).toContain(+ "不是合法的 JSON",+ );+ expect(body.rejected.find((entry) => entry.file === "risky.json")!.errors.join(" ")).toContain(+ "--ui-canvas",+ );++ const css = await (await t.app.request("/api/themes.css")).text();+ expect(css).toContain(':root[data-theme="warm-paper"]');+ // Nothing of the refused file reaches the sheet: not its name, not the value it tried.+ expect(css).not.toContain("risky");+ expect(css).not.toContain("example.test");+ });++ it("两个文件抢同一个主题名:后面那个被拒,先来的照常上色", async () => {+ const t = await appWithThemes({+ "a-good.json": WARM_PAPER,+ "b-clash.json": { ...WARM_PAPER, name: "Warm Paper Again" },+ });+ const { cookie } = await provisionUser(t.app, "theme_reader");++ const body = (await (await listThemes(t, cookie)).json()) as ImportedThemesResponse;+ expect(body.themes.map((entry) => entry.file)).toEqual(["a-good.json"]);+ expect(body.rejected).toHaveLength(1);+ expect(body.rejected[0]!.file).toBe("b-clash.json");+ expect(body.rejected[0]!.errors.join(" ")).toContain("warm-paper");+ });++ it("文件是现读的:加进去、改掉、删掉都在下一次请求里生效", async () => {+ const t = await appWithThemes();+ const { cookie } = await provisionUser(t.app, "theme_reader");+ const file = path.join(t.root, "themes", "warm-paper.json");++ await fs.mkdir(path.dirname(file), { recursive: true });+ await fs.writeFile(file, JSON.stringify(WARM_PAPER), "utf8");+ let body = (await (await listThemes(t, cookie)).json()) as ImportedThemesResponse;+ expect(body.themes.map((entry) => entry.theme.id)).toEqual(["warm-paper"]);++ await fs.writeFile(file, JSON.stringify({ ...WARM_PAPER, nameZh: "暖纸二" }), "utf8");+ body = (await (await listThemes(t, cookie)).json()) as ImportedThemesResponse;+ expect(body.themes[0]!.theme.nameZh).toBe("暖纸二");++ await fs.rm(file);+ body = (await (await listThemes(t, cookie)).json()) as ImportedThemesResponse;+ expect(body.themes).toEqual([]);+ });+});diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.tsindex c4ef701b..159566b5 100644--- a/packages/ui-gallery/src/app/mock/routes.ts+++ b/packages/ui-gallery/src/app/mock/routes.ts@@ -71,6 +71,7 @@ import type {ModelsResponse,ModelTestResponse,ModelVisionDetectResponse,+ ImportedThemesResponse,OrganizationsResponse,PluginConfigActionResponse,PluginConfigResponse,@@ -2790,3 +2791,16 @@ router// ---------------------------------------------------------------------------------------------router.get("/api/terminals", () => ({ terminals: [] }));++// ---------------------------------------------------------------------------------------------+// Imported themes: the demo has none (a gallery is not an installation), so the appearance page+// shows the directory to drop a file in and nothing else. The stylesheet the app links+// (`/api/themes.css`) is not fetched by the app itself — the real server turns the same files+// into CSS for the browser — so only the list is answered here.+// ---------------------------------------------------------------------------------------------++router.get("/api/themes", (): ImportedThemesResponse => ({+ dir: "/data/themes",+ themes: [],+ rejected: [],+}));diff --git a/packages/ui/src/boot.ts b/packages/ui/src/boot.tsindex 4359b965..cdb1b006 100644--- a/packages/ui/src/boot.ts+++ b/packages/ui/src/boot.ts@@ -11,7 +11,7 @@* The inline copy in index.html must equal {@link BOOT_SCRIPT} byte for byte; a test asserts it.* Change the constants here, then paste the regenerated string there.*/-import { ACCENT_PRESET_IDS, DEFAULT_THEME_ID, THEME_IDS } from "./tokens";+import { DEFAULT_THEME_ID, THEME_ID_PATTERN } from "./tokens";import type { AccentPreset, ThemeId } from "./tokens";/**@@ -173,18 +173,20 @@ export const THEME_FONTS: Readonly<Record<ThemeId, ThemeFonts>> = {/*** `neutral` is the stored value for "no preset": the theme's own accent, no `data-accent`. Any- * other known id is written to the root as it is, whichever theme is active: a theme's preset- * rules match only their own theme, so an id the active theme does not list paints nothing (the- * theme's own accent shows) and takes effect again when the user returns to a theme that lists- * it. The resolution lives in the CSS, and `resolveAccent` (tokens.ts) only mirrors it for a- * picker.+ * other well-formed id is written to the root as it is, whichever theme is active: a theme's+ * preset rules match only their own theme, so an id the active theme does not list paints nothing+ * (the theme's own accent shows) and takes effect again when the user returns to a theme that+ * lists it. The resolution lives in the CSS, and `resolveAccent` (tokens.ts) only mirrors it for a+ * picker. The id space is open — an imported theme brings presets of its own — so this is a+ * string with the shipped ids documented rather than a closed union.*/-export type AccentChoice = "neutral" | AccentPreset;+export type AccentChoice = AccentPreset | "neutral" | (string & {});export interface ThemeAttributes {/** The resolved mode (a `system` preference already resolved against the media query). */dark: boolean;- themeId: ThemeId;+ /** A shipped theme's id or an imported one's (tokens.ts, `THEME_ID_PATTERN`). */+ themeId: string;accent: AccentChoice;textSize: TextSize;/** `theme` is the theme's own face and writes no attribute, like `neutral` for the accent. */@@ -219,7 +221,6 @@ export function applyThemeAttributes(root: HTMLElement, attrs: Partial<ThemeAttr// The pre-paint script// ----------------------------------------------------------------------------const NON_DEFAULT_THEMES = THEME_IDS.filter((id) => id !== DEFAULT_THEME_ID);/** The ids that write an attribute: every option but `theme`, which is the attribute's absence. */const chosenFaces = (options: readonly FontOption[]) =>optionIds(options).filter((id) => id !== "theme");@@ -233,13 +234,21 @@ const K = THEME_STORAGE_KEYS;* as the provider will, and it swallows everything — storage can throw (disabled cookies,* sandboxed frames) and the page must still render. The text-size migration writes storage last* and in its own try, so a store that reads but refuses writes still paints the migrated size.+ *+ * The theme and the accent are validated by PATTERN rather than by list: an installation can+ * import themes (and themes bring presets), so the ids cannot be enumerated here. The pattern is+ * tried against a STRING only — a store that holds no value gives null, and `RegExp.test` would+ * read that as the four-letter id "null". A well-formed id that names nothing simply paints+ * nothing — an id the active theme does not list is already how a preset outlives its theme (see+ * AccentChoice) — so the worst a stale value costs is a hairline the running app corrects a frame+ * later.*/export const BOOT_SCRIPT ="(function(){try{" +- `var d=document.documentElement,s=localStorage,m=s.getItem(${j(K.mode)});` ++ `var d=document.documentElement,s=localStorage,T=new RegExp(${j(THEME_ID_PATTERN.source)}),m=s.getItem(${j(K.mode)});` +'if(m==="dark"||(m!=="light"&&matchMedia("(prefers-color-scheme: dark)").matches))d.classList.add("dark");' +- `var t=s.getItem(${j(K.themeId)});if(${j(NON_DEFAULT_THEMES)}.indexOf(t)>=0)d.dataset.theme=t;` +- `var a=s.getItem(${j(K.accent)});if(${j(ACCENT_PRESET_IDS)}.indexOf(a)>=0)d.dataset.accent=a;` ++ `var t=s.getItem(${j(K.themeId)});if(typeof t==="string"&&t!==${j(DEFAULT_THEME_ID)}&&T.test(t))d.dataset.theme=t;` ++ `var a=s.getItem(${j(K.accent)});if(typeof a==="string"&&a!=="neutral"&&T.test(a))d.dataset.accent=a;` +`var l=s.getItem(${j(K.fontLatin)});if(${j(chosenFaces(FONT_LATIN_OPTIONS))}.indexOf(l)>=0)d.dataset.fontLatin=l;` +`var c=s.getItem(${j(K.fontCjk)});if(${j(chosenFaces(FONT_CJK_OPTIONS))}.indexOf(c)>=0)d.dataset.fontCjk=c;` +`var z=s.getItem(${j(K.textSize)}),g=null,o=-1;` +diff --git a/packages/ui/src/tokens.ts b/packages/ui/src/tokens.tsindex 8facdad2..84e41d4d 100644--- a/packages/ui/src/tokens.ts+++ b/packages/ui/src/tokens.ts@@ -53,6 +53,24 @@export const THEME_IDS = ["github", "modern", "geek"] as const;export type ThemeId = (typeof THEME_IDS)[number];+/**+ * The id space of a theme, open: an installation can import themes of its own (external-theme.ts)+ * besides the three this package ships. One pattern covers both — the shipped ids are just short+ * ones — and it is the same pattern the pre-paint script applies, so the first frame and the+ * running app agree about what a stored id may be.+ */+export const THEME_ID_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;++/** Whether a stored theme id is one this app may put on `<html data-theme>`. */+export function isThemeId(value: unknown): value is string {+ return typeof value === "string" && THEME_ID_PATTERN.test(value);+}++/** Whether an id is one of the three themes the package ships (and so has tables here). */+export function isBuiltinTheme(id: string): id is ThemeId {+ return (THEME_IDS as readonly string[]).includes(id);+}+/** The theme an absent or unknown `data-theme` resolves to. Its file needs no attribute selector. */export const DEFAULT_THEME_ID: ThemeId = "github";@@ -148,16 +166,29 @@ type OwnAccents = Readonly<Record<ThemeId, Readonly<Record<ThemeModeName, string/*** What a stored choice paints under a theme: the preset when the theme lists it, otherwise* `null` — the theme's own accent, exactly as `neutral`. The CSS resolves the same way on its- * own; this is for a picker that must show which swatch is in effect.+ * own; this is for a picker that must show which swatch is in effect. A theme the package does+ * not ship lists its presets in its own file, so it resolves to `null` here and the caller+ * resolves it against what that file declares.*/export function resolveAccent(- themeId: ThemeId,+ themeId: string,choice: string | null | undefined,): AccentPreset | null {+ if (!isBuiltinTheme(themeId)) return null;const listed = THEME_ACCENT_PRESETS[themeId];return (listed as readonly string[]).includes(choice ?? "") ? (choice as AccentPreset) : null;}+/** The presets a shipped theme lists, in its own order — empty for an imported theme. */+export function themeAccentPresets(themeId: string): readonly AccentPresetSpec[] {+ return isBuiltinTheme(themeId) ? ACCENT_PRESETS[themeId] : [];+}++/** The accent a shipped theme paints when no preset is chosen; `null` for an imported theme. */+export function themeOwnAccent(themeId: string, mode: ThemeModeName): string | null {+ return isBuiltinTheme(themeId) ? THEME_OWN_ACCENTS[themeId][mode] : null;+}+/** Semantic tones. `busy` is a JS alias of `success` (see the web app's `tone.ts`), not a token. */export const TONES = ["success", "attention", "danger", "done", "neutral", "info"] as const;export type ToneName = (typeof TONES)[number];diff --git a/packages/ui/test/boot-script.test.ts b/packages/ui/test/boot-script.test.tsindex 70894fde..0244a73c 100644--- a/packages/ui/test/boot-script.test.ts+++ b/packages/ui/test/boot-script.test.ts@@ -28,14 +28,13 @@ import {isFontLatin,readTextSize,} from "../src/boot";-import type { AccentChoice } from "../src/boot";import {ACCENT_PRESET_IDS,DEFAULT_THEME_ID,THEME_ACCENT_PRESETS,THEME_IDS,+ isThemeId,} from "../src/tokens";-import type { ThemeId } from "../src/tokens";import { WEB_DIR } from "./helpers/paths";/** The attributes the script and the provider write, captured from a stand-in `<html>`. */@@ -114,11 +113,15 @@ function runBoot(stored: Record<string, string | null>, systemDark: boolean, thr/*** What the provider resolves the same stored values to, written from the stored-preference rules- * rather than from the script: an unknown mode means "system", an unknown theme id the default- * theme, an unknown accent `neutral`, an unknown face the theme's own, and the text size is what- * `readTextSize` says (the legacy scale mapped and migrated on the way). A preset any theme lists- * is written to the root whichever theme is active — the theme files scope their presets to- * their own root, so an unlisted one paints nothing and comes back with its theme.+ * rather than from the script: an unknown mode means "system", an unknown face the theme's own,+ * and the text size is what `readTextSize` says (the legacy scale mapped and migrated on the way).+ *+ * The theme and the accent are checked by PATTERN (`isThemeId`), the rule both frames share: the id+ * space is open (an installation imports themes, and each brings presets), so a well-formed id is+ * written to the root whichever theme is active — the shipped theme files scope their own rules to+ * their root, so an id nothing ships paints nothing and takes effect again when its theme is back.+ * A malformed one, and an absent value (null must not read as the four-letter id "null"), reads as+ * the default theme and as `neutral`.*/function viaProvider(stored: Record<string, string | null>, systemDark: boolean) {const mode = stored[THEME_STORAGE_KEYS.mode];@@ -130,12 +133,8 @@ function viaProvider(stored: Record<string, string | null>, systemDark: boolean)const root = fakeRoot();applyThemeAttributes(root as unknown as HTMLElement, {dark: mode === "dark" || (mode !== "light" && systemDark),- themeId: (THEME_IDS as readonly (string | null | undefined)[]).includes(themeId)- ? (themeId as ThemeId)- : DEFAULT_THEME_ID,- accent: (ACCENT_PRESET_IDS as readonly (string | null | undefined)[]).includes(accent)- ? (accent as AccentChoice)- : "neutral",+ themeId: isThemeId(themeId) ? themeId : DEFAULT_THEME_ID,+ accent: isThemeId(accent) ? accent : "neutral",textSize: readTextSize(storage),fontLatin: isFontLatin(latin) ? latin : "theme",fontCjk: isFontCjk(cjk) ? cjk : "theme",@@ -188,6 +187,30 @@ describe("BOOT_SCRIPT", () => {expect(mismatches.slice(0, 5)).toEqual([]);});+ it("keeps a well-formed id no list would have held, and drops a malformed one", () => {+ // The ids the sweep cannot afford to multiply over: an imported theme's, one whose file is+ // gone, and the shapes the pattern refuses. Boot and provider must agree on every one — the+ // "null" entries are the letters an absent store would hand to a bare pattern test.+ for (const [key, value] of [+ [THEME_STORAGE_KEYS.themeId, "warm-paper"],+ [THEME_STORAGE_KEYS.themeId, "retro"],+ [THEME_STORAGE_KEYS.themeId, "null"],+ [THEME_STORAGE_KEYS.themeId, "Retro"],+ [THEME_STORAGE_KEYS.themeId, "9lives"],+ [THEME_STORAGE_KEYS.themeId, ""],+ [THEME_STORAGE_KEYS.themeId, `${"x".repeat(33)}`],+ [THEME_STORAGE_KEYS.accent, "terracotta"],+ [THEME_STORAGE_KEYS.accent, "null"],+ [THEME_STORAGE_KEYS.accent, "Not-A-Preset"],+ [THEME_STORAGE_KEYS.accent, ""],+ ] as const) {+ const stored = { [key]: value };+ const boot = runBoot(stored, false);+ const provider = viaProvider(stored, false);+ expect(JSON.stringify(boot), `${key}=${value}`).toBe(JSON.stringify(provider));+ }+ });+it("migrates the retired three-step scale by pixels, once, and drops its key", () => {// sm was 16px, md 18px, lg 20px: the size with the same pixels, written under the new key so// the next load is a plain read; a step the scale never had is dropped without a write.diff --git a/packages/web/index.html b/packages/web/index.htmlindex 7699c7c5..b8be18fd 100644--- a/packages/web/index.html+++ b/packages/web/index.html@@ -14,12 +14,18 @@<meta name="theme-color" content="#000000" media="(prefers-color-scheme: dark)" /><link rel="icon" type="image/svg+xml" href="/adelie-icon.svg" /><title>Adelie</title>+ <!-- Imported themes: the CSS every theme file in <data root>/themes/ becomes (server,+ GET /api/themes.css, no auth so the sign-in page paints the user's own theme too). Served+ empty when nothing is imported, so this link is never a failed request. It is here rather+ than injected after login so the first paint already has it: the sheet only contains+ :root[data-theme="…"] rules, which paint nothing until the attribute says so. -->+ <link rel="stylesheet" href="/api/themes.css" /><!-- Pre-paint theme: sets html.dark, data-theme, data-accent and the root font size from thestored preferences before the first frame, so a dark or non-default page never flashesthe light default and the first frame never renders at 16px and reflows. Must equalBOOT_SCRIPT in @adelie/ui/boot byte for byte (a test compares them). --><!-- prettier-ignore -->- <script>(function(){try{var d=document.documentElement,s=localStorage,m=s.getItem("penguin.theme");if(m==="dark"||(m!=="light"&&matchMedia("(prefers-color-scheme: dark)").matches))d.classList.add("dark");var t=s.getItem("penguin.themeId");if(["modern","geek"].indexOf(t)>=0)d.dataset.theme=t;var a=s.getItem("penguin.accent");if(["blue","green","violet","rose","amber","ocean","clay","plum","honey","slate","orange","phosphor","cyan","magenta","gold","cobalt"].indexOf(a)>=0)d.dataset.accent=a;var l=s.getItem("penguin.fontLatin");if(["system","mona-sans","ibm-plex-sans","misans"].indexOf(l)>=0)d.dataset.fontLatin=l;var c=s.getItem("penguin.fontCjk");if(["system","noto-sans-sc","misans"].indexOf(c)>=0)d.dataset.fontCjk=c;var z=s.getItem("penguin.textSize"),g=null,o=-1;if(["xs","s","m","l","xl"].indexOf(z)<0){g=s.getItem("penguin.fontScale");o=["sm","md","lg"].indexOf(g);z=o<0?"m":["m","l","xl"][o]}d.style.fontSize={"xs":"14px","s":"15px","m":"16px","l":"18px","xl":"20px"}[z];if(g!==null){try{if(o>=0)s.setItem("penguin.textSize",z);s.removeItem("penguin.fontScale")}catch(e){}}}catch(e){}})()</script>+ <script>(function(){try{var d=document.documentElement,s=localStorage,T=new RegExp("^[a-z][a-z0-9-]{0,31}$"),m=s.getItem("penguin.theme");if(m==="dark"||(m!=="light"&&matchMedia("(prefers-color-scheme: dark)").matches))d.classList.add("dark");var t=s.getItem("penguin.themeId");if(typeof t==="string"&&t!=="github"&&T.test(t))d.dataset.theme=t;var a=s.getItem("penguin.accent");if(typeof a==="string"&&a!=="neutral"&&T.test(a))d.dataset.accent=a;var l=s.getItem("penguin.fontLatin");if(["system","mona-sans","ibm-plex-sans","misans"].indexOf(l)>=0)d.dataset.fontLatin=l;var c=s.getItem("penguin.fontCjk");if(["system","noto-sans-sc","misans"].indexOf(c)>=0)d.dataset.fontCjk=c;var z=s.getItem("penguin.textSize"),g=null,o=-1;if(["xs","s","m","l","xl"].indexOf(z)<0){g=s.getItem("penguin.fontScale");o=["sm","md","lg"].indexOf(g);z=o<0?"m":["m","l","xl"][o]}d.style.fontSize={"xs":"14px","s":"15px","m":"16px","l":"18px","xl":"20px"}[z];if(g!==null){try{if(o>=0)s.setItem("penguin.textSize",z);s.removeItem("penguin.fontScale")}catch(e){}}}catch(e){}})()</script></head><body><div id="root"></div>diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex e8ef7ec8..8d9a6521 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -63,6 +63,7 @@ import type {FilesStatResponse,FilesWriteRequest,GoalResponse,+ ImportedThemesResponse,InstallResponse,MachinesResponse,McpServerTestResponse,@@ -2715,3 +2716,16 @@ export const clearBuiltinBrowserData = (storages: BuiltinBrowserStorage[]) =>body: { storages },server: null,});++// ---- Themes this installation imported (a data root's own `themes/` directory) ----+/**+ * What this installation put in its data root's `themes/`, plus the files that would not read and+ * why. The server reads the directory on every request, so a file added, edited or deleted shows up+ * on the next read; the stylesheet the browser links from `<head>` is `/api/themes.css`, which the+ * app never fetches itself — the server turns the same files into CSS for it.+ *+ * This server's own directory, never a machine's: the sheet is linked by the page the server just+ * served, so the two would otherwise describe different machines.+ */+export const getImportedThemes = () =>+ apiFetch<ImportedThemesResponse>("/api/themes", { server: null });diff --git a/packages/web/src/features/settings/appearance-section.tsx b/packages/web/src/features/settings/appearance-section.tsxindex 1aed84a9..1442304b 100644--- a/packages/web/src/features/settings/appearance-section.tsx+++ b/packages/web/src/features/settings/appearance-section.tsx@@ -10,6 +10,13 @@* that is not drawn by this page at all: the desktop shell's tray icon and its pet window. Both* belong to the shell, only the shell's own window may reach them (see isDesktopShellWindow), so* both rows are absent in a browser.+ *+ * THEMES AN INSTALLATION IMPORTED are rows of the theme picker like the three the UI package+ * ships, and they arrive as data: this page lists them, paints their accents and says what a file+ * got wrong — the file games no say in the layout, because a theme is only values (see+ * state/external-themes.ts). The note under the theme row is where the reader learns which+ * directory to drop a file in and why one did not read, since nothing here discovers files by+ * itself: the browser cannot see the server's disk.*/import { useEffect, useState, useSyncExternalStore } from "react";import { PrefRow, Segmented, Select, SwatchPicker, THEME_IDS, ToggleRow } from "@adelie/ui";@@ -24,15 +31,16 @@ import {writeLauncherHidden,} from "../dock/dock-launcher-state";import { useAuth } from "../../state/auth";-import { accentSwatches, useTheme } from "../../state/theme";-import type {- FontCjk,- FontLatin,- TerminalThemeMode,- TextSize,- ThemeId,- ThemeMode,-} from "../../state/theme";+import { useLocale } from "../../state/locale";+import { useTheme } from "../../state/theme";+import type { FontCjk, FontLatin, ThemeMode, TerminalThemeMode, TextSize } from "../../state/theme";+import {+ accentSwatches,+ refreshImportedThemes,+ useImportedThemes,+} from "../../state/external-themes";+import type { ImportedThemesState } from "../../state/external-themes";+import { localizedText } from "../chat/skill-use";import { FONT_FOLLOWS_THEME, effectiveAccent } from "../../state/theme-prefs";/**@@ -95,6 +103,101 @@ function FontSelect<T extends string>({);}+/** Whether the picker already offers this id: one the package ships, or one a file brought. */+function themeIdOptionsInclude(state: ImportedThemesState, themeId: string): boolean {+ return (+ (THEME_IDS as readonly string[]).includes(themeId) ||+ state.themes.some((theme) => theme.id === themeId)+ );+}++/** Token names in the reader's own separator, at most five of them spelled out. */+function nameList(names: readonly string[], locale: "zh" | "en"): string {+ const separator = locale === "zh" ? "、" : ", ";+ const shown = names.slice(0, 5).join(separator);+ return names.length <= 5 ? shown : `${shown} ${S.settings.importedThemesMore(names.length - 5)}`;+}++/**+ * What this installation imported, under the theme row: the directory to drop a file in, and one+ * line per thing that did not come out right. Nothing is said while the list has not arrived (or+ * when the request itself failed, which is one line rather than a claim about the directory).+ *+ * An imported theme that is merely FILLED IN PARTLY says so here and still paints — a name it+ * leaves out keeps the default theme's value — while a file that would not read is reported with+ * the reason the server gave, because its author has to see it somewhere.+ */+function ImportedThemesNote({+ state,+ activeId,+ locale,+}: {+ state: ImportedThemesState;+ activeId: string;+ locale: "zh" | "en";+}) {+ const [reading, setReading] = useState(false);+ if (state.failed)+ return (+ <p className="py-3.5 text-xs text-gray-500 dark:text-gray-400">+ {S.settings.importedThemesFailed}+ </p>+ );+ if (state.dir === null) return null;+ const problems = state.themes.filter(+ (theme) => theme.unknown.length > 0 || theme.missing.length > 0,+ );+ const orphan = themeIdOptionsInclude(state, activeId) ? null : activeId;+ return (+ <div className="space-y-1 py-3.5 text-xs text-gray-500 dark:text-gray-400">+ <p className="flex flex-wrap items-center gap-x-2 gap-y-1">+ <span className="font-mono break-all">{S.settings.importedThemesDir(state.dir)}</span>+ <button+ type="button"+ disabled={reading}+ onClick={() => {+ setReading(true);+ void refreshImportedThemes(true).finally(() => setReading(false));+ }}+ className="shrink-0 text-gray-600 underline transition-colors duration-150 hover:text-gray-900 disabled:opacity-50 dark:text-gray-300 dark:hover:text-gray-100"+ >+ {S.settings.importedThemesReadAgain}+ </button>+ </p>+ <p>{S.settings.importedThemesHint}</p>+ {orphan !== null && <p>{S.settings.importedThemesNoFile(orphan)}</p>}+ {problems.map((theme) => (+ <div key={theme.id}>+ <p className="text-gray-600 dark:text-gray-300">+ {localizedText(locale, theme.name, theme.nameZh)}+ </p>+ {theme.unknown.length > 0 && (+ <p>+ {S.settings.importedThemeUnknown(+ theme.unknown.length,+ nameList(theme.unknown, locale),+ )}+ </p>+ )}+ {theme.missing.length > 0 && (+ <p>+ {S.settings.importedThemeMissing(+ theme.missing.length,+ nameList(theme.missing, locale),+ )}+ </p>+ )}+ </div>+ ))}+ {state.rejected.map(({ file, errors }) => (+ <p key={file} className="font-mono break-all">+ {S.settings.importedThemeRejected(file, errors.join(locale === "zh" ? ";" : "; "))}+ </p>+ ))}+ </div>+ );+}+export function AppearanceSection() {const {mode,@@ -115,6 +218,10 @@ export function AppearanceSection() {setToolAliases,dark,} = useTheme();+ const { locale } = useLocale();+ // What this installation imported, read once per page load (the server reads the directory per+ // request, so the note below can ask for it again).+ const imported = useImportedThemes();// The fan's "hide launcher" entry writes the same preference, so this row follows it.useSyncExternalStore(subscribeLauncherHidden, launcherHiddenVersion);const launcherShown = !readLauncherHidden();@@ -177,10 +284,18 @@ export function AppearanceSection() {{ value: "light", label: S.settings.themeLight },{ value: "dark", label: S.settings.themeDark },];- const themeIdOptions: ReadonlyArray<{ value: ThemeId; label: string }> = THEME_IDS.map((id) => ({- value: id,- label: S.settings.themeNames[id],- }));+ const themeIdOptions: ReadonlyArray<{ value: string; label: string }> = [+ ...THEME_IDS.map((id) => ({ value: id, label: S.settings.themeNames[id] })),+ ...imported.themes.map((theme) => ({+ value: theme.id,+ label: localizedText(locale, theme.name, theme.nameZh),+ })),+ // A stored id nothing provides keeps its place in the picker: the row then shows what the root+ // actually carries (and the note below says why nothing paints for it) rather than quietly+ // claiming the default theme is what was chosen.+ ...(themeIdOptionsInclude(imported, themeId) ? [] : [{ value: themeId, label: themeId }]),+ ];+ const swatches = accentSwatches(themeId, dark, imported.themes);const textSizeOptions: ReadonlyArray<{ value: TextSize; label: string }> = TEXT_SIZES.map((size) => ({ value: size, label: S.settings.textSizeNames[size] }),);@@ -190,19 +305,23 @@ export function AppearanceSection() {<PrefRow label={S.settings.theme} info={S.settings.themeInfo}><Segmented options={themeIdOptions} value={themeId} onChange={setThemeId} /></PrefRow>+ <ImportedThemesNote state={imported} activeId={themeId} locale={locale} /><PrefRow label={S.settings.colorMode} info={S.settings.colorModeInfo}><Segmented options={themeOptions} value={mode} onChange={setMode} /></PrefRow>- {/* The swatches are the active theme's own; a stored preset it does not list is shown+ {/* The swatches are the active theme's own; a stored preset it does not offer is shownas the theme's own accent, which is what the page paints, and comes back with the- theme that lists it. */}+ theme that offers it. */}<PrefRow label={S.settings.accent} info={S.settings.accentInfo}><SwatchPicker- options={accentSwatches(themeId, dark).map((swatch) => ({+ options={swatches.map((swatch) => ({...swatch,label: S.settings.accentNames[swatch.value] ?? swatch.value,}))}- value={effectiveAccent(themeId, accent)}+ value={effectiveAccent(+ accent,+ swatches.map((swatch) => swatch.value),+ )}onChange={setAccent}/></PrefRow>diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 5713bb8c..960f8aa8 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -740,6 +740,20 @@ export const en: Strings = {themeInfo:"The app's overall style: layout, lines, type and motion change with it; content and every other setting stay as they are.",themeNames: { github: "Primer", modern: "Frost", geek: "Console" },+ /** The row under the theme picker: where a theme file goes, and what one got wrong. */+ importedThemesDir: (dir: string) => `Themes directory ${dir}`,+ importedThemesHint:+ "Drop a theme's .json file in this directory and reload the page: it appears in the theme list above. The format is in the repository's examples/themes/warm-paper.json.",+ importedThemesReadAgain: "Read again",+ importedThemesFailed: "Could not read the imported themes list this time. Try again later.",+ importedThemesNoFile: (id: string) =>+ `No theme file provides the chosen "${id}"; the default theme paints for now.`,+ importedThemesMore: (count: number) => `and ${count} more`,+ importedThemeUnknown: (count: number, names: string) =>+ `${count} name${count === 1 ? "" : "s"} this build does not know (${names}): those settings do nothing.`,+ importedThemeMissing: (count: number, names: string) =>+ `${count} token${count === 1 ? "" : "s"} this theme leaves out (${names}): they keep the default theme's values.`,+ importedThemeRejected: (file: string, reason: string) => `${file}: ${reason}`,colorMode: "Mode",colorModeInfo: "Light or dark look of the app.",themeLight: "Light",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex cf66e4c0..4e5cdd54 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -798,6 +798,20 @@ export const zh = {themeInfo: "应用的整体风格:布局、线条、字体与动效随之改变,内容与其他设置不受影响。",/** Display names of the three themes; the ids stay github / modern / geek. */themeNames: { github: "通用", modern: "白领", geek: "极客" },+ /** The row under the theme picker: where a theme file goes, and what one got wrong. */+ importedThemesDir: (dir: string) => `主题目录 ${dir}`,+ importedThemesHint:+ "把主题的 .json 文件放进这个目录、刷新页面,它就会出现在上面的主题列表里;格式见仓库里的 examples/themes/warm-paper.json。",+ importedThemesReadAgain: "重新读取",+ importedThemesFailed: "这次没读到导入的主题列表,稍后再试。",+ importedThemesNoFile: (id: string) =>+ `现在选的「${id}」没有对应的主题文件,页面先用默认主题画。`,+ importedThemesMore: (count: number) => `等 ${count} 个`,+ importedThemeUnknown: (count: number, names: string) =>+ `${count} 个名字这边不认识(${names}),这些设置不会生效。`,+ importedThemeMissing: (count: number, names: string) =>+ `${count} 个令牌这个主题没写(${names}),它们沿用「通用」主题的值。`,+ importedThemeRejected: (file: string, reason: string) => `${file}:${reason}`,colorMode: "明暗",colorModeInfo: "应用的明暗外观。",themeLight: "浅色",diff --git a/packages/web/src/state/external-themes.ts b/packages/web/src/state/external-themes.tsnew file mode 100644index 00000000..a1e1088b--- /dev/null+++ b/packages/web/src/state/external-themes.ts@@ -0,0 +1,176 @@+/**+ * The themes an installation imported: read from the server, judged against the token contract,+ * and shaped for the pickers that offer them.+ *+ * WHY THIS IS THE APP'S JUDGEMENT AND NOT CORE'S. Core reads a theme file (shape, safety: its+ * internal/external-theme.ts) and the server turns the same files into the stylesheet the browser+ * links. Neither of them knows which token names exist — that is the UI package's contract — and+ * the app is the only place that depends on both, so the contract check lands here:+ *+ * - a name the contract has never heard of is REPORTED, because it paints nothing;+ * - a name the file leaves out is only a WARNING, because it falls through to the default theme's+ * value — a half-filled theme paints, it is just more Primer than its author meant.+ *+ * WHAT THE PICKERS NEED. A theme is data here: its display name in both languages, its accent+ * presets (id plus the colour to paint the swatch with, taken from the file's own `--ui-accent`),+ * and the accent it paints when no preset is chosen. Nothing is cached across a page load: the+ * server reads the directory per request, so a file added while the page is open appears after one+ * "read again", and a file deleted stops painting on the next page load — its CSS is simply gone.+ */+import { useEffect, useSyncExternalStore } from "react";+import {+ DEFAULT_THEME_ID,+ THEME_OWN_ACCENTS,+ TOKEN_NAMES,+ isBuiltinTheme,+ themeAccentPresets,+} from "@adelie/ui";+import type { ExternalTheme } from "@adelie/core";+import { getImportedThemes } from "../api/endpoints";++/** One imported theme, as the appearance page reads it. */+export interface ImportedThemeView {+ /** The file it came from, under the themes directory. */+ readonly file: string;+ readonly id: string;+ /** Its name in English, and in Chinese when the file gives one. */+ readonly name: string;+ readonly nameZh?: string;+ /** The presets it lists, in the file's own order, each with the colour its swatch shows. */+ readonly presets: ReadonlyArray<{ readonly id: string; readonly swatch: string }>;+ /** The accent it paints when no preset is chosen, per mode (`neutral`'s swatch). */+ readonly own: { readonly light: string; readonly dark: string };+ /** Token names the contract has never heard of — they paint nothing. */+ readonly unknown: readonly string[];+ /** Token names the file does not set — they keep the default theme's values. */+ readonly missing: readonly string[];+}++export interface ImportedThemesState {+ /** The directory the server read, for the line that says where to put a file; null until read. */+ readonly dir: string | null;+ readonly themes: readonly ImportedThemeView[];+ /** Files that are not a theme, with the reason. */+ readonly rejected: ReadonlyArray<{ readonly file: string; readonly errors: readonly string[] }>;+ /** The request itself failed — the list is unknown rather than empty. */+ readonly failed: boolean;+}++const EMPTY: ImportedThemesState = { dir: null, themes: [], rejected: [], failed: false };++let state: ImportedThemesState = EMPTY;+let pending: Promise<void> | null = null;+const listeners = new Set<() => void>();++function publish(next: ImportedThemesState): void {+ state = next;+ for (const listener of listeners) listener();+}++/** The default theme's own accent — what a name a theme leaves out ends up painting. */+const FALLBACK_ACCENT = THEME_OWN_ACCENTS[DEFAULT_THEME_ID];++/** The `--ui-accent` a token map sets, or null when it does not set one at all. */+function accentOf(tokens: Readonly<Record<string, string>> | undefined): string | null {+ return tokens?.["--ui-accent"] ?? null;+}++/** One file's theme as the page reads it, with the contract judged for both modes. */+export function viewOfTheme(file: string, theme: ExternalTheme): ImportedThemeView {+ const light = theme.light;+ const names = [+ ...Object.keys(light),+ ...Object.keys(theme.dark ?? {}),+ ...(theme.accents ?? []).flatMap((accent) => [+ ...Object.keys(accent.light),+ ...Object.keys(accent.dark ?? {}),+ ]),+ ];+ const contract: readonly string[] = TOKEN_NAMES;+ const ownLight = accentOf(light) ?? FALLBACK_ACCENT.light;+ return {+ file,+ id: theme.id,+ name: theme.name,+ ...(theme.nameZh === undefined ? {} : { nameZh: theme.nameZh }),+ presets: (theme.accents ?? []).map((accent) => ({+ id: accent.id,+ // What the preset paints in light mode; one that sets no `--ui-accent` paints nothing, so its+ // swatch is the theme's own accent — which is what the page shows.+ swatch: accentOf(accent.light) ?? ownLight,+ })),+ // `neutral` is the accent the theme itself paints: its own `--ui-accent` where it sets one, and+ // the default theme's where it does not (a name it leaves out keeps the default's value).+ own: { light: ownLight, dark: accentOf(theme.dark) ?? FALLBACK_ACCENT.dark },+ unknown: [...new Set(names.filter((name) => !contract.includes(name)))],+ missing: contract.filter((name) => !(name in light)),+ };+}++/** Re-reads the directory. Concurrent calls share one request; `force` re-reads after an answer. */+export function refreshImportedThemes(force = false): Promise<void> {+ if (pending) return pending;+ if (state.dir !== null && !force) return Promise.resolve();+ pending = getImportedThemes()+ .then((response) => {+ publish({+ dir: response.dir,+ themes: response.themes.map((entry) => viewOfTheme(entry.file, entry.theme)),+ rejected: response.rejected.map(({ file, errors }) => ({ file, errors: [...errors] })),+ failed: false,+ });+ })+ .catch(() => publish({ ...EMPTY, failed: true }))+ .finally(() => {+ pending = null;+ });+ return pending;+}++/** Test seam: drop what was read, so the next read asks the server again. */+export function resetImportedThemes(): void {+ state = EMPTY;+ pending = null;+}++function subscribe(listener: () => void): () => void {+ listeners.add(listener);+ return () => void listeners.delete(listener);+}++/** What was read last: the same value the hook returns, for anything outside a component. */+export function importedThemes(): ImportedThemesState {+ return state;+}++/** The imported themes of this installation, read once per page load. */+export function useImportedThemes(): ImportedThemesState {+ const current = useSyncExternalStore(subscribe, importedThemes);+ useEffect(() => {+ void refreshImportedThemes();+ }, []);+ return current;+}++/**+ * The swatches a theme offers, for the accent picker: "neutral" first (the theme's own accent),+ * then its presets. A shipped theme's presets are the package's own tables; an imported one's come+ * from its file; an id that names neither offers only "neutral" — which is all the CSS paints for+ * it either.+ */+export function accentSwatches(+ themeId: string,+ dark: boolean,+ imported: readonly ImportedThemeView[],+): ReadonlyArray<{ value: string; color: string }> {+ const mode = dark ? "dark" : "light";+ const view = imported.find((theme) => theme.id === themeId);+ const own = view+ ? view.own[mode]+ : THEME_OWN_ACCENTS[isBuiltinTheme(themeId) ? themeId : DEFAULT_THEME_ID][mode];+ const presets = view ? view.presets : themeAccentPresets(themeId);+ return [+ { value: "neutral", color: own },+ ...presets.map((preset) => ({ value: preset.id, color: preset.swatch })),+ ];+}diff --git a/packages/web/src/state/theme-prefs.ts b/packages/web/src/state/theme-prefs.tsindex bda781fe..39c8af31 100644--- a/packages/web/src/state/theme-prefs.ts+++ b/packages/web/src/state/theme-prefs.ts@@ -4,11 +4,16 @@** Pure on purpose — no React, no `window` — so the one place that decides what a stored value* means is testable against an in-memory store, and the provider (theme.tsx) only holds state.- * Every key and every value list comes from the shared UI package, which also owns the boot- * script: the first frame and the running app then cannot disagree about a stored value.+ * Every key comes from the shared UI package, which also owns the boot script: the first frame and+ * the running app then cannot disagree about a stored value.+ *+ * The theme and the accent are validated by PATTERN, not by list, exactly as the script does: an+ * installation imports themes of its own (state/external-themes.ts) and each brings presets, so the+ * ids cannot be enumerated here. A well-formed id that names nothing paints nothing — the worst a+ * stale value costs is one frame's hairline — and an imported theme's id survives a reload even+ * before its file is read again.*/-import { ACCENT_PRESET_IDS, DEFAULT_THEME_ID, THEME_IDS, resolveAccent } from "@adelie/ui";-import type { ThemeId } from "@adelie/ui";+import { DEFAULT_THEME_ID, isThemeId } from "@adelie/ui";import {FONT_CJK_OPTIONS,FONT_LATIN_OPTIONS,@@ -25,28 +30,31 @@ export type PrefStorage = Pick<Storage, "getItem" | "setItem" | "removeItem">;/** "Use the theme's own face" — stored like any other choice, applied as no attribute at all. */export const FONT_FOLLOWS_THEME = "theme";-export function readThemeId(storage: PrefStorage): ThemeId {+/** A stored theme id this app may name on <html>: a shipped one, an imported one, or neither yet. */+export function readThemeId(storage: PrefStorage): string {const stored = storage.getItem(THEME_STORAGE_KEYS.themeId);- return THEME_IDS.find((id) => id === stored) ?? DEFAULT_THEME_ID;+ return isThemeId(stored) ? stored : DEFAULT_THEME_ID;}/**- * Any preset any theme lists is kept as stored: the theme files scope their presets to their own+ * Any well-formed preset id is kept as stored: the theme files scope their presets to their own* root, so one the active theme does not list paints nothing (the theme's own accent shows) and* comes back when that theme is active again.*/export function readAccent(storage: PrefStorage): AccentChoice {const stored = storage.getItem(THEME_STORAGE_KEYS.accent);if (stored === "neutral") return stored;- return ACCENT_PRESET_IDS.find((id) => id === stored) ?? "neutral";+ return isThemeId(stored) ? stored : "neutral";}/**- * The accent a picker should mark under a theme: the stored preset when the theme lists it,- * otherwise "neutral" — which is what the CSS paints in that case too.+ * The accent a picker should mark under a theme: the stored preset when the theme offers it,+ * otherwise "neutral" — which is what the CSS paints in that case too. `offered` is the picker's+ * own list of values (state/external-themes.ts), so the same judgement covers a shipped theme, an+ * imported one and an id that names neither.*/-export function effectiveAccent(themeId: ThemeId, accent: AccentChoice): AccentChoice {- return accent === "neutral" ? accent : (resolveAccent(themeId, accent) ?? "neutral");+export function effectiveAccent(accent: AccentChoice, offered: readonly string[]): AccentChoice {+ return accent === "neutral" || offered.includes(accent) ? accent : "neutral";}export function readFontLatin(storage: PrefStorage): FontLatin {diff --git a/packages/web/src/state/theme.tsx b/packages/web/src/state/theme.tsxindex c186f65f..28ce0edd 100644--- a/packages/web/src/state/theme.tsx+++ b/packages/web/src/state/theme.tsx@@ -3,8 +3,9 @@* and accent.* - Mode: html.dark class + Tailwind dark: variant; system mode tracks prefers-color-scheme* live.- * - Theme: html[data-theme] selects one of the shared UI package's themes (absent = the- * default, Primer). Offered in Settings → Appearance.+ * - Theme: html[data-theme] names a theme — one of the three the shared UI package ships, or one+ * this installation imported (state/external-themes.ts); absent = the default, Primer. Offered+ * in Settings → Appearance.* - Text size: five steps that set the root font-size, so every rem-based type and density* token scales with it.* - Font pairing: html[data-font-latin] / [data-font-cjk] override the reading and interface@@ -26,14 +27,12 @@*/import { createContext, useCallback, useContext, useEffect, useState } from "react";import type { ReactNode } from "react";-import { ACCENT_PRESETS, THEME_OWN_ACCENTS } from "@adelie/ui";-import type { ThemeId } from "@adelie/ui";import { applyThemeAttributes, THEME_STORAGE_KEYS } from "@adelie/ui/boot";import type { AccentChoice } from "@adelie/ui/boot";import { readThemePrefs } from "./theme-prefs";import type { FontCjk, FontLatin, TextSize } from "./theme-prefs";-export type { FontCjk, FontLatin, TextSize, ThemeId };+export type { FontCjk, FontLatin, TextSize };export type ThemeMode = "light" | "dark" | "system";export type Accent = AccentChoice;/**@@ -64,9 +63,9 @@ interface ThemeContextValue {/** Resolved effective theme (system mode already resolved against the system preference). */dark: boolean;setMode: (mode: ThemeMode) => void;- /** Which theme renders the app. */- themeId: ThemeId;- setThemeId: (themeId: ThemeId) => void;+ /** Which theme renders the app: a shipped id or one this installation imported. */+ themeId: string;+ setThemeId: (themeId: string) => void;textSize: TextSize;setTextSize: (size: TextSize) => void;/** The Latin sans the theme's own is replaced with ("theme" = keep the theme's). */@@ -123,7 +122,7 @@ export function ThemeProvider({ children }: { children: ReactNode }) {const [sysDark, setSysDark] = useState(systemDark);// One read for the lot, which also migrates the legacy text-size key.const [initial] = useState(() => readThemePrefs(localStorage));- const [themeId, setThemeIdState] = useState<ThemeId>(initial.themeId);+ const [themeId, setThemeIdState] = useState<string>(initial.themeId);const [textSize, setTextSizeState] = useState<TextSize>(initial.textSize);const [fontLatin, setFontLatinState] = useState<FontLatin>(initial.fontLatin);const [fontCjk, setFontCjkState] = useState<FontCjk>(initial.fontCjk);@@ -173,7 +172,7 @@ export function ThemeProvider({ children }: { children: ReactNode }) {setModeState(next);}, []);- const setThemeId = useCallback((next: ThemeId) => {+ const setThemeId = useCallback((next: string) => {localStorage.setItem(THEME_ID_KEY, next);setThemeIdState(next);}, []);@@ -248,21 +247,3 @@ export function useTheme(): ThemeContextValue {if (!ctx) throw new Error("useTheme must be used within a ThemeProvider");return ctx;}--/**- * The accent swatches a theme offers: "neutral" first (the theme's own accent, painted as a- * plain gray because it is the absence of a choice, not a hue), then the theme's own presets in- * its own order, painted in their light values.- */-export function accentSwatches(- themeId: ThemeId,- dark = false,-): ReadonlyArray<{ value: Accent; color: string }> {- // "Theme's own" paints the accent that choice resolves to — Console's and Primer's are black- // (white in dark), Frost's its green — rather than a stand-in grey.- const own = THEME_OWN_ACCENTS[themeId];- return [- { value: "neutral", color: dark ? own.dark : own.light },- ...ACCENT_PRESETS[themeId].map((preset) => ({ value: preset.id, color: preset.swatch })),- ];-}diff --git a/packages/web/test/external-themes.test.ts b/packages/web/test/external-themes.test.tsnew file mode 100644index 00000000..3d62512f--- /dev/null+++ b/packages/web/test/external-themes.test.ts@@ -0,0 +1,155 @@+/**+ * The themes an installation imported (state/external-themes.ts): the contract judgement, the+ * swatches the pickers paint, and the read that fills the page's list.+ *+ * - The judgement no other layer can make: a name the token contract has never heard of is+ * reported (it paints nothing), while a name a theme leaves out is only listed as missing (it+ * keeps the default theme's value). Names are collected across light, dark and every accent+ * preset, once each.+ * - The accents a picker offers: a shipped theme's come from the package's own tables, an imported+ * one's from its file (a preset with no `--ui-accent` of its own shows the theme's accent, which+ * is what the page paints), and an id nothing provides offers only the theme's own — the default+ * theme's own, since that is the accent the CSS ends up using.+ * - The read: one request per page load however many components ask, a failed request says so+ * rather than claiming an empty directory, and "read again" goes back for a fresh answer.+ */+import { afterEach, describe, expect, it, vi } from "vitest";+import { ACCENT_PRESETS, THEME_OWN_ACCENTS, TOKEN_NAMES } from "@adelie/ui";+import type { ExternalTheme } from "@adelie/core";+import {+ accentSwatches,+ importedThemes,+ refreshImportedThemes,+ resetImportedThemes,+ viewOfTheme,+} from "../src/state/external-themes";++afterEach(() => resetImportedThemes());++/** A theme file that sets one name of the contract and nothing else, for the warning cases. */+function themeFile(overrides: Partial<ExternalTheme> = {}): ExternalTheme {+ return {+ id: "warm-paper",+ name: "Warm Paper",+ light: { "--ui-canvas": "#f7f3ec" },+ ...overrides,+ };+}++describe("what an imported theme file gets wrong", () => {+ it("reports names the contract has never heard of, once each, from every map in the file", () => {+ const view = viewOfTheme(+ "warm-paper.json",+ themeFile({+ light: { "--ui-canvas": "#f7f3ec", "--ui-paper-grain": "4px" },+ dark: { "--ui-canvas": "#16130f", "--ui-paper-grain": "6px" },+ accents: [{ id: "terracotta", light: { "--ui-accent": "#b4552d", "--ui-clay": "#c06" } }],+ }),+ );+ expect(view.unknown).toEqual(["--ui-paper-grain", "--ui-clay"]);+ expect(view.file).toBe("warm-paper.json");+ expect(view.nameZh).toBeUndefined();+ });++ it("lists the names a theme leaves out, because they keep the default theme's values", () => {+ const view = viewOfTheme("warm-paper.json", themeFile());+ expect(view.missing).toContain("--ui-surface");+ expect(view.missing).not.toContain("--ui-canvas");+ // Everything the file does not set is the contract minus its light keys — no more, no less.+ expect(view.missing.length).toBe(TOKEN_NAMES.length - 1);+ });+});++describe("the accents a picker paints", () => {+ it("takes a shipped theme's swatches from the package", () => {+ for (const mode of ["light", "dark"] as const) {+ const dark = mode === "dark";+ const swatches = accentSwatches("github", dark, []);+ expect(swatches[0]).toEqual({ value: "neutral", color: THEME_OWN_ACCENTS.github[mode] });+ expect(swatches.slice(1)).toEqual(+ ACCENT_PRESETS.github.map((preset) => ({ value: preset.id, color: preset.swatch })),+ );+ }+ });++ it("takes an imported theme's swatches from its file, falling back to the theme's own accent", () => {+ const view = viewOfTheme(+ "warm-paper.json",+ themeFile({+ light: { "--ui-canvas": "#f7f3ec", "--ui-accent": "#8a4b2a" },+ dark: { "--ui-accent": "#d98a63" },+ accents: [+ { id: "terracotta", light: { "--ui-accent": "#b4552d" } },+ // No `--ui-accent`: the rule paints nothing, so the theme's own accent is what shows.+ { id: "plain", light: { "--ui-canvas": "#fffdf8" } },+ ],+ }),+ );+ expect(accentSwatches("warm-paper", false, [view])).toEqual([+ { value: "neutral", color: "#8a4b2a" },+ { value: "terracotta", color: "#b4552d" },+ { value: "plain", color: "#8a4b2a" },+ ]);+ // Dark gets its own "theme's own" swatch; the presets keep the light values they declare.+ expect(accentSwatches("warm-paper", true, [view])[0]).toEqual({+ value: "neutral",+ color: "#d98a63",+ });+ });++ it("falls back to the default theme's own accent when the file sets none", () => {+ const view = viewOfTheme("half.json", themeFile({ id: "half" }));+ expect(accentSwatches("half", false, [view])).toEqual([+ { value: "neutral", color: THEME_OWN_ACCENTS.github.light },+ ]);+ });++ it("offers only the theme's own for an id nothing provides", () => {+ expect(accentSwatches("gone", false, [])).toEqual([+ { value: "neutral", color: THEME_OWN_ACCENTS.github.light },+ ]);+ expect(accentSwatches("gone", true, [])).toEqual([+ { value: "neutral", color: THEME_OWN_ACCENTS.github.dark },+ ]);+ });+});++describe("reading the list", () => {+ const answer = (body: unknown, status = 200) =>+ new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });++ it("fills the list from one request, however many callers ask", async () => {+ const fetchMock = vi.fn(async () =>+ answer({+ dir: "/data/themes",+ themes: [{ file: "warm-paper.json", theme: themeFile() }],+ rejected: [{ file: "broken.json", errors: ["不是合法的 JSON"] }],+ }),+ );+ vi.stubGlobal("fetch", fetchMock);++ await Promise.all([refreshImportedThemes(), refreshImportedThemes()]);+ const state = importedThemes();+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(state.dir).toBe("/data/themes");+ expect(state.themes.map((theme) => theme.id)).toEqual(["warm-paper"]);+ expect(state.rejected[0]!.file).toBe("broken.json");+ expect(state.failed).toBe(false);++ // Nothing asks again on its own; "read again" is the one way to a second request.+ await refreshImportedThemes();+ expect(fetchMock).toHaveBeenCalledTimes(1);+ await refreshImportedThemes(true);+ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it("says the read failed rather than claiming the directory is empty", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => answer({ error: { code: "nope", message: "nope" } }, 500)),+ );+ await refreshImportedThemes();+ expect(importedThemes().failed).toBe(true);+ expect(importedThemes().dir).toBeNull();+ });+});diff --git a/packages/web/test/theme-prefs.test.ts b/packages/web/test/theme-prefs.test.tsindex 8f0b6a92..1e353c11 100644--- a/packages/web/test/theme-prefs.test.ts+++ b/packages/web/test/theme-prefs.test.ts@@ -6,8 +6,10 @@* - An empty store reads as Primer, its own accent, 16px and its own faces.* - The legacy three-step font scale migrates by pixels once and its key is dropped; a stored* text size is kept and anything unknown reads as the default.- * - The theme and font faces are validated against the package's lists; another theme's accent- * is kept as stored while the theme's own accent is the one in effect.+ * - The theme id and the accent are checked by pattern, the way the pre-paint script checks them —+ * the id space is open, so an imported theme's id is as good as a shipped one's — while the font+ * faces stay checked against the package's lists. An accent the active theme does not offer reads+ * as the theme's own.* - A chosen face is named on <html>, the theme's own face leaves no attribute, and the text* size sets the root font size.* - Every theme, text size and accent preset of the UI package is named in both languages.@@ -15,7 +17,7 @@* dictionary.*/import { afterEach, describe, expect, it } from "vitest";-import { ACCENT_PRESET_IDS, THEME_IDS } from "@adelie/ui";+import { ACCENT_PRESET_IDS, THEME_ACCENT_PRESETS, THEME_IDS } from "@adelie/ui";import {FONT_CJK_OPTIONS,FONT_LATIN_OPTIONS,@@ -115,7 +117,7 @@ describe("reading the stored appearance", () => {);});- it("validates the theme and the font faces against the package's lists", () => {+ it("keeps a well-formed theme id — an imported one included — and drops a malformed one", () => {const storage = memoryStorage({[THEME_STORAGE_KEYS.themeId]: "geek",[THEME_STORAGE_KEYS.fontLatin]: FONT_LATIN_OPTIONS.at(-1)!.id,@@ -125,17 +127,27 @@ describe("reading the stored appearance", () => {expect(prefs.themeId).toBe("geek");expect(prefs.fontLatin).toBe(FONT_LATIN_OPTIONS.at(-1)!.id);expect(prefs.fontCjk).toBe("theme");- expect(readThemePrefs(memoryStorage({ [THEME_STORAGE_KEYS.themeId]: "neon" })).themeId).toBe(- "github",- );+ // A theme this installation imported, or one whose file is gone: the id is the app's to carry,+ // so reading it back is a pattern check, never a list (the pre-paint script does the same).+ expect(+ readThemePrefs(memoryStorage({ [THEME_STORAGE_KEYS.themeId]: "warm-paper" })).themeId,+ ).toBe("warm-paper");+ for (const malformed of ["Warm-Paper", "9lives", "no dots", "", "x".repeat(33)]) {+ expect(+ readThemePrefs(memoryStorage({ [THEME_STORAGE_KEYS.themeId]: malformed })).themeId,+ ).toBe("github");+ }});- it("keeps another theme's accent as stored, and marks the theme's own in effect", () => {+ it("keeps a stored accent as written, and marks the theme's own in effect", () => {const prefs = readThemePrefs(memoryStorage({ [THEME_STORAGE_KEYS.accent]: "ocean" }));expect(prefs.accent).toBe("ocean");- expect(effectiveAccent("modern", prefs.accent)).toBe("ocean");- expect(effectiveAccent("github", prefs.accent)).toBe("neutral");- expect(effectiveAccent("github", "blue")).toBe("blue");+ expect(effectiveAccent(prefs.accent, THEME_ACCENT_PRESETS.modern)).toBe("ocean");+ expect(effectiveAccent(prefs.accent, THEME_ACCENT_PRESETS.github)).toBe("neutral");+ expect(effectiveAccent("blue", THEME_ACCENT_PRESETS.github)).toBe("blue");+ // An imported theme's presets are the picker's own list, so the same judgement covers them.+ expect(effectiveAccent("terracotta", ["terracotta"])).toBe("terracotta");+ expect(effectiveAccent("ocean", [])).toBe("neutral");});});