Skip to content

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

feat(web,server): 外观页里能导入主题,选个文件或填个地址

lmliheng80ccb1bd5398
diff --git a/changelog/unreleased/2026-10-25-import-themes.md b/changelog/unreleased/2026-10-25-import-themes.md
new file mode 100644
index 00000000..fa6c5914
--- /dev/null
+++ b/changelog/unreleased/2026-10-25-import-themes.md
@@ -0,0 +1,54 @@
+# Import a theme from the app: pick a file, or paste an address
+
+- **Date:** 2026-10-25
+- **Type:** feat
+- **Scope:** `core`, `server`, `web`
+- **Breaking:** no
+
+[中文](2026-10-25-import-themes.zh.md)
+
+A theme could always be installed by dropping it in the data root's `themes/` directory. Now the
+line in **Settings › Appearance** that names that directory gives an admin one more thing — "Import
+a theme…": pick a `.json` file, or paste an address for the server to fetch, the same two ways the
+plugin library has always imported plugins. Importing is not a second kind of install: the same
+file lands in the same directory and is read by the same reader.
+
+The file is written under the name the theme gives itself (`Warm Paper` → `warm-paper.json`), so
+importing the same theme again is an update rather than a second copy: it asks first, and confirming
+replaces the file that provides it — whatever that file happens to be called. A file that does not
+read writes nothing at all, and the reader's own words come back with it: which field, which value it
+cannot take, for whoever has to fix it.
+
+## Details
+
+- **The server** (`server/src/http/routes/themes.ts`) gets two routes: `POST /api/themes/upload`
+ (the file as base64 in the body — the shape the plugin, skill and hook imports all take) and
+ `POST /api/themes/download` (fetched by the server; a local or private address is refused). Both
+ are admin-only and answer 403 `admin_required` otherwise; 409 `theme_exists` means a file already
+ provides that theme's id, and resending with `overwrite: true` replaces it.
+- **"Fetched by the server" is one bounded request**: a 30s deadline, a cap enforced while streaming
+ (a `content-length` is a claim, and a chunked body makes none), and a re-check of the host that
+ actually answered, because a redirect may have left the network the URL declared. The host guard
+ is the plugin download's own (`isBlockedHost` in `services/plugin-download.ts`) — imported, not
+ copied.
+- **The cap is the format's own**: `MAX_THEME_FILE_BYTES` (256KB, in core). The directory reader,
+ the decoded upload and the downloaded body all read that one number, because accepting a byte more
+ would install a theme the reader then refuses to paint.
+- **The appearance page** (`features/settings/appearance-section.tsx`, `theme-import-dialog.tsx`):
+ the directory line gains one entry for an admin, and it opens one dialog — a two-way switch (a
+ local file / an address), the field that switch implies, and a single confirm. Nobody else gets a
+ word there: the server refuses them anyway, so the entry is drawn only for who can use it.
+- **Tests**: `server/test/themes.test.ts` grows by 9 (the file on disk and visible to both reads at
+ once, a 409 then an overwrite that leaves one file, replacing the file that claimed the id under
+ another name, a bad file refused with its reasons and nothing written, the 413, a member refused
+ before any request is made, an address import, a download that is not a theme / 404 / unreachable
+ / not http, a private address and both ways past the cap), and `web/test/theme-import.test.ts`
+ holds the failure copy and the two copies of the cap equal.
+
+## Compatibility
+
+- No interface breaks: the two read routes are untouched and `/api/themes` answers exactly as it did.
+- An admin who would rather not use the dialog changes nothing: a hand-placed file is still the whole
+ install, and importing is that step moved into the interface.
+- A theme is still values for token names only — it cannot add components, layout or rules.
+- No dependency change, no version bump.
diff --git a/changelog/unreleased/2026-10-25-import-themes.zh.md b/changelog/unreleased/2026-10-25-import-themes.zh.md
new file mode 100644
index 00000000..54e576da
--- /dev/null
+++ b/changelog/unreleased/2026-10-25-import-themes.zh.md
@@ -0,0 +1,42 @@
+# 主题也能在界面上导入:选个文件,或者填个地址
+
+- **Date:** 2026-10-25
+- **Type:** feat
+- **Scope:** `core`, `server`, `web`
+- **Breaking:** no
+
+[English](2026-10-25-import-themes.md)
+
+主题一直可以放进数据根的 `themes/` 目录里用。现在**设置 › 外观**那块写着目录的地方,管理员多了一个
+「导入主题…」:选一个 `.json` 文件上传,或者填一个地址让服务端取回来——和插件那两条导入一个道理。导入与
+手放文件没有区别:写的还是同一个目录、同一个文件,校验用的还是同一个读法。
+
+导入的文件按主题自己的名字落盘(`暖纸` → `warm-paper.json`),所以同一个主题再导一次是更新,而不是多出
+一份:这时会先问一句覆盖,确认后替换它原来那个文件(哪怕那个文件叫别的名字)。读不出来的文件一个字节都不
+写,而且把读法的原话带回来——哪个字段、哪个值不能要,写文件的人照着改就行。
+
+## 细节
+
+- **服务端**(`server/src/http/routes/themes.ts`)两条新路由:`POST /api/themes/upload`(文件以 base64 放在
+ 请求体里,和插件、技能、钩子的导入同一个形状)与 `POST /api/themes/download`(由服务端去取,本机与内网
+ 地址直接拒掉)。两条都要管理员,否则 403 `admin_required`;409 `theme_exists` 表示这个主题名已经有文件
+ 占了,带上 `overwrite: true` 重发即替换。
+- **「服务端去取」是一次有界请求**:30 秒时限、边读边卡上限(`content-length` 只是声明,chunked 连声明都
+ 没有)、并对真正回答的那个地址再查一次主机——重定向可能把请求带到别处。主机守卫直接复用插件那条
+ (`services/plugin-download.ts` 的 `isBlockedHost`),没有第二份。
+- **上限是格式自己的**:`MAX_THEME_FILE_BYTES`(256 KB,在 core)。读目录的那道检查、上传解码后的字节、
+ 取回来的字节,三处是同一个数——收下一个读法会拒的文件,等于装了一套永远不上色的主题。
+- **外观页**(`features/settings/appearance-section.tsx` 与 `theme-import-dialog.tsx`):目录那一行里,
+ 管理员多一个入口,打开一个框:上面两选一(本地文件 / 地址),下面是对应的字段,确认按钮只有一个。非管理员
+ 那一行一个字都不多——服务端本来就会拒,入口只画给能用的人。
+- **测试**:`server/test/themes.test.ts` 增补 9 条(落盘与两处读取立刻可见、同名先 409 再覆盖以后只有一份、
+ 别的文件占了这个主题名时替换的是那个文件、坏文件带原因且不落盘、超限 413、成员 403 且不发出请求、地址
+ 导入、取回来不是主题/404/连不上/非 http 地址、内网地址与两种超限方式),`web/test/theme-import.test.ts`
+ 5 条(错误文案,以及界面上的上限与 core 是同一个数)。
+
+## 兼容性
+
+- 没有接口破坏:原来两条读路由一个字没改,`/api/themes` 的响应形状也没变。
+- 不想用界面的管理员什么都不用改:手放文件进目录照旧是完整的用法,导入只是把这一步搬到界面上。
+- 仍然是「只收令牌取值」:外置主题改不了组件、布局与规则,只能给令牌名换值。
+- 没有依赖变化,没有版本号变化。
diff --git a/docs/FORK-PROGRESS.md b/docs/FORK-PROGRESS.md
index a92f955b..54de7b14 100644
--- a/docs/FORK-PROGRESS.md
+++ b/docs/FORK-PROGRESS.md
@@ -15731,3 +15731,87 @@ toast」扫描线在 `features/company/` 上的第一处:组织日历(`featu
`1f8167e2` 删除组织 · `3859ef58` 删除手册文档 · `21b9fe8e` 组织图「离任」· `40bf7203` 加入频道两个入口)
与 `c5f6d9e3` 插件库收录图表技能 `use-lieflat-charts`。
- 汇报:校园邮箱这一轮又只试一次(`/dev/tcp/202.197.64.20/993` 超时),改走飞书。
+## 第一百二十九轮:主题也能在界面上导入(本地文件 + 地址),只限管理员(2026-10-25,用户点单)
+
+### 为什么是这一条
+
+上一轮把外置主题做成了「把 .json 放进数据根的 `themes/` 目录」。用户看到现网那块提示后问:
+「支持主题导入吗 和插件远程导入,本地导入一个道理」——即照着插件库那两条路(本地上传 zip、
+从地址或 npm 取回)给主题也加上。我摆了两个要拍板的选项,用户回「都加,只限制管理员」。
+
+落点几乎不用想:主题只是一份 JSON,插件的两条导入是现成先例(`plugins.ts` 的
+`POST /api/plugins/upload` 与 `/download`,都在路由里 `requireAdmin`,都写进安装级目录、不用重启)。
+所以服务端加两条同样形状的路由,读法仍然是 core 那一个(`readExternalTheme`)——两条来源、一套校验。
+
+### 改了什么(8 处源码 + 2 个新测试 + 文档)
+
+- `packages/core/src/internal/external-theme.ts`:把「一个主题文件最多多少字节」从服务端的局部常量提到
+ 格式常量里(`MAX_THEME_FILE_BYTES`,256 KB),经 `core/src/index.ts` 导出。三处必须同一个数:读目录
+ 的那道检查、上传解码后的字节、取回来的字节——收下一个读法会拒的文件,等于装一套永远不上色的主题。
+- `packages/server/src/services/theme-download.ts`(新):`fetchThemeFile(url)` 一次有界取回。主机守卫
+ **直接 import 插件那条**(`plugin-download.ts` 的 `isBlockedHost`,没有第二份实现),自己只管时限
+ (30 s)、边读边卡上限、以及对真正回答的地址再查一次主机(重定向可能把请求带到别处)。错误码沿用插件
+ 那套(`blocked_url` / `download_failed` / `unsupported_url`)加自己的 413 `theme_too_large`。
+- `packages/server/src/http/routes/themes.ts`:`POST /api/themes/upload`(文件 base64 放在请求体里)与
+ `POST /api/themes/download`(服务端去取),两条都 `requireAdmin`(403 `admin_required`)。共同落盘函数
+ `installTheme(root, text, overwrite)`:先 `readExternalTheme`(原因全带回来,400 `theme_invalid`),文件名
+ 取主题自己的 id(`<id>.json`,所以再导一次是更新而不是多一份),id 已被别的文件占用时 409 `theme_exists`,
+ `overwrite` 就删掉那个文件再写(不这么做会留下两个抢同一个 id 的文件,读法只认前一个,导入看着成功却
+ 不上色)。文件原样写下去,不重新序列化;UTF-8 用 `fatal` 解码(否则非法字节会被换成替换字符,JSON 还会
+ 照收),顺手去掉 BOM。
+- `packages/server/src/api/types.ts`:`ThemeUploadRequest` / `ThemeDownloadRequest` / `ThemeImportResponse`。
+- `packages/web/src/features/settings/theme-import-dialog.tsx`(新):**一个框、两种来源**(本地文件 / 地址
+ 的两选一),因为主题本来就只有一份 JSON、名字由文件自己说;插件那两个框是因为它要解包、要取名。一次
+ 409 打开覆盖确认,确认后用同一份请求重发(不会让用户再选一次文件),其余失败弹 toast。
+- `packages/web/src/features/settings/theme-import.ts`(新):失败文案的映射(`theme_invalid` 把读法的原话
+ 带上,其余码各有说法,不认识的走共用错误表),以及浏览器这边的 256 KB 上限判断。
+- `packages/web/src/features/settings/appearance-section.tsx`:目录那行里,管理员多一个「导入主题…」(服务端
+ 本来就会拒,入口只画给能用的人);`api/endpoints.ts` 两个封装;`lib/strings{,-en}.ts` 各一套文案(原来的
+ 提示补一句「管理员也可以直接导入」)。
+- `packages/web/src/state/external-themes.ts`:**「再来一次」时把页面链接的那张样式表也重挂一遍**。这是真
+ 浏览器探针抓出来的坑:一张样式表每个文档只取一次,而 `/api/themes.css` 是页面加载时取的——导入成功后
+ 主题出现在选择器里、选上却什么都不画,要刷新才生效(看着像坏主题)。重挂 link(`?again=<时间戳>`,服务端
+ 本来就按请求重读目录)就当场生效;只有 force 的那次才做这件事。
+- `packages/ui-gallery/src/app/mock/routes.ts`:两条导入 POST 走 `readOnly`(与插件一致,画廊没有服务端)。
+- 测试:`packages/server/test/themes.test.ts` 增补 9 条(落盘+两处读取立刻可见、同名 409 → 覆盖后只剩一份、
+ 别的文件占了 id 时替换的是那个文件、坏文件带原因且不落盘、超限 413、成员 403 且不发出请求、地址导入、
+ 取回来不是主题/404/连不上/非 http 地址、内网地址与两种超限方式),`packages/web/test/theme-import.test.ts`
+ (新,5 条:错误文案、上限两端同一个数),`packages/web/test/external-themes.test.ts` 增 1 条(重挂样式表
+ 只在「再来一次」时发生)。
+- 文档:changelog 一对 `changelog/unreleased/2026-10-25-import-themes{,.zh}.md`、`examples/themes` 两份 README
+ 各补一句、本节。
+
+### 验证(都不是推测)
+
+- 逐包测试全绿:core **1420 通过 / 6 跳过**、ui **1053**、server **2970 通过 / 4 跳过**(其中
+ `themes.test.ts` **15 / 15** = 旧 6 + 新 9)、web **3249 通过 / 2 跳过**(新增 `theme-import.test.ts`
+ **5 / 5**,`external-themes.test.ts` 增到 **9 / 9**)、cli **561**、desktop **304**、ui-gallery **140**、
+ amsp **68**、docs **62**,`pnpm -r test` 退出码 0。
+- **真服务 + 真浏览器**(一次性数据根 `/tmp/tmp.4tBH7RBjG1`,服务 8956、假模型 8933,`packages/{server,web}/dist`
+ 都是本轮新构建的):两条 playwright 用例都过。管理员那条走完:目录那行点「导入主题…」→ 选示例文件 →
+ 「上传并导入」→ toast「已导入主题 暖纸」、主题行里出现「暖纸」→ 选上后浏览器算出来的 `--ui-canvas` =
+ `#f6f1e7`(**不是**刷新后才生效:这正是重挂样式表那条改动)→ 再导同一份文件得到「覆盖已导入的主题」确认框,
+ 确认后仍然是那一份文件 → 换成「地址」填公网 raw 地址(GitHub 上 `examples/themes/warm-paper.json`),
+ 服务端取回来后同样是 409 → 覆盖 → `GET /api/themes` 只列 `warm-paper.json`、`rejected` 为空 →
+ 填 `http://localhost:8956/api/themes` 时弹「这个地址指向本机或内网,服务端不会去取。」。普通成员那条:
+ 目录那行照旧有、主题照旧可选,「导入主题…」按钮一个都没有。
+- 服务端手工核过磁盘:跑完后 `$DATA/themes/warm-paper.json` 是 2938 字节,与仓库里那份示例逐字节同源。
+- 截图在 scratchpad `r116/probe/{1-imported-file,2-overwrite,3-blocked-url,4-member}.png`;探针脚本
+ `r116/probe/theme-import-probe.spec.mjs`(跑完已从 `packages/web/e2e/` 删掉,不提交)。
+- 端口只用 8956(探针自己)与 8933(假模型);3003 / 4000 / 7364 / 7372 一个没碰;数据只落在 `mktemp` 的
+ 一次性根与 scratchpad 的 `r116/` 下。
+- 门禁:`npx oxlint` 0 警告 0 错误(2286 文件)、`npx prettier --check .` 全过、`pnpm typecheck`(含
+ `gen:ifaces`,各包 Done)、`pnpm -r test` 与 `pnpm -r build`(全部 Done,退出码 0)都全绿。
+
+### 没做 / 还差什么
+
+- 主题仍然创建不了文件系统之外的东西:没有删除/停用某个导入主题的按钮(要删还是去目录里删),也没有
+ 「从插件里带一份主题」那条路——上一轮就留着,用户没点。
+- 一个文件的 id 撞上自带三套主题(`github` / `modern` / `geek`)时,服务端不会拒(它不带自带的 id 表,
+ 这是上一轮定的),那种文件基本是哑的:它只在自己的 `data-theme` 下上色,而自带主题的规则不分层、优先。
+ 页面把导入的排在内置之后,这时选择器里会出现两个同名项。留给下一轮要不要在界面这一侧拦下。
+- 现网(`/root/.adelie`)还是 0.5.6 那一版构架,本轮改动要等下一版才看得见。
+
+### 汇报
+
+- 校园邮箱照旧只试一次(超时),改走飞书,正文留底在 scratchpad 的 `r116/report.md`。
diff --git a/examples/themes/README.md b/examples/themes/README.md
index 6ea3ab04..32734568 100644
--- a/examples/themes/README.md
+++ b/examples/themes/README.md
@@ -14,6 +14,10 @@ page prints the exact directory it read, so there is nothing to guess. A default
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.
+An admin can skip the walk: in **Settings › Appearance**, the line naming the directory carries
+"Import a theme…" — pick this file, or paste a URL that serves it, and either way what lands is
+exactly what the `cp` above puts there.
+
## What a theme may say
A theme is **values for the UI's token names**, and nothing else — no components, no layout, no code
diff --git a/examples/themes/README.zh.md b/examples/themes/README.zh.md
index 367ae1a0..c70f31f1 100644
--- a/examples/themes/README.zh.md
+++ b/examples/themes/README.zh.md
@@ -12,6 +12,9 @@ cp examples/themes/warm-paper.json "<数据根>/themes/"
的数据根是 `~/.penguin/data`。不用重启,也没有缓存:服务端每次请求都会读一遍目录,所以改过、加过、
删过的文件,下一次刷新页面就是结果。
+管理员也可以省掉这一趟:**设置 › 外观**的目录那行里点「导入主题…」,选这个文件上传,或者填一个
+`warm-paper.json` 的地址让服务端取回来——两条路落成的东西和上面 `cp` 完全一样。
+
## 主题能写什么
主题只是**一组 UI 令牌名的取值**,别的都不是——没有组件、没有布局、没有会跑起来的代码。正因为
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 3e58b612..1bbee10a 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -85,6 +85,7 @@ export type { AtomicWriteOptions } from "./internal/atomic-write.js";
// data. Both ends need it and neither may import the other, so it is here.
export {
EXTERNAL_THEME_SCHEMA_VERSION,
+ MAX_THEME_FILE_BYTES,
THEME_ID_PATTERN,
isThemeId,
readExternalTheme,
diff --git a/packages/core/src/internal/external-theme.ts b/packages/core/src/internal/external-theme.ts
index 23fb7b79..463a510b 100644
--- a/packages/core/src/internal/external-theme.ts
+++ b/packages/core/src/internal/external-theme.ts
@@ -65,6 +65,15 @@ const FETCHES = /url\s*\(|image-set\s*\(|expression\s*\(/i;
const MAX_TOKENS = 400;
const MAX_ACCENTS = 12;
+/**
+ * How big a theme file may be. It lives here, with the format's other caps, because three places
+ * have to agree on one number: the reader that refuses an oversized file it finds in the directory,
+ * and the two import routes (an upload's bytes, a download's response) that must not write a file
+ * the reader would then refuse. The format is values — a few hundred token names and their colours
+ * — so the room is generous for what it holds and still nowhere near a megabyte.
+ */
+export const MAX_THEME_FILE_BYTES = 256 * 1024;
+
/** One accent preset an imported theme lists, shaped like the shipped themes' own. */
export interface ExternalThemeAccent {
readonly id: string;
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index a420d2e5..a06d64cd 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -2220,6 +2220,40 @@ export interface ImportedThemesResponse {
rejected: Array<{ file: string; errors: string[] }>;
}
+/** What an import (upload or download) wrote: the file it landed in, and the theme it holds. */
+export interface ThemeImportResponse {
+ /** The file under the themes directory — the theme's own id plus `.json`. */
+ file: string;
+ theme: ExternalTheme;
+}
+
+/**
+ * POST /api/themes/upload: install a theme from a file the operator picked. The file is the theme
+ * JSON itself, base64 in the body (the same shape the plugin, skill and hook imports take, so the
+ * request stays JSON and needs no multipart handling). Admin-only.
+ *
+ * Errors, shared with the download route below: 403 `admin_required`, 413 `theme_too_large` (past
+ * the format's own cap of 256KB, checked on the decoded bytes), 400 `theme_invalid` (not UTF-8,
+ * not JSON, or the reader's reasons), 409 `theme_exists` (another file already provides this
+ * theme's id — `overwrite` replaces that file) and 400 `bad_request` for a malformed request.
+ */
+export interface ThemeUploadRequest {
+ dataBase64: string;
+ overwrite?: boolean;
+}
+
+/**
+ * POST /api/themes/download: the same import, fetched server-side from an http(s) address — the
+ * server is what can reach it. Answers the same errors as the upload route above, plus 400
+ * `unsupported_url` (not an absolute http(s) URL), 400 `blocked_url` (a loopback, private or
+ * link-local host), 400 `download_failed` (the request or its status). Admin-only.
+ */
+export interface ThemeDownloadRequest {
+ /** The address of a theme JSON file. */
+ url: string;
+ 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.ts
index e3b9f964..cab2afef 100644
--- a/packages/server/src/http/routes/themes.ts
+++ b/packages/server/src/http/routes/themes.ts
@@ -1,8 +1,22 @@
/**
* 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)
+ * GET /api/themes the list, for the appearance page (auth: user)
+ * 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)
+ *
+ * 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
+ * reader, and it lands under the name the theme gives itself (`<id>.json`) so importing it again is
+ * an update rather than a second copy — which is what makes "overwrite" a question worth asking.
+ * Importing over an id another file already claims is refused (409 `theme_exists`) unless the
+ * request says `overwrite`, in which case that file is the one replaced, whatever it is called: the
+ * reader would otherwise have to drop one of the two claimants and the operator would be left
+ * guessing which. Both routes are the admin's, for the reason the plugin directory's imports are —
+ * every browser that signs in on this machine is painted by these files, and the server reads them
+ * from its own data root. Neither route is needed to use the directory, though: a hand-placed file
+ * is still read exactly the same way.
*
* 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
@@ -22,22 +36,23 @@
* 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 { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Hono } from "hono";
-import { externalThemesCss, readExternalTheme } from "@adelie/core";
+import type { Context } from "hono";
+import { externalThemesCss, MAX_THEME_FILE_BYTES, 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 type { ImportedThemesResponse, ThemeImportResponse } 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";
/** 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;
@@ -74,8 +89,8 @@ export async function readImportedThemes(root: string): Promise<ReadThemes> {
rejected.push({ file, errors: [`读不了这个文件:${(error as Error).message}`] });
continue;
}
- if (text.length > MAX_FILE_BYTES) {
- rejected.push({ file, errors: [`文件超过 ${MAX_FILE_BYTES} 字节`] });
+ if (text.length > MAX_THEME_FILE_BYTES) {
+ rejected.push({ file, errors: [`文件超过 ${MAX_THEME_FILE_BYTES} 字节`] });
continue;
}
let parsed: unknown;
@@ -105,6 +120,97 @@ export async function readImportedThemes(root: string): Promise<ReadThemes> {
return { dir, themes, rejected };
}
+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 guard on the two import routes. They write into the installation's data root, and every
+ * browser that signs in on this machine is painted by what is in there, so the capability is the
+ * admin's — the way installing to a machine is — and not a Project owner's. The reads stay open:
+ * the appearance page's list is every user's screen.
+ */
+function requireAdmin(c: Context<AppEnv>): void {
+ if (!c.var.user.isAdmin) {
+ throw new HttpError(403, "admin_required", "Only an admin can import themes.");
+ }
+}
+
+/**
+ * The bytes of a theme file as text. UTF-8 is the only encoding the reader has, and a body that is
+ * not that is a file nobody meant to write rather than one to be quietly mangled into replacement
+ * characters (which a lenient decode would do, and JSON would then accept). A leading BOM is
+ * dropped because an editor that writes one is common and the JSON parser would refuse it.
+ */
+function readThemeText(bytes: Uint8Array): string {
+ try {
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes).replace(/^\uFEFF/, "");
+ } catch {
+ throw new HttpError(400, "theme_invalid", "The file is not UTF-8 text.");
+ }
+}
+
+/** Reads a theme file's text, or refuses it with every reason the reader collected. */
+export function readThemeTextAsTheme(text: string): ExternalTheme {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(text);
+ } catch (error) {
+ throw new HttpError(400, "theme_invalid", `不是合法的 JSON:${(error as Error).message}`);
+ }
+ const read = readExternalTheme(parsed);
+ if (!read.ok) throw new HttpError(400, "theme_invalid", read.errors.join(";"));
+ return read.theme;
+}
+
+/**
+ * Writes one theme file into the directory. The file is named after the theme's own id, which is
+ * what makes a second import of the same theme an update: the id is the identity both the reader
+ * and the appearance page's picker use, so the file name follows it rather than the operator's
+ * file system.
+ *
+ * An id another file already claims is a 409 unless the request says `overwrite`, and then it is
+ * THAT file that is replaced — deleting it first when it is called something else. The alternative
+ * — writing `<id>.json` beside it — would leave two files claiming one id, of which the reader
+ * serves only the earlier one, so the import would look successful and paint nothing.
+ *
+ * The text is written exactly as it arrived: this is the operator's file, and the directory is the
+ * source of truth whether the file was dropped there or imported.
+ */
+export async function installTheme(
+ root: string,
+ text: string,
+ overwrite: boolean,
+): Promise<ReadTheme> {
+ const theme = readThemeTextAsTheme(text);
+ const file = `${theme.id}.json`;
+ const claimed = (await readImportedThemes(root)).themes.find(
+ (entry) => entry.theme.id === theme.id,
+ )?.file;
+ if (claimed !== undefined && !overwrite) {
+ throw new HttpError(
+ 409,
+ "theme_exists",
+ `A theme named ${theme.id} is already imported as ${claimed}.`,
+ );
+ }
+ const dir = join(root, THEMES_DIR);
+ await mkdir(dir, { recursive: true });
+ if (claimed !== undefined && claimed !== file) await rm(join(dir, claimed));
+ await writeFile(join(dir, file), text, "utf8");
+ return { file, theme };
+}
+
export function themesRoutes(deps: { root: string }): Hono<AppEnv> {
const routes = new Hono<AppEnv>();
routes.get("/", async (c) => {
@@ -115,20 +221,44 @@ export function themesRoutes(deps: { root: string }): Hono<AppEnv> {
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",
- });
+ // Install one theme from a file the operator picked (admin). The body carries the file base64 —
+ // the shape the plugin, skill and hook imports all take — so the request stays JSON throughout
+ // and needs no multipart handling. The cap is the format's own, checked on the DECODED bytes:
+ // the encoded length is a different number, and saying "too large" about the wrong one would be
+ // a refusal the operator cannot reproduce anywhere else.
+ routes.post("/upload", async (c) => {
+ requireAdmin(c);
+ const body = await readJson(c);
+ const dataBase64 = requireString(body, "dataBase64", { minLen: 1, label: "dataBase64" });
+ const bytes = Buffer.from(dataBase64, "base64");
+ if (bytes.byteLength === 0) throw badRequest("The file is empty.");
+ if (bytes.byteLength > MAX_THEME_FILE_BYTES) throw themeTooLarge();
+ const { file, theme } = await installTheme(
+ deps.root,
+ readThemeText(bytes),
+ optionalBoolean(body, "overwrite") ?? false,
+ );
+ return c.json({ file, theme } satisfies ThemeImportResponse, 201);
});
+
+ // Install one theme from an address (admin): the server fetches it, because the server is what
+ // can reach it, and the bytes are then read by the same reader the upload path uses — one
+ // judging of what a theme file is, whichever way it arrived.
+ routes.post("/download", async (c) => {
+ requireAdmin(c);
+ const body = await readJson(c);
+ const url = requireString(body, "url", { minLen: 1, maxLen: 2048 });
+ const bytes = await fetchThemeFile(url);
+ if (bytes.byteLength === 0) throw badRequest("The download is empty.");
+ const { file, theme } = await installTheme(
+ deps.root,
+ readThemeText(bytes),
+ 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.ts
new file mode 100644
index 00000000..501f4abf
--- /dev/null
+++ b/packages/server/src/services/theme-download.ts
@@ -0,0 +1,127 @@
+/**
+ * Remote theme import: one address in, one theme file's bytes out.
+ *
+ * A theme is a single JSON file, so this is the whole of "download" where a plugin needs an
+ * archive reader (services/plugin-download.ts): fetch it, bound it, and hand it over. What the two
+ * do share is the safety posture rather than the code, and the load-bearing half of it is IMPORTED
+ * rather than copied — `isBlockedHost`, the literal-host guard that refuses the addresses which can
+ * only be the server's own network, so a typo or a redirect cannot aim the server at itself.
+ *
+ * Bounded three ways, for the reason the plugin download states: a deadline, a size cap enforced
+ * while streaming (a `content-length` is a claim, and a chunked response makes no claim at all), and
+ * a re-check of the host that actually answered. The cap is the format's own
+ * ({@link MAX_THEME_FILE_BYTES}), because a file this route writes has to be a file the reader will
+ * read afterwards: accepting a byte more would install a theme that never paints.
+ *
+ * WHAT THIS DOES NOT DO is read the bytes. What a theme is, is core's question and the route asks
+ * it, so an upload and a download are judged by one reading rather than two; this module's job ends
+ * at "these are the bytes that host served". Every failure is an HttpError the route returns as-is,
+ * with the codes the plugin import already answers (`blocked_url`, `download_failed`,
+ * `unsupported_url`) plus this route's own 413 `theme_too_large`.
+ */
+import { MAX_THEME_FILE_BYTES } from "@adelie/core";
+import { HttpError } from "../http/errors.js";
+import { isBlockedHost } from "./plugin-download.js";
+
+/**
+ * How long one download may take. Shorter than a plugin archive's 60s on purpose: this pulls a
+ * small JSON file, not a repository checkout, and a bound is what keeps an unresponsive host from
+ * pinning a request handler.
+ */
+const DOWNLOAD_TIMEOUT_MS = 30_000;
+
+/** Refuses a host that can only be the server's own network (see the module header). */
+function assertHostAllowed(url: URL): void {
+ if (isBlockedHost(url.hostname)) {
+ throw new HttpError(
+ 400,
+ "blocked_url",
+ `Refusing to fetch from a local or private host: ${url.hostname}`,
+ );
+ }
+}
+
+/** A file past the format's cap, uploaded or downloaded alike — one answer, one place the number is read. */
+export function themeTooLarge(): HttpError {
+ return new HttpError(
+ 413,
+ "theme_too_large",
+ `The theme file exceeds the ${Math.floor(MAX_THEME_FILE_BYTES / 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.
+ */
+export async function fetchThemeFile(
+ rawUrl: string,
+ options: { fetchImpl?: typeof fetch; timeoutMs?: number } = {},
+): Promise<Buffer> {
+ let url: URL;
+ try {
+ url = new URL(rawUrl.trim());
+ } catch {
+ throw new HttpError(400, "unsupported_url", "url must be an absolute http(s) URL.");
+ }
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
+ throw new HttpError(400, "unsupported_url", "url must be an http(s) URL.");
+ }
+ assertHostAllowed(url);
+
+ const doFetch = options.fetchImpl ?? fetch;
+ let res: Response;
+ try {
+ res = await doFetch(url.toString(), {
+ method: "GET",
+ redirect: "follow",
+ // A theme is JSON, but a host may serve it as text/plain (a raw file link, a gist) — the
+ // bytes decide, so the accept header asks without insisting.
+ headers: { accept: "application/json, text/plain, */*" },
+ signal: AbortSignal.timeout(options.timeoutMs ?? DOWNLOAD_TIMEOUT_MS),
+ });
+ } catch (err) {
+ throw new HttpError(400, "download_failed", `Could not download: ${message(err)}`);
+ }
+ if (res.url) {
+ try {
+ assertHostAllowed(new URL(res.url));
+ } catch (err) {
+ if (err instanceof HttpError) throw err;
+ throw new HttpError(400, "download_failed", "Could not read the URL that answered.");
+ }
+ }
+ if (!res.ok) {
+ await res.body?.cancel().catch(() => undefined);
+ 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) {
+ await res.body?.cancel().catch(() => undefined);
+ throw themeTooLarge();
+ }
+ return readBounded(res);
+}
+
+/** Reads the body, refusing the moment it passes the cap rather than after buffering it all. */
+async function readBounded(res: Response): Promise<Buffer> {
+ const reader = res.body?.getReader();
+ if (!reader) return Buffer.from(await res.arrayBuffer());
+ const chunks: Uint8Array[] = [];
+ let total = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > MAX_THEME_FILE_BYTES) {
+ await reader.cancel().catch(() => undefined);
+ throw themeTooLarge();
+ }
+ chunks.push(value);
+ }
+ return Buffer.concat(chunks);
+}
+
+function message(err: unknown): string {
+ return err instanceof Error ? err.message : String(err);
+}
diff --git a/packages/server/test/themes.test.ts b/packages/server/test/themes.test.ts
index da691122..71b295d4 100644
--- a/packages/server/test/themes.test.ts
+++ b/packages/server/test/themes.test.ts
@@ -1,6 +1,7 @@
/**
- * Imported themes over HTTP: the appearance page's list (`GET /api/themes`) and the stylesheet the
- * app links from `<head>` (`GET /api/themes.css`).
+ * Imported themes over HTTP: the appearance page's list (`GET /api/themes`), the stylesheet the
+ * app links from `<head>` (`GET /api/themes.css`), and the two imports — a picked file
+ * (`POST /api/themes/upload`) and an address (`POST /api/themes/download`).
*
* - 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
@@ -12,12 +13,18 @@
* 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.
+ * - An import writes the file the directory would have held anyway, under the theme's own id, and
+ * it is judged by the reader that would have read it there (core's readExternalTheme): these
+ * tests are mostly about that equivalence — a bad file is refused with its reasons and nothing is
+ * written, an id another file claims is a 409 rather than a second claimant, and `overwrite`
+ * replaces THAT file. Both routes are the admin's; the list stays every user's.
*/
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 { afterEach, describe, expect, it, vi } from "vitest";
+import { MAX_THEME_FILE_BYTES } from "@adelie/core";
+import type { ImportedThemesResponse, ThemeImportResponse } from "../src/api/types.js";
+import { apiClient, createTestApp, loginAdmin, provisionUser } from "./helpers.js";
import type { TestApp } from "./helpers.js";
/** A theme file that reads: everything the format allows. */
@@ -56,6 +63,7 @@ async function appWithThemes(files: Record<string, string | object> = {}): Promi
}
afterEach(async () => {
+ vi.unstubAllGlobals();
const open = live;
live = [];
await Promise.all(open.map((t) => t.cleanup()));
@@ -65,6 +73,40 @@ async function listThemes(t: TestApp, cookie?: string): Promise<Response> {
return t.app.request("/api/themes", cookie ? { headers: { cookie } } : {});
}
+/** A refused request's error body, read once: the code is the contract, the message is the reason. */
+async function readError(res: Response): Promise<{ code: string; message: string }> {
+ const body = (await res.json()) as { error: { code: string; message: string } };
+ return body.error;
+}
+
+/** Who may import and who may not: the admin, a member, and the admin's cookie for the raw list reads. */
+async function importers(t: TestApp) {
+ const admin = await loginAdmin(t.app);
+ return {
+ cookie: admin.cookie,
+ admin: apiClient(t.app, admin.cookie),
+ member: apiClient(t.app, (await provisionUser(t.app, "theme_member")).cookie),
+ };
+}
+
+/** The upload body for one theme file, as the picked-file flow sends it. */
+function uploadBody(theme: object, extra: Record<string, unknown> = {}): Record<string, unknown> {
+ return { dataBase64: Buffer.from(JSON.stringify(theme), "utf8").toString("base64"), ...extra };
+}
+
+/** A response body that never declares its length, so the reader's own cap is what stops it. */
+function streamed(bytes: Buffer): Response {
+ return new Response(
+ new ReadableStream({
+ start(controller) {
+ controller.enqueue(bytes);
+ controller.close();
+ },
+ }),
+ { status: 200 },
+ );
+}
+
describe("imported themes", () => {
it("没有 themes 目录时:列表是空的,样式表只有一句注释", async () => {
const t = await appWithThemes();
@@ -184,3 +226,226 @@ describe("imported themes", () => {
expect(body.themes).toEqual([]);
});
});
+
+describe("导入主题", () => {
+ it("上传一份文件:按主题自己的名字落盘,列表和样式表立刻就有它", async () => {
+ const t = await appWithThemes();
+ const { cookie, admin } = await importers(t);
+
+ const res = await admin.post("/api/themes/upload", uploadBody(WARM_PAPER));
+ expect(res.status).toBe(201);
+ const imported = (await res.json()) as ThemeImportResponse;
+ expect(imported.file).toBe("warm-paper.json");
+ expect(imported.theme.nameZh).toBe("暖纸");
+ // The file lands exactly as it arrived — the operator's own file, not a re-serialized copy of
+ // it — so what the directory holds is what they picked.
+ expect(await fs.readFile(path.join(t.root, "themes", "warm-paper.json"), "utf8")).toBe(
+ JSON.stringify(WARM_PAPER),
+ );
+
+ // The two reads the page does see it without a restart, which is the whole point of writing
+ // into the directory the server re-reads per request.
+ const body = (await (await listThemes(t, cookie)).json()) as ImportedThemesResponse;
+ expect(body.themes.map((entry) => entry.file)).toEqual(["warm-paper.json"]);
+ expect(await (await t.app.request("/api/themes.css")).text()).toContain(
+ ':root[data-theme="warm-paper"]',
+ );
+ });
+
+ it("同一个主题名再导一次:先 409 问一句,覆盖之后只有一份文件", async () => {
+ const t = await appWithThemes();
+ const { cookie, admin } = await importers(t);
+ await admin.post("/api/themes/upload", uploadBody(WARM_PAPER));
+
+ const updated = { ...WARM_PAPER, nameZh: "暖纸二" };
+ const again = await admin.post("/api/themes/upload", uploadBody(updated));
+ expect(again.status).toBe(409);
+ expect((await readError(again)).code).toBe("theme_exists");
+ // Without the confirmation nothing was touched: the theme still reads as it did.
+ let body = (await (await listThemes(t, cookie)).json()) as ImportedThemesResponse;
+ expect(body.themes[0]!.theme.nameZh).toBe("暖纸");
+
+ const over = await admin.post("/api/themes/upload", uploadBody(updated, { overwrite: true }));
+ expect(over.status).toBe(201);
+ body = (await (await listThemes(t, cookie)).json()) as ImportedThemesResponse;
+ expect(body.themes.map((entry) => entry.file)).toEqual(["warm-paper.json"]);
+ expect(body.themes[0]!.theme.nameZh).toBe("暖纸二");
+ expect(body.rejected).toEqual([]);
+ expect(await fs.readdir(path.join(t.root, "themes"))).toEqual(["warm-paper.json"]);
+ });
+
+ it("别的文件占了同一个主题名:覆盖时替换的是那个文件,不再多写一份", async () => {
+ const t = await appWithThemes({ "b-claims-warm-paper.json": WARM_PAPER });
+ const { cookie, admin } = await importers(t);
+
+ const other = { ...WARM_PAPER, name: "Other" };
+ expect((await admin.post("/api/themes/upload", uploadBody(other))).status).toBe(409);
+
+ const ok = await admin.post("/api/themes/upload", uploadBody(other, { overwrite: true }));
+ expect(ok.status).toBe(201);
+ // One file, and it is the new one: writing `<id>.json` BESIDE the claimant would have left two
+ // files claiming one id, of which the reader serves the earlier — a successful import that
+ // paints the old theme.
+ const body = (await (await listThemes(t, cookie)).json()) as ImportedThemesResponse;
+ expect(body.themes.map((entry) => entry.file)).toEqual(["warm-paper.json"]);
+ expect(body.themes[0]!.theme.name).toBe("Other");
+ expect(body.rejected).toEqual([]);
+ expect(await fs.readdir(path.join(t.root, "themes"))).toEqual(["warm-paper.json"]);
+ });
+
+ it("读不出来的文件:连原因一起拒掉,一个字节都不落盘", async () => {
+ const t = await appWithThemes();
+ const { admin } = await importers(t);
+
+ const notJson = await admin.post("/api/themes/upload", {
+ dataBase64: Buffer.from("{ nope", "utf8").toString("base64"),
+ });
+ expect(notJson.status).toBe(400);
+ const notJsonError = await readError(notJson);
+ expect(notJsonError.code).toBe("theme_invalid");
+ expect(notJsonError.message).toContain("不是合法的 JSON");
+
+ // The reader's own reasons, all of them, rather than a generic refusal: the author of the file
+ // is who has to fix it.
+ const wrongShape = await admin.post("/api/themes/upload", {
+ dataBase64: Buffer.from(
+ JSON.stringify({ id: "Warm Paper", name: "x", light: {} }),
+ "utf8",
+ ).toString("base64"),
+ });
+ expect(wrongShape.status).toBe(400);
+ const message = (await readError(wrongShape)).message;
+ expect(message).toContain("id");
+ expect(message).toContain("light");
+
+ // Not one byte: the directory was never even created.
+ await expect(fs.readdir(path.join(t.root, "themes"))).rejects.toThrow();
+ });
+
+ it("超过格式上限:413,而且按解码后的字节算", async () => {
+ const t = await appWithThemes();
+ const { admin } = await importers(t);
+ const res = await admin.post("/api/themes/upload", {
+ dataBase64: Buffer.alloc(MAX_THEME_FILE_BYTES + 1, 0x20).toString("base64"),
+ });
+ expect(res.status).toBe(413);
+ expect((await readError(res)).code).toBe("theme_too_large");
+ });
+
+ it("两个导入只有管理员能做,读列表照旧谁都可以", async () => {
+ const t = await appWithThemes();
+ const { admin, member } = await importers(t);
+ const fetchSpy = vi.fn();
+ vi.stubGlobal("fetch", fetchSpy);
+
+ expect((await member.post("/api/themes/upload", uploadBody(WARM_PAPER))).status).toBe(403);
+ const refused = await member.post("/api/themes/upload", uploadBody(WARM_PAPER));
+ expect((await readError(refused)).code).toBe("admin_required");
+ const memberDownload = await member.post("/api/themes/download", {
+ url: "https://themes.example.test/warm.json",
+ });
+ expect(memberDownload.status).toBe(403);
+ // Refused before anything left the machine.
+ expect(fetchSpy).not.toHaveBeenCalled();
+
+ // The list is every user's screen, and the admin's own import still works.
+ expect((await member.get("/api/themes")).status).toBe(200);
+ expect((await admin.get("/api/themes")).status).toBe(200);
+ });
+
+ it("从地址导入:服务端取回来,落成和上传完全相同的一份", async () => {
+ const t = await appWithThemes();
+ const { cookie, admin } = await importers(t);
+ const calls: string[] = [];
+ vi.stubGlobal("fetch", async (input: Parameters<typeof fetch>[0]) => {
+ calls.push(String(input));
+ return new Response(JSON.stringify(WARM_PAPER), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+ });
+
+ const res = await admin.post("/api/themes/download", {
+ url: "https://themes.example.test/themes/warm.json",
+ });
+ expect(res.status).toBe(201);
+ expect(calls).toEqual(["https://themes.example.test/themes/warm.json"]);
+ // The file name comes from the theme, not from the URL's last segment: an address and a picked
+ // file install the same thing.
+ expect(((await res.json()) as ThemeImportResponse).file).toBe("warm-paper.json");
+ const body = (await (await listThemes(t, cookie)).json()) as ImportedThemesResponse;
+ expect(body.themes.map((entry) => entry.theme.id)).toEqual(["warm-paper"]);
+ });
+
+ it("从地址取回来的不是主题:按同一个读法给出原因", async () => {
+ const t = await appWithThemes();
+ const { admin } = await importers(t);
+
+ vi.stubGlobal("fetch", async () => new Response("<html>nope</html>", { status: 200 }));
+ const html = await admin.post("/api/themes/download", {
+ url: "https://themes.example.test/x.json",
+ });
+ expect(html.status).toBe(400);
+ expect((await readError(html)).code).toBe("theme_invalid");
+
+ vi.stubGlobal("fetch", async () => new Response("gone", { status: 404 }));
+ const missing = await admin.post("/api/themes/download", {
+ url: "https://themes.example.test/x.json",
+ });
+ expect(missing.status).toBe(400);
+ expect((await readError(missing)).code).toBe("download_failed");
+
+ vi.stubGlobal("fetch", async () => {
+ throw new Error("getaddrinfo ENOTFOUND");
+ });
+ const unreachable = await admin.post("/api/themes/download", {
+ url: "https://themes.example.test/x.json",
+ });
+ expect(unreachable.status).toBe(400);
+ expect((await readError(unreachable)).code).toBe("download_failed");
+
+ const notAUrl = await admin.post("/api/themes/download", { url: "file:///etc/passwd" });
+ expect(notAUrl.status).toBe(400);
+ expect((await readError(notAUrl)).code).toBe("unsupported_url");
+ });
+
+ it("地址是内网、或者回来的东西太大:都不落盘", async () => {
+ const t = await appWithThemes();
+ const { admin } = await importers(t);
+
+ const fetchSpy = vi.fn();
+ vi.stubGlobal("fetch", fetchSpy);
+ const blocked = await admin.post("/api/themes/download", {
+ url: "http://127.0.0.1:7364/api/themes",
+ });
+ expect(blocked.status).toBe(400);
+ expect((await readError(blocked)).code).toBe("blocked_url");
+ expect(fetchSpy).not.toHaveBeenCalled();
+
+ // A declared length past the cap: refused before reading the body.
+ vi.stubGlobal(
+ "fetch",
+ async () =>
+ new Response("x", {
+ status: 200,
+ headers: { "content-length": String(MAX_THEME_FILE_BYTES * 4) },
+ }),
+ );
+ const declared = await admin.post("/api/themes/download", {
+ url: "https://themes.example.test/big.json",
+ });
+ expect(declared.status).toBe(413);
+ expect((await readError(declared)).code).toBe("theme_too_large");
+
+ // A length that is not declared at all (a chunked body): the cap has to hold while streaming,
+ // because a `content-length` is only a claim.
+ vi.stubGlobal("fetch", async () => streamed(Buffer.alloc(MAX_THEME_FILE_BYTES * 2, 0x20)));
+ const streamedTooBig = await admin.post("/api/themes/download", {
+ url: "https://themes.example.test/big.json",
+ });
+ expect(streamedTooBig.status).toBe(413);
+ expect((await readError(streamedTooBig)).code).toBe("theme_too_large");
+
+ await expect(fs.readdir(path.join(t.root, "themes"))).rejects.toThrow();
+ });
+});
diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.ts
index 159566b5..9f9e1eb1 100644
--- a/packages/ui-gallery/src/app/mock/routes.ts
+++ b/packages/ui-gallery/src/app/mock/routes.ts
@@ -2804,3 +2804,10 @@ router.get("/api/themes", (): ImportedThemesResponse => ({
themes: [],
rejected: [],
}));
+
+// An import needs a server: the file would have to be validated and written, and a download
+// fetched. The gallery has none, the same answer the plugin imports give — and its demo identity
+// is not an admin, so the appearance page does not draw the entry at all.
+router
+ .post("/api/themes/upload", () => readOnly("import a theme from a file"))
+ .post("/api/themes/download", () => readOnly("import a theme from an address"));
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 8d9a6521..0f145d34 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -64,6 +64,9 @@ import type {
FilesWriteRequest,
GoalResponse,
ImportedThemesResponse,
+ ThemeDownloadRequest,
+ ThemeImportResponse,
+ ThemeUploadRequest,
InstallResponse,
MachinesResponse,
McpServerTestResponse,
@@ -2729,3 +2732,22 @@ export const clearBuiltinBrowserData = (storages: BuiltinBrowserStorage[]) =>
*/
export const getImportedThemes = () =>
apiFetch<ImportedThemesResponse>("/api/themes", { server: null });
+
+/**
+ * Import a theme from a file the operator picked: the theme JSON, base64 in the body — the same
+ * shape the plugin, skill and hook imports take. 201 returns the file it was written to (the
+ * theme's own id plus `.json`) and the theme as data. Admin-only, and 409 `theme_exists` when a
+ * file already provides that theme's id — the retry sends the same body with `overwrite: true`.
+ */
+export const importThemeArchive = (body: ThemeUploadRequest) =>
+ apiFetch<ThemeImportResponse>("/api/themes/upload", { method: "POST", body, server: null });
+
+/**
+ * The same import, fetched by the server from an http(s) address — the server is what can reach
+ * it. Read by the same reader the upload path uses, so a link to a theme JSON installs what
+ * picking that file installs. Answers the same 409 (and the same `overwrite` retry) plus 400
+ * `unsupported_url`, 400 `blocked_url` (a local or private host) and 400 `download_failed`.
+ * Admin-only.
+ */
+export const importThemeFromUrl = (body: ThemeDownloadRequest) =>
+ apiFetch<ThemeImportResponse>("/api/themes/download", { method: "POST", body, server: null });
diff --git a/packages/web/src/features/settings/appearance-section.tsx b/packages/web/src/features/settings/appearance-section.tsx
index 1442304b..f5e7ebab 100644
--- a/packages/web/src/features/settings/appearance-section.tsx
+++ b/packages/web/src/features/settings/appearance-section.tsx
@@ -16,7 +16,10 @@
* 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.
+ * itself: the browser cannot see the server's disk. An admin gets one more thing in that line — the
+ * import entry, for the 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.
*/
import { useEffect, useState, useSyncExternalStore } from "react";
import { PrefRow, Segmented, Select, SwatchPicker, THEME_IDS, ToggleRow } from "@adelie/ui";
@@ -42,6 +45,7 @@ import {
import type { ImportedThemesState } from "../../state/external-themes";
import { localizedText } from "../chat/skill-use";
import { FONT_FOLLOWS_THEME, effectiveAccent } from "../../state/theme-prefs";
+import { ThemeImportActions } from "./theme-import-dialog";
/**
* A font select's choices: the theme's own face first — it is the default, and the named faces
@@ -131,10 +135,13 @@ function ImportedThemesNote({
state,
activeId,
locale,
+ canImport,
}: {
state: ImportedThemesState;
activeId: string;
locale: "zh" | "en";
+ /** Whether the reader may import one: the entry is the server's own admin rule, drawn or not. */
+ canImport: boolean;
}) {
const [reading, setReading] = useState(false);
if (state.failed)
@@ -163,6 +170,9 @@ function ImportedThemesNote({
>
{S.settings.importedThemesReadAgain}
</button>
+ {/* Right beside the path it writes into, because it is the same install: the file that
+ would have been dropped there, put there. */}
+ {canImport && <ThemeImportActions onImported={() => refreshImportedThemes(true)} />}
</p>
<p>{S.settings.importedThemesHint}</p>
{orphan !== null && <p>{S.settings.importedThemesNoFile(orphan)}</p>}
@@ -225,7 +235,7 @@ export function AppearanceSection() {
// The fan's "hide launcher" entry writes the same preference, so this row follows it.
useSyncExternalStore(subscribeLauncherHidden, launcherHiddenVersion);
const launcherShown = !readLauncherHidden();
- const { desktopMode, sessionVia } = useAuth();
+ const { user, desktopMode, sessionVia } = useAuth();
const offersShellChrome = isDesktopShellWindow({ desktopMode, sessionVia });
// The shell owns this one, so it is fetched rather than read from a store. Anything the
// shell has not told us — no push yet, a request that failed — reads as on, the shell's
@@ -305,7 +315,12 @@ 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} />
+ <ImportedThemesNote
+ state={imported}
+ activeId={themeId}
+ locale={locale}
+ canImport={user?.isAdmin === 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-dialog.tsx b/packages/web/src/features/settings/theme-import-dialog.tsx
new file mode 100644
index 00000000..7ef0b648
--- /dev/null
+++ b/packages/web/src/features/settings/theme-import-dialog.tsx
@@ -0,0 +1,280 @@
+/**
+ * Importing a theme, from the appearance page: ONE dialog with two sources, because a theme is one
+ * small JSON file either way.
+ *
+ * The plugin library needs two dialogs and two name fields — a plugin archive carries a directory
+ * layout, and its name may have to be typed. A theme answers all of that itself: the file says what
+ * it is called, and the server writes it under that name (`<id>.json`), so the only question left
+ * is where the bytes come from. That is a two-way switch, and everything after it is shared — one
+ * body, one confirm button, one overwrite confirmation, one success path — which is what keeps the
+ * dialog from being two nearly identical ones. The switch is also why this is not the note's own
+ * pair of buttons: the directory line is a line of small text, and two buttons there would shout.
+ *
+ * Both flows are the same import twice, as in the plugin dialogs: one carries the file in the
+ * request, the other a URL the server fetches, and a 409 `theme_exists` opens the overwrite
+ * confirmation whose confirm resends THAT request with `overwrite: true` (so the user never picks
+ * the file twice), while any other failure rolls back to a toast. The list is re-read on success,
+ * which is how the new theme appears in the picker above.
+ *
+ * Admin-only by the server's own rule — the themes directory is installation-level, and every
+ * browser that signs in on this machine is painted by it — so the caller (the appearance section)
+ * renders the entry only for an admin, and both routes answer 403 `admin_required` regardless.
+ */
+import { useState } from "react";
+import type { ChangeEvent } from "react";
+import {
+ Button,
+ ConfirmModal,
+ HiddenFileInput,
+ Input,
+ Modal,
+ Segmented,
+ toastError,
+ toastSuccess,
+} from "@adelie/ui";
+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 { UPLOAD_LABEL_CLASS } from "../agents/skills-tab";
+import { themeFileTooLarge, themeImportErrorText } from "./theme-import";
+
+/** Which way the file arrives: picked here, or fetched by the server from an address. */
+type Source = "upload" | "download";
+
+/**
+ * One import request, in the shape the overwrite retry needs: repeatable exactly as it was sent.
+ * Two variants for the plugin dialogs' reason — the uploaded bytes cannot be recovered once the
+ * POST is gone, while a download re-fetches from its URL.
+ */
+type ImportRequest = { source: "upload"; dataBase64: string } | { source: "download"; url: string };
+
+/** A picked file already read into the request body, with the name the user sees. */
+interface PickedFile {
+ dataBase64: string;
+ fileName: string;
+}
+
+export function ThemeImportActions({
+ onImported,
+}: {
+ /** Called once an import landed and was toasted: re-read the list, so the new theme is in the picker. */
+ onImported: () => Promise<void> | void;
+}) {
+ const { locale } = useLocale();
+ const [open, setOpen] = useState(false);
+ const [source, setSource] = useState<Source>("upload");
+ const [busy, setBusy] = useState(false);
+ // The picked file is held rather than posted from the picker's own callback: the confirm is what
+ // sends it, and closing the dialog drops it (a base64 body held in memory has no second use).
+ const [picked, setPicked] = useState<PickedFile | null>(null);
+ const [url, setUrl] = useState("");
+ // The 409 confirmation, the only state the two flows share.
+ const [pending, setPending] = useState<ImportRequest | null>(null);
+
+ const close = () => {
+ setOpen(false);
+ setPicked(null);
+ };
+
+ /** Success path, shared by both flows: close, toast, re-read the list. */
+ const imported = async (name: string) => {
+ setPending(null);
+ setOpen(false);
+ setPicked(null);
+ setUrl("");
+ toastSuccess(S.settings.themeImportDone(name));
+ await onImported();
+ };
+
+ /**
+ * A 409 lands in the overwrite confirmation instead of a toast — it is a question, not a failure
+ * — and every other refusal (or a missing admin right) rolls back to one.
+ */
+ const failed = (e: unknown, request: ImportRequest) => {
+ if (e instanceof ApiError && e.status === 409 && e.code === "theme_exists") {
+ setPending(request);
+ } else {
+ setPending(null);
+ toastError(themeImportErrorText(e));
+ }
+ };
+
+ const upload = async (dataBase64: string, overwrite: boolean) => {
+ setBusy(true);
+ try {
+ const res = await api.importThemeArchive({ dataBase64, ...(overwrite ? { overwrite } : {}) });
+ await imported(localizedText(locale, res.theme.name, res.theme.nameZh));
+ } catch (e) {
+ failed(e, { source: "upload", dataBase64 });
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const download = async (target: string, overwrite: boolean) => {
+ setBusy(true);
+ try {
+ const res = await api.importThemeFromUrl({
+ url: target,
+ ...(overwrite ? { overwrite } : {}),
+ });
+ await imported(localizedText(locale, res.theme.name, res.theme.nameZh));
+ } catch (e) {
+ failed(e, { source: "download", url: target });
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ /** Read the picked file now, post it later: the confirm is what sends it. */
+ const onPickFile = (e: ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ // Clear the picker's value so picking the SAME file again after a refusal still fires a change
+ // event (the Skills tab's import does the same, for the same reason).
+ e.target.value = "";
+ if (!file) return;
+ // Refused before reading: a theme file is small, and reading a large one into a base64 body
+ // only to be told so is work nobody asked for.
+ if (themeFileTooLarge(file.size)) {
+ toastError(S.settings.themeImportTooLarge);
+ return;
+ }
+ const reader = new FileReader();
+ reader.onload = () => {
+ const dataUrl = reader.result as string;
+ // Strip the `data:…;base64,` prefix the FileReader adds.
+ setPicked({
+ dataBase64: dataUrl.slice(dataUrl.indexOf(",") + 1),
+ fileName: file.name,
+ });
+ };
+ reader.onerror = () => toastError(S.common.unknownError);
+ reader.readAsDataURL(file);
+ };
+
+ const submit = () => {
+ if (source === "upload") {
+ if (picked !== null) void upload(picked.dataBase64, false);
+ } else {
+ void download(url.trim(), false);
+ }
+ };
+
+ const confirmOverwrite = () => {
+ if (pending === null) return;
+ if (pending.source === "upload") void upload(pending.dataBase64, true);
+ else void download(pending.url, true);
+ };
+
+ const canSubmit = source === "upload" ? picked !== null : url.trim() !== "";
+
+ return (
+ <>
+ {/* The entry sits in the directory line, beside "read again": the two are the same read and
+ the same write, so they belong to the same sentence about the folder. */}
+ <button
+ type="button"
+ onClick={() => setOpen(true)}
+ className="shrink-0 text-gray-600 underline transition-colors duration-150 hover:text-gray-900 dark:text-gray-300 dark:hover:text-gray-100"
+ >
+ {S.settings.themeImport}
+ </button>
+
+ <Modal
+ open={open}
+ title={S.settings.themeImportTitle}
+ onClose={close}
+ widthClass="sm:max-w-lg"
+ footer={
+ <>
+ <Button size="sm" onClick={close}>
+ {S.common.cancel}
+ </Button>
+ {/* One confirm for both sources: disabled until the chosen source has something to
+ send, and while an import runs. */}
+ <Button size="sm" variant="primary" disabled={busy || !canSubmit} onClick={submit}>
+ {busy
+ ? S.settings.themeImportBusy
+ : source === "upload"
+ ? S.settings.themeImportUploadAction
+ : S.settings.themeImportDownloadAction}
+ </Button>
+ </>
+ }
+ >
+ <div className="space-y-3">
+ <Segmented<Source>
+ cols={2}
+ options={[
+ { value: "upload", label: S.settings.themeImportSourceFile },
+ { value: "download", label: S.settings.themeImportSourceUrl },
+ ]}
+ value={source}
+ onChange={setSource}
+ />
+ {source === "upload" ? (
+ <>
+ <p className="text-xs text-gray-500 dark:text-gray-400">
+ {S.settings.themeImportFileDesc}
+ </p>
+ <div className="flex items-center gap-2">
+ <label
+ className={`${UPLOAD_LABEL_CLASS} ${busy ? "pointer-events-none opacity-60" : ""}`}
+ >
+ <HiddenFileInput
+ accept=".json,application/json"
+ disabled={busy}
+ onChange={onPickFile}
+ />
+ {S.settings.themeImportPickFile}
+ </label>
+ {/* Which file the next confirm will send: without it, picking one shows nothing. */}
+ {picked !== null && (
+ <span className="truncate text-xs text-gray-500 dark:text-gray-400">
+ {S.settings.themeImportPicked(picked.fileName)}
+ </span>
+ )}
+ </div>
+ </>
+ ) : (
+ <>
+ <p className="text-xs text-gray-500 dark:text-gray-400">
+ {S.settings.themeImportUrlDesc}
+ </p>
+ <Input
+ size="sm"
+ label={S.settings.themeImportUrlLabel}
+ value={url}
+ onChange={(e) => setUrl(e.target.value)}
+ placeholder={S.settings.themeImportUrlPlaceholder}
+ autoComplete="off"
+ autoFocus
+ />
+ </>
+ )}
+ </div>
+ </Modal>
+
+ {/* Overwrite confirmation: the dialog that asked stays underneath (Cancel returns to it, file
+ and URL both intact), and confirm resends the same request with `overwrite: true`. */}
+ {pending !== null && (
+ <ConfirmModal
+ open
+ title={S.settings.themeImportOverwriteTitle}
+ tone="primary"
+ confirmLabel={S.settings.themeImportOverwriteAction}
+ cancelLabel={S.common.cancel}
+ busy={busy}
+ onClose={() => setPending(null)}
+ onConfirm={confirmOverwrite}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {S.settings.themeImportOverwriteBody}
+ </p>
+ </ConfirmModal>
+ )}
+ </>
+ );
+}
diff --git a/packages/web/src/features/settings/theme-import.ts b/packages/web/src/features/settings/theme-import.ts
new file mode 100644
index 00000000..a052bd4c
--- /dev/null
+++ b/packages/web/src/features/settings/theme-import.ts
@@ -0,0 +1,52 @@
+/**
+ * The parts of importing a theme that are not the dialog, kept out of it so they can be tested: how
+ * a failed import reads, and the two checks the browser can make before anything is sent.
+ *
+ * A failure's text is mostly the server's own codes turned into the reader's language
+ * (`theme-import-dialog.tsx` explains why the dialog branches the same way). One code is special:
+ * `theme_invalid` carries the reader's collected REASONS — what the file got wrong, in as many
+ * lines as it takes — and those are the whole message for whoever wrote the file, so they are shown
+ * as they came rather than replaced by a sentence of the app's own.
+ */
+import { ApiError } from "../../api/client";
+import { apiErrorText } from "../../lib/api-error";
+import { S } from "../../lib/strings";
+
+/**
+ * The cap the server and core apply to a theme file. The browser refuses to read a picked file past
+ * it, the way the plugin and skill imports do: reading 40MB into a base64 body to be told it is too
+ * large is work nobody asked for. The number is core's `MAX_THEME_FILE_BYTES`, which the web does
+ * not import (it is a data contract, and this is a screen) — a test holds the two equal.
+ */
+export const THEME_FILE_LIMIT_KB = 256;
+
+/** Whether a picked file is past the cap, judged on the file itself rather than after reading it. */
+export function themeFileTooLarge(sizeBytes: number): boolean {
+ return sizeBytes > THEME_FILE_LIMIT_KB * 1024;
+}
+
+/**
+ * The text of a failed theme import: the codes the two 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.
+ */
+export function themeImportErrorText(err: unknown): string {
+ if (err instanceof ApiError) {
+ switch (err.code) {
+ case "theme_invalid":
+ return S.settings.themeImportInvalid(err.message);
+ case "theme_too_large":
+ return S.settings.themeImportTooLarge;
+ case "unsupported_url":
+ return S.settings.themeImportBadUrl;
+ case "blocked_url":
+ return S.settings.themeImportBlockedUrl;
+ case "download_failed":
+ return S.settings.themeImportDownloadFailed;
+ default:
+ break;
+ }
+ }
+ return apiErrorText(err);
+}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index b8b01a80..970c41df 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -743,8 +743,38 @@ export const en: Strings = {
/** 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.",
+ "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. An admin can import one here as well.",
importedThemesReadAgain: "Read again",
+ /** The admin's entry beside the directory line: the same install, without walking to the folder. */
+ themeImport: "Import a theme…",
+ themeImportTitle: "Import a theme",
+ /** The dialog's source switch: the two ways a theme file reaches the server. */
+ themeImportSourceFile: "A local file",
+ themeImportSourceUrl: "An address",
+ themeImportFileDesc:
+ "Pick a theme's .json file (the format is in examples/themes/warm-paper.json). The theme name inside the file is its identity: importing the same one again asks before it replaces anything.",
+ themeImportPickFile: "Choose a .json file",
+ themeImportPicked: (file: string) => `${file} chosen`,
+ themeImportUrlDesc:
+ "Paste the address of a theme .json file and the server fetches it — a local or private address is refused, and what comes back is read the same way a picked file is.",
+ themeImportUrlLabel: "Address of the theme file",
+ themeImportUrlPlaceholder: "https://example.com/theme.json",
+ themeImportUploadAction: "Upload and import",
+ themeImportDownloadAction: "Download and import",
+ themeImportBusy: "Importing…",
+ themeImportDone: (name: string) => `Imported theme ${name}`,
+ /** The 409 both imports answer with, when a file already provides this theme's id. */
+ themeImportOverwriteTitle: "Replace an imported theme",
+ themeImportOverwriteBody:
+ "A theme with the name this file carries is already imported. Replacing it writes this file over the one that provides it, and there is no undo. Continue?",
+ themeImportOverwriteAction: "Replace it",
+ themeImportTooLarge: "This file is past the 256KB limit.",
+ themeImportInvalid: (reason: string) => `This file holds no theme: ${reason}`,
+ themeImportBlockedUrl:
+ "That address points at this machine or a private network; the server will not fetch it.",
+ 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://.",
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.ts
index 70e70fd3..ef5ddf5f 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -801,8 +801,36 @@ export const zh = {
/** 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。",
+ "把主题的 .json 文件放进这个目录、刷新页面,它就会出现在上面的主题列表里;格式见仓库里的 examples/themes/warm-paper.json。管理员也可以直接导入。",
importedThemesReadAgain: "重新读取",
+ /** The admin's entry beside the directory line: the same install, without walking to the folder. */
+ themeImport: "导入主题…",
+ themeImportTitle: "导入主题",
+ /** The dialog's source switch: the two ways a theme file reaches the server. */
+ themeImportSourceFile: "本地文件",
+ themeImportSourceUrl: "地址",
+ themeImportFileDesc:
+ "选一个主题的 .json 文件(格式见 examples/themes/warm-paper.json)。文件里的主题名就是它的身份:同名再来一次会先问一句覆盖。",
+ themeImportPickFile: "选择 .json 文件",
+ themeImportPicked: (file: string) => `已选择 ${file}`,
+ themeImportUrlDesc:
+ "填一个主题 .json 的地址,由服务端取回来——本机或内网地址会被拒绝,取回的内容按同一套读法校验。",
+ themeImportUrlLabel: "主题文件地址",
+ themeImportUrlPlaceholder: "https://example.com/theme.json",
+ themeImportUploadAction: "上传并导入",
+ themeImportDownloadAction: "下载并导入",
+ themeImportBusy: "正在导入…",
+ themeImportDone: (name: string) => `已导入主题 ${name}`,
+ /** The 409 both imports answer with, when a file already provides this theme's id. */
+ themeImportOverwriteTitle: "覆盖已导入的主题",
+ themeImportOverwriteBody:
+ "这个文件里的主题名已经有一套主题占了(同一个主题名)。覆盖会用这个文件替换它现在的文件,不可恢复。确认继续?",
+ themeImportOverwriteAction: "覆盖导入",
+ themeImportTooLarge: "这个文件超过了 256 KB 的上限。",
+ themeImportInvalid: (reason: string) => `这个文件读不出一个主题:${reason}`,
+ themeImportBlockedUrl: "这个地址指向本机或内网,服务端不会去取。",
+ themeImportDownloadFailed: "取不回来:地址、网络或对方的状态码有问题。",
+ themeImportBadUrl: "地址要是一个 http:// 或 https:// 开头的网址。",
importedThemesFailed: "这次没读到导入的主题列表,稍后再试。",
importedThemesNoFile: (id: string) =>
`现在选的「${id}」没有对应的主题文件,页面先用默认主题画。`,
diff --git a/packages/web/src/state/external-themes.ts b/packages/web/src/state/external-themes.ts
index a1e1088b..b5a8e31b 100644
--- a/packages/web/src/state/external-themes.ts
+++ b/packages/web/src/state/external-themes.ts
@@ -119,6 +119,9 @@ export function refreshImportedThemes(force = false): Promise<void> {
rejected: response.rejected.map(({ file, errors }) => ({ file, errors: [...errors] })),
failed: false,
});
+ // A forced read means "the directory may have changed since this page loaded", which is
+ // exactly when the sheet the page already applied is stale.
+ if (force) rereadThemeSheet();
})
.catch(() => publish({ ...EMPTY, failed: true }))
.finally(() => {
@@ -127,6 +130,28 @@ export function refreshImportedThemes(force = false): Promise<void> {
return pending;
}
+/**
+ * Re-reads the stylesheet the page links, by pointing that link at the same sheet through a fresh
+ * URL.
+ *
+ * WHY THIS IS HERE AND NOT THE BROWSER'S BUSINESS: a stylesheet is fetched once per document, and
+ * this one is fetched at load — before anyone could have imported anything. So a theme that arrives
+ * from the import dialog would be offered by the picker and paint NOTHING until the page was
+ * reloaded, which reads as a theme that does not work; the same goes for a file dropped into the
+ * directory while the page is open and then "read again". Re-pointing the link is what makes the
+ * browser fetch the sheet as it is now (the server reads the directory per request and sends
+ * `no-cache`); the extra parameter only says "again" and means nothing to the server.
+ *
+ * Guarded because this module is also read where there is no document (the unit suite runs it in
+ * node): there is no link to re-point there, and no paint to correct.
+ */
+function rereadThemeSheet(): void {
+ if (typeof document === "undefined") return;
+ const link = document.querySelector('link[rel="stylesheet"][href^="/api/themes.css"]');
+ if (link === null) return;
+ link.setAttribute("href", `/api/themes.css?again=${Date.now()}`);
+}
+
/** Test seam: drop what was read, so the next read asks the server again. */
export function resetImportedThemes(): void {
state = EMPTY;
diff --git a/packages/web/test/external-themes.test.ts b/packages/web/test/external-themes.test.ts
index 3d62512f..6090e099 100644
--- a/packages/web/test/external-themes.test.ts
+++ b/packages/web/test/external-themes.test.ts
@@ -152,4 +152,29 @@ describe("reading the list", () => {
expect(importedThemes().failed).toBe(true);
expect(importedThemes().dir).toBeNull();
});
+
+ it("读过之后是「再来一次」时,把页面链接的那张样式表也重挂一遍", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => answer({ dir: "/data/themes", themes: [], rejected: [] })),
+ );
+ // A stylesheet is fetched once per document, so the sheet the page already applied is the one
+ // from load — an import that lands afterwards paints nothing until the link is re-pointed.
+ const hrefs: string[] = [];
+ const link = {
+ setAttribute: (name: string, value: string) => hrefs.push(`${name}=${value}`),
+ };
+ const querySelector = vi.fn(() => link);
+ vi.stubGlobal("document", { querySelector });
+
+ // A plain read is the page load's own: the sheet is the one it just fetched, nothing to redo.
+ await refreshImportedThemes();
+ expect(querySelector).not.toHaveBeenCalled();
+ expect(hrefs).toEqual([]);
+
+ await refreshImportedThemes(true);
+ expect(querySelector).toHaveBeenCalledWith('link[rel="stylesheet"][href^="/api/themes.css"]');
+ expect(hrefs).toHaveLength(1);
+ expect(hrefs[0]!).toMatch(/^href=\/api\/themes\.css\?again=\d+$/);
+ });
});
diff --git a/packages/web/test/theme-import.test.ts b/packages/web/test/theme-import.test.ts
new file mode 100644
index 00000000..1859176b
--- /dev/null
+++ b/packages/web/test/theme-import.test.ts
@@ -0,0 +1,70 @@
+/**
+ * The two pure parts of the theme import dialog (features/settings/theme-import.ts): what a failed
+ * import says, and the check the browser makes before reading a picked file.
+ *
+ * What is worth pinning here is that a refusal is never replaced by a sentence of the app's own
+ * when the server had something specific to say: `theme_invalid` carries the reader's collected
+ * reasons — the file's author is who has to fix them — while a code the app has its own copy for
+ * gets that copy, because the server's message is English-only and the UI language may not be.
+ * The cap is pinned against core's own constant: the browser refusing to read a file the server
+ * would accept, or reading one it would refuse, is the one way these two numbers can disagree.
+ */
+import { describe, expect, it } from "vitest";
+import { MAX_THEME_FILE_BYTES } from "@adelie/core";
+import { ApiError } from "../src/api/client";
+import { apiErrorText } from "../src/lib/api-error";
+import { S } from "../src/lib/strings";
+import {
+ THEME_FILE_LIMIT_KB,
+ themeFileTooLarge,
+ themeImportErrorText,
+} from "../src/features/settings/theme-import";
+
+describe("主题导入失败时说的话", () => {
+ it("读不出来时,服务端给的原因原样带上", () => {
+ const reason = "id: 「Warm Paper」不是合法的主题名(要小写字母开头…)";
+ const text = themeImportErrorText(new ApiError(400, "theme_invalid", reason));
+ expect(text).toBe(S.settings.themeImportInvalid(reason));
+ // The reason itself survives into the sentence rather than being summarized away.
+ expect(text).toContain("Warm Paper");
+ });
+
+ it("每个码都有自己的说法:超限、地址不对、内网、取不回来", () => {
+ expect(themeImportErrorText(new ApiError(413, "theme_too_large", "…"))).toBe(
+ S.settings.themeImportTooLarge,
+ );
+ expect(themeImportErrorText(new ApiError(400, "unsupported_url", "…"))).toBe(
+ S.settings.themeImportBadUrl,
+ );
+ expect(
+ themeImportErrorText(
+ new ApiError(
+ 400,
+ "blocked_url",
+ "Refusing to fetch from a local or private host: 127.0.0.1",
+ ),
+ ),
+ ).toBe(S.settings.themeImportBlockedUrl);
+ expect(themeImportErrorText(new ApiError(400, "download_failed", "…"))).toBe(
+ S.settings.themeImportDownloadFailed,
+ );
+ });
+
+ it("不认识的码走共用的那张表,不是自己编一句", () => {
+ const empty = new ApiError(400, "bad_request", "The file is empty.");
+ expect(themeImportErrorText(empty)).toBe(apiErrorText(empty));
+ // Not an ApiError at all (a thrown non-HTTP failure): the shared text, not a crash or a blank.
+ expect(themeImportErrorText(new Error("boom"))).toBe(S.common.unknownError);
+ });
+});
+
+describe("读取之前的那道上限", () => {
+ it("浏览器这边的上限就是 core 的格式上限", () => {
+ expect(THEME_FILE_LIMIT_KB * 1024).toBe(MAX_THEME_FILE_BYTES);
+ });
+
+ it("按文件大小判断,正好到上限时不拦", () => {
+ expect(themeFileTooLarge(THEME_FILE_LIMIT_KB * 1024)).toBe(false);
+ expect(themeFileTooLarge(THEME_FILE_LIMIT_KB * 1024 + 1)).toBe(true);
+ });
+});