A local-first multi-agent app development platform, built on PenguinHarness
feat: 外观页多了个「主题库」,装别人的主题不用再去找文件
lmliheng1a223bf77a0a
diff --git a/changelog/unreleased/2026-10-29-theme-registry.md b/changelog/unreleased/2026-10-29-theme-registry.mdnew file mode 100644index 00000000..fe8e486f--- /dev/null+++ b/changelog/unreleased/2026-10-29-theme-registry.md@@ -0,0 +1,83 @@+# Theme library: install a theme from a remote catalogue in one click, and a Trae-CN look to start with++- **Date:** 2026-10-29+- **Type:** feature+- **Scope:** `server`, `web`, `core`, `docs`+- **Breaking:** no++[中文](2026-10-29-theme-registry.zh.md)++Until now another person's theme had to reach you as a file: dropped into the data root's `themes/`,+or uploaded / fetched by an address through the admin's "Import a theme…". The appearance page now+carries one more row — the **theme library**: a remote catalogue the server reads and draws as+cards, where pressing **Import** installs a theme on this machine as exactly the file the manual+route would have written. The first catalogue ships one theme, **Trae CN**: near-black greys with+the brand green, blue links, blue input focus, and four accent presets.++The library is its own repository (`lmliheng/adelie-themes`) and its own npm package+(`@lmliheng/adelie-themes`): `index.json` is the catalogue and `themes/<id>.json` is the theme file,+in the format an installation already imports. Adding a theme is therefore a file and an entry, with+no change to Adelie.++## Details++- `packages/core/src/internal/theme-registry.ts` (new): the catalogue's shape and its reader. An+ index is all-or-nothing — every reason listed, nothing half-read — because a catalogue silently+ missing its author's newest entry reads as "it did not take effect" and nobody can locate that. An+ entry's `file` must be a repository-relative path (absolute URLs, `..` and backslashes refused),+ its swatch may only name `--ui-canvas` / `--ui-surface` / `--ui-fg` / `--ui-accent`, and its values+ pass the theme format's own safety rule (`;{}<>@`, newlines, `url(` refused).+ `resolveRegistryFile(base, file)` is the one way an address is built, shared by both routes.+- `packages/server/src/services/theme-registry.ts` (new): reading the catalogue, caching it (five+ minutes on success, thirty seconds on failure, concurrent reads sharing one request) and choosing+ where to read it. Two default addresses: the npm mirror+ `registry.npmmirror.com/@lmliheng/adelie-themes/latest/files/`, and jsDelivr's GitHub copy+ `cdn.jsdelivr.net/gh/lmliheng/adelie-themes@main/`. The first is fast inside mainland China but+ waits for the mirror to sync a release — measured this round: a brand-new package was still+ missing more than ten minutes after publishing; the second knows a commit at once and is slower.+ The second is tried only when the first fails at the TRANSPORT level: a catalogue that answers and+ does not read is reported as such, because both addresses serve the same file.+ `ADELIE_THEME_REGISTRY` replaces the whole list with one address.+- `packages/server/src/services/theme-download.ts`: `fetchThemeFile` takes `maxBytes`, because a+ catalogue's cap (128KB) is not a theme file's (256KB); the refusal names the cap it enforced.+- `packages/server/src/http/routes/themes.ts`: `GET /api/themes/registry` (any signed-in user: the+ catalogue, each entry marked installed or not, and the reason when it could not be read) and+ `POST /api/themes/registry/import` (admin, `{id, overwrite?}`). An import is the address import+ again — the same `fetchThemeFile`, the same `installTheme` — so the private-host guard, the size+ cap and the 409 `theme_exists` behave identically; it adds one check: a file whose own id is not+ the one the catalogue listed it under is refused BEFORE anything is written+ (`registry_mismatch`).+- `packages/web/src/features/settings/theme-registry-section.tsx` (new): the cards on the appearance+ page, drawn for an admin only (the one action a card offers is an import, and importing is the+ admin's). Each card paints what the theme looks like in light and in dark — canvas, surface, ink,+ accent — beside its author, version and one-line description. A library that cannot be read is a+ line, not an empty page; a successful import refreshes the theme list above and then re-reads the+ catalogue, so "installed" follows the server's reading rather than a guess.+- Copy: `packages/web/src/lib/strings{,-en}.ts` carry the library's words; the error mapping in+ `features/settings/theme-import.ts` gained the library's five codes+ (`registry_theme_not_found`, `registry_mismatch`, `registry_unusable`, `registry_unavailable`,+ `registry_invalid`), because the server's own sentence is English-only.+- Tests: `packages/core/test/theme-registry.test.ts` (11: the shape, optional fields, six bad `file`+ values, duplicate ids, unknown swatch names, unsafe values, one bad entry failing the lot, an empty+ catalogue, a missing `themes`, address joining); `packages/server/test/theme-registry.test.ts` (16:+ catalogue and cards, the login requirement, unreachable / unreadable / one bad entry, the cache, the+ fallback address with the file fetched from it, install, 409 and overwrite, unknown id, mismatched+ id, non-admin); `packages/web/test/theme-import.test.ts` pins the new codes' sentences.+- The content repository `lmliheng/adelie-themes`: `index.json`, `themes/trae-cn.json` (33 light+ tokens, 31 dark, four accent presets), a README with both formats' field tables and the "add a+ theme" steps, Apache-2.0. It is `@lmliheng/[email protected]` on npm.+- Docs: `packages/docs/content/settings.{zh,en}.md` gained a paragraph on the library after the one+ on imported themes.++## Compatibility++- No breaking change to a protocol, the disk or the API: two routes and two DTOs are added; the+ `themes/` folder, the file format and the stylesheet are untouched.+- With no `ADELIE_THEME_REGISTRY` the defaults above apply; an address that is not http(s) is+ reported as `registry_unusable` rather than silently falling back, so a page never shows a+ catalogue from a host nobody chose.+- Verified against the real addresses: the catalogue read from jsDelivr (one entry), its+ `themes/trae-cn.json` fetched (3130 bytes) and recognised by core's reader (33 light tokens). The+ npm package took more than ten minutes to appear on `registry.npmjs.org` and had not synced to+ npmmirror at all by the end of this round — which is why the second address is load-bearing rather+ than a spare.diff --git a/changelog/unreleased/2026-10-29-theme-registry.zh.md b/changelog/unreleased/2026-10-29-theme-registry.zh.mdnew file mode 100644index 00000000..4c4d5079--- /dev/null+++ b/changelog/unreleased/2026-10-29-theme-registry.zh.md@@ -0,0 +1,64 @@+# 主题库:一套主题从远端点一下就装到本机,还带了个仿 Trae 国内版的++- **Date:** 2026-10-29+- **Type:** feature+- **Scope:** `server`, `web`, `core`, `docs`+- **Breaking:** no++[English](2026-10-29-theme-registry.md)++在此之前,想要一个别人做的主题只能拿到文件:放进数据根的 `themes/` 目录,或者管理员用「导入主题…」+上传、填地址。现在外观页多了一栏**主题库**——远端的一份主题目录,服务端读进来画成卡片,挑一个点+**导入**就装到本机,和手动放进去的文件一模一样。第一期随目录带一个**仿 Trae 国内版**的主题:近黑灰底+配品牌绿、蓝色链接、输入框蓝色焦点,四个强调色预设。++主题库自己是一个独立仓库(`lmliheng/adelie-themes`)加一个同名 npm 包 `@lmliheng/adelie-themes`:+`index.json` 是目录,`themes/<id>.json` 是主题文件,格式就是本机导入的那套。所以加一个主题只是往仓库里+放一个文件、在目录里加一条,不用改 Adelie。++## 细节++- `packages/core/src/internal/theme-registry.ts`(新增):目录格式的读取与校验。整套目录**要么全收、+ 要么全拒**并列出全部原因——少一条的目录看起来像「作者刚加的没生效」,谁也定位不到。条目里的 `file`+ 只能是仓库内的相对路径(拒绝绝对地址、`..`、反斜杠),小色板只能用 `--ui-canvas` / `--ui-surface` /+ `--ui-fg` / `--ui-accent` 四个名字,取值沿用主题文件那套安全规则(禁 `;{}<>\\@`、换行与 `url(`)。+ `resolveRegistryFile(base, file)` 负责拼地址,两条路由与客户端共用一个拼法。+- `packages/server/src/services/theme-registry.ts`(新增):目录的读取、缓存(成功五分钟、失败三十秒、+ 同时在途的两次读共用一次请求)与"从哪读"。默认两个地址:npm 镜像+ `registry.npmmirror.com/@lmliheng/adelie-themes/latest/files/`,以及 jsDelivr 的 GitHub 副本+ `cdn.jsdelivr.net/gh/lmliheng/adelie-themes@main/`——前者在国内快但新版本要等它同步(这次实测新包+ 十几分钟还没到位),后者立刻就有、但慢一些。第一个地址**网络层面**不通才换第二个;目录本身读不出来+ (不是 JSON、有条目越界)就直接报原因,因为两个地址给的是同一份文件。`ADELIE_THEME_REGISTRY` 把+ 整条链换成自己那一个地址。+- `packages/server/src/services/theme-download.ts`:`fetchThemeFile` 多了 `maxBytes`,因为目录的+ 上限(128 KB)与主题文件的上限(256 KB)不是一个数;超限的报错按实际用的那个上限说话。+- `packages/server/src/http/routes/themes.ts`:`GET /api/themes/registry`(登录即可读,返回目录、每条+ 是否已装、以及目录读不到时的原因)与 `POST /api/themes/registry/import`(管理员,`{id, overwrite?}`)。+ 导入走的是**地址导入那两条路**:同一份 `fetchThemeFile` 抓、同一个 `installTheme` 写,所以内网地址+ 守卫、大小上限、`theme_exists` 的 409 全都一样;另外多一道检查——目录把 `trae-cn` 指向一个自称别的+ 名字的文件时,在落盘**之前**拒绝(`registry_mismatch`)。+- `packages/web/src/features/settings/theme-registry-section.tsx`(新增):外观页的卡片栏,只给管理员看+ (卡片上唯一的动作就是导入,而导入是管理员的)。每张卡片画着它在浅色与深色下的底色、面板色、文字色+ 与强调色,以及作者、版本、一句简介。目录读不到是一行说明而不是空页面;导入成功后先刷新上面的主题+ 列表,再重新读一遍目录,让「已安装」跟服务端的判断走。+- 文案:`packages/web/src/lib/strings{,-en}.ts` 加了主题库那一段;`features/settings/theme-import.ts` 的+ 错误映射多了主题库的五个码(`registry_theme_not_found` / `registry_mismatch` / `registry_unusable` /+ `registry_unavailable` / `registry_invalid`),因为服务端那句话只有英文。+- 测试:`packages/core/test/theme-registry.test.ts`(11 条:读入、可选字段、六种越界 `file`、重复 id、+ 未知色板名、危险取值、一条坏即整体失败、空目录、缺 `themes`、拼地址);`packages/server/test/+ theme-registry.test.ts`(16 条:目录与卡片、登录要求、读不到/读不出/一条坏、缓存只走一次网络、第一个+ 地址不通换第二个并从那一个取文件、导入、409 与覆盖、未知 id、名字对不上、非管理员);`packages/web/+ test/theme-import.test.ts` 补了主题库几个码的说法。+- 主题内容仓库 `lmliheng/adelie-themes`:`index.json`、`themes/trae-cn.json`(33 个浅色令牌 / 31 个深色+ 令牌 / 4 个强调色预设)、README(两份格式的字段表与"加一个主题"的步骤)、Apache-2.0。npm 上是+ `@lmliheng/[email protected]`。+- 文档:`packages/docs/content/settings.{zh,en}.md` 在「导入的主题」之后加了「主题库」一段。++## 兼容++- 没有协议、磁盘或接口的破坏性改动:多了两条路由和两个 DTO,`themes/` 目录、文件格式、样式表都没动。+- 不配 `ADELIE_THEME_REGISTRY` 时默认地址就是上面那两个;配了一个不能用的地址(不是 http(s))会明确+ 报 `registry_unusable`,而不是悄悄退回默认的,免得显示的是你没选的那台机器上的目录。+- 真地址验过一遍:从 jsDelivr 读到目录(1 条),取回 `themes/trae-cn.json`(3130 字节),core 的读取器+ 认成主题(33 个浅色令牌)。npm 包发布后十几分钟 `registry.npmjs.org` 才可见、npmmirror 至今没同步,+ 所以第二个地址不是备胎而是必需。diff --git a/docs/FORK-PROGRESS.md b/docs/FORK-PROGRESS.mdindex 98d8d0a1..994b8968 100644--- a/docs/FORK-PROGRESS.md+++ b/docs/FORK-PROGRESS.md@@ -18732,3 +18732,53 @@ CI 上 `test (rest)` / `test-macos (rest)` / `test-windows (rest)` 三个分片- **SSH 推拉又不行了**:`git fetch origin` 报 `[email protected]: Permission denied (publickey)`;本轮用 `git -c http.extraheader="Authorization: Basic …(GITHUB_PAT)…" fetch https://github.com/lmliheng/Adelie.git main`拉到的,结论是 `origin/main` 与本机 `HEAD` **同为 `46d49e1f`**,没有落后。++## 第一百五十八轮:主题库整条链落地,远端主题点一下就装(2026-10-29,用户「继续」)++### 上一轮那条判断的结果++第一百五十七轮把工作树里那 15 条当成「别人会话死掉的半成品」,给了三条路。用户说的是**继续**,而作者会话+(`session-2026-10-27-20-43-36-0f67df1c`)本身就是本线 —— 于是走的是「①在原会话里继续」,只不过不是把半成品+留在原地,而是这一轮把它做完并落地:core 格式、服务端服务与两条路由、web 卡片栏、内容仓库、npm 包、+文档、changelog 全在树上,一起提交。++### 本轮做完的++- **core** `internal/theme-registry.ts`(索引格式与校验,全收或全拒)+ 11 条用例。上一轮点的+ `test/theme-registry.test.ts(61,12): TS2532` 已修(`themes[0]!`),`pnpm --filter @adelie/core typecheck` 干净。+- **server** `services/theme-registry.ts`:目录读取、缓存(成功 5 分钟 / 失败 30 秒 / 在途共用一次请求)、+ 两个默认地址(npmmirror 文件目录 → jsDelivr 的 GitHub 副本,只有**网络层面**失败才换,目录本身坏就报原因)。+ `GET /api/themes/registry`(user)与 `POST /api/themes/registry/import`(admin)走地址导入同一套+ `fetchThemeFile` + `installTheme`,多一道 `registry_mismatch`(文件自称的 id 与目录条目不一致,落盘前拒)。+ `theme-download.ts` 的 `fetchThemeFile` 多了 `maxBytes`(目录 128 KB ≠ 主题 256 KB)。16 条新用例 + 原+ 15 条主题用例全绿。+- **web** 外观页 `theme-registry-section.tsx`:只给管理员,卡片画浅/深两态四色 + 作者/版本/简介,+ 导入→刷新列表→重读目录让「已安装」跟服务端走;错误文案映射加了五个 `registry_*` 码。web typecheck+ 干净,`test/theme-import.test.ts` 6 条(含新码)全绿。+- **内容仓库** `lmliheng/adelie-themes`(GitHub)+ `@lmliheng/[email protected]`(npm):+ `index.json`、`themes/trae-cn.json`(仿 Trae 国内版:33 浅 / 31 深 / 4 个强调色预设)、README(两份字段表)、+ Apache-2.0。core 的读取器认它,`externalThemesCss` 正常出层。+- **文档 / changelog**:`packages/docs/content/settings.{zh,en}.md` 各加一段;changelog 中英一对;+ `packages/ui-gallery/src/app/mock/routes.ts` 补两条 mock(否则画廊那条覆盖守卫会多出两个缺口)。++### 真地址验过什么、还差什么++- 真网络跑 `createThemeRegistry()`:npmmirror **404**(新包十几分钟还没同步)→ 退到 jsDelivr → 读到目录+ 1 条 → 取回 `themes/trae-cn.json` 3130 字节 → core 读成主题(33 个浅色令牌)。这是本轮唯一一次真跑,+ 走的是服务层,不是浏览器界面。+- `registry.npmjs.org/@lmliheng%2fadelie-themes` 在发布后约十几分钟变 200(PUT 当时回的是 **202**);+ `registry.npmmirror.com/.../latest/files/index.json` 到本轮结束仍是 **404**。所以第二个地址不是备胎。+- **没做**:真浏览器里点一遍「导入 Trae CN 然后 `--ui-canvas` 变了」—— 需要起 dev server 加一条 Playwright,+ 留给下一轮(记忆里那套假模型 + 临时数据根 + 单条 spec 的法子)。++### 门禁++`core` typecheck 干净 / 用例 11+11 绿;`server` typecheck 干净 / 主题相关 16+15 绿;`web` typecheck 干净 /+主题导入 6 绿;`ui-gallery` typecheck 干净;prettier + oxlint 对改动文件干净。+**仍然红的只有一条**:`packages/ui-gallery/test/mock-api.test.ts` 的 `workspaceFileTextUrl` /+`workspaceDirFileTextUrl` 两个既有缺口 —— 与第一百五十七轮记的是同一处,本轮没接手(不属本轮范围)。++### 下一轮++豆包式画板的**二期界面**(`packages/ui/src/components/overlays/lightbox/lightbox.tsx` 的胶囊工具条 ++同批缩略图 + 真实像素角标),以及顺手把 ui-gallery 那条既有红修掉(两个 mock 路由即可)。diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex befc0789..19494b30 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -97,6 +97,22 @@ export type {ExternalThemeAccent,ExternalThemeRead,} from "./internal/external-theme.js";+// A theme registry: the index a shared repository publishes, so an installation can browse what+// exists instead of being handed a URL. The theme FILE it points at is still read by the module+// above; this one only says which files there are and where.+export {+ MAX_REGISTRY_FILE_BYTES,+ SWATCH_NAMES,+ THEME_REGISTRY_SCHEMA_VERSION,+ readThemeRegistry,+ resolveRegistryFile,+} from "./internal/theme-registry.js";+export type {+ RegistrySwatch,+ RegistryThemeEntry,+ ThemeRegistry,+ ThemeRegistryRead,+} from "./internal/theme-registry.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/theme-registry.ts b/packages/core/src/internal/theme-registry.tsnew file mode 100644index 00000000..3a9cab17--- /dev/null+++ b/packages/core/src/internal/theme-registry.ts@@ -0,0 +1,240 @@+/**+ * A theme REGISTRY: the index a shared theme repository publishes, so an installation can browse+ * what exists instead of being handed a URL.+ *+ * The directory an installation keeps (`<data root>/themes/`) is still the whole install — a+ * registry changes only where the FILE comes from: an index names the themes, each entry points at+ * one file in the same repository, and the install path (fetch, read, write `<id>.json`) is the one+ * the download import already used. So the index is a catalogue, never a second format: the theme+ * file it points at is read by `readExternalTheme`, with the same caps and the same refusal list.+ *+ * WHY THE INDEX IS CHECKED HERE AND NOT BY EACH CLIENT. Two readers exist — the server that fetches+ * it and the page that draws the cards — and a catalogue half-understood by one of them is a theme+ * that appears and then fails to import. It lives in core for the same reason the theme format+ * does: both ends already depend on core, and neither may depend on the other.+ *+ * WHAT A FILE PATH MAY BE. Repository-relative and plain: the registry is one host serving its own+ * files, so `file` is joined onto the registry's base address and nothing else. An entry that asks+ * for an absolute URL, a scheme, or a `..` hop is refused here, not at fetch time — the point of an+ * index is that one host answers for all of it, and an index that can send a reader anywhere is an+ * open redirect with extra steps.+ */++/** The index shape this module reads. A later shape bumps it rather than half-reading an old one. */+export const THEME_REGISTRY_SCHEMA_VERSION = 1;++/** How big a registry index may be — a list of names, not a payload. */+export const MAX_REGISTRY_FILE_BYTES = 128 * 1024;++/** The most themes one index may offer. */+const MAX_REGISTRY_THEMES = 200;++/** Display copy is copy: bounded, not patterned. */+const NAME = /^[\s\S]{1,60}$/;+const AUTHOR = /^[\s\S]{1,60}$/;+const DESCRIPTION = /^[\s\S]{1,280}$/;+const VERSION = /^[0-9A-Za-z.+-]{1,32}$/;++/**+ * A repository-relative path: segments of plain characters, never `.`/`..`, never an absolute URL+ * and never a backslash (which Windows would read as a separator while this module would not).+ */+const FILE_PATH = /^(?!\/)(?!.*(?:^|\/)\.\.(?:\/|$))[A-Za-z0-9][A-Za-z0-9._\-/]*$/;++/** The four colours a card paints, and the only swatch names this format knows. */+export const SWATCH_NAMES = ["--ui-canvas", "--ui-surface", "--ui-fg", "--ui-accent"] as const;++/** A token value's safety is the theme format's rule, reused rather than restated. */+const SAFE_VALUE = /^[^;{}<>\\@\n\r]{1,120}$/;+const FETCHES = /url\s*\(|image-set\s*\(|expression\s*\(/i;++export interface RegistrySwatch {+ /** The four colours above, as the theme paints them in this mode. */+ readonly light?: Readonly<Record<string, string>>;+ readonly dark?: Readonly<Record<string, string>>;+}++/** One theme the registry offers. */+export interface RegistryThemeEntry {+ readonly id: string;+ readonly name: string;+ readonly nameZh?: string;+ readonly author: string;+ readonly description?: string;+ readonly descriptionZh?: string;+ /** Repository-relative path of the theme file. */+ readonly file: string;+ /** The theme file's own version, for cards that show one. */+ readonly version?: string;+ readonly swatch?: RegistrySwatch;+}++export interface ThemeRegistry {+ readonly schemaVersion: number;+ /** The registry's own name, shown above its list. */+ readonly name?: string;+ readonly updatedAt?: string;+ readonly themes: readonly RegistryThemeEntry[];+}++export type ThemeRegistryRead =+ | { readonly ok: true; readonly registry: ThemeRegistry }+ | { 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);+}++/**+ * The four-name swatch: undefined when the entry carries none, null when it carries one this+ * format does not understand. A swatch that fails fails its whole entry rather than being+ * half-drawn — a card's colours are the only reason the index carries them.+ */+function readSwatch(+ value: unknown,+ where: string,+ errors: string[],+): RegistrySwatch | null | undefined {+ if (value === undefined) return undefined;+ if (!isPlainObject(value)) {+ errors.push(`${where}: 要是一个对象(light / dark)`);+ return null;+ }+ const out: { light?: Record<string, string>; dark?: Record<string, string> } = {};+ for (const mode of ["light", "dark"] as const) {+ const tokens = value[mode];+ if (tokens === undefined) continue;+ if (!isPlainObject(tokens)) {+ errors.push(`${where}.${mode}: 要是一个对象`);+ return null;+ }+ const colours: Record<string, string> = {};+ for (const [name, raw] of Object.entries(tokens)) {+ if (!(SWATCH_NAMES as readonly string[]).includes(name)) {+ errors.push(+ `${where}.${mode}: 「${name}」不是色板里的名字(只能是 ${SWATCH_NAMES.join(" / ")})`,+ );+ return null;+ }+ if (typeof raw !== "string" || !SAFE_VALUE.test(raw) || FETCHES.test(raw)) {+ errors.push(`${where}.${mode}: 「${name}」的值不能用`);+ return null;+ }+ colours[name] = raw;+ }+ if (Object.keys(colours).length > 0) out[mode] = colours;+ }+ return Object.keys(out).length === 0 ? undefined : out;+}++/** One entry, or the reasons it is not one. */+function readEntry(+ entry: unknown,+ where: string,+ seen: Set<string>,+): { ok: true; entry: RegistryThemeEntry } | { ok: false; errors: string[] } {+ const errors: string[] = [];+ if (!isPlainObject(entry)) return { ok: false, errors: [`${where}: 要是一个对象`] };+ const id = entry.id;+ if (typeof id !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(id))+ return { ok: false, errors: [`${where}.id: 「${String(id)}」不是合法的主题名`] };+ if (seen.has(id)) return { ok: false, errors: [`${where}.id: 「${id}」出现了两次`] };+ const name = entry.name;+ if (typeof name !== "string" || !NAME.test(name))+ return { ok: false, errors: [`${where}.name: 要有 1–60 个字的显示名`] };+ const author = entry.author;+ if (typeof author !== "string" || !AUTHOR.test(author))+ return { ok: false, errors: [`${where}.author: 要有 1–60 个字的作者名`] };+ const file = entry.file;+ if (typeof file !== "string" || !FILE_PATH.test(file))+ return { ok: false, errors: [`${where}.file: 「${String(file)}」不是仓库内的相对路径`] };+ const nameZh = entry.nameZh;+ if (nameZh !== undefined && (typeof nameZh !== "string" || !NAME.test(nameZh)))+ return { ok: false, errors: [`${where}.nameZh: 要有 1–60 个字(不写就用 name)`] };+ const description = entry.description;+ if (+ description !== undefined &&+ (typeof description !== "string" || !DESCRIPTION.test(description))+ )+ return { ok: false, errors: [`${where}.description: 要有 1–280 个字`] };+ const descriptionZh = entry.descriptionZh;+ if (+ descriptionZh !== undefined &&+ (typeof descriptionZh !== "string" || !DESCRIPTION.test(descriptionZh))+ )+ return { ok: false, errors: [`${where}.descriptionZh: 要有 1–280 个字`] };+ const version = entry.version;+ if (version !== undefined && (typeof version !== "string" || !VERSION.test(version)))+ return { ok: false, errors: [`${where}.version: 「${String(version)}」不像一个版本号`] };+ const swatch = readSwatch(entry.swatch, `${where}.swatch`, errors);+ if (swatch === null || errors.length > 0) return { ok: false, errors };+ seen.add(id);+ return {+ ok: true,+ entry: {+ id,+ name,+ ...(nameZh === undefined ? {} : { nameZh }),+ author,+ ...(description === undefined ? {} : { description }),+ ...(descriptionZh === undefined ? {} : { descriptionZh }),+ file,+ ...(version === undefined ? {} : { version }),+ ...(swatch === undefined ? {} : { swatch }),+ },+ };+}++/**+ * Reads one index. Errors are collected rather than thrown on the first one: a registry author+ * gets the whole list, and an entry that fails is dropped — one broken line must not hide the rest+ * of the catalogue.+ */+export function readThemeRegistry(value: unknown): ThemeRegistryRead {+ if (!isPlainObject(value)) return { ok: false, errors: ["顶层必须是一个对象"] };+ const errors: string[] = [];+ const schema = value.schemaVersion;+ if (schema !== undefined && schema !== THEME_REGISTRY_SCHEMA_VERSION) {+ errors.push(+ `schemaVersion: ${String(schema)} 不是本版本认识的 ${THEME_REGISTRY_SCHEMA_VERSION}`,+ );+ }+ const raw = value.themes;+ if (!Array.isArray(raw)) return { ok: false, errors: [...errors, "themes: 要是一个数组"] };+ if (raw.length > MAX_REGISTRY_THEMES) {+ errors.push(`themes: ${raw.length} 条,超过上限 ${MAX_REGISTRY_THEMES}`);+ }+ const themes: RegistryThemeEntry[] = [];+ const seen = new Set<string>();+ for (const [index, entry] of raw.slice(0, MAX_REGISTRY_THEMES).entries()) {+ const read = readEntry(entry, `themes[${index}]`, seen);+ if (!read.ok) {+ errors.push(...read.errors);+ continue;+ }+ themes.push(read.entry);+ }+ const registry: ThemeRegistry = {+ schemaVersion: THEME_REGISTRY_SCHEMA_VERSION,+ ...(typeof value.name === "string" && NAME.test(value.name) ? { name: value.name } : {}),+ ...(typeof value.updatedAt === "string" && VERSION.test(value.updatedAt)+ ? { updatedAt: value.updatedAt }+ : {}),+ themes,+ };+ if (themes.length === 0 && errors.length === 0) errors.push("themes: 一条都没有");+ // All or nothing: a catalogue that silently lacks the entry its author just added reads as a+ // registry problem that nobody can locate. The whole list of reasons is the useful answer.+ return errors.length > 0 ? { ok: false, errors } : { ok: true, registry };+}++/**+ * One entry's address: the registry's base, its trailing slash normalised, plus the entry's own+ * relative path. Null when the base is not http(s) or the path is not one this format accepts —+ * the same rule as the reader's, so nothing that passed the index can fail here.+ */+export function resolveRegistryFile(base: string, file: string): string | null {+ if (!/^https?:\/\//i.test(base)) return null;+ if (!FILE_PATH.test(file)) return null;+ return `${base.replace(/\/+$/, "")}/${file}`;+}diff --git a/packages/core/test/theme-registry.test.ts b/packages/core/test/theme-registry.test.tsnew file mode 100644index 00000000..270d2792--- /dev/null+++ b/packages/core/test/theme-registry.test.ts@@ -0,0 +1,151 @@+/**+ * The theme registry's index: what a shared repository publishes, read the same way by the server+ * that fetches it and the page that draws its cards.+ *+ * The rules worth pinning are the ones a broken catalogue would hide: an entry pointing outside the+ * repository is refused (an index that can send a reader anywhere is an open redirect), a swatch+ * name this format does not know fails its entry rather than half-drawing a card, and one bad entry+ * fails the whole index — a list that silently lacks the theme its author just added is a support+ * question with no answer in it.+ */+import { describe, expect, it } from "vitest";+import { readThemeRegistry, resolveRegistryFile } from "../src/index.js";++const entry = {+ id: "trae-cn",+ name: "Trae CN",+ nameZh: "Trae 国产版",+ author: "lmliheng",+ description: "Near-black canvas with Trae's green accent.",+ descriptionZh: "近黑底、Trae 的绿色强调色。",+ file: "themes/trae-cn.json",+ version: "1.0.0",+ swatch: {+ light: {+ "--ui-canvas": "#f5f9fe",+ "--ui-surface": "#ffffff",+ "--ui-fg": "#0c0c0d",+ "--ui-accent": "#00a56e",+ },+ dark: {+ "--ui-canvas": "#0a0b0d",+ "--ui-surface": "#111318",+ "--ui-fg": "#edeff2",+ "--ui-accent": "#32f08c",+ },+ },+};++const index = (themes: unknown[], extra: Record<string, unknown> = {}) => ({+ schemaVersion: 1,+ name: "Adelie themes",+ updatedAt: "2026-10-28",+ themes,+ ...extra,+});++describe("readThemeRegistry", () => {+ it("reads an index into entries, swatches and all", () => {+ const read = readThemeRegistry(index([entry]));+ expect(read.ok).toBe(true);+ if (!read.ok) return;+ expect(read.registry.name).toBe("Adelie themes");+ expect(read.registry.themes).toHaveLength(1);+ expect(read.registry.themes[0]).toMatchObject({+ id: "trae-cn",+ nameZh: "Trae 国产版",+ author: "lmliheng",+ file: "themes/trae-cn.json",+ version: "1.0.0",+ });+ expect(read.registry.themes[0]!.swatch?.dark?.["--ui-accent"]).toBe("#32f08c");+ });++ it("keeps the optional fields absent when the author left them out", () => {+ const read = readThemeRegistry(+ index([{ id: "plain", name: "Plain", author: "someone", file: "themes/plain.json" }]),+ );+ expect(read.ok).toBe(true);+ if (!read.ok) return;+ expect(read.registry.themes[0]).toEqual({+ id: "plain",+ name: "Plain",+ author: "someone",+ file: "themes/plain.json",+ });+ });++ it("refuses a file path that leaves the repository", () => {+ for (const file of [+ "https://evil.example/theme.json",+ "/etc/passwd",+ "../outside.json",+ "themes/../../outside.json",+ "themes\\trae-cn.json",+ "themes/trae cn.json",+ ]) {+ const read = readThemeRegistry(index([{ ...entry, file }]));+ expect(read.ok, file).toBe(false);+ if (!read.ok) expect(read.errors.join(" ")).toContain(".file");+ }+ });++ it("refuses two entries claiming one id", () => {+ const read = readThemeRegistry(index([entry, { ...entry, file: "themes/again.json" }]));+ expect(read.ok).toBe(false);+ if (!read.ok) expect(read.errors.join(" ")).toContain("出现了两次");+ });++ it("refuses a swatch name the cards cannot paint", () => {+ const read = readThemeRegistry(+ index([{ ...entry, swatch: { dark: { "--ui-primary": "#fff" } } }]),+ );+ expect(read.ok).toBe(false);+ if (!read.ok) expect(read.errors.join(" ")).toContain("不是色板里的名字");+ });++ it("refuses a swatch value that could fetch or escape its declaration", () => {+ for (const value of ["url(http://x/y.png)", "#fff;color:red", "#fff}body{"]) {+ const read = readThemeRegistry(+ index([{ ...entry, swatch: { light: { "--ui-fg": value } } }]),+ );+ expect(read.ok, value).toBe(false);+ }+ });++ it("fails the whole index — not just the bad line — when one entry is wrong", () => {+ const read = readThemeRegistry(index([entry, { ...entry, id: "Bad ID", file: "b.json" }]));+ expect(read.ok).toBe(false);+ if (!read.ok) expect(read.errors.join(" ")).toContain("不是合法的主题名");+ });++ it("refuses an empty catalogue and an unknown schema", () => {+ expect(readThemeRegistry(index([])).ok).toBe(false);+ const read = readThemeRegistry(index([entry], { schemaVersion: 2 }));+ expect(read.ok).toBe(false);+ if (!read.ok) expect(read.errors.join(" ")).toContain("schemaVersion");+ });++ it("needs a themes array at all", () => {+ const read = readThemeRegistry({ schemaVersion: 1 });+ expect(read.ok).toBe(false);+ if (!read.ok) expect(read.errors.join(" ")).toContain("themes");+ });+});++describe("resolveRegistryFile", () => {+ it("joins the entry onto the base, normalising the trailing slash", () => {+ expect(resolveRegistryFile("https://themes.example/v1/", "themes/trae-cn.json")).toBe(+ "https://themes.example/v1/themes/trae-cn.json",+ );+ expect(resolveRegistryFile("https://themes.example/v1", "themes/trae-cn.json")).toBe(+ "https://themes.example/v1/themes/trae-cn.json",+ );+ });++ it("refuses a base that is not http(s) and a path that is not repository-relative", () => {+ expect(resolveRegistryFile("file:///etc", "themes/x.json")).toBeNull();+ expect(resolveRegistryFile("https://themes.example", "../x.json")).toBeNull();+ expect(resolveRegistryFile("https://themes.example", "/x.json")).toBeNull();+ });+});diff --git a/packages/docs/content/settings.en.md b/packages/docs/content/settings.en.mdindex 2b0c4aaa..f3f69913 100644--- a/packages/docs/content/settings.en.md+++ b/packages/docs/content/settings.en.md@@ -131,6 +131,8 @@ The **Appearance** page is personal.About **imported themes**: a theme is only a set of values, which is why a machine can have its own. Drop a theme's `.json` file into the data root's `themes/` folder and choose **Read again** under the theme list: it appears as a card in the **Imported** group, painted with its own colors. The "?" beside those two actions says where the folder is and what a file looks like, and an admin can instead press **Import a theme…** and upload the file without walking to the folder. A file may set only part of the values: the names it leaves out keep the default theme's, and the lines under the list say how many token names went unrecognised and how many keep the default — click one to see the names themselves.+About **the theme library**: an admin sees one more row of cards under the theme list — a **remote catalogue of themes** the server reads. Each card paints what that theme looks like in both light and dark: canvas, surface, ink and accent. Press **Import** and the server fetches that theme's file, checks it the same way it checks an imported file, and writes it into this machine's `themes/` folder, so it appears in the **Imported** group above straight away; a card already installed says so, and pressing it again asks before replacing anything. The default catalogue is the `@lmliheng/adelie-themes` package on npm (the mainland mirror first, jsDelivr's GitHub copy when that does not answer yet); point `ADELIE_THEME_REGISTRY` at your own mirror to use another. A library with nothing you want, or a machine with no route to it, leaves the themes and imports above untouched — the library is one more way in, not a dependency.+About **Tray icon**: the desktop app keeps an icon in the system tray: the Windows notification area, the macOS menu bar, or the Linux tray. It stays there for as long as the app runs. Click the icon to come back to the window. Right-click it to start a new Session or quit.Turning it off removes the icon at once, with no restart. Closing the window then no longer hides it there: the app stays in the Dock on macOS, and quits on Windows and Linux.diff --git a/packages/docs/content/settings.zh.md b/packages/docs/content/settings.zh.mdindex 353d25b6..ab1b6263 100644--- a/packages/docs/content/settings.zh.md+++ b/packages/docs/content/settings.zh.md@@ -135,6 +135,13 @@ Trace 会成为该 Agent 的一段新对话。如果该 Agent 下已有相同 id传上去,不用走到目录里。主题文件只写得出一部分取值也没关系:没写的那些沿用「通用」主题,列表下方会写哪几个令牌不认识、哪几个沿用了默认值,点一下能看见具体名字。+关于**主题库**:管理员在主题列表下面还会看到一栏卡片,那是**远端的一份主题目录**——服务端把目录读进来,+每张卡片画着它在浅色和深色下的底色、面板色、文字色与强调色。点**导入**,服务端就取回那份主题文件、按同+一套读法校验、写进本机的 `themes/` 目录,于是它立刻出现在上面的「导入主题」组里;已经装过的那张会标+「已安装」,再点一次先问要不要覆盖。默认目录来自 npm 上的 `@lmliheng/adelie-themes`(国内镜像,取不到时+退到 jsDelivr 的 GitHub 副本),自建镜像设环境变量 `ADELIE_THEME_REGISTRY` 指向自己的目录即可。目录里+没有想要的、或者这台机器连不上外网,都不影响上面的主题与导入:主题库只是多一条来路。+关于**托盘图标**:桌面应用运行期间,会在系统托盘(Windows 的通知区域、macOS 的菜单栏、Linux 的托盘)里常驻一个图标。点击图标回到窗口,右键可以开新会话或退出。关掉后图标立即消失,无需重启。此后关闭窗口不再收进托盘:macOS 上应用留在 Dock 中,Windows 和 Linux 上则直接退出。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 405515da..51dc295e 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -25,7 +25,13 @@ 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, ExternalTheme } from "@adelie/core";+import type {+ HarnessInfo,+ VersionReport,+ HarnessHistory,+ ExternalTheme,+ RegistryThemeEntry,+} from "@adelie/core";import type { IfacesDiff } from "@adelie/hmr";import type { WorkflowInfo } from "../mechanisms/workflows.js";@@ -2278,6 +2284,57 @@ export interface ThemeDownloadRequest {overwrite?: boolean;}+/** One theme a registry offers, plus whether this installation already reads it. */+export interface ThemeRegistryTheme extends RegistryThemeEntry {+ /**+ * True when a theme with this id is already imported here — the card then offers "重新导入"+ * (with the overwrite the import route asks for) rather than "导入".+ */+ installed: boolean;+}++/**+ * GET /api/themes/registry: the catalogue a remote registry publishes, read by the server (the+ * machine that can reach it) and shaped for the appearance page's cards. Auth: user, like the list+ * of imported themes — reading a catalogue is not installing anything.+ *+ * A registry that cannot be read is an ANSWER, not a failure: `error` carries the reason and+ * `themes` is empty, because the page still has this installation's own themes to show and a+ * catalogue nobody can reach is a note above the picker rather than a broken page.+ */+export interface ThemeRegistryResponse {+ /**+ * The address the catalogue actually came from. The server tries npmmirror first and jsDelivr's+ * GitHub copy second (a fresh npm release lags on the first), so this names the one that answered;+ * null when none did, or when `ADELIE_THEME_REGISTRY` is unusable.+ */+ base: string | null;+ /** The registry's own name, when its index carries one. */+ name?: string;+ updatedAt?: string;+ /** When the index behind this answer was fetched (ms since epoch; a cached read keeps its own). */+ fetchedAt?: number;+ themes: ThemeRegistryTheme[];+ error?: { code: string; message: string };+}++/**+ * POST /api/themes/registry/import: install one theme the registry names, by id — the server fetches+ * that entry's file and writes it exactly as the other two imports do. Admin-only.+ *+ * Errors: 403 `admin_required`, 404 `registry_theme_not_found` (no such id in the index),+ * 400 `registry_unavailable` / `registry_invalid` (the index could not be read),+ * 400 `registry_mismatch` (the file's own id is not the id the index listed it under), plus every+ * error the download import answers (`unsupported_url`, `blocked_url`, `download_failed`,+ * `theme_too_large`, `theme_invalid`, 409 `theme_exists` without `overwrite`).+ */+export interface ThemeRegistryImportRequest {+ /** The entry's id, as the index spells it. */+ id: string;+ /** Replace the theme this installation already has under that id. */+ overwrite?: boolean;+}+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.tsindex cab2afef..998f4206 100644--- a/packages/server/src/http/routes/themes.ts+++ b/packages/server/src/http/routes/themes.ts@@ -5,6 +5,15 @@* GET /api/themes.css the same files as one stylesheet (auth: none)* POST /api/themes/upload install one from a file the operator picked (auth: admin)* POST /api/themes/download install one fetched from an address (auth: admin)+ * GET /api/themes/registry what a remote theme registry offers (auth: user)+ * POST /api/themes/registry/import install one it names, by id (auth: admin)+ *+ * A REGISTRY IS THE FOURTH COLUMN OF THE SAME TABLE. It changes where a file's address comes from+ * and nothing else: the server reads the catalogue (services/theme-registry.ts), finds the entry the+ * request names, fetches that entry's file through the download route's own guards, and then hands+ * the bytes to the same reader and the same writer as the two imports above. So a theme installed+ * from a catalogue is the file a hand-dropped copy would have been — same name, same validation,+ * same `theme_exists` question on a second install.** THE TWO IMPORTS ARE THE DIRECTORY, WITH THE WALK TAKEN OUT OF IT. Dropping a file in the folder* stays the whole install, and these two routes write that same file: the JSON is read by the same@@ -44,11 +53,16 @@ import { externalThemesCss, MAX_THEME_FILE_BYTES, readExternalTheme } from "@adeimport type { ExternalTheme } from "@adelie/core";import { Bind, Component, Use } from "@adelie/core/kernel";import type { AppEnv } from "../../auth/middleware.js";-import type { ImportedThemesResponse, ThemeImportResponse } from "../../api/types.js";+import type {+ ImportedThemesResponse,+ ThemeImportResponse,+ ThemeRegistryResponse,+} from "../../api/types.js";import { Config } from "../../hmr/capabilities.js";import { HttpError } from "../errors.js";import { badRequest, optionalBoolean, readJson, requireString } from "../validate.js";import { fetchThemeFile, themeTooLarge } from "../../services/theme-download.js";+import { createThemeRegistry } from "../../services/theme-registry.js";/** Where an installation's themes live, under the data root. */export const THEMES_DIR = "themes";@@ -213,6 +227,9 @@ export async function installTheme(export function themesRoutes(deps: { root: string }): Hono<AppEnv> {const routes = new Hono<AppEnv>();+ // One client per route set, so its index cache is the app's: warm for every request, and gone+ // with the process.+ const registry = createThemeRegistry();routes.get("/", async (c) => {const { dir, themes, rejected } = await readImportedThemes(deps.root);return c.json({@@ -259,6 +276,65 @@ export function themesRoutes(deps: { root: string }): Hono<AppEnv> {return c.json({ file, theme } satisfies ThemeImportResponse, 201);});+ // What the registry offers (user): the catalogue, with each entry marked as already imported or+ // not. Every user may read it — reading a catalogue installs nothing, and the page's cards are+ // the same page the imported list is on. A registry that cannot be read is an answer with its+ // reason, not a failed request: the installation's own themes still exist.+ routes.get("/registry", async (c) => {+ const { themes } = await readImportedThemes(deps.root);+ const installed = new Set(themes.map((entry) => entry.theme.id));+ const load = await registry.read();+ if (!load.ok) {+ return c.json({+ base: null,+ themes: [],+ error: { code: load.error.code, message: load.error.message },+ } satisfies ThemeRegistryResponse);+ }+ const index = load.registry;+ return c.json({+ base: load.base,+ ...(index.name === undefined ? {} : { name: index.name }),+ ...(index.updatedAt === undefined ? {} : { updatedAt: index.updatedAt }),+ fetchedAt: load.fetchedAt,+ themes: index.themes.map((entry) => ({ ...entry, installed: installed.has(entry.id) })),+ } satisfies ThemeRegistryResponse);+ });++ // Install one entry (admin), the same way the address import does: fetch, read, write. The id+ // comes from the catalogue rather than from the caller, so the page never has to carry an address+ // — and a file whose own id is not the one it was listed under is refused BEFORE it is written,+ // because installing it would put a theme on this machine that the card the operator clicked does+ // not name.+ routes.post("/registry/import", async (c) => {+ requireAdmin(c);+ const body = await readJson(c);+ const id = requireString(body, "id", { minLen: 1, maxLen: 32, label: "id" });+ const load = await registry.read();+ if (!load.ok) throw new HttpError(400, load.error.code, load.error.message);+ const entry = load.registry.themes.find((candidate) => candidate.id === id);+ if (entry === undefined) {+ throw new HttpError(404, "registry_theme_not_found", `主题库里没有「${id}」这个主题。`);+ }+ const bytes = await registry.fetchEntryBytes(entry, load.base);+ if (bytes.byteLength === 0) throw badRequest("The download is empty.");+ const text = readThemeText(bytes);+ const listed = readThemeTextAsTheme(text);+ if (listed.id !== entry.id) {+ throw new HttpError(+ 400,+ "registry_mismatch",+ `主题库把「${entry.id}」指向了一个自称「${listed.id}」的文件。`,+ );+ }+ const { file, theme } = await installTheme(+ deps.root,+ text,+ optionalBoolean(body, "overwrite") ?? false,+ );+ return c.json({ file, theme } satisfies ThemeImportResponse, 201);+ });+return routes;}diff --git a/packages/server/src/services/theme-download.ts b/packages/server/src/services/theme-download.tsindex 501f4abf..71f1a4a1 100644--- a/packages/server/src/services/theme-download.ts+++ b/packages/server/src/services/theme-download.ts@@ -42,21 +42,26 @@ function assertHostAllowed(url: URL): void {}/** A file past the format's cap, uploaded or downloaded alike — one answer, one place the number is read. */-export function themeTooLarge(): HttpError {+export function themeTooLarge(maxBytes: number = MAX_THEME_FILE_BYTES): HttpError {return new HttpError(413,"theme_too_large",- `The theme file exceeds the ${Math.floor(MAX_THEME_FILE_BYTES / 1024)}KB limit.`,+ `The theme file exceeds the ${Math.floor(maxBytes / 1024)}KB limit.`,);}/*** Fetches one theme file. `fetchImpl` is the seam the tests use (as the plugin download's own is),* so a suite can answer with the bytes of a theme without a network.+ *+ * `maxBytes` defaults to the theme format's cap and is only lowered by a caller that is fetching+ * something of the same shape but a smaller kind — the registry index, whose own cap is a quarter+ * of a theme file's (core's `MAX_REGISTRY_FILE_BYTES`). Raising it is not what this option is for:+ * a file this server writes has to be one the reader will read afterwards.*/export async function fetchThemeFile(rawUrl: string,- options: { fetchImpl?: typeof fetch; timeoutMs?: number } = {},+ options: { fetchImpl?: typeof fetch; timeoutMs?: number; maxBytes?: number } = {},): Promise<Buffer> {let url: URL;try {@@ -96,15 +101,16 @@ export async function fetchThemeFile(throw new HttpError(400, "download_failed", `Download failed with HTTP ${res.status}.`);}const declared = Number(res.headers.get("content-length") ?? "");- if (Number.isFinite(declared) && declared > MAX_THEME_FILE_BYTES) {+ const cap = options.maxBytes ?? MAX_THEME_FILE_BYTES;+ if (Number.isFinite(declared) && declared > cap) {await res.body?.cancel().catch(() => undefined);- throw themeTooLarge();+ throw themeTooLarge(cap);}- return readBounded(res);+ return readBounded(res, cap);}/** Reads the body, refusing the moment it passes the cap rather than after buffering it all. */-async function readBounded(res: Response): Promise<Buffer> {+async function readBounded(res: Response, cap: number): Promise<Buffer> {const reader = res.body?.getReader();if (!reader) return Buffer.from(await res.arrayBuffer());const chunks: Uint8Array[] = [];@@ -113,9 +119,9 @@ async function readBounded(res: Response): Promise<Buffer> {const { done, value } = await reader.read();if (done) break;total += value.byteLength;- if (total > MAX_THEME_FILE_BYTES) {+ if (total > cap) {await reader.cancel().catch(() => undefined);- throw themeTooLarge();+ throw themeTooLarge(cap);}chunks.push(value);}diff --git a/packages/server/src/services/theme-registry.ts b/packages/server/src/services/theme-registry.tsnew file mode 100644index 00000000..226d5dde--- /dev/null+++ b/packages/server/src/services/theme-registry.ts@@ -0,0 +1,272 @@+/**+ * A remote theme REGISTRY: one address that serves an index of themes, and the theme files it+ * names.+ *+ * The install path is unchanged — fetch the theme file, read it with core's `readExternalTheme`,+ * write `<id>.json` into `<data root>/themes/` (http/routes/themes.ts). What a registry adds is that+ * the reader no longer has to be handed an address per theme: it names what exists, and the address+ * of each file is that name joined onto the registry's own base. So this module is three things and+ * no fourth: the base address (a default, overridable), the index read (bounded, checked by core,+ * cached), and one theme file's bytes (the download route's own `fetchThemeFile`, reused rather than+ * re-implemented, so a registry file is judged by the same guards and the same cap as a typed URL).+ *+ * WHY THE INDEX IS CACHED AND ITS THEMES ARE NOT. The index is a catalogue that two clicks may ask+ * for twice, and it changes when its author publishes — five minutes of staleness costs nothing,+ * while every page load hitting the network would make this machine's appearance page depend on+ * somebody else's uptime. An import, on the other hand, is a deliberate act and reads the file it is+ * about right then; caching that would be caching a version the operator did not ask for. A failed+ * index read is remembered for much less time (30s) — long enough that a page that renders once+ * does not retry on every card, short enough that a network blip does not hide the catalogue for+ * five minutes.+ *+ * WHY THE DEFAULT IS AN npm MIRROR AND NOT A RAW GITHUB URL. The registry is published both as a+ * GitHub repository and as an npm package, and the files are identical; the package is what has a+ * stable, versioned address, and npmmirror is the copy that answers inside mainland China, which is+ * where this installation runs. jsDelivr's GitHub copy is the second address because the npm mirror+ * lags a fresh release by up to an hour, and a catalogue that exists but cannot be read yet is the+ * one failure a second address fixes for free. `ADELIE_THEME_REGISTRY` replaces the whole list with+ * one address — a mirror, a fork, or a directory someone serves on their own machine — because the+ * format, not the host, is what this module knows.+ */+import { MAX_REGISTRY_FILE_BYTES, readThemeRegistry, resolveRegistryFile } from "@adelie/core";+import type { RegistryThemeEntry, ThemeRegistry } from "@adelie/core";+import { HttpError } from "../http/errors.js";+import { fetchThemeFile } from "./theme-download.js";++/**+ * Where the catalogue this app ships against lives: the npm package's files, served by npmmirror's+ * file proxy, with jsDelivr's GitHub copy behind it.+ *+ * Two addresses and not one because the same bytes travel two ways and the two fail differently.+ * npmmirror answers fast inside mainland China and lags a fresh npm release by minutes to an hour+ * (a package it has not synced yet is a 404), while jsDelivr serves the repository's files straight+ * from GitHub and knows a new commit at once — the reverse trade, and slower or unreachable in some+ * networks. The client tries them in this order and keeps whichever answered (see+ * {@link createThemeRegistry}), so a release is visible on one of them immediately and the other+ * becomes the one that works where the first does not.+ */+export const DEFAULT_THEME_REGISTRY_BASES: readonly string[] = [+ "https://registry.npmmirror.com/@lmliheng/adelie-themes/latest/files/",+ "https://cdn.jsdelivr.net/gh/lmliheng/adelie-themes@main/",+];++/** The first of the defaults — what "the address" means when someone asks for one. */+export const DEFAULT_THEME_REGISTRY_BASE = DEFAULT_THEME_REGISTRY_BASES[0]!;++/** The environment variable that replaces the base (a mirror, a fork, a LAN copy). */+export const THEME_REGISTRY_ENV = "ADELIE_THEME_REGISTRY";++/** The index's own file name, under the base address. */+export const THEME_REGISTRY_INDEX = "index.json";++/** How long a read index is reused. */+const INDEX_TTL_MS = 5 * 60_000;++/** How long a failed read is remembered — a page load's worth of clicks, not five minutes of them. */+const INDEX_FAILURE_TTL_MS = 30_000;++/**+ * The addresses to read from, in order: `ADELIE_THEME_REGISTRY` when it is set (one address, alone),+ * the defaults otherwise. Null when the variable is set to something that is not an http(s)+ * address — the caller reports that instead of quietly falling back, because an operator who set it+ * meant it, and a silent fallback would show a catalogue from a host they did not choose.+ */+export function registryBases(env: NodeJS.ProcessEnv = process.env): readonly string[] | null {+ const raw = env[THEME_REGISTRY_ENV]?.trim();+ if (!raw) return DEFAULT_THEME_REGISTRY_BASES;+ let url: URL;+ try {+ url = new URL(raw);+ } catch {+ return null;+ }+ if (url.protocol !== "http:" && url.protocol !== "https:") return null;+ return [url.toString()];+}++/** The first address to read from — the one worth naming when a page shows a single one. */+export function registryBaseUrl(env: NodeJS.ProcessEnv = process.env): string | null {+ return registryBases(env)?.[0] ?? null;+}++/** One read of the index, success or the reason it is not. */+export type ThemeRegistryLoad =+ | {+ readonly ok: true;+ readonly registry: ThemeRegistry;+ /** The address that answered — the one an entry's file is then fetched from. */+ readonly base: string;+ /** When these bytes were fetched (ms since epoch) — a cached answer keeps its own time. */+ readonly fetchedAt: number;+ }+ | {+ readonly ok: false;+ readonly error: { readonly code: string; readonly message: string };+ };++export interface ThemeRegistryClient {+ /** The addresses this client reads from, in the order it tries them. */+ readonly bases: readonly string[];+ /** The catalogue, from the cache when it is warm, else over the network. Never throws. */+ read(): Promise<ThemeRegistryLoad>;+ /** One entry's file, from the address that answered, under the download route's own guards. */+ fetchEntryBytes(entry: RegistryThemeEntry, base: string): Promise<Buffer>;+}++export interface ThemeRegistryOptions {+ /** One address, alone. Defaults to `registryBases()` — the environment's, not a hardcoded one. */+ base?: string | null;+ /** The addresses, in order. Takes precedence over `base`; the tests use one. */+ bases?: readonly string[];+ ttlMs?: number;+ failureTtlMs?: number;+ now?: () => number;+ /** The tests' seam, as the download service's own: answer with a file, no network. */+ fetchImpl?: typeof fetch;+}++/**+ * One client per app: it owns the cache, so a warm index is shared by every request that asks and+ * two simultaneous reads share one fetch rather than racing. A new app (a test, a restart) starts+ * cold, which is what makes a directory edit visible on the next boot.+ */+export function createThemeRegistry(options: ThemeRegistryOptions = {}): ThemeRegistryClient {+ // One address when it was configured (or handed in by a test), the default list otherwise. `null`+ // is "configured but unusable", which is an error rather than a reason to try the defaults.+ const configured: readonly string[] | null =+ options.bases ??+ (options.base === undefined ? registryBases() : options.base === null ? null : [options.base]);+ const bases = configured ?? [];+ const ttl = options.ttlMs ?? INDEX_TTL_MS;+ const failureTtl = options.failureTtlMs ?? INDEX_FAILURE_TTL_MS;+ const now = options.now ?? Date.now;+ let cached: { readonly load: ThemeRegistryLoad; readonly at: number } | null = null;+ let inflight: Promise<ThemeRegistryLoad> | null = null;++ /** One address's answer: a transport failure is worth asking elsewhere, a bad catalogue is not. */+ type Attempt =+ | { readonly ok: true; readonly load: ThemeRegistryLoad }+ | {+ readonly ok: false;+ readonly retry: boolean;+ readonly error: { readonly code: string; readonly message: string };+ };++ async function readFrom(base: string): Promise<Attempt> {+ const indexUrl = resolveRegistryFile(base, THEME_REGISTRY_INDEX);+ if (indexUrl === null) {+ return {+ ok: false,+ retry: true,+ error: { code: "registry_unusable", message: `主题库地址拼不出目录:${base}` },+ };+ }+ let bytes: Buffer;+ try {+ bytes = await fetchThemeFile(indexUrl, {+ ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),+ maxBytes: MAX_REGISTRY_FILE_BYTES,+ });+ } catch (err) {+ const error = err instanceof HttpError ? err : null;+ return {+ ok: false,+ retry: true,+ error: {+ code: "registry_unavailable",+ message: error ? error.message : `读不到主题库目录:${message(err)}`,+ },+ };+ }+ let parsed: unknown;+ try {+ // Fatal decoding: a catalogue that is not UTF-8 is a file nobody meant to publish, and the+ // JSON parser behind a lenient decode would only say so about a different file.+ const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes).replace(/^\uFEFF/, "");+ parsed = JSON.parse(text);+ } catch (err) {+ return {+ ok: false,+ retry: false,+ error: { code: "registry_invalid", message: `主题库目录读不出来:${message(err)}` },+ };+ }+ const read = readThemeRegistry(parsed);+ if (!read.ok) {+ // This host answered and its answer is a broken catalogue: the other address serves the SAME+ // file, so asking it would only spend the timeout to be told the same thing.+ return {+ ok: false,+ retry: false,+ error: { code: "registry_invalid", message: read.errors.join(";") },+ };+ }+ return {+ ok: true,+ load: { ok: true, registry: read.registry, base, fetchedAt: now() },+ };+ }++ async function loadIndex(): Promise<ThemeRegistryLoad> {+ if (configured === null) {+ return {+ ok: false,+ error: {+ code: "registry_unusable",+ message: `${THEME_REGISTRY_ENV} 不是一个 http(s) 地址。`,+ },+ };+ }+ let last: { readonly code: string; readonly message: string } | null = null;+ for (const base of bases) {+ const attempt = await readFrom(base);+ if (attempt.ok) return attempt.load;+ last = attempt.error;+ if (!attempt.retry) break;+ }+ return {+ ok: false,+ error: last ?? {+ code: "registry_unusable",+ message: "没有可用的主题库地址。",+ },+ };+ }++ return {+ bases,+ async read() {+ const at = now();+ if (cached !== null && at - cached.at < (cached.load.ok ? ttl : failureTtl)) {+ return cached.load;+ }+ if (inflight !== null) return inflight;+ inflight = loadIndex()+ .then((load) => {+ cached = { load, at: now() };+ return load;+ })+ .finally(() => {+ inflight = null;+ });+ return inflight;+ },+ async fetchEntryBytes(entry: RegistryThemeEntry, base: string) {+ const url = resolveRegistryFile(base, entry.file);+ if (url === null) {+ // Unreachable through the route (the index's reader only hands back paths this accepts), and+ // refused anyway rather than fetching an address an entry invented.+ throw new HttpError(+ 400,+ "registry_invalid",+ `主题「${entry.id}」的路径不是仓库内的相对路径:${entry.file}`,+ );+ }+ return fetchThemeFile(url, options.fetchImpl ? { fetchImpl: options.fetchImpl } : {});+ },+ };+}++function message(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}diff --git a/packages/server/test/theme-registry.test.ts b/packages/server/test/theme-registry.test.tsnew file mode 100644index 00000000..b674a593--- /dev/null+++ b/packages/server/test/theme-registry.test.ts@@ -0,0 +1,427 @@+/**+ * The remote theme registry, service and routes: the catalogue read (`GET /api/themes/registry`)+ * and the install by id (`POST /api/themes/registry/import`).+ *+ * - What a registry changes is where a file's ADDRESS comes from. These tests are mostly about that+ * equivalence holding: an id imports the file the index points at, written by the same reader and+ * the same writer as the address import, landing under the theme's own `<id>.json`.+ * - A catalogue nobody can reach is an answer with its reason, not a failed request: the page still+ * has this installation's themes to show.+ * - The index is checked by core's reader (all or nothing), so an index that half-reads is refused+ * with the reasons rather than shown with entries missing.+ * - The index is cached (five minutes; thirty seconds for a failure) and a theme file never is: an+ * import is a deliberate act and must fetch the file it is about right then.+ * - A file whose own id is not the one the index listed it under is refused before anything is+ * written — the card the operator clicked has to be the theme that lands.+ */+import fs from "node:fs/promises";+import path from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { ImportedThemesResponse, ThemeRegistryResponse } from "../src/api/types.js";+import {+ DEFAULT_THEME_REGISTRY_BASE,+ createThemeRegistry,+ registryBaseUrl,+} from "../src/services/theme-registry.js";+import { apiClient, createTestApp, loginAdmin, provisionUser } from "./helpers.js";+import type { TestApp } from "./helpers.js";++/** A theme file that reads: everything the format needs. */+const TRAE_THEME = {+ schemaVersion: 1,+ id: "trae-cn",+ name: "Trae CN",+ nameZh: "Trae 国内版",+ light: { "--ui-canvas": "#f5f9fe", "--ui-accent": "#00a56e" },+ dark: { "--ui-canvas": "#0a0b0d", "--ui-accent": "#32f08c" },+};++/** The catalogue that points at it. */+const INDEX = {+ schemaVersion: 1,+ name: "Adelie 主题库",+ updatedAt: "2026-10-29",+ themes: [+ {+ id: "trae-cn",+ name: "Trae CN",+ nameZh: "Trae 国内版",+ author: "lmliheng",+ description: "Trae's near-black greys with its brand green",+ descriptionZh: "Trae 的近黑灰底配品牌绿",+ file: "themes/trae-cn.json",+ version: "1.0.0",+ swatch: {+ light: { "--ui-canvas": "#f5f9fe", "--ui-accent": "#00a56e" },+ dark: { "--ui-canvas": "#0a0b0d", "--ui-accent": "#32f08c" },+ },+ },+ ],+};++const INDEX_URL = `${DEFAULT_THEME_REGISTRY_BASE}index.json`;+const THEME_URL = `${DEFAULT_THEME_REGISTRY_BASE}themes/trae-cn.json`;+/** The second address the client falls back to when the npm mirror has not synced yet. */+const JSDELIVR_BASE = "https://cdn.jsdelivr.net/gh/lmliheng/adelie-themes@main/";+const JSDELIVR_INDEX_URL = `${JSDELIVR_BASE}index.json`;+const JSDELIVR_THEME_URL = `${JSDELIVR_BASE}themes/trae-cn.json`;++let live: TestApp[] = [];++async function appWithThemes(files: Record<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) {+ await fs.writeFile(path.join(dir, name), JSON.stringify(files[name]), "utf8");+ }+ },+ });+ live.push(t);+ return t;+}++afterEach(async () => {+ vi.unstubAllGlobals();+ vi.unstubAllEnvs();+ const open = live;+ live = [];+ await Promise.all(open.map((t) => t.cleanup()));+});++/** A registry host: URL in, these files out — and every address it was asked for, in order. */+function registryHost(files: Record<string, object | string>): {+ calls: string[];+ fetchImpl: typeof fetch;+} {+ const calls: string[] = [];+ const fetchImpl = (async (input: Parameters<typeof fetch>[0]) => {+ const url = String(input);+ calls.push(url);+ const body = files[url];+ if (body === undefined) return new Response("not found", { status: 404 });+ return new Response(typeof body === "string" ? body : JSON.stringify(body), {+ status: 200,+ headers: { "content-type": "application/json" },+ });+ }) as typeof fetch;+ return { calls, fetchImpl };+}++async function cookieFor(t: TestApp): Promise<string> {+ return (await provisionUser(t.app, "theme_reader")).cookie;+}++async function readRegistry(t: TestApp, cookie?: string): Promise<ThemeRegistryResponse> {+ const res = await t.app.request("/api/themes/registry", cookie ? { headers: { cookie } } : {});+ expect(res.status).toBe(200);+ return (await res.json()) as ThemeRegistryResponse;+}++async function readError(res: Response): Promise<{ code: string; message: string }> {+ const body = (await res.json()) as { error: { code: string; message: string } };+ return body.error;+}++describe("主题库目录", () => {+ it("目录读进来:卡片要的资料齐了,已装的那一条标出来", async () => {+ const t = await appWithThemes({ "trae-cn.json": TRAE_THEME });+ const cookie = await cookieFor(t);+ const { calls, fetchImpl } = registryHost({+ [INDEX_URL]: INDEX,+ [THEME_URL]: TRAE_THEME,+ });+ vi.stubGlobal("fetch", fetchImpl);++ const body = await readRegistry(t, cookie);+ expect(body.base).toBe(DEFAULT_THEME_REGISTRY_BASE);+ expect(body.name).toBe("Adelie 主题库");+ expect(body.error).toBeUndefined();+ expect(calls).toEqual([INDEX_URL]);+ expect(body.themes).toHaveLength(1);+ const entry = body.themes[0]!;+ expect(entry.id).toBe("trae-cn");+ expect(entry.nameZh).toBe("Trae 国内版");+ expect(entry.file).toBe("themes/trae-cn.json");+ expect(entry.swatch?.dark?.["--ui-accent"]).toBe("#32f08c");+ // Already imported on this installation — the card offers "重新导入" rather than "导入".+ expect(entry.installed).toBe(true);+ // Reading a catalogue fetches no theme file.+ expect(calls).not.toContain(THEME_URL);+ });++ it("只有登录过的用户能看,客人看目录之前什么都不会出去", async () => {+ const t = await appWithThemes();+ const fetchSpy = vi.fn();+ vi.stubGlobal("fetch", fetchSpy);+ const anonymous = await t.app.request("/api/themes/registry");+ expect(anonymous.status).toBe(401);+ expect(fetchSpy).not.toHaveBeenCalled();+ });++ it("目录读不到:还是一个回答,带上原因,主题列表是空的", async () => {+ const t = await appWithThemes();+ const cookie = await cookieFor(t);++ vi.stubGlobal("fetch", async () => new Response("gone", { status: 404 }));+ let body = await readRegistry(t, cookie);+ expect(body.themes).toEqual([]);+ expect(body.error?.code).toBe("registry_unavailable");++ vi.stubGlobal("fetch", async () => {+ throw new Error("getaddrinfo ENOTFOUND");+ });+ body = await readRegistry(t, cookie);+ expect(body.error?.code).toBe("registry_unavailable");+ });++ it("目录不是 JSON:说读不出来,而不是当成空目录", async () => {+ const t = await appWithThemes();+ const cookie = await cookieFor(t);+ vi.stubGlobal("fetch", async () => new Response("{ not json", { status: 200 }));++ const body = await readRegistry(t, cookie);+ expect(body.error?.code).toBe("registry_invalid");+ expect(body.error?.message).toContain("JSON");+ });++ it("目录里有一条不合规:按 core 的读法把原因一条条列出来,不是少几条了事", async () => {+ const t = await appWithThemes();+ const cookie = await cookieFor(t);++ // A path out of the repository, and a colour value that is CSS rather than a colour: the whole+ // index is refused, with both reasons named.+ const { fetchImpl } = registryHost({+ [INDEX_URL]: {+ schemaVersion: 1,+ themes: [+ { id: "one", name: "One", author: "a", file: "../escape.json" },+ {+ id: "two",+ name: "Two",+ author: "a",+ file: "themes/two.json",+ swatch: { light: { "--ui-accent": "red;background:url(http://x.test/a.png)" } },+ },+ ],+ },+ });+ vi.stubGlobal("fetch", fetchImpl);++ const body = await readRegistry(t, cookie);+ expect(body.error?.code).toBe("registry_invalid");+ expect(body.error?.message).toContain("file");+ expect(body.error?.message).toContain("--ui-accent");+ expect(body.themes).toEqual([]);+ });++ it("第一个地址不通就退到第二个:同一份目录,换一条路进来", async () => {+ const t = await appWithThemes();+ const cookie = await cookieFor(t);+ // The npm mirror has not synced this release yet (a 404), jsDelivr's GitHub copy has it.+ const { calls, fetchImpl } = registryHost({+ [JSDELIVR_INDEX_URL]: INDEX,+ [JSDELIVR_THEME_URL]: TRAE_THEME,+ });+ vi.stubGlobal("fetch", fetchImpl);++ const body = await readRegistry(t, cookie);+ expect(body.error).toBeUndefined();+ expect(body.base).toBe("https://cdn.jsdelivr.net/gh/lmliheng/adelie-themes@main/");+ expect(calls).toEqual([INDEX_URL, JSDELIVR_INDEX_URL]);+ // ... and an import fetches from the address that answered, not from the first one.+ const admin = await loginAdmin(t.app);+ const res = await apiClient(t.app, admin.cookie).post("/api/themes/registry/import", {+ id: "trae-cn",+ });+ expect(res.status).toBe(201);+ expect(calls).toEqual([INDEX_URL, JSDELIVR_INDEX_URL, JSDELIVR_THEME_URL]);+ });++ it("目录有缓存:五分钟内两次读只走一次网络", async () => {+ const t = await appWithThemes();+ const cookie = await cookieFor(t);+ const { calls, fetchImpl } = registryHost({ [INDEX_URL]: INDEX });+ vi.stubGlobal("fetch", fetchImpl);++ await readRegistry(t, cookie);+ await readRegistry(t, cookie);+ expect(calls).toEqual([INDEX_URL]);+ });+});++describe("从主题库导入", () => {+ it("按 id 导入:取的是目录指向的那份文件,落成和地址导入完全相同的一份", async () => {+ const t = await appWithThemes();+ const admin = await loginAdmin(t.app);+ const { calls, fetchImpl } = registryHost({+ [INDEX_URL]: INDEX,+ [THEME_URL]: TRAE_THEME,+ });+ vi.stubGlobal("fetch", fetchImpl);++ const res = await apiClient(t.app, admin.cookie).post("/api/themes/registry/import", {+ id: "trae-cn",+ });+ expect(res.status).toBe(201);+ const imported = (await res.json()) as { file: string; theme: { id: string } };+ expect(imported.file).toBe("trae-cn.json");+ expect(imported.theme.id).toBe("trae-cn");+ expect(calls).toEqual([INDEX_URL, THEME_URL]);+ // The file is the registry's own bytes, written under the theme's id.+ expect(await fs.readFile(path.join(t.root, "themes", "trae-cn.json"), "utf8")).toBe(+ JSON.stringify(TRAE_THEME),+ );+ // And it paints: the sheet the page links carries it.+ const css = await (await t.app.request("/api/themes.css")).text();+ expect(css).toContain(':root[data-theme="trae-cn"]');++ const list = (await (+ await t.app.request("/api/themes", { headers: { cookie: admin.cookie } })+ ).json()) as ImportedThemesResponse;+ expect(list.themes.map((entry) => entry.theme.id)).toEqual(["trae-cn"]);+ // The catalogue now says it is installed.+ expect((await readRegistry(t, admin.cookie)).themes[0]!.installed).toBe(true);+ });++ it("导第二次:先 409 问一句,overwrite 之后还是一份文件", async () => {+ const t = await appWithThemes({ "trae-cn.json": TRAE_THEME });+ const admin = await loginAdmin(t.app);+ const { fetchImpl } = registryHost({ [INDEX_URL]: INDEX, [THEME_URL]: TRAE_THEME });+ vi.stubGlobal("fetch", fetchImpl);+ const client = apiClient(t.app, admin.cookie);++ const again = await client.post("/api/themes/registry/import", { id: "trae-cn" });+ expect(again.status).toBe(409);+ expect((await readError(again)).code).toBe("theme_exists");++ const over = await client.post("/api/themes/registry/import", {+ id: "trae-cn",+ overwrite: true,+ });+ expect(over.status).toBe(201);+ expect(await fs.readdir(path.join(t.root, "themes"))).toEqual(["trae-cn.json"]);+ });++ it("目录里没有这个 id:404,一个字节都不去取", async () => {+ const t = await appWithThemes();+ const admin = await loginAdmin(t.app);+ const { calls, fetchImpl } = registryHost({ [INDEX_URL]: INDEX });+ vi.stubGlobal("fetch", fetchImpl);++ const res = await apiClient(t.app, admin.cookie).post("/api/themes/registry/import", {+ id: "no-such-theme",+ });+ expect(res.status).toBe(404);+ expect((await readError(res)).code).toBe("registry_theme_not_found");+ expect(calls).toEqual([INDEX_URL]);+ });++ it("目录指向的文件自称别的名字:拒掉,不落盘", async () => {+ const t = await appWithThemes();+ const admin = await loginAdmin(t.app);+ const { fetchImpl } = registryHost({+ [INDEX_URL]: INDEX,+ [THEME_URL]: { ...TRAE_THEME, id: "someone-else" },+ });+ vi.stubGlobal("fetch", fetchImpl);++ const res = await apiClient(t.app, admin.cookie).post("/api/themes/registry/import", {+ id: "trae-cn",+ });+ expect(res.status).toBe(400);+ expect((await readError(res)).code).toBe("registry_mismatch");+ await expect(fs.readdir(path.join(t.root, "themes"))).rejects.toThrow();+ });++ it("目录读不到的时候:导入不成,原因和列表那边一样", async () => {+ const t = await appWithThemes();+ const admin = await loginAdmin(t.app);+ vi.stubGlobal("fetch", async () => {+ throw new Error("getaddrinfo ENOTFOUND");+ });++ const res = await apiClient(t.app, admin.cookie).post("/api/themes/registry/import", {+ id: "trae-cn",+ });+ expect(res.status).toBe(400);+ expect((await readError(res)).code).toBe("registry_unavailable");+ });++ it("导入只有管理员能做:别人点了按钮,连目录都不去取", async () => {+ const t = await appWithThemes();+ const member = apiClient(t.app, (await provisionUser(t.app, "theme_member")).cookie);+ const fetchSpy = vi.fn();+ vi.stubGlobal("fetch", fetchSpy);++ const res = await member.post("/api/themes/registry/import", { id: "trae-cn" });+ expect(res.status).toBe(403);+ expect((await readError(res)).code).toBe("admin_required");+ expect(fetchSpy).not.toHaveBeenCalled();+ });+});++describe("主题库地址与缓存", () => {+ it("默认是 npmmirror 上的包文件;环境变量可以整条换掉", () => {+ expect(registryBaseUrl({})).toBe(DEFAULT_THEME_REGISTRY_BASE);+ expect(registryBaseUrl({ ADELIE_THEME_REGISTRY: "" })).toBe(DEFAULT_THEME_REGISTRY_BASE);+ expect(registryBaseUrl({ ADELIE_THEME_REGISTRY: "https://mirror.test/themes" })).toBe(+ "https://mirror.test/themes",+ );+ // Something that is not an http(s) address is reported rather than replaced by the default: an+ // operator who set it meant it.+ expect(registryBaseUrl({ ADELIE_THEME_REGISTRY: "file:///srv/themes" })).toBeNull();+ expect(registryBaseUrl({ ADELIE_THEME_REGISTRY: "not a url" })).toBeNull();+ });++ it("失败只记三十秒:网络抖一下不该让目录消失五分钟", async () => {+ let clock = 0;+ let ok = false;+ const fetchImpl = (async () =>+ ok+ ? new Response(JSON.stringify(INDEX), { status: 200 })+ : new Response("boom", { status: 500 })) as unknown as typeof fetch;+ const client = createThemeRegistry({+ base: "https://registry.test/",+ fetchImpl,+ now: () => clock,+ });++ expect((await client.read()).ok).toBe(false);+ clock = 10_000;+ expect((await client.read()).ok).toBe(false);+ // Past the failure window the catalogue is asked for again — and now it answers.+ ok = true;+ clock = 31_000;+ const load = await client.read();+ expect(load.ok).toBe(true);+ // ... and then the successful answer holds for the full five minutes.+ clock = 31_000 + 4 * 60_000;+ expect((await client.read()).ok).toBe(true);+ });++ it("同一个时刻的两次读共用一次请求,不各自去敲网络", async () => {+ let release: (() => void) | null = null;+ const gate = new Promise<void>((done) => {+ release = done;+ });+ let calls = 0;+ const fetchImpl = (async () => {+ calls += 1;+ await gate;+ return new Response(JSON.stringify(INDEX), { status: 200 });+ }) as unknown as typeof fetch;+ const client = createThemeRegistry({ base: "https://registry.test/", fetchImpl });++ const both = Promise.all([client.read(), client.read()]);+ await new Promise((done) => setTimeout(done, 0));+ expect(calls).toBe(1);+ release!();+ const [first, second] = await both;+ expect(first.ok && second.ok).toBe(true);+ expect(calls).toBe(1);+ });+});diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.tsindex fb4a48a2..f4d772c6 100644--- a/packages/ui-gallery/src/app/mock/routes.ts+++ b/packages/ui-gallery/src/app/mock/routes.ts@@ -72,6 +72,7 @@ import type {ModelTestResponse,ModelVisionDetectResponse,ImportedThemesResponse,+ ThemeRegistryResponse,OrganizationsResponse,PluginConfigActionResponse,PluginConfigResponse,@@ -2814,3 +2815,42 @@ router.get("/api/themes", (): ImportedThemesResponse => ({router.post("/api/themes/upload", () => readOnly("import a theme from a file")).post("/api/themes/download", () => readOnly("import a theme from an address"));++// The remote catalogue the appearance page offers an admin: one entry, from the real library, so+// the gallery shows what a card is. Nobody here can import one (the demo is not an admin), so the+// import route is the same refusal the two above give.+router.get("/api/themes/registry", (): ThemeRegistryResponse => ({+ base: "https://cdn.jsdelivr.net/gh/lmliheng/adelie-themes@main/",+ name: "Adelie Themes",+ updatedAt: "2026-10-29",+ fetchedAt: 1_761_700_800_000,+ themes: [+ {+ id: "trae-cn",+ name: "Trae CN",+ nameZh: "Trae 国内版",+ author: "lmliheng",+ description: "Trae's near-black greys with its brand green.",+ descriptionZh: "Trae 国内版的近黑灰底与品牌绿。",+ file: "themes/trae-cn.json",+ version: "1.0.0",+ swatch: {+ light: {+ "--ui-canvas": "#f5f9fe",+ "--ui-surface": "#ffffff",+ "--ui-fg": "#1c2026",+ "--ui-accent": "#00a56e",+ },+ dark: {+ "--ui-canvas": "#0a0b0d",+ "--ui-surface": "#0c0c0d",+ "--ui-fg": "#edeff2",+ "--ui-accent": "#32f08c",+ },+ },+ installed: false,+ },+ ],+}));++router.post("/api/themes/registry/import", () => readOnly("import a theme from the theme library"));diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 2003624d..e812abc0 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -66,6 +66,8 @@ import type {ImportedThemesResponse,ThemeDownloadRequest,ThemeImportResponse,+ ThemeRegistryImportRequest,+ ThemeRegistryResponse,ThemeUploadRequest,InstallResponse,MachinesResponse,@@ -2772,3 +2774,25 @@ export const importThemeArchive = (body: ThemeUploadRequest) =>*/export const importThemeFromUrl = (body: ThemeDownloadRequest) =>apiFetch<ThemeImportResponse>("/api/themes/download", { method: "POST", body, server: null });++/**+ * The catalogue a remote theme registry publishes (npmmirror's copy of the theme package, or+ * whatever `ADELIE_THEME_REGISTRY` names), with each entry marked installed or not. Read by the+ * server, because the server is what can reach it. A registry that could not be read answers 200+ * with `error` and no themes — a note above the picker, not a failed page.+ */+export const getThemeRegistry = () =>+ apiFetch<ThemeRegistryResponse>("/api/themes/registry", { server: null });++/**+ * Install one entry the catalogue names, by id: the server fetches that entry's file through the+ * same guards as the address import and writes it through the same reader, so 409 `theme_exists`+ * (and the same `overwrite` retry) is answered here too. Unknown id: 404+ * `registry_theme_not_found`. Admin-only.+ */+export const importThemeFromRegistry = (body: ThemeRegistryImportRequest) =>+ apiFetch<ThemeImportResponse>("/api/themes/registry/import", {+ method: "POST",+ body,+ server: null,+ });diff --git a/packages/web/src/features/settings/appearance-section.tsx b/packages/web/src/features/settings/appearance-section.tsxindex 450f8274..1e434b8f 100644--- a/packages/web/src/features/settings/appearance-section.tsx+++ b/packages/web/src/features/settings/appearance-section.tsx@@ -22,6 +22,12 @@* same install without the walk to the folder, and it is the server's own rule that decides who* may use it: the routes answer 403 to anyone else, so the entry is drawn for an admin only rather* than offered and refused.+ *+ * AND A LIBRARY BESIDE THE FOLDER. A theme can also arrive from a remote catalogue (the registry+ * routes) — the same installation, one fetch the server makes instead of the operator — so the page+ * carries its cards under the same picker, again for an admin only, because importing is the one+ * thing a card offers. Its own state is its own: a library nobody can reach leaves the picker and+ * the folder row exactly as they were.*/import { useEffect, useState, useSyncExternalStore } from "react";import {@@ -59,6 +65,7 @@ import { localizedText } from "../chat/skill-use";import { FONT_FOLLOWS_THEME, effectiveAccent } from "../../state/theme-prefs";import { ThemeImportActions } from "./theme-import-dialog";import { ThemePicker } from "./theme-picker";+import { ThemeRegistrySection } from "./theme-registry-section";/*** A font select's choices: the theme's own face first — it is the default, and the named faces@@ -356,6 +363,11 @@ export function AppearanceSection() {locale={locale}canImport={user?.isAdmin === true}/>+ {/* The remote catalogue, for an admin only: a card's one action is an import, which is the+ admin's to make — a member would be shown a list of themes they cannot have. */}+ {user?.isAdmin === true && (+ <ThemeRegistrySection onImported={() => refreshImportedThemes(true)} />+ )}{" "}<PrefRow label={S.settings.colorMode} info={S.settings.colorModeInfo}><Segmented options={themeOptions} value={mode} onChange={setMode} /></PrefRow>diff --git a/packages/web/src/features/settings/theme-import.ts b/packages/web/src/features/settings/theme-import.tsindex a052bd4c..84d2ed02 100644--- a/packages/web/src/features/settings/theme-import.ts+++ b/packages/web/src/features/settings/theme-import.ts@@ -26,10 +26,14 @@ export function themeFileTooLarge(sizeBytes: number): boolean {}/**- * The text of a failed theme import: the codes the two routes answer with get their own copy (the+ * The text of a failed theme import: the codes the import routes answer with get their own copy (the* server's message is English-only, and the UI language may not be), everything else goes through* the shared error mapping. A 409 `theme_exists` never arrives here — the caller turns it into the* overwrite confirmation, which is a question rather than a failure.+ *+ * The registry import answers the same codes — it fetches and writes through the same two steps —+ * plus the four that only it can answer, which are here for the same reason the others are: the+ * server's own sentence is not translated.*/export function themeImportErrorText(err: unknown): string {if (err instanceof ApiError) {@@ -44,6 +48,16 @@ export function themeImportErrorText(err: unknown): string {return S.settings.themeImportBlockedUrl;case "download_failed":return S.settings.themeImportDownloadFailed;+ case "registry_theme_not_found":+ return S.settings.themeRegistryGone;+ case "registry_mismatch":+ return S.settings.themeRegistryMismatch;+ case "registry_unusable":+ return S.settings.themeRegistryUnusable;+ case "registry_unavailable":+ return S.settings.themeRegistryFailed;+ case "registry_invalid":+ return S.settings.themeRegistryInvalid(err.message);default:break;}diff --git a/packages/web/src/features/settings/theme-registry-section.tsx b/packages/web/src/features/settings/theme-registry-section.tsxnew file mode 100644index 00000000..19ffcb0c--- /dev/null+++ b/packages/web/src/features/settings/theme-registry-section.tsx@@ -0,0 +1,288 @@+/**+ * The theme library: the remote catalogue this installation can import themes from, drawn under the+ * theme picker as a row of cards.+ *+ * A CARD IS A THEME AND A BUTTON, nothing more: the four colours the registry published for it (both+ * modes, so a dark-only theme is visible in a light page), its name in the reader's language, its+ * author, its description, and one import. Nothing here fetches a theme file to show a preview — the+ * catalogue carries exactly those four colours for that reason, and the whole file arrives when the+ * operator decides to install it.+ *+ * WHO SEES IT: an admin, because an import is the only thing a card offers and the routes are the+ * admin's (every browser that signs in on this machine is painted by what lands in the themes+ * directory). Offering the cards to a member would be a list of things they cannot have.+ *+ * A LIBRARY THAT CANNOT BE READ IS A LINE, NOT AN EMPTY PAGE. The server answers 200 with the reason+ * (`registry_unavailable`, `registry_invalid`, `registry_unusable`), the card grid is empty, and the+ * page's own themes above are untouched — this row is an addition to the picker, never a dependency+ * of it. "Refresh" asks again; the index is cached server-side for five minutes, so a hand-edited+ * mirror needs no restart, just patience or a fresh base address.+ *+ * A SECOND IMPORT OF THE SAME THEME is the same question the file dialog asks: 409 `theme_exists`+ * opens the overwrite confirmation, whose confirm resends with `overwrite: true`. The card carries+ * "installed" from the server's answer (it compares the catalogue against the directory per+ * request), so after an import the grid is re-read rather than guessed at.+ */+import { useCallback, useEffect, useState } from "react";+import { Button, ConfirmModal, InfoPopover, toastError, toastSuccess } from "@adelie/ui";+import type { ThemeRegistryResponse, ThemeRegistryTheme } from "@adelie/server/api";+import * as api from "../../api/endpoints";+import { ApiError } from "../../api/client";+import { S } from "../../lib/strings";+import { useLocale } from "../../state/locale";+import { localizedText } from "../chat/skill-use";+import { themeImportErrorText } from "./theme-import";++/** One mode's four colours, filled in where the catalogue left a name out. */+type ModeColours = Readonly<Record<string, string>>;++/** The two modes a card paints; each half of the chip is its own mode. */+function modalColours(entry: ThemeRegistryTheme): { light?: ModeColours; dark?: ModeColours } {+ return { light: entry.swatch?.light, dark: entry.swatch?.dark };+}++/**+ * The chip: each mode the catalogue described, side by side — its canvas, a surface bar, the ink it+ * writes with and the accent beside it. A mode it did not describe is simply absent, which is why a+ * dark-only theme paints one half rather than a half of invented colours.+ */+function RegistryChip({ entry }: { entry: ThemeRegistryTheme }) {+ const modes = modalColours(entry);+ const halves = (["light", "dark"] as const)+ .map((mode) => ({ mode, colours: modes[mode] }))+ .filter((half): half is { mode: "light" | "dark"; colours: ModeColours } => !!half.colours);+ if (halves.length === 0) {+ return (+ <span+ aria-hidden+ className="flex h-9 items-center justify-center rounded-[var(--ui-radius-sm)] border border-dashed border-line text-[10px] text-fg-subtle"+ >+ {S.settings.themeRegistry}+ </span>+ );+ }+ return (+ <span aria-hidden className="flex h-9 overflow-hidden rounded-[var(--ui-radius-sm)]">+ {halves.map(({ mode, colours }) => (+ <span+ key={mode}+ className="relative min-w-0 flex-1"+ style={{ background: colours["--ui-canvas"] }}+ >+ <span+ className="absolute inset-x-1 top-1 block rounded-[2px]"+ style={{+ background: colours["--ui-surface"],+ border: `1px solid ${colours["--ui-fg"] ?? "transparent"}22`,+ height: "0.5rem",+ }}+ />+ <span+ className="absolute bottom-1 left-1 block rounded-full"+ style={{ background: colours["--ui-accent"], height: "0.25rem", width: "0.75rem" }}+ />+ <span+ className="absolute bottom-1 right-1 block rounded-full"+ style={{+ background: colours["--ui-fg"],+ height: "0.25rem",+ opacity: 0.45,+ width: "0.5rem",+ }}+ />+ </span>+ ))}+ </span>+ );+}++function RegistryCard({+ entry,+ locale,+ busy,+ onInstall,+}: {+ entry: ThemeRegistryTheme;+ locale: "zh" | "en";+ busy: boolean;+ onInstall: () => void;+}) {+ const description =+ entry.description === undefined+ ? null+ : localizedText(locale, entry.description, entry.descriptionZh);+ const version = entry.version === undefined ? null : `v${entry.version}`;+ return (+ <div className="flex flex-col gap-1.5 rounded-[var(--ui-radius-md)] border border-line bg-surface p-2">+ <RegistryChip entry={entry} />+ <p className="min-w-0">+ <span className="block truncate text-sm text-fg-emphasis">+ {localizedText(locale, entry.name, entry.nameZh)}+ </span>+ <span className="block truncate text-[11px] text-fg-subtle">+ {S.settings.themeRegistryBy(entry.author)}+ {version === null ? "" : ` · ${version}`}+ </span>+ </p>+ {description !== null && <p className="line-clamp-2 text-xs text-fg-muted">{description}</p>}+ <span className="mt-auto flex items-center gap-1.5 pt-0.5">+ {entry.installed && (+ <span className="text-[11px] text-fg-subtle">{S.settings.themeRegistryInstalled}</span>+ )}+ <Button+ size="sm"+ variant={entry.installed ? "ghost" : "secondary"}+ className="ml-auto"+ disabled={busy}+ onClick={onInstall}+ >+ {busy+ ? S.settings.themeImportBusy+ : entry.installed+ ? S.settings.themeRegistryReimport+ : S.settings.themeRegistryImport}+ </Button>+ </span>+ </div>+ );+}++/** Which entry is waiting on the overwrite confirmation. */+interface Pending {+ readonly id: string;+ readonly name: string;+}++export function ThemeRegistrySection({+ onImported,+}: {+ /** Called after an import landed: re-read the imported list, so the new theme is in the picker. */+ onImported: () => Promise<void> | void;+}) {+ const { locale } = useLocale();+ const [catalogue, setCatalogue] = useState<ThemeRegistryResponse | null>(null);+ const [reading, setReading] = useState(true);+ const [busyId, setBusyId] = useState<string | null>(null);+ const [pending, setPending] = useState<Pending | null>(null);+ const [failed, setFailed] = useState(false);++ const load = useCallback(async () => {+ setReading(true);+ try {+ const res = await api.getThemeRegistry();+ setCatalogue(res);+ setFailed(false);+ } catch {+ // The request itself failed (not the registry): the shared sentence, and a row that can be+ // asked again rather than a page that pretends there is no library.+ setFailed(true);+ } finally {+ setReading(false);+ }+ }, []);++ useEffect(() => {+ void load();+ }, [load]);++ const install = async (entry: ThemeRegistryTheme, overwrite: boolean) => {+ setBusyId(entry.id);+ try {+ const res = await api.importThemeFromRegistry({+ id: entry.id,+ ...(overwrite ? { overwrite } : {}),+ });+ setPending(null);+ toastSuccess(+ S.settings.themeRegistryImported(localizedText(locale, res.theme.name, res.theme.nameZh)),+ );+ // The picker first (that is what the reader came here for), then the catalogue: its+ // "installed" marks are the server's reading of the directory, not a guess of ours.+ await onImported();+ await load();+ } catch (e) {+ if (e instanceof ApiError && e.status === 409 && e.code === "theme_exists") {+ setPending({ id: entry.id, name: localizedText(locale, entry.name, entry.nameZh) });+ } else {+ setPending(null);+ toastError(themeImportErrorText(e));+ }+ } finally {+ setBusyId(null);+ }+ };++ const error = catalogue?.error ?? null;+ const themes = catalogue?.themes ?? [];++ return (+ <div className="space-y-2 py-3.5">+ <div className="flex flex-wrap items-center gap-2">+ <p className="flex items-center gap-1.5 text-xs text-fg-muted">+ {S.settings.themeRegistry}+ <InfoPopover label={S.settings.themeRegistryInfo}>+ <div className="space-y-1.5">+ <p>{S.settings.themeRegistryInfo}</p>+ {catalogue?.base != null && <p className="font-mono break-all">{catalogue.base}</p>}+ </div>+ </InfoPopover>+ </p>+ <Button size="sm" variant="ghost" disabled={reading} onClick={() => void load()}>+ {S.settings.themeRegistryReadAgain}+ </Button>+ </div>++ {reading && catalogue === null && (+ <p className="text-xs text-fg-subtle">{S.settings.themeRegistryLoading}</p>+ )}+ {failed && <p className="text-xs text-fg-subtle">{S.settings.themeRegistryFailed}</p>}+ {/* A catalogue that answered with a reason is a line, not an empty grid: the reader has to+ know the difference between "nothing there" and "could not look". */}+ {error !== null && (+ <p className="text-xs break-words text-fg-subtle">+ {error.code === "registry_invalid"+ ? S.settings.themeRegistryInvalid(error.message)+ : error.code === "registry_unusable"+ ? S.settings.themeRegistryUnusable+ : S.settings.themeRegistryFailed}+ </p>+ )}+ {!reading && error === null && !failed && themes.length === 0 && (+ <p className="text-xs text-fg-subtle">{S.settings.themeRegistryEmpty}</p>+ )}+ {themes.length > 0 && (+ <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">+ {themes.map((entry) => (+ <RegistryCard+ key={entry.id}+ entry={entry}+ locale={locale}+ busy={busyId === entry.id}+ onInstall={() => void install(entry, entry.installed)}+ />+ ))}+ </div>+ )}++ {pending !== null && (+ <ConfirmModal+ open+ title={S.settings.themeImportOverwriteTitle}+ tone="primary"+ confirmLabel={S.settings.themeImportOverwriteAction}+ cancelLabel={S.common.cancel}+ busy={busyId !== null}+ onClose={() => setPending(null)}+ onConfirm={() => {+ const entry = themes.find((candidate) => candidate.id === pending.id);+ if (entry !== undefined) void install(entry, true);+ }}+ >+ <p className="text-sm text-gray-600 dark:text-gray-300">+ {S.settings.themeImportOverwriteBody}+ </p>+ </ConfirmModal>+ )}+ </div>+ );+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex e77b8144..e0c8ee47 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -786,6 +786,24 @@ export const en: Strings = {themeImportDownloadFailed:"Could not fetch it: the address, the network or the answer's status.",themeImportBadUrl: "The address has to be a URL starting with http:// or https://.",+ /** The theme library: a remote catalogue this installation can import from. */+ themeRegistry: "Theme library",+ themeRegistryInfo:+ "A theme catalogue served somewhere remote and read by the server; a theme you like installs with one click. By default it is the @lmliheng/adelie-themes package on npm — set ADELIE_THEME_REGISTRY to point at your own mirror.",+ themeRegistryReadAgain: "Refresh",+ themeRegistryLoading: "Reading the theme library…",+ themeRegistryEmpty: "The theme library has no themes right now.",+ themeRegistryFailed: "Could not read the theme library this time. Try again later.",+ themeRegistryInvalid: (reason: string) => `The theme library's index does not read: ${reason}`,+ themeRegistryUnusable: "The theme library address is not http(s); check ADELIE_THEME_REGISTRY.",+ themeRegistryImport: "Import",+ themeRegistryReimport: "Re-import",+ themeRegistryInstalled: "Installed",+ themeRegistryImported: (name: string) => `Imported ${name} from the theme library`,+ themeRegistryGone: "The theme library no longer lists this theme; refresh and look again.",+ themeRegistryMismatch:+ "The theme library points this entry at the wrong file: what it served is not the name it listed.",+ themeRegistryBy: (author: string) => `by ${author}`,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.`,diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 3dc5ddeb..4869a74c 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -836,6 +836,23 @@ export const zh = {themeImportBlockedUrl: "这个地址指向本机或内网,服务端不会去取。",themeImportDownloadFailed: "取不回来:地址、网络或对方的状态码有问题。",themeImportBadUrl: "地址要是一个 http:// 或 https:// 开头的网址。",+ /** The theme library: a remote catalogue this installation can import from. */+ themeRegistry: "主题库",+ themeRegistryInfo:+ "远端的一份主题目录,服务端读进来,适合的主题点一下就装到本机。默认是 npm 上 @lmliheng/adelie-themes 的主题包,也可以用 ADELIE_THEME_REGISTRY 换成自建镜像。",+ themeRegistryReadAgain: "刷新",+ themeRegistryLoading: "正在读取主题库…",+ themeRegistryEmpty: "主题库里暂时没有主题。",+ themeRegistryFailed: "这次没读到主题库,稍后再试。",+ themeRegistryInvalid: (reason: string) => `主题库目录读不出来:${reason}`,+ themeRegistryUnusable: "主题库地址不是 http(s) 地址,检查 ADELIE_THEME_REGISTRY。",+ themeRegistryImport: "导入",+ themeRegistryReimport: "重新导入",+ themeRegistryInstalled: "已安装",+ themeRegistryImported: (name: string) => `已从主题库导入 ${name}`,+ themeRegistryGone: "主题库里已经没有这个主题了,刷新一下再看。",+ themeRegistryMismatch: "主题库把这一条指错了文件:装下来的主题不是它写的那个名字。",+ themeRegistryBy: (author: string) => `作者 ${author}`,importedThemesFailed: "这次没读到导入的主题列表,稍后再试。",importedThemesNoFile: (id: string) =>`现在选的「${id}」没有对应的主题文件,页面先用默认主题画。`,diff --git a/packages/web/test/theme-import.test.ts b/packages/web/test/theme-import.test.tsindex 1859176b..c8bc7bb2 100644--- a/packages/web/test/theme-import.test.ts+++ b/packages/web/test/theme-import.test.ts@@ -50,6 +50,25 @@ describe("主题导入失败时说的话", () => {);});+ it("主题库导入的四个码也在同一张表上", () => {+ expect(themeImportErrorText(new ApiError(404, "registry_theme_not_found", "…"))).toBe(+ S.settings.themeRegistryGone,+ );+ expect(themeImportErrorText(new ApiError(400, "registry_mismatch", "…"))).toBe(+ S.settings.themeRegistryMismatch,+ );+ expect(themeImportErrorText(new ApiError(400, "registry_unusable", "…"))).toBe(+ S.settings.themeRegistryUnusable,+ );+ expect(themeImportErrorText(new ApiError(400, "registry_unavailable", "…"))).toBe(+ S.settings.themeRegistryFailed,+ );+ // The index reader's own reasons survive, as `theme_invalid`'s do.+ expect(+ themeImportErrorText(new ApiError(400, "registry_invalid", "themes[0].file: 「../x」不是")),+ ).toBe(S.settings.themeRegistryInvalid("themes[0].file: 「../x」不是"));+ });+it("不认识的码走共用的那张表,不是自己编一句", () => {const empty = new ApiError(400, "bad_request", "The file is empty.");expect(themeImportErrorText(empty)).toBe(apiErrorText(empty));