A local-first multi-agent app development platform, built on PenguinHarness
feat(web,docs): merge the scattered settings into a System settings dialog (#369)
Yaowei Zhengdaf8c72a84af
diff --git a/changelog/unreleased/2026-08-20-system-settings-page.md b/changelog/unreleased/2026-08-20-system-settings-page.mdnew file mode 100644index 00000000..8905edfe--- /dev/null+++ b/changelog/unreleased/2026-08-20-system-settings-page.md@@ -0,0 +1,30 @@+# System settings dialog++- **Date:** 2026-08-20+- **Type:** feature+- **Scope:** `web`, `docs`+- **PR:** [#369](https://github.com/Prism-Shadow/penguin-harness/pull/369)++[中文版](2026-08-20-system-settings-page.zh.md)++Merged the settings that sat as separate rows and dialogs in the sidebar user menu into one **System settings dialog**, opened from the menu's single remaining System settings row: a left rail of pages — grouped Personal / Server — with each page a list of title-and-description rows. The rail, pages and row layout follow the Project-settings-style paged dialog; the shell is a reusable `PagedDialog` component. The old `/settings/:section` and `/admin/users` routes were removed along with the standalone settings page.++## Pages++- **Personal → General** — interface language, display currency, and the per-user **Show CLI sessions** switch; each applies the moment it is touched, as in the menu.+- **Personal → Appearance** — app theme, terminal theme, font size and accent color, moved out of the user menu unchanged.+- **Personal → Account** — the Change password action; the page exists only where a password exists to change (the desktop shell's own window never sees one).+- **Server → Proxy options / Upload limits** — admin only; both kept their single-PUT save, inline rejections, and follow-up behavior from the previous settings page.+- **Server → Updates** — the manual check-for-updates action with the running version and its release-date hint, and — once a newer release is known — the entry into the update dialog. Hidden in desktop mode, where updating is the shell's job. The user menu keeps the reminder: its dot and a "New version available" row that opens this page directly.+- **Server → Users** — user management (list / create / reset password / delete), moved off its own route into the dialog; admin only and absent in desktop mode.++## Terminal theme follows the app by default++The terminal theme's default changed from pinned dark to **follow the app theme**: with nothing chosen, switching the app light/dark carries the terminal along. An explicitly saved light/dark choice is untouched — an absent stored value reads as "follow", and pinning either mode still decouples the two.++## Details++- Page visibility is one registry consulted by both the rail and the landing-page request, so a non-admin asking for an admin page lands on their own first page — the same answer an unknown request gets — and is never told the page exists. The admin APIs answer 403 regardless.+- The desktop shell's window drops the Account, Updates and Users pages (token session, shell-owned updates, single-user server); a password session against the same desktop-mode server keeps Account.+- No server change: the surfaces moved, the endpoints behind them did not.+- The Web App reference's System Settings chapter now describes the dialog and its pages, and the Version-and-Updates chapter points at the Updates page.diff --git a/changelog/unreleased/2026-08-20-system-settings-page.zh.md b/changelog/unreleased/2026-08-20-system-settings-page.zh.mdnew file mode 100644index 00000000..3a3ef491--- /dev/null+++ b/changelog/unreleased/2026-08-20-system-settings-page.zh.md@@ -0,0 +1,30 @@+# 系统设置弹窗++- **Date:** 2026-08-20+- **Type:** feature+- **Scope:** `web`, `docs`+- **PR:** [#369](https://github.com/Prism-Shadow/penguin-harness/pull/369)++[English](2026-08-20-system-settings-page.md)++把散落在侧边栏用户菜单里的各项设置合并进一个**系统设置弹窗**,入口是菜单仅存的「系统设置」行:左侧一列页面导航(按「个人 / 服务器」分组),每页是一列「标题 + 说明」式设置行。导航、页面与行布局与项目设置同款的分页弹窗一致;外壳抽成了可复用的 `PagedDialog` 组件。原 `/settings/:section` 与 `/admin/users` 路由随独立设置页一并移除。++## 页面++- **个人 → 通用**——界面语言、显示币种,以及按用户存储的**显示 CLI 会话**开关;与菜单中一样,改动即刻生效。+- **个人 → 外观**——应用主题、终端主题、字号与主题色,从用户菜单原样迁入。+- **个人 → 账户**——修改密码操作;该页只在存在可修改密码时出现(桌面 shell 自己的窗口从未见过密码)。+- **服务器 → 代理选项 / 上传限制**——仅管理员;两页保留原设置页的单次 PUT 保存、行内拒绝与后续行为。+- **服务器 → 更新**——手动检查更新操作,旁附当前版本号与发布日期提示;得知新版本后由此进入更新弹窗。桌面模式下隐藏(更新由 shell 负责)。用户菜单保留提醒:圆点与「有新版本可用」行,点击直达本页。+- **服务器 → 用户管理**——用户管理(列出 / 创建 / 重置密码 / 删除)从独立路由迁入弹窗;仅管理员,桌面模式下不出现。++## 终端主题默认跟随应用++终端主题的默认值由固定深色改为**跟随应用主题**:未显式选择时,应用切换明暗会带动终端。已显式保存的浅色/深色选择不受影响——存储值缺失即视为「跟随」,显式选定任一模式仍可与应用解耦。++## 细节++- 页面可见性收敛为一个注册表,导航与落地页请求共用同一规则:非管理员请求管理员页面会落到自己的第一页——与未知请求得到同一答案——不会得知该页存在;接口侧一律 403。+- 桌面 shell 自己的窗口没有账户、更新、用户管理三页(token 会话、shell 负责更新、单用户服务端);用密码登录同一桌面模式服务器的会话保留账户页。+- 服务端零改动:迁移的是界面,背后的接口未动。+- Web App 参考的系统设置章节改述弹窗及其页面,「版本与更新」章节指向更新页。diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.mdindex 04be7170..3cf3499a 100644--- a/packages/docs/content/web-app.en.md+++ b/packages/docs/content/web-app.en.md@@ -67,7 +67,7 @@ Copy buttons across the app confirm at the button itself: the copy icon flips to### Input and Shortcuts- Enter sends, Shift+Enter inserts a newline, and images can be pasted — an image placed inline in the conversation is capped at 20MB, separately from file attachments and not raised along with them: an inline image enters the conversation and the Trace, where its size is paid again on every history page and every session resume, whereas an attachment is only ever read from disk by path;-- The "+" menu holds the input add-ons: **image upload**, **file attachment** and goal mode. An attachment can be any type (up to 20 at a time, and by default ≤ 100MB each and 120MB in total — an admin can change both sizes under **Upload limits** in the user menu, see below; an oversize pick is refused before it is read, so nothing is uploaded to earn the rejection, and the message names the limit actually in force); selected files show as removable chips above the text body in the order they were picked, and a message with attachments and no text is sendable. On send the files are written into the Session's scratchpad — deleted with the Session — and the message gains an `[attached file: <path>]` line per file, which the conversation renders as an "Attached files" notice: the bytes never enter the conversation, the model opens each file by path with its ordinary file tools;+- The "+" menu holds the input add-ons: **image upload**, **file attachment** and goal mode. An attachment can be any type (up to 20 at a time, and by default ≤ 100MB each and 120MB in total — an admin can change both sizes under **System settings → Upload limits**, see below; an oversize pick is refused before it is read, so nothing is uploaded to earn the rejection, and the message names the limit actually in force); selected files show as removable chips above the text body in the order they were picked, and a message with attachments and no text is sendable. On send the files are written into the Session's scratchpad — deleted with the Session — and the message gains an `[attached file: <path>]` line per file, which the conversation renders as an "Attached files" notice: the bytes never enter the conversation, the model opens each file by path with its ordinary file tools;- Files can also be **dragged onto the chat area** — the conversation and the composer, on the chat page and the draft page alike: while a file drag is over that region a "Drop files to attach" overlay covers it (it hides as soon as the drag moves off; dragging text or anything that isn't a file is ignored), and releasing attaches the whole batch to the composer — images join the pasted-image pipeline, everything else becomes file attachments, with the same type and size validation and the same errors as the "+" menu. Dropping works while a Task is running too (the attachments then send per the mid-run send mode below); goal mode takes dropped images but refuses files with a notice. Only the chat area reacts: dropping a file on the sidebar, the top bar, the docked panels or any page without a composer attaches nothing and shows nothing — it is simply ignored, instead of the browser navigating away to the dropped file;- Typing `/` opens the slash menu: trigger context compaction (`/compact`), hand the conversation over to another Agent (`/agent`), switch the model (`/model`) — both switch commands appear in an active session only, since a draft has nothing to switch and picks its Agent and model up front — or toggle installed Skills — chosen Skills are sent along with the message in a `[use_skills]` block;- While a Task is running the input stays live and the toolbar keeps a single action button: an empty composer shows **Stop**, and typing turns it into **Send**, whose behavior follows the **mid-run send mode** from the toolbar's More-settings popover (a compact extensible settings panel, also available in draft state; the choice is remembered): **Steer** (default) delivers the text **and any attached images** mid-run as a `[user_steering]` user message with the next turn (an image with no caption sends on its own, and the delivered message renders as a steering chip with its images inside it), **Queue** holds the whole message server-side as a follow-up and auto-sends it as an ordinary new message when the run finishes (an "N queued" hint shows near the input until then; the queue survives page reloads). A draft steering cannot carry — selected skills, file attachments, or a staged `/agent` or `/model` pick, with no text and no image — falls back to the queue for that one send, so the button never sits disabled with Stop displaced. Each queued hint line — an undelivered steering message or a queued follow-up — ends in a **recall** control (a curved-back arrow, "Recall") that withdraws the message back into the input box (attachments included) for editing and resending; a steering message that already reached the model can no longer be recalled;@@ -122,13 +122,35 @@ Drill down Agent → date → Session → Trace file. Per-turn cards show a contRead-only scoreboards per Benchmark: switch the metric (score / cost / duration), drill into each Case's runs, and jump to the linked Session and Trace. Works together with the [Self-Improvement](/self-improvement) workflow.-## User Administration (/admin/users)+## System Settings-Admin only: list and create users, reset passwords, and delete users (the built-in admin cannot be deleted).+One dialog for the settings that belong to neither a Project nor an Agent, opened from the sidebar user menu's **System settings** row: a left rail of pages, each page a list of rows — title and a one-line explanation on the left, the control on the right.-## Upload Limits+The rail is grouped. **Personal** holds preferences that belong to the signed-in account and apply the moment they are touched — no Save button, nothing to lose by closing the dialog. **Server** holds the server-global surfaces: the settings written through `GET|PUT /api/admin/settings` and user management are admin-only — a non-admin gets neither those entries nor any hint they exist, and the APIs answer a non-admin with 403 whatever the browser rendered — while the Updates page is visible to every account outside the desktop app. In the desktop app the update and user-management pages are absent entirely (updating is the desktop shell's job, and the server runs single-user), and the shell's own window also has no Account page — it signs in through the shell's token and holds no password to change, while a browser signed into the same server with a password keeps it.-Admin only: **Upload limits** in the sidebar user menu opens a server-global form with two sizes — the **per-file attachment cap** and the **per-message total** — both whole MB, defaulting to 100MB and 120MB. Each may be set between 1 and 200MB, and the total may not sit below the per-file cap (that combination would make a legal single attachment unsendable). A value outside the range — "100GB" typed into a MB field as 102400, say — is refused with the reason shown under the input rather than accepted. Validation precedes every write: one bad field in a PUT leaves the other fields untouched too.+### General++Personal. **Language** (Chinese / English / follow the browser) and the **display currency** for prices (USD / CNY; storage is always USD — conversion happens only at the edge of the screen). **Show CLI sessions** (default off): off, the conversation list holds only Sessions created in the Web App and is served straight from the database; on, the Trace directories are scanned too and CLI-created Sessions are listed alongside them. Stored per user, and the Trace browser follows the same preference.++### Appearance++Personal. The app **theme** (light / dark / follow the system), the **terminal theme** — the terminal panel keeps its own light/dark and by default follows the app theme; pin it light or dark to decouple the two, for prompts and TUIs tuned to one screen — the interface **font size**, and the **accent color**.++### Account++The **Change password** action. The page exists only where a password exists to change: the desktop shell's own window signs in through the shell's one-shot token and never sees one.++### Users++Admin only, outside the desktop app: list and create users, reset passwords, and delete users (the built-in admin cannot be deleted).++### Proxy Options++Admin only, server-global. Two switches — **Application uses the proxy** (the server's own outbound traffic: LLM requests, the update check, image fetches) and **Agent environment uses the proxy** (agent command subprocess environments) — share one optional **proxy address**; empty means follow the proxy environment variables. The address accepts any proxy URL undici's dispatcher takes (`http://`, `https://`, `socks5://`, credentials allowed) or a bare `host[:port]`, which is stored normalized to `http://…`; anything else is refused with the reason under the input. Nothing is written until Save, which applies the whole form in one PUT, so a rejected address writes none of it. A save rebuilds the outbound dispatcher and takes effect on new connections with no restart; loopback always goes direct.++### Upload Limits++Admin only, server-global: two sizes — the **per-file attachment cap** and the **per-message total** — both whole MB, defaulting to 100MB and 120MB. Each may be set between 1 and 200MB, and the total may not sit below the per-file cap (that combination would make a legal single attachment unsendable). A value outside the range — "100GB" typed into a MB field as 102400, say — is refused with the reason shown under the input rather than accepted. Validation precedes every write: one bad field in a PUT leaves the other fields untouched too.Saving takes effect immediately, with no restart: the attachment validators and the request body cap both read the setting per request. The body cap is not configured separately but derived from the total — attachments ride the request as base64 `data:` URLs, which inflates them by 4/3, so it has to rise with them or a request whose every attachment was individually legal would die at the HTTP layer instead.@@ -136,7 +158,7 @@ Two numbers are deliberately not exposed. The per-message file **count** stays a## Version and Updates-The sidebar user menu carries a manual "Check for updates" action directly below "Change password"; the running version sits muted on the right of that row, and its release date — stamped into the build by the release workflow, displayed without any network access — appears as the row's localized "Last updated Jul 26"-style tooltip (dev builds and releases that predate the stamping, v0.1.2 and earlier, have no date). The new-chat page shows the same identity as a version line under the brand. The app checks GitHub for a newer release once the menu has first been opened, and immediately — bypassing the cached result — when the manual action is clicked; the latter reports "You're on the latest version" when nothing newer exists. When a newer release is found, a dot appears on the user button, the version displays gain a small superscript "New version available" badge (the draft-page badge links to the release), and the menu gains a release-notes link, plus an "Update now" action for admins that runs `penguin update` on the server (the data directory is untouched). The service must be restarted afterwards for the update to take effect. Set `PENGUIN_UPDATE_CHECK=off` to disable the update check entirely — see the [Configuration Reference](/configuration).+System settings → **Updates** carries the manual "Check for updates" action; the running version sits muted beside it, and its release date — stamped into the build by the release workflow, displayed without any network access — appears as the row's localized "Last updated Jul 26"-style hint (dev builds and releases that predate the stamping, v0.1.2 and earlier, have no date). The new-chat page shows the same identity as a version line under the brand. The app checks GitHub for a newer release once the sidebar user menu has first been opened, and immediately — bypassing the cached result — when the manual action is clicked; the latter reports "You're on the latest version" when nothing newer exists. When a newer release is found, a dot appears on the user button, the draft page's version line gains a small superscript "New version available" badge linking to the release, and the menu gains a "New version available" row that opens the Updates page, whose dialog carries the release-notes link, plus an "Update now" action for admins that runs `penguin update` on the server (the data directory is untouched). The service must be restarted afterwards for the update to take effect. Set `PENGUIN_UPDATE_CHECK=off` to disable the update check entirely — see the [Configuration Reference](/configuration).## Projects and Membersdiff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.mdindex f169dfdd..f5e0c6da 100644--- a/packages/docs/content/web-app.zh.md+++ b/packages/docs/content/web-app.zh.md@@ -67,7 +67,7 @@ penguin web### 输入与快捷操作- Enter 发送,Shift+Enter 换行,支持粘贴图片——嵌入对话的图片单独设有 20MB 上限,不随附件上限一起放宽:图片会进入对话与轨迹,此后每次翻阅历史、恢复会话都要重新付出它的体积,而附件只是按路径从磁盘读取;-- 「+」菜单收纳输入附加项:**上传图片**、**上传文件**与目标模式。附件不限类型(一次最多 20 个,默认单个 ≤ 100MB、合计 ≤ 120MB——两个尺寸均可由管理员在用户菜单的**上传限制**中调整,见下文;超限的文件在读取前即被拒绝,不会先上传再报错,提示中会写出当前生效的上限),已选文件按选择顺序以可移除的小卡片显示在文本框上方;只带附件、没有正文也可发送。发送时文件写入该 Session 的 scratchpad(随 Session 一并删除),消息里每个文件追加一行 `[attached file: <path>]`,对话中渲染为一条「附加文件」提示:文件内容不进入对话,模型用普通文件工具按路径读取;+- 「+」菜单收纳输入附加项:**上传图片**、**上传文件**与目标模式。附件不限类型(一次最多 20 个,默认单个 ≤ 100MB、合计 ≤ 120MB——两个尺寸均可由管理员在**系统设置 → 上传限制**中调整,见下文;超限的文件在读取前即被拒绝,不会先上传再报错,提示中会写出当前生效的上限),已选文件按选择顺序以可移除的小卡片显示在文本框上方;只带附件、没有正文也可发送。发送时文件写入该 Session 的 scratchpad(随 Session 一并删除),消息里每个文件追加一行 `[attached file: <path>]`,对话中渲染为一条「附加文件」提示:文件内容不进入对话,模型用普通文件工具按路径读取;- 也可以把文件**拖拽到聊天区**上传(聊天区即对话与输入框所在区域,会话页与草稿页皆可):文件拖到该区域上方时显示覆盖该区域的「松开以添加附件」浮层(拖离即消失,拖动文本等非文件内容不触发),松开即把整批文件附加到输入框——图片走粘贴图片的同一管线,其余文件成为附件,类型与大小校验及报错与「+」菜单一致。任务运行中同样可以拖入(附件按下述运行中发送方式送出);目标模式下拖入的图片照常附加、文件会以提示拒绝。只有聊天区会响应:把文件放到侧边栏、顶栏、右侧停靠面板或任何没有输入框的页面上,既不显示浮层也不会添加附件,只是被直接忽略,同时不会让浏览器跳转打开该文件;- 输入 `/` 打开快捷菜单:触发上下文压缩(`/compact`)、把会话交接给其他 Agent(`/agent`)、切换模型(`/model`)——两个切换命令都只在进行中的会话里提供,草稿没有可切换的对话,Agent 与模型本就在草稿页选定——或勾选已安装的 Skill——所选 Skill 会以 `[use_skills]` 块随消息发送;- Task 运行期间输入框保持可用,工具条只保留一个操作按钮:输入框为空时是**停止**,一旦输入内容即变为**发送**,其行为遵循工具条「更多设置」弹出分组中的**运行中发送方式**(一个可扩展的设置面板,草稿态同样可设,选择会被记忆):**插话**(默认)把文字以 `[user_steering]` 用户消息随下一轮送达运行中的 Agent;**排队** 把整条消息暂存在服务端,本轮结束后自动作为普通新消息发出(期间在输入框附近显示「N 条已排队」提示;队列存放在服务端,刷新页面不丢失)。每条排队提示——未送达的插话或排队中的跟进消息——行尾都带一枚**撤回**按钮(一个向回弯的箭头图标),可把消息(含附件)撤回到输入框编辑后重新发送;插话一旦送达模型即不可撤回;@@ -121,13 +121,35 @@ Memory 标签页的开关拨动即写入,不参与标签页的保存按钮,只读展示各 Benchmark 的评分板,可切换指标(得分 / 费用 / 耗时),下钻查看每个 Case 的多次运行结果,并跳转到关联的 Session 与 Trace。配合[自我进化](/self-improvement)工作流使用。-## 用户管理(/admin/users)+## 系统设置-仅管理员可见:列出与创建用户、重置密码、删除用户(内置 admin 不可删除)。+把既不属于 Project 也不属于 Agent 的设置收进一个弹窗,入口是侧边栏用户菜单的「系统设置」:左侧一列页面导航,右侧每页是一列设置行——左边标题加一行说明,右边控件。-## 上传限制+导航按组划分。**个人**组存放属于当前账号的偏好,改动即刻生效,没有保存按钮,关闭弹窗也不会丢失什么;**服务器**组存放服务器全局的界面:经 `GET|PUT /api/admin/settings` 写入的设置与用户管理仅管理员可见——非管理员既看不到这些条目、也不会得知它们存在,无论前端渲染成什么,接口对非管理员一律返回 403——而「更新」页对桌面应用之外的所有账号可见。桌面应用中没有更新与用户管理两页(更新由桌面 shell 负责,服务端是单用户模式);桌面 shell 自己的窗口还没有「账户」页——它通过 shell 的一次性 token 登录,没有可修改的密码,而用密码登录同一服务器的浏览器会话仍保留该页。-仅管理员可见:侧边栏用户菜单的「上传限制」打开一个服务器全局的表单,可调整两个尺寸——**单个附件上限**与**单条消息附件合计上限**,均以整数 MB 填写,默认 100MB 与 120MB。两者的取值范围为 1–200MB,且合计不得低于单个上限(否则一个本身合法的附件将无法发送);超出范围的值——例如把「100GB」按 MB 填成 102400——会被服务端明确拒绝并在输入框下方给出原因,不会被接受。校验先于写入:一次 PUT 中只要有一个字段非法,其余字段也不会落库。+### 通用++个人设置。**语言**(中文 / English / 跟随浏览器)与价格的**显示币种**(USD / CNY;存储始终为美元,换算只发生在显示层)。**显示 CLI 会话**(默认关):关闭时会话列表只列出在 Web 端创建的 Session,直接由数据库返回;开启后会额外扫描轨迹目录,把 CLI 创建的会话一并列出。按用户存储,轨迹观测页遵循同一偏好。++### 外观++个人设置。应用**主题**(浅色 / 深色 / 跟随系统)、**终端主题**——终端面板保留自己的明暗配色,默认跟随应用主题,显式选定浅色或深色即与应用解耦,适合提示符与 TUI 只为一种屏幕调校过的场景——以及界面**字号**与**主题色**。++### 账户++**修改密码**操作。该页只在存在可修改密码时出现:桌面 shell 自己的窗口通过 shell 的一次性 token 登录,从未见过密码。++### 用户管理++仅管理员可见、桌面应用中不出现:列出与创建用户、重置密码、删除用户(内置 admin 不可删除)。++### 代理选项++仅管理员可见、服务器全局。两个开关——**应用程序使用代理**(server 自身出网:LLM 请求、更新检查、图片抓取)与 **Agent 环境使用代理**(Agent 命令子进程环境)——共用一个可选的**代理地址**,留空即跟随代理环境变量。地址接受 undici dispatcher 认可的任意代理 URL(`http://`、`https://`、`socks5://`,可带凭据)或裸 `host[:port]`(归一化为 `http://…` 后存储),其余一律拒绝并在输入框下方给出原因。保存前不写入任何内容,保存以单次 PUT 整体提交,因此地址被拒时其余字段也不会落库。保存后重建出网 dispatcher,对新发起的连接即时生效、无需重启;回环地址始终直连。++### 上传限制++仅管理员可见、服务器全局:两个尺寸——**单个附件上限**与**单条消息附件合计上限**,均以整数 MB 填写,默认 100MB 与 120MB。两者的取值范围为 1–200MB,且合计不得低于单个上限(否则一个本身合法的附件将无法发送);超出范围的值——例如把「100GB」按 MB 填成 102400——会被服务端明确拒绝并在输入框下方给出原因,不会被接受。校验先于写入:一次 PUT 中只要有一个字段非法,其余字段也不会落库。保存即刻生效,无需重启:附件校验与请求体上限都在每次请求时读取该设置。请求体上限本身不单独配置,而是由合计上限推导——附件以 base64 `data:` URL 随请求送达,体积膨胀 4/3,因此上限必须随之上浮,否则每个附件单独合法的请求会在 HTTP 层被拒。@@ -135,7 +157,7 @@ Memory 标签页的开关拨动即写入,不参与标签页的保存按钮,## 版本与更新-侧边栏用户菜单在「修改密码」下方提供手动「检查更新」按钮,当前运行版本号以浅色显示在该行右侧;其发布日期(由发布流程在构建时打入、直接显示、无需联网)以「最近更新日期 7 月 26 日」样式的悬浮提示展示(开发构建以及打入机制之前的发布版,v0.1.2 及以前,没有日期)。新对话页在品牌下方以版本行显示同样的信息。菜单首次打开后会向 GitHub 查询是否有新版本;点击「检查更新」则立即查询(绕过缓存结果),已是最新时以提示告知。发现新版本时,用户按钮上会出现提示圆点,版本显示处会出现「有新版本可用」上标小徽标(新对话页的徽标可跳转 Release 页面),菜单内提供更新说明链接;管理员还可点击"立即更新",在服务器上执行 `penguin update`(数据目录不受影响)。更新完成后需要重启服务才会生效。设置 `PENGUIN_UPDATE_CHECK=off` 可完全关闭新版本检查——见[配置参考](/configuration)。+系统设置的**更新**页提供手动「检查更新」按钮,当前运行版本号以浅色显示在旁;其发布日期(由发布流程在构建时打入、直接显示、无需联网)以「最近更新日期 7 月 26 日」样式的提示展示(开发构建以及打入机制之前的发布版,v0.1.2 及以前,没有日期)。新对话页在品牌下方以版本行显示同样的信息。侧边栏用户菜单首次打开后会向 GitHub 查询是否有新版本;点击「检查更新」则立即查询(绕过缓存结果),已是最新时以提示告知。发现新版本时,用户按钮上会出现提示圆点,新对话页的版本行会出现可跳转 Release 页面的「有新版本可用」上标小徽标,菜单内出现「有新版本可用」行,点击直达更新页;其弹窗提供更新说明链接,管理员还可点击「立即更新」,在服务器上执行 `penguin update`(数据目录不受影响)。更新完成后需要重启服务才会生效。设置 `PENGUIN_UPDATE_CHECK=off` 可完全关闭新版本检查——见[配置参考](/configuration)。## Project 与成员diff --git a/packages/web/src/components/account/proxy-settings-dialog.tsx b/packages/web/src/components/account/proxy-settings-dialog.tsxdeleted file mode 100644index a4ae619b..00000000--- a/packages/web/src/components/account/proxy-settings-dialog.tsx+++ /dev/null@@ -1,131 +0,0 @@-/**- * Admin proxy options dialog (server-global), opened from- * the sidebar user menu. A form, not a live surface: two switches — "Application uses- * the proxy" (the server's own outbound dispatcher) and "Agent environment uses the- * proxy" (command subprocess environments) — share one proxy address, and nothing is- * written until Save, which applies everything atomically via a single PUT. The server- * validates and normalizes the address (bare "host:port" is stored as- * "http://host:port"); a rejected address renders inline under the input (models-dialog- * convention) and the atomic PUT writes nothing. Save with no modifications sends no- * request and toasts "no changes" (the app's form convention); success- * toasts and closes. Settings hydrate fresh on every open; the controls and Save stay- * disabled until they arrive, and Cancel/Esc discards edits.- */-import { useEffect, useState } from "react";-import type { ServerSettings } from "@prismshadow/penguin-server/api";-import * as api from "../../api/endpoints";-import { ApiError } from "../../api/client";-import { S } from "../../lib/strings";-import { apiErrorText } from "../../lib/api-error";-import { Button } from "../ui/button";-import { Input } from "../ui/input";-import { Modal } from "../ui/modal";-import { Switch } from "../ui/switch";-import { toastError, toastInfo, toastSuccess } from "../ui/toast";--export function ProxySettingsDialog({ open, onClose }: { open: boolean; onClose: () => void }) {- /** Stored settings as hydrated on open (null until then) — the no-change baseline. */- const [settings, setSettings] = useState<ServerSettings | null>(null);- // Form drafts; the pre-hydration values mirror the server defaults (on, on, empty).- const [proxyForApp, setProxyForApp] = useState(true);- const [proxyForAgent, setProxyForAgent] = useState(true);- const [proxyUrl, setProxyUrl] = useState("");- /** Inline error under the address input (the server's invalid_proxy_url rejection). */- const [addressError, setAddressError] = useState<string | null>(null);- const [busy, setBusy] = useState(false);-- useEffect(() => {- if (!open) return;- let cancelled = false;- setSettings(null);- setAddressError(null);- setBusy(false);- void api- .adminGetSettings()- .then((res) => {- if (cancelled) return;- setSettings(res.settings);- setProxyForApp(res.settings.proxyForApp);- setProxyForAgent(res.settings.proxyForAgent);- setProxyUrl(res.settings.proxyUrl ?? "");- })- .catch((e: unknown) => {- // Controls stay disabled; closing and reopening retries the fetch.- if (!cancelled) toastError(apiErrorText(e));- });- return () => {- cancelled = true;- };- }, [open]);-- const save = async () => {- if (settings === null || busy) return;- const unchanged =- proxyForApp === settings.proxyForApp &&- proxyForAgent === settings.proxyForAgent &&- proxyUrl.trim() === (settings.proxyUrl ?? "");- if (unchanged) {- toastInfo(S.common.noChangesToSave);- return;- }- setBusy(true);- setAddressError(null);- try {- await api.adminPutSettings({ proxyForApp, proxyForAgent, proxyUrl });- toastSuccess(S.common.saved);- onClose();- } catch (e) {- // The address is the only validated field: its rejection renders inline;- // anything else (auth, network) is a generic failure toast.- if (e instanceof ApiError && e.code === "invalid_proxy_url") {- setAddressError(apiErrorText(e));- } else {- toastError(apiErrorText(e));- }- } finally {- setBusy(false);- }- };-- const hydrated = settings !== null;- return (- <Modal- open={open}- title={S.settings.proxyDialogTitle}- onClose={onClose}- footer={- <>- <Button onClick={onClose} disabled={busy}>- {S.common.cancel}- </Button>- <Button variant="primary" disabled={!hydrated || busy} onClick={() => void save()}>- {S.common.save}- </Button>- </>- }- >- <div className="space-y-4">- <div className="flex items-center justify-between gap-3">- <span className="text-sm font-medium">{S.settings.proxyForApp}</span>- <Switch checked={proxyForApp} onChange={setProxyForApp} disabled={!hydrated} />- </div>- <div className="flex items-center justify-between gap-3">- <span className="text-sm font-medium">{S.settings.proxyForAgent}</span>- <Switch checked={proxyForAgent} onChange={setProxyForAgent} disabled={!hydrated} />- </div>- <Input- label={S.settings.proxyAddress}- size="sm"- value={proxyUrl}- placeholder={S.settings.proxyAddressPlaceholder}- disabled={!hydrated}- {...(addressError !== null ? { error: addressError } : {})}- onChange={(e) => {- setProxyUrl(e.target.value);- if (addressError !== null) setAddressError(null);- }}- />- </div>- </Modal>- );-}diff --git a/packages/web/src/components/account/upload-limits-dialog.tsx b/packages/web/src/components/account/upload-limits-dialog.tsxdeleted file mode 100644index 2fdad1a8..00000000--- a/packages/web/src/components/account/upload-limits-dialog.tsx+++ /dev/null@@ -1,160 +0,0 @@-/**- * Admin upload-limits dialog (server-global), opened from the sidebar user menu next to the- * proxy options it is modelled on. Two whole-MB numbers — the per-file attachment cap and the- * per-message total — written together by a single PUT to /api/admin/settings, so a rejected- * value writes nothing.- *- * The bounds and the fixed limits quoted in the hint come from the server (`/api/me`- * uploadLimits) rather than from constants here: the range is a statement about what the server- * can survive, and a second copy of it in the browser would be a copy that goes stale. A value- * outside it is refused by the server with `invalid_attachment_limit` and rendered inline under- * the field, the same way the proxy dialog handles a bad address.- *- * Saving takes effect immediately — the attachment validators and the request body cap both read- * the setting per request — so there is nothing to restart and nothing to warn about.- */-import { useEffect, useState } from "react";-import type { ServerSettings } from "@prismshadow/penguin-server/api";-import * as api from "../../api/endpoints";-import { ApiError } from "../../api/client";-import { S } from "../../lib/strings";-import { apiErrorText } from "../../lib/api-error";-import { useAuth } from "../../state/auth";-import { Button } from "../ui/button";-import { Input } from "../ui/input";-import { Modal } from "../ui/modal";-import { toastError, toastInfo, toastSuccess } from "../ui/toast";--export function UploadLimitsDialog({ open, onClose }: { open: boolean; onClose: () => void }) {- const { uploadLimits, refresh } = useAuth();- /** Stored settings as hydrated on open (null until then) — the no-change baseline. */- const [settings, setSettings] = useState<ServerSettings | null>(null);- // Kept as strings: a number input that clears to NaN cannot be typed into (backspacing the- // last digit would snap the field back to a value the user is in the middle of replacing).- const [maxMb, setMaxMb] = useState("");- const [totalMb, setTotalMb] = useState("");- /** Inline error under whichever field the server rejected. */- const [limitError, setLimitError] = useState<string | null>(null);- const [busy, setBusy] = useState(false);-- useEffect(() => {- if (!open) return;- let cancelled = false;- setSettings(null);- setLimitError(null);- setBusy(false);- void api- .adminGetSettings()- .then((res) => {- if (cancelled) return;- setSettings(res.settings);- setMaxMb(String(res.settings.attachmentMaxMb));- setTotalMb(String(res.settings.attachmentTotalMb));- })- .catch((e: unknown) => {- // Controls stay disabled; closing and reopening retries the fetch.- if (!cancelled) toastError(apiErrorText(e));- });- return () => {- cancelled = true;- };- }, [open]);-- const save = async () => {- if (settings === null || busy) return;- const parsedMax = Number(maxMb.trim());- const parsedTotal = Number(totalMb.trim());- // Shape-check locally so an empty or non-numeric field never becomes a NaN in the request- // body; the RANGE is left to the server, which owns it (this dialog only reports its verdict).- if (- maxMb.trim() === "" ||- totalMb.trim() === "" ||- !Number.isInteger(parsedMax) ||- !Number.isInteger(parsedTotal)- ) {- setLimitError(S.errors.byCode.invalid_attachment_limit);- return;- }- if (parsedMax === settings.attachmentMaxMb && parsedTotal === settings.attachmentTotalMb) {- toastInfo(S.common.noChangesToSave);- return;- }- setBusy(true);- setLimitError(null);- try {- await api.adminPutSettings({ attachmentMaxMb: parsedMax, attachmentTotalMb: parsedTotal });- // The composer reads the limits from /api/me, so re-pull them: without this the tab that- // just raised the cap would keep refusing files at the old number until the next reload.- await refresh().catch(() => {});- toastSuccess(S.common.saved);- onClose();- } catch (e) {- if (e instanceof ApiError && e.code === "invalid_attachment_limit") {- setLimitError(apiErrorText(e));- } else {- toastError(apiErrorText(e));- }- } finally {- setBusy(false);- }- };-- const hydrated = settings !== null;- return (- <Modal- open={open}- title={S.settings.uploadLimitsDialogTitle}- onClose={onClose}- footer={- <>- <Button onClick={onClose} disabled={busy}>- {S.common.cancel}- </Button>- <Button variant="primary" disabled={!hydrated || busy} onClick={() => void save()}>- {S.common.save}- </Button>- </>- }- >- <div className="space-y-4">- <Input- label={S.settings.attachmentMaxMb}- size="sm"- type="number"- inputMode="numeric"- min={uploadLimits.attachmentLimitMinMb}- max={uploadLimits.attachmentLimitMaxMb}- value={maxMb}- disabled={!hydrated}- onChange={(e) => {- setMaxMb(e.target.value);- if (limitError !== null) setLimitError(null);- }}- />- <Input- label={S.settings.attachmentTotalMb}- size="sm"- type="number"- inputMode="numeric"- min={uploadLimits.attachmentLimitMinMb}- max={uploadLimits.attachmentLimitMaxMb}- value={totalMb}- disabled={!hydrated}- {...(limitError !== null ? { error: limitError } : {})}- onChange={(e) => {- setTotalMb(e.target.value);- if (limitError !== null) setLimitError(null);- }}- />- <p className="text-xs text-gray-500 dark:text-gray-400">- {S.settings.uploadLimitsHint(- uploadLimits.attachmentLimitMinMb,- uploadLimits.attachmentLimitMaxMb,- uploadLimits.attachmentMaxCount,- uploadLimits.imageMaxMb,- )}- </p>- </div>- </Modal>- );-}diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex 6bf479f9..728eec46 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -15,7 +15,7 @@* trailing slot shows the compact last-active time at rest and swaps to archive + delete* icon buttons on hover/focus; the full set (pin, rename, archive, delete) opens as a* context menu on right-click, Shift+F10, or a press-and-hold on touch- * -> bottom user config (theme / language / logout).+ * -> bottom user config (theme / language / System settings / logout).* Desktop keeps it pinned as the left column; mobile puts the whole thing in a drawer.* New chats always enter draft state (/chat/new, route state specifies the Agent and optionally* the Workspace): Model / Workspace / approval mode are all chosen on the draft input card, so@@ -32,17 +32,13 @@ import type {} from "@prismshadow/penguin-server/api";import * as api from "../../api/endpoints";import { S } from "../../lib/strings";-import { formatMonthDay, formatRelativeShort } from "../../lib/format";+import { formatRelativeShort } from "../../lib/format";import { sessionRowActivity } from "../../lib/session-activity";import type { SessionActivity } from "../../lib/session-activity";import { forgetSession, noteSessionSeen, useSessionSeen } from "../../lib/session-seen";import { apiErrorText } from "../../lib/api-error";-import { offersChangePassword } from "../../lib/account-menu";import { useAuth } from "../../state/auth";import { useLocale } from "../../state/locale";-import type { LangPref } from "../../state/locale";-import { ACCENT_SWATCHES, useTheme } from "../../state/theme";-import type { Accent, Currency, FontScale, TerminalThemeMode, ThemeMode } from "../../state/theme";import { agentDisplayName, projectDisplayName, useProject } from "../../state/project";import { useSessions } from "../../state/sessions";import {@@ -90,7 +86,6 @@ import {storeSessionSortMode,} from "../../lib/session-order";import type { SessionSortMode } from "../../lib/session-order";-import { Switch } from "../ui/switch";import { Dropdown } from "../ui/dropdown";import { useRowContextMenu } from "../ui/context-menu";import {@@ -122,7 +117,7 @@ import {storeGroupMode,} from "../ui/group-list";import type { GroupMode } from "../ui/group-list";-import { toastError, toastInfo, toastSuccess } from "../ui/toast";+import { toastError } from "../ui/toast";import { Truncated } from "../ui/truncated";import { Badge } from "../ui/badge";import { SessionActivityIcon } from "../ui/session-activity-icon";@@ -130,7 +125,6 @@ import { Modal } from "../ui/modal";import { ConfirmModal } from "../ui/confirm-modal";import { Button } from "../ui/button";import { Input, noAutofill } from "../ui/input";-import { Segmented } from "../ui/segmented";import { SkeletonList } from "../ui/skeleton";import { DRAFT_SESSION_ID } from "../../features/chat/chat-page";import { WorkspaceSelect } from "../../features/chat/workspace-select";@@ -143,11 +137,9 @@ import {} from "../../features/chat/draft-sessions";import type { DraftSessionEntry } from "../../features/chat/draft-sessions";import { CreateProjectDialog, ProjectSettingsDialog } from "./project-dialogs";-import { ChangePasswordDialog } from "../account/change-password-dialog";-import { ProxySettingsDialog } from "../account/proxy-settings-dialog";-import { UploadLimitsDialog } from "../account/upload-limits-dialog";-import { UpdateDialog } from "../account/update-dialog";-import { forceUpdateCheck, updateCheckOutcome, useVersionInfo } from "../../lib/use-version-info";+import { useVersionInfo } from "../../lib/use-version-info";+import { SettingsDialog } from "../../features/settings/settings-dialog";+import type { SettingsSectionKey } from "../../lib/settings-sections";import { ICON_SIZE } from "../../lib/icon-scale";/** New-chat pencil (the pinned "New chat" button and the collapsed rail share it). */@@ -287,20 +279,8 @@ export function Sidebar({onCollapse?: () => void;}) {const navigate = useNavigate();- const { user, logout, desktopMode, sessionVia } = useAuth();- const {- mode,- setMode,- fontScale,- setFontScale,- accent,- setAccent,- currency,- setCurrency,- terminalMode,- setTerminalMode,- } = useTheme();- const { lang, locale, setLang } = useLocale();+ const { user, logout, desktopMode } = useAuth();+ const { locale } = useLocale();const {projects,currentProject,@@ -321,8 +301,6 @@ export function Sidebar({loading,remove,replace,- showCliSessions,- setShowCliSessions,} = useSessions();const chatMatch = useMatch("/chat/:sessionId");const activeSessionId = chatMatch?.params.sessionId ?? null;@@ -331,10 +309,11 @@ export function Sidebar({const [userOpen, setUserOpen] = useState(false);const [createProjectOpen, setCreateProjectOpen] = useState(false);const [projectSettingsOpen, setProjectSettingsOpen] = useState(false);- const [changePasswordOpen, setChangePasswordOpen] = useState(false);- const [updateDialogOpen, setUpdateDialogOpen] = useState(false);- // Version row + update reminder: nothing is fetched until the dropdown first opens.- const { version, update } = useVersionInfo(userOpen);+ const [settingsOpen, setSettingsOpen] = useState(false);+ /** Page the settings dialog lands on: the update reminder row jumps straight to Updates. */+ const [settingsSection, setSettingsSection] = useState<SettingsSectionKey>("general");+ // Update reminder: nothing is fetched until the dropdown first opens.+ const { update } = useVersionInfo(userOpen);const updateAvailable = update?.updateAvailable === true;/*** The newer release's version string, or null while none is known — the single update row's@@ -343,47 +322,6 @@ export function Sidebar({* than rendering a versionless reminder.*/const newVersion = updateAvailable ? (update?.latestVersion ?? null) : null;- // The running version's release date, stamped into core's BUILD_DATE at build time by- // the release workflow — displayed as-is, no network involved. Dev builds and releases- // that predate the stamping (v0.1.2 and earlier) carry null. Shown as the localized- // "last updated" tooltip on the check-for-updates row (the row itself stays uncluttered).- const versionDate = version?.buildDate ?? null;- /** Manual "check for updates" in flight (row disabled, busy label). */- const [updateChecking, setUpdateChecking] = useState(false);- /**- * Manual update check (owner request): forces a lookup past the server's TTL cache and- * pushes the result into the shared version-info store, so the reminder rows, badge,- * and dot appear immediately when a newer release is found. Every outcome also toasts —- * up to date, found (naming the release; the row below turns into the update entry),- * checks disabled, and a failed lookup (the check is fail-soft — failure arrives as the- * `error` field, not an exception; the catch handles our own server being unreachable).- */- const runUpdateCheck = async () => {- if (updateChecking) return;- setUpdateChecking(true);- try {- const outcome = updateCheckOutcome(await forceUpdateCheck());- if (outcome.kind === "disabled") toastInfo(S.update.checkDisabled);- else if (outcome.kind === "failed") toastError(S.update.checkFailed);- else if (outcome.kind === "found") toastSuccess(S.update.foundNew(outcome.latestVersion));- else toastSuccess(S.update.upToDate);- } catch (e) {- toastError(apiErrorText(e));- } finally {- setUpdateChecking(false);- }- };- /**- * Admin-only server-global proxy settings dialog: the menu carries only the opener- * row; the controls, their form semantics, and the open-time hydration all live in- * ProxySettingsDialog.- */- const [proxySettingsOpen, setProxySettingsOpen] = useState(false);- /**- * Admin-only server-global upload limits, alongside the proxy row and built the same way:- * the menu carries the opener, the form and its hydration live in UploadLimitsDialog.- */- const [uploadLimitsOpen, setUploadLimitsOpen] = useState(false);const currentProjectId = currentProject?.projectId ?? null;/** This Project's read markers; re-renders the rows whenever one is stamped. */const sessionSeen = useSessionSeen(currentProjectId);@@ -1129,33 +1067,6 @@ export function Sidebar({(key) => ({ to: `/${key}`, label: S.nav[key], icon: NAV_ICONS[key] }),);- const themeOptions: ReadonlyArray<{ value: ThemeMode; label: string }> = [- { value: "light", label: S.settings.themeLight },- { value: "dark", label: S.settings.themeDark },- { value: "system", label: S.settings.followSystem },- ];- const langOptions: ReadonlyArray<{ value: LangPref; label: string }> = [- { value: "en", label: S.settings.langEn },- { value: "zh", label: S.settings.langZh },- { value: "system", label: S.settings.followSystem },- ];- // The terminal keeps its own light/dark rather than inheriting the app's — see- // TerminalThemeMode. "跟随主题" is the opt-in that couples them.- const terminalThemeOptions: ReadonlyArray<{ value: TerminalThemeMode; label: string }> = [- { value: "light", label: S.settings.themeLight },- { value: "dark", label: S.settings.themeDark },- { value: "app", label: S.settings.followAppTheme },- ];- const fontOptions: ReadonlyArray<{ value: FontScale; label: string }> = [- { value: "sm", label: S.settings.fontSmall },- { value: "md", label: S.settings.fontMedium },- { value: "lg", label: S.settings.fontLarge },- ];- const currencyOptions: ReadonlyArray<{ value: Currency; label: string }> = [- { value: "USD", label: S.models.currencyUsd },- { value: "CNY", label: S.models.currencyCny },- ];-return (<div className="flex h-full w-full flex-col">{/* Project switcher (+ collapse sidebar) */}@@ -1756,162 +1667,37 @@ export function Sidebar({</button>}>- <div className="space-y-2.5 px-3 py-2">- <SettingRow label={S.settings.theme}>- <Segmented options={themeOptions} value={mode} onChange={setMode} />- </SettingRow>- <SettingRow label={S.settings.terminalTheme}>- <Segmented- options={terminalThemeOptions}- value={terminalMode}- onChange={setTerminalMode}- />- </SettingRow>- <SettingRow label={S.settings.fontSize}>- <Segmented options={fontOptions} value={fontScale} onChange={setFontScale} />- </SettingRow>- <SettingRow label={S.settings.accent}>- <AccentPicker value={accent} onChange={setAccent} />- </SettingRow>- <SettingRow label={S.models.currency}>- <Segmented- options={currencyOptions}- value={currency}- onChange={setCurrency}- cols={2}- />- </SettingRow>- <SettingRow label={S.settings.language}>- <Segmented options={langOptions} value={lang} onChange={setLang} />- </SettingRow>- {/* Off (default) = the sidebar lists only web-created Sessions, served straight- from the DB; on = CLI Sessions are discovered from the Trace directory too. */}- <SettingRow label={S.settings.showCliSessions}>- <Switch checked={showCliSessions} onChange={setShowCliSessions} />- </SettingRow>- </div>- <div className="mt-1 border-t border-gray-100 pt-1 dark:border-gray-800">- {/* Hidden in the desktop shell's own window: it signs in through the shell's- one-shot token rather than a login form, and the seed password of a- desktop-created root is fully random and never printed — there is no- password its holder has seen, or needs. Deliberately NOT keyed on- desktopMode alone: a browser signed into the same desktop-mode server over- loopback holds a password session that can, and still does, change it.- See offersChangePassword for the full rule. */}- {offersChangePassword({ desktopMode, sessionVia }) && (- <button- type="button"- className={menuItemClass}- onClick={() => {- setUserOpen(false);- setChangePasswordOpen(true);- }}- >- {S.account.changePassword}- </button>- )}- {/* Admin-only, server-global proxy settings: one menu row opening the- dialog (same idiom as Change password above) — the switch, address- input and their live-save semantics live in ProxySettingsDialog. */}- {user?.isAdmin && (- <button- type="button"- className={menuItemClass}- onClick={() => {- setUserOpen(false);- setProxySettingsOpen(true);- }}- >- {S.settings.proxyMenu}- </button>- )}- {/* Admin-only, server-global upload limits: same one-row idiom as the proxy- opener above. */}- {user?.isAdmin && (- <button- type="button"- className={menuItemClass}- onClick={() => {- setUserOpen(false);- setUploadLimitsOpen(true);- }}- >- {S.settings.uploadLimitsMenu}- </button>- )}- {/* THE update row — one button, two jobs, directly below Change password (owner- layout: the menu used to stack a release-notes link, an admin "Update now" row- and this check row on top of each other). It reads "Check for updates" and runs- the manual check until a newer release is known; from then on it reads "New- version vX available" with a leading accent dot and opens the update dialog- instead, which carries the release-notes link and the admin-only self-update.- The running version sits muted on the right — no product-name prefix, and no- superscript badge any more: the label itself already names the new version.- The "last updated" date lives in the row tooltip, keeping the row uncluttered.- While checking, the label swaps to the busy text and the version stays put.- Nothing is fetched until the menu first opens; the version span appears once- /api/version resolves. */}- {/* Hidden in desktop mode: updates are the desktop app's job (electron-updater),- and the dialog's admin self-update re-runs the CLI entry, which does not- exist under the desktop shell. */}- {!desktopMode && (- <button- type="button"- disabled={updateChecking}- onClick={() => {- if (newVersion !== null) {- setUserOpen(false);- setUpdateDialogOpen(true);- } else {- void runUpdateCheck();- }- }}- {...(versionDate !== null- ? { title: S.update.lastUpdated(formatMonthDay(versionDate, locale)) }- : {})}- className={`${menuItemClass} flex items-center justify-between gap-2 disabled:cursor-default disabled:opacity-60`}- >- <span className="flex min-w-0 items-center gap-2">- {updateChecking && (- <span- aria-hidden- className="inline-block h-3 w-3 shrink-0 animate-spin rounded-full border-[1.5px] border-current border-t-transparent opacity-70"- />- )}- {!updateChecking && newVersion !== null && (- <span- aria-hidden- className="h-2 w-2 shrink-0 rounded-full bg-[var(--accent-bg)]"- />- )}- <span className="min-w-0 truncate">- {updateChecking- ? S.update.checking- : newVersion !== null- ? S.update.newVersion(newVersion)- : S.update.checkNow}- </span>- </span>- {version !== null && (- <span className="shrink-0 text-xs text-gray-400 dark:text-gray-500">- {`v${version.version}`}- </span>- )}- </button>- )}- {/* User management is visible only to admins (the page route also has its own- guard as a fallback), and never in desktop mode: the desktop app is- single-user and the server rejects the routes (desktop_single_user). */}- {user?.isAdmin && !desktopMode && (+ <div className="py-1">+ {/* System settings dialog: everyone gets the row — the dialog always has the+ personal pages, and the server-global ones inside it stay gated by the+ section registry rather than by this row. The preference rows that used to+ stack here live on its pages now. */}+ <button+ type="button"+ className={menuItemClass}+ onClick={() => {+ setUserOpen(false);+ setSettingsSection("general");+ setSettingsOpen(true);+ }}+ >+ {S.settings.systemSettings}+ </button>+ {/* Update reminder row: only once the lazy check (menu open) has found a newer+ release. Opens the dialog straight on its Updates page; the manual check+ lives there too. Desktop mode never checks — updating is the shell's job. */}+ {!desktopMode && newVersion !== null && (<buttontype="button"- className={menuItemClass}+ className={`${menuItemClass} flex items-center gap-2`}onClick={() => {setUserOpen(false);- go("/admin/users");+ setSettingsSection("updates");+ setSettingsOpen(true);}}>- {S.admin.users}+ <span aria-hidden className="h-2 w-2 shrink-0 rounded-full bg-[var(--accent-bg)]" />+ <span className="min-w-0 truncate">{S.update.newVersion(newVersion)}</span></button>)}{/* Hidden in desktop mode: the window IS the session — logging out would@@ -1932,24 +1718,10 @@ export function Sidebar({</Dropdown></div>- <ChangePasswordDialog- open={changePasswordOpen}- onClose={() => setChangePasswordOpen(false)}- />- <ProxySettingsDialog open={proxySettingsOpen} onClose={() => setProxySettingsOpen(false)} />- <UploadLimitsDialog open={uploadLimitsOpen} onClose={() => setUploadLimitsOpen(false)} />- <UpdateDialog- open={updateDialogOpen}- onClose={() => setUpdateDialogOpen(false)}- latestVersion={newVersion}- releaseUrl={update?.releaseUrl ?? null}- canUpdate={user?.isAdmin === true}- /* A finished self-update makes the reminder stale, and the row stops offering the- manual check while a newer release is known — so re-check here, or the row would- still read "New version vX available" after updating to exactly that version, with- no way back short of reloading the page. Silent: the row's own change is the- feedback, and a toast would fire while the user is closing the dialog. */- onRunFinished={() => void forceUpdateCheck().catch(() => undefined)}+ <SettingsDialog+ open={settingsOpen}+ onClose={() => setSettingsOpen(false)}+ initialSection={settingsSection}/><CreateProjectDialog@@ -2489,36 +2261,3 @@ function MenuRadioRow({</button>);}--function SettingRow({ label, children }: { label: string; children: ReactNode }) {- return (- <div>- <p className="mb-1 text-[11px] font-medium text-gray-500 dark:text-gray-400">{label}</p>- {children}- </div>- );-}--/** Accent color picker: a row of swatches, with a ring on the selected one. */-function AccentPicker({ value, onChange }: { value: Accent; onChange: (a: Accent) => void }) {- return (- <div className="flex items-center gap-1.5">- {ACCENT_SWATCHES.map((s) => (- <button- key={s.value}- type="button"- title={S.settings.accentNames[s.value]}- aria-label={S.settings.accentNames[s.value]}- aria-pressed={value === s.value}- onClick={() => onChange(s.value)}- className={`h-5 w-5 rounded-full border transition-transform duration-150 hover:scale-110 ${- value === s.value- ? "border-gray-500 ring-2 ring-gray-400/50 dark:border-gray-300"- : "border-transparent"- }`}- style={{ backgroundColor: s.color }}- />- ))}- </div>- );-}diff --git a/packages/web/src/components/ui/modal.tsx b/packages/web/src/components/ui/modal.tsxindex 0a0fede8..cfc27e31 100644--- a/packages/web/src/components/ui/modal.tsx+++ b/packages/web/src/components/ui/modal.tsx@@ -27,6 +27,8 @@ export interface ModalProps {widthClass?: string;/** No header bar (no visible title, no close button): compact dialogs like confirmations — the title still names the dialog for assistive tech. */headerless?: boolean;+ /** Render children full-bleed: no built-in padding or 70vh scroller. For dialogs that own their inner layout and scroll regions (PagedDialog); the caller then also owns a close control. */+ bare?: boolean;}/**@@ -67,6 +69,7 @@ export function Modal({footer,widthClass,headerless,+ bare,}: ModalProps) {useEffect(() => {if (!open) return;@@ -99,7 +102,7 @@ export function Modal({<CloseButton onClose={onClose} /></div>)}- <div className="max-h-[70vh] overflow-y-auto px-4 py-4">{children}</div>+ {bare ? children : <div className="max-h-[70vh] overflow-y-auto px-4 py-4">{children}</div>}{footer && (<div className="flex justify-end gap-2 border-t border-gray-200 px-4 py-3 dark:border-gray-800">{footer}diff --git a/packages/web/src/components/ui/paged-dialog.tsx b/packages/web/src/components/ui/paged-dialog.tsxnew file mode 100644index 00000000..4346fdc7--- /dev/null+++ b/packages/web/src/components/ui/paged-dialog.tsx@@ -0,0 +1,110 @@+/**+ * PagedDialog: a large modal whose left rail switches sub-pages — the shared shell for+ * multi-page settings surfaces (System settings today; Project settings converges on the+ * same shell). Purely presentational: the caller owns which pages exist, which one is+ * active, and what the pane renders; the shell draws the rail (grouped, icon + label,+ * solid-fill active row — the sidebar's convention), the pane heading, and the close+ * control.+ *+ * Built on Modal, so it inherits the portal, the Escape layer stack (nested dialogs and+ * menus close in visual order) and the bottom-sheet posture on narrow screens — where the+ * rail folds into a horizontal scroller above the pane and group headings are dropped+ * along with the second dimension (Tabs' convention).+ */+import type { ReactNode } from "react";+import { Modal } from "./modal";+import { CloseButton } from "./icons";++export interface PagedDialogItem<K extends string> {+ key: K;+ label: string;+ /** Small leading glyph in the rail; sized by the caller (16px reads well). */+ icon?: ReactNode;+}++export interface PagedDialogGroup<K extends string> {+ key: string;+ /** Rail heading; omitted entirely when the dialog has a single group (a lone heading implies a second). */+ label?: string;+ items: ReadonlyArray<PagedDialogItem<K>>;+}++/** Rail entry: solid gray fill when active, gray hover otherwise (the sidebar's convention). */+const railItemClass = (active: boolean) =>+ `flex w-full items-center gap-2 whitespace-nowrap rounded-md px-2.5 py-1.5 text-sm transition-colors duration-150 ${+ active+ ? "bg-gray-200/70 font-medium text-gray-900 dark:bg-gray-800 dark:text-gray-100"+ : "text-gray-600 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-400 dark:hover:bg-gray-800/70 dark:hover:text-gray-200"+ }`;++export function PagedDialog<K extends string>({+ open,+ onClose,+ title,+ groups,+ active,+ onSelect,+ children,+}: {+ open: boolean;+ onClose: () => void;+ /** Dialog name for assistive tech; the visible heading is the active page's label. */+ title: string;+ groups: ReadonlyArray<PagedDialogGroup<K>>;+ active: K;+ onSelect: (key: K) => void;+ /** The active page's content. */+ children: ReactNode;+}) {+ const showGroupHeadings = groups.length > 1;+ const activeLabel =+ groups.flatMap((g) => g.items).find((item) => item.key === active)?.label ?? title;++ return (+ <Modal open={open} onClose={onClose} title={title} headerless bare widthClass="sm:max-w-3xl">+ <div className="flex h-[min(40rem,85vh)] flex-col sm:flex-row">+ {/* Rail: vertical on desktop, a horizontal scroller above the pane on narrow screens. */}+ <nav+ aria-label={title}+ className="flex shrink-0 gap-1 overflow-x-auto border-b border-gray-100 p-2 sm:w-44 sm:flex-col sm:overflow-x-visible sm:overflow-y-auto sm:border-b-0 sm:border-r sm:p-3 dark:border-gray-800"+ >+ {groups.map((group) => (+ <div key={group.key} className="contents sm:mt-3 sm:block sm:first:mt-0">+ {showGroupHeadings && group.label !== undefined && (+ <p className="hidden px-2.5 pb-1 text-[11px] font-medium uppercase tracking-wide text-gray-400 sm:block dark:text-gray-500">+ {group.label}+ </p>+ )}+ {group.items.map((item) => (+ <button+ key={item.key}+ type="button"+ className={railItemClass(item.key === active)}+ aria-current={item.key === active ? "page" : undefined}+ onClick={() => onSelect(item.key)}+ >+ {item.icon !== undefined && (+ <span aria-hidden className="shrink-0 text-gray-400 dark:text-gray-500">+ {item.icon}+ </span>+ )}+ <span className="min-w-0 truncate">{item.label}</span>+ </button>+ ))}+ </div>+ ))}+ </nav>++ <div className="flex min-w-0 flex-1 flex-col">+ <div className="flex shrink-0 items-center justify-between gap-2 px-4 pt-4 sm:px-6 sm:pt-5">+ <h2 className="text-lg font-semibold">{activeLabel}</h2>+ <CloseButton onClose={onClose} />+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto px-4 pb-4 pt-3 sm:px-6 sm:pb-6">+ {children}+ </div>+ </div>+ </div>+ </Modal>+ );+}diff --git a/packages/web/src/features/admin/admin-users-page.tsx b/packages/web/src/features/admin/admin-users-page.tsxindex 2a291e06..4d1eda00 100644--- a/packages/web/src/features/admin/admin-users-page.tsx+++ b/packages/web/src/features/admin/admin-users-page.tsx@@ -1,11 +1,11 @@/**- * User management page (admin only): user list + create / reset password / delete.+ * User management (admin only): user list + create / reset password / delete. Rendered as+ * a page of the System settings dialog rather than a routed page of its own.* Registration is closed: new users are created here, with the initial password set by the admin and* communicated offline; deleting a user also deletes all their Projects (including data directories),* with a confirmation dialog.*/import { useCallback, useEffect, useState } from "react";-import { Navigate } from "react-router";import type { UserInfo } from "@prismshadow/penguin-server/api";import * as api from "../../api/endpoints";import { ApiError } from "../../api/client";@@ -13,7 +13,6 @@ import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";import { USERNAME_PATTERN } from "../../lib/semantic-id";import { formatDateTime } from "../../lib/format";-import { useDocumentTitle } from "../../lib/use-document-title";import { useAuth } from "../../state/auth";import { Badge } from "../../components/ui/badge";import { Button } from "../../components/ui/button";@@ -21,8 +20,7 @@ import { Input } from "../../components/ui/input";import { PasswordInput } from "../../components/ui/password-input";import { Modal } from "../../components/ui/modal";-export function AdminUsersPage() {- useDocumentTitle(S.admin.users);+export function AdminUsersSection() {const { user, desktopMode } = useAuth();const [users, setUsers] = useState<UserInfo[] | null>(null);const [listError, setListError] = useState<string | null>(null);@@ -43,71 +41,68 @@ export function AdminUsersPage() {if (user?.isAdmin && !desktopMode) void reload();}, [user?.isAdmin, desktopMode, reload]);- // Route guard fallback: non-admins are redirected back to the chat page (the sidebar has- // no entry point anyway); same for desktop mode, where the app is single-user and the- // server rejects the admin-user routes (desktop_single_user).- if (user && (!user.isAdmin || desktopMode)) return <Navigate to="/chat" replace />;+ // Registry guard fallback: the settings dialog never offers this page to non-admins or+ // in desktop mode (where the server rejects the admin-user routes, desktop_single_user);+ // render nothing rather than half a surface if reached anyway.+ if (user && (!user.isAdmin || desktopMode)) return null;return (- <div className="h-full overflow-y-auto p-4 md:p-6">- <div className="mx-auto max-w-3xl">- <div className="mb-4 flex items-center justify-between">- <h1 className="text-xl font-semibold">{S.admin.users}</h1>- <Button variant="primary" onClick={() => setCreateOpen(true)}>- {S.admin.createUser}- </Button>- </div>+ <div>+ <div className="mb-4 flex justify-end">+ <Button variant="primary" onClick={() => setCreateOpen(true)}>+ {S.admin.createUser}+ </Button>+ </div>- {users === null ? (- <p className="text-sm text-gray-400">{S.common.loading}</p>- ) : (- <div className="overflow-x-auto rounded-lg border border-gray-200 dark:border-gray-800">- <table className="w-full text-sm">- <thead>- <tr className="border-b border-gray-100 bg-gray-50 text-left text-xs text-gray-500 dark:border-gray-800 dark:bg-gray-900/60 dark:text-gray-400">- <th className="whitespace-nowrap px-3 py-2 font-medium">{S.common.username}</th>- <th className="whitespace-nowrap px-3 py-2 font-medium">{S.common.role}</th>- <th className="whitespace-nowrap px-3 py-2 font-medium">{S.common.created}</th>- <th className="whitespace-nowrap px-3 py-2 text-right font-medium">- {S.common.actions}- </th>- </tr>- </thead>- <tbody className="divide-y divide-gray-100 dark:divide-gray-800/60">- {users.map((u) => (- <tr key={u.userId}>- <td className="whitespace-nowrap px-3 py-2 font-medium">- {u.userId}- {u.passwordIsInitial && (- <span className="ml-2 align-middle">- <Badge tone="gray">{S.admin.initialPasswordFlag}</Badge>- </span>- )}- </td>- <td className="whitespace-nowrap px-3 py-2">- <Badge tone="gray">{u.isAdmin ? S.admin.roleAdmin : S.admin.roleUser}</Badge>- </td>- <td className="whitespace-nowrap px-3 py-2 text-gray-500 dark:text-gray-400">- {formatDateTime(u.createdAt)}- </td>- <td className="whitespace-nowrap px-3 py-1.5 text-right">- <Button size="sm" variant="ghost" onClick={() => setResetting(u)}>- {S.admin.resetPassword}+ {users === null ? (+ <p className="text-sm text-gray-400">{S.common.loading}</p>+ ) : (+ <div className="overflow-x-auto rounded-lg border border-gray-200 dark:border-gray-800">+ <table className="w-full text-sm">+ <thead>+ <tr className="border-b border-gray-100 bg-gray-50 text-left text-xs text-gray-500 dark:border-gray-800 dark:bg-gray-900/60 dark:text-gray-400">+ <th className="whitespace-nowrap px-3 py-2 font-medium">{S.common.username}</th>+ <th className="whitespace-nowrap px-3 py-2 font-medium">{S.common.role}</th>+ <th className="whitespace-nowrap px-3 py-2 font-medium">{S.common.created}</th>+ <th className="whitespace-nowrap px-3 py-2 text-right font-medium">+ {S.common.actions}+ </th>+ </tr>+ </thead>+ <tbody className="divide-y divide-gray-100 dark:divide-gray-800/60">+ {users.map((u) => (+ <tr key={u.userId}>+ <td className="whitespace-nowrap px-3 py-2 font-medium">+ {u.userId}+ {u.passwordIsInitial && (+ <span className="ml-2 align-middle">+ <Badge tone="gray">{S.admin.initialPasswordFlag}</Badge>+ </span>+ )}+ </td>+ <td className="whitespace-nowrap px-3 py-2">+ <Badge tone="gray">{u.isAdmin ? S.admin.roleAdmin : S.admin.roleUser}</Badge>+ </td>+ <td className="whitespace-nowrap px-3 py-2 text-gray-500 dark:text-gray-400">+ {formatDateTime(u.createdAt)}+ </td>+ <td className="whitespace-nowrap px-3 py-1.5 text-right">+ <Button size="sm" variant="ghost" onClick={() => setResetting(u)}>+ {S.admin.resetPassword}+ </Button>+ {!u.isAdmin && (+ <Button size="sm" variant="ghost" onClick={() => setDeleting(u)}>+ {S.common.delete}</Button>- {!u.isAdmin && (- <Button size="sm" variant="ghost" onClick={() => setDeleting(u)}>- {S.common.delete}- </Button>- )}- </td>- </tr>- ))}- </tbody>- </table>- </div>- )}- {listError && <p className="mt-2 text-xs text-red-600 dark:text-red-400">{listError}</p>}- </div>+ )}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}+ {listError && <p className="mt-2 text-xs text-red-600 dark:text-red-400">{listError}</p>}<CreateUserDialogopen={createOpen}diff --git a/packages/web/src/features/settings/account-section.tsx b/packages/web/src/features/settings/account-section.tsxnew file mode 100644index 00000000..df5f8cf0--- /dev/null+++ b/packages/web/src/features/settings/account-section.tsx@@ -0,0 +1,28 @@+/**+ * Account page of System settings: the credentials the signed-in account can change. Only+ * mounted where a password exists to change — the desktop shell's own window signs in+ * through a one-shot token and is filtered out by the section registry (see+ * offersChangePassword for the full rule).+ */+import { useState } from "react";+import { S } from "../../lib/strings";+import { Button } from "../../components/ui/button";+import { ChangePasswordDialog } from "../../components/account/change-password-dialog";+import { PrefRow } from "./setting-row";++export function AccountSection() {+ const [changePasswordOpen, setChangePasswordOpen] = useState(false);+ return (+ <div className="divide-y divide-gray-100 dark:divide-gray-800/60">+ <PrefRow label={S.account.changePassword} hint={S.settings.changePasswordHint}>+ <Button variant="secondary" onClick={() => setChangePasswordOpen(true)}>+ {S.account.changePassword}+ </Button>+ </PrefRow>+ <ChangePasswordDialog+ open={changePasswordOpen}+ onClose={() => setChangePasswordOpen(false)}+ />+ </div>+ );+}diff --git a/packages/web/src/features/settings/appearance-section.tsx b/packages/web/src/features/settings/appearance-section.tsxnew file mode 100644index 00000000..bf4ad1ce--- /dev/null+++ b/packages/web/src/features/settings/appearance-section.tsx@@ -0,0 +1,59 @@+/**+ * Appearance page: the look-and-feel preferences that used to sit as rows in the sidebar+ * user menu. Everything applies on the spot (the theme store persists per browser), so+ * there is no Save button. The terminal keeps its own theme row because plenty of people+ * pin a dark terminal inside a light app; it follows the app unless pinned (see+ * TerminalThemeMode).+ */+import { S } from "../../lib/strings";+import { Segmented } from "../../components/ui/segmented";+import { useTheme } from "../../state/theme";+import type { FontScale, TerminalThemeMode, ThemeMode } from "../../state/theme";+import { AccentPicker, PrefRow } from "./setting-row";++export function AppearanceSection() {+ const {+ mode,+ setMode,+ fontScale,+ setFontScale,+ accent,+ setAccent,+ terminalMode,+ setTerminalMode,+ } = useTheme();++ const themeOptions: ReadonlyArray<{ value: ThemeMode; label: string }> = [+ { value: "light", label: S.settings.themeLight },+ { value: "dark", label: S.settings.themeDark },+ { value: "system", label: S.settings.followSystem },+ ];+ // Follow-the-app first: it is the default, and the pinned modes are the opt-out.+ const terminalThemeOptions: ReadonlyArray<{ value: TerminalThemeMode; label: string }> = [+ { value: "app", label: S.settings.followAppTheme },+ { value: "light", label: S.settings.themeLight },+ { value: "dark", label: S.settings.themeDark },+ ];+ const fontOptions: ReadonlyArray<{ value: FontScale; label: string }> = [+ { value: "sm", label: S.settings.fontSmall },+ { value: "md", label: S.settings.fontMedium },+ { value: "lg", label: S.settings.fontLarge },+ ];++ return (+ <div className="divide-y divide-gray-100 dark:divide-gray-800/60">+ <PrefRow label={S.settings.theme} hint={S.settings.themeHint}>+ <Segmented options={themeOptions} value={mode} onChange={setMode} />+ </PrefRow>+ <PrefRow label={S.settings.terminalTheme} hint={S.settings.terminalThemeHint}>+ <Segmented options={terminalThemeOptions} value={terminalMode} onChange={setTerminalMode} />+ </PrefRow>+ <PrefRow label={S.settings.fontSize} hint={S.settings.fontSizeHint}>+ <Segmented options={fontOptions} value={fontScale} onChange={setFontScale} />+ </PrefRow>+ <PrefRow label={S.settings.accent} hint={S.settings.accentHint}>+ <AccentPicker value={accent} onChange={setAccent} />+ </PrefRow>+ </div>+ );+}diff --git a/packages/web/src/features/settings/general-section.tsx b/packages/web/src/features/settings/general-section.tsxnew file mode 100644index 00000000..9ba22dcd--- /dev/null+++ b/packages/web/src/features/settings/general-section.tsx@@ -0,0 +1,47 @@+/**+ * General page of System settings: per-account preferences that are neither appearance nor+ * credentials. Everything applies the moment it is touched — the stores persist each value+ * (language and currency per browser, the CLI-sessions filter per user via PUT /me/prefs)+ * — so the page carries no Save button and no draft state to lose.+ */+import { S } from "../../lib/strings";+import { Segmented } from "../../components/ui/segmented";+import { Switch } from "../../components/ui/switch";+import { useLocale } from "../../state/locale";+import type { LangPref } from "../../state/locale";+import { useTheme } from "../../state/theme";+import type { Currency } from "../../state/theme";+import { useSessions } from "../../state/sessions";+import { PrefRow } from "./setting-row";++export function GeneralSection() {+ const { lang, setLang } = useLocale();+ const { currency, setCurrency } = useTheme();+ const { showCliSessions, setShowCliSessions } = useSessions();++ const langOptions: ReadonlyArray<{ value: LangPref; label: string }> = [+ { value: "en", label: S.settings.langEn },+ { value: "zh", label: S.settings.langZh },+ { value: "system", label: S.settings.followSystem },+ ];+ const currencyOptions: ReadonlyArray<{ value: Currency; label: string }> = [+ { value: "USD", label: S.models.currencyUsd },+ { value: "CNY", label: S.models.currencyCny },+ ];++ return (+ <div className="divide-y divide-gray-100 dark:divide-gray-800/60">+ <PrefRow label={S.settings.language} hint={S.settings.languageHint}>+ <Segmented options={langOptions} value={lang} onChange={setLang} />+ </PrefRow>+ <PrefRow label={S.models.currency} hint={S.settings.currencyHint}>+ <Segmented options={currencyOptions} value={currency} onChange={setCurrency} cols={2} />+ </PrefRow>+ {/* Flipping this refetches the whole conversation list under the new filter, so the+ sidebar behind the dialog updates without a reload. */}+ <PrefRow label={S.settings.showCliSessions} hint={S.settings.showCliSessionsHint}>+ <Switch checked={showCliSessions} onChange={setShowCliSessions} />+ </PrefRow>+ </div>+ );+}diff --git a/packages/web/src/features/settings/proxy-section.tsx b/packages/web/src/features/settings/proxy-section.tsxnew file mode 100644index 00000000..7f1e4714--- /dev/null+++ b/packages/web/src/features/settings/proxy-section.tsx@@ -0,0 +1,124 @@+/**+ * Proxy options (admin only, server-global). A form, not a live surface: two switches —+ * "Application uses the proxy" (the server's own outbound dispatcher) and "Agent environment+ * uses the proxy" (command subprocess environments) — share one proxy address, and nothing is+ * written until Save, which applies everything atomically via a single PUT. The server+ * validates and normalizes the address (bare "host:port" is stored as "http://host:port"); a+ * rejected address renders inline under the input and the atomic PUT writes nothing. Save with+ * no modifications sends no request and toasts "no changes"; a successful save takes effect+ * without a restart.+ *+ * Settings hydrate when the section mounts — which is every time it is navigated to — and the+ * controls and Save stay disabled until they arrive. The saved response is adopted as the new+ * baseline, including the address in the exact form the server stored, so the page reflects+ * what is on the server rather than what was typed at it.+ */+import { useEffect, useState } from "react";+import type { ServerSettings } from "@prismshadow/penguin-server/api";+import * as api from "../../api/endpoints";+import { ApiError } from "../../api/client";+import { S } from "../../lib/strings";+import { apiErrorText } from "../../lib/api-error";+import { Button } from "../../components/ui/button";+import { Input } from "../../components/ui/input";+import { Switch } from "../../components/ui/switch";+import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";+import { SectionShell } from "./section-shell";++export function ProxySection() {+ /** Stored settings as hydrated on mount (null until then) — the no-change baseline. */+ const [settings, setSettings] = useState<ServerSettings | null>(null);+ // Form drafts; the pre-hydration values mirror the server defaults (on, on, empty).+ const [proxyForApp, setProxyForApp] = useState(true);+ const [proxyForAgent, setProxyForAgent] = useState(true);+ const [proxyUrl, setProxyUrl] = useState("");+ /** Inline error under the address input (the server's invalid_proxy_url rejection). */+ const [addressError, setAddressError] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);++ /** Adopt server-side truth: the baseline and the drafts move together. */+ const adopt = (next: ServerSettings) => {+ setSettings(next);+ setProxyForApp(next.proxyForApp);+ setProxyForAgent(next.proxyForAgent);+ setProxyUrl(next.proxyUrl ?? "");+ };++ useEffect(() => {+ let cancelled = false;+ void api+ .adminGetSettings()+ .then((res) => {+ if (!cancelled) adopt(res.settings);+ })+ .catch((e: unknown) => {+ // Controls stay disabled; leaving and returning to the section retries the fetch.+ if (!cancelled) toastError(apiErrorText(e));+ });+ return () => {+ cancelled = true;+ };+ }, []);++ const save = async () => {+ if (settings === null || busy) return;+ const unchanged =+ proxyForApp === settings.proxyForApp &&+ proxyForAgent === settings.proxyForAgent &&+ proxyUrl.trim() === (settings.proxyUrl ?? "");+ if (unchanged) {+ toastInfo(S.common.noChangesToSave);+ return;+ }+ setBusy(true);+ setAddressError(null);+ try {+ const res = await api.adminPutSettings({ proxyForApp, proxyForAgent, proxyUrl });+ adopt(res.settings);+ toastSuccess(S.common.saved);+ } catch (e) {+ // The address is the only validated field: its rejection renders inline;+ // anything else (auth, network) is a generic failure toast.+ if (e instanceof ApiError && e.code === "invalid_proxy_url") {+ setAddressError(apiErrorText(e));+ } else {+ toastError(apiErrorText(e));+ }+ } finally {+ setBusy(false);+ }+ };++ const hydrated = settings !== null;+ return (+ <SectionShell+ description={S.settings.proxyHint}+ actions={+ <Button variant="primary" disabled={!hydrated || busy} onClick={() => void save()}>+ {S.common.save}+ </Button>+ }+ >+ <div className="flex items-center justify-between gap-3">+ <span className="text-sm font-medium">{S.settings.proxyForApp}</span>+ <Switch checked={proxyForApp} onChange={setProxyForApp} disabled={!hydrated} />+ </div>+ <div className="flex items-center justify-between gap-3">+ <span className="text-sm font-medium">{S.settings.proxyForAgent}</span>+ <Switch checked={proxyForAgent} onChange={setProxyForAgent} disabled={!hydrated} />+ </div>+ <Input+ label={S.settings.proxyAddress}+ size="sm"+ value={proxyUrl}+ placeholder={S.settings.proxyAddressPlaceholder}+ disabled={!hydrated}+ {...(addressError !== null ? { error: addressError } : {})}+ onChange={(e) => {+ setProxyUrl(e.target.value);+ if (addressError !== null) setAddressError(null);+ }}+ />+ </SectionShell>+ );+}diff --git a/packages/web/src/features/settings/section-shell.tsx b/packages/web/src/features/settings/section-shell.tsxnew file mode 100644index 00000000..fb0cd784--- /dev/null+++ b/packages/web/src/features/settings/section-shell.tsx@@ -0,0 +1,32 @@+/**+ * Shared frame for a System settings page that saves explicitly: optional explanatory+ * line, body, and a trailing action row. The dialog pane already draws the page heading,+ * so the shell adds no title and no box of its own. Pages that apply on the spot pass no+ * actions and the row is not drawn, so nothing on screen suggests an unsaved edit is+ * waiting.+ */+import type { ReactNode } from "react";++export function SectionShell({+ description,+ actions,+ children,+}: {+ description?: string;+ actions?: ReactNode;+ children: ReactNode;+}) {+ return (+ <section>+ {description !== undefined && (+ <p className="text-xs text-gray-500 dark:text-gray-400">{description}</p>+ )}+ <div className="mt-4 space-y-4">{children}</div>+ {actions !== undefined && (+ <div className="mt-5 flex justify-end gap-2 border-t border-gray-100 pt-4 dark:border-gray-800/60">+ {actions}+ </div>+ )}+ </section>+ );+}diff --git a/packages/web/src/features/settings/setting-row.tsx b/packages/web/src/features/settings/setting-row.tsxnew file mode 100644index 00000000..76550444--- /dev/null+++ b/packages/web/src/features/settings/setting-row.tsx@@ -0,0 +1,63 @@+/**+ * Row primitives for the System settings dialog's pages: a labelled preference row —+ * title with an optional one-line hint on the left, the control on the right — meant to+ * be stacked inside a `divide-y` container so rows separate with rules rather than boxes.+ * AccentPicker lives here too: the accent swatches moved out of the sidebar user menu+ * together with the rows that used them.+ */+import type { ReactNode } from "react";+import { S } from "../../lib/strings";+import { ACCENT_SWATCHES } from "../../state/theme";+import type { Accent } from "../../state/theme";++export function PrefRow({+ label,+ hint,+ children,+}: {+ label: string;+ hint?: string;+ children: ReactNode;+}) {+ return (+ <div className="flex items-center justify-between gap-4 py-3.5 first:pt-0 last:pb-0">+ <div className="min-w-0">+ <p className="text-sm font-medium">{label}</p>+ {hint !== undefined && (+ <p className="mt-0.5 text-xs text-gray-500 dark:text-gray-400">{hint}</p>+ )}+ </div>+ <div className="shrink-0">{children}</div>+ </div>+ );+}++/** Accent color picker: a row of swatches, with a ring on the selected one. */+export function AccentPicker({+ value,+ onChange,+}: {+ value: Accent;+ onChange: (a: Accent) => void;+}) {+ return (+ <div className="flex items-center gap-1.5">+ {ACCENT_SWATCHES.map((s) => (+ <button+ key={s.value}+ type="button"+ title={S.settings.accentNames[s.value]}+ aria-label={S.settings.accentNames[s.value]}+ aria-pressed={value === s.value}+ onClick={() => onChange(s.value)}+ className={`h-5 w-5 rounded-full border transition-transform duration-150 hover:scale-110 ${+ value === s.value+ ? "border-gray-500 ring-2 ring-gray-400/50 dark:border-gray-300"+ : "border-transparent"+ }`}+ style={{ backgroundColor: s.color }}+ />+ ))}+ </div>+ );+}diff --git a/packages/web/src/features/settings/settings-dialog.tsx b/packages/web/src/features/settings/settings-dialog.tsxnew file mode 100644index 00000000..d4a09943--- /dev/null+++ b/packages/web/src/features/settings/settings-dialog.tsx@@ -0,0 +1,128 @@+/**+ * System settings dialog: one popup holding the settings that used to sit as separate rows+ * in the sidebar user menu, on the PagedDialog shell (left rail of pages, ChatGPT-style+ * rows on the right). The rail is grouped — Personal for the viewer's own preferences,+ * Server for the server-global settings an admin writes — and both the rail and the pane+ * go through visibleSettingsSections, so a viewer neither sees a page they may not open+ * nor reaches it by request: an unknown or forbidden `initialSection` is replaced with the+ * first page they can actually open.+ */+import { useEffect, useState } from "react";+import { S } from "../../lib/strings";+import {+ resolveSettingsSection,+ settingsGroups,+ visibleSettingsSections,+} from "../../lib/settings-sections";+import type { SettingsGroupKey, SettingsSectionKey } from "../../lib/settings-sections";+import { useAuth } from "../../state/auth";+import { PagedDialog } from "../../components/ui/paged-dialog";+import type { PagedDialogGroup } from "../../components/ui/paged-dialog";+import { Icon } from "../../components/ui/group-list";+import { GEAR_ICON } from "../../components/ui/icons";+import { GeneralSection } from "./general-section";+import { AppearanceSection } from "./appearance-section";+import { AccountSection } from "./account-section";+import { ProxySection } from "./proxy-section";+import { UploadsSection } from "./uploads-section";+import { UpdatesSection } from "./updates-section";+import { AdminUsersSection } from "../admin/admin-users-page";++/** Rail glyphs, on the shared 24x24 stroke grid (see NAV_ICONS' conventions). */+const SECTION_ICONS: Record<SettingsSectionKey, string> = {+ general: GEAR_ICON,+ /** Sun: appearance. */+ appearance:+ "M12 17a5 5 0 1 0 0-10 5 5 0 0 0 0 10zM12 2v2m0 16v2M4.9 4.9l1.4 1.4m11.4 11.4l1.4 1.4M2 12h2m16 0h2M4.9 19.1l1.4-1.4m11.4-11.4l1.4-1.4",+ /** Single person: the signed-in account. */+ account: "M20 21a8 8 0 0 0-16 0M12 13a5 5 0 1 0 0-10 5 5 0 0 0 0 10z",+ /** Globe: outbound traffic. */+ proxy:+ "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM3.6 9h16.8M3.6 15h16.8M12 3a15 15 0 0 0 0 18M12 3a15 15 0 0 1 0 18",+ /** Up arrow over a base: uploads. */+ uploads: "M12 15V4m0 0L7 9m5-5l5 5M4 20h16",+ /** Down arrow into a tray: updates arriving. */+ updates: "M12 3v10m0 0l-4-4m4 4l4-4M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2",+ /** Two people: user management. */+ users:+ "M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM22 21v-2a4 4 0 0 0-3-3.87M16 3.13a4 4 0 0 1 0 7.75",+};++export function SettingsDialog({+ open,+ onClose,+ initialSection,+}: {+ open: boolean;+ onClose: () => void;+ /** Page to land on when opening (e.g. the update reminder jumps to "updates"); resolved against what this viewer may open. */+ initialSection?: SettingsSectionKey;+}) {+ const { user, desktopMode, sessionVia } = useAuth();+ const sections = visibleSettingsSections({+ isAdmin: user?.isAdmin === true,+ desktopMode,+ sessionVia,+ });+ const [active, setActive] = useState<SettingsSectionKey | null>(null);++ // Re-resolve the landing page each time the dialog opens (and whenever the viewer's+ // section list would invalidate the current choice).+ // Deliberately keyed on `open` alone: the landing page matters at the moment of opening,+ // and re-running on every sections identity change would yank the user off a page they+ // navigated to. `current` below re-resolves against the live list on every render anyway.+ useEffect(() => {+ if (open) setActive(resolveSettingsSection(initialSection, sections));+ }, [open]);++ const current = resolveSettingsSection(active, sections);+ if (current === null) return null;++ // Read inside the component: after a language switch remount, these pick up the current dictionary.+ const sectionLabel: Record<SettingsSectionKey, string> = {+ general: S.settings.generalTitle,+ appearance: S.settings.appearanceTitle,+ account: S.settings.accountTitle,+ proxy: S.settings.proxyTitle,+ uploads: S.settings.uploadLimitsTitle,+ updates: S.settings.updatesTitle,+ users: S.admin.users,+ };+ const groupLabel: Record<SettingsGroupKey, string> = {+ personal: S.settings.groupPersonal,+ server: S.settings.groupServer,+ };++ const groups: Array<PagedDialogGroup<SettingsSectionKey>> = settingsGroups(sections).map(+ (group) => ({+ key: group,+ label: groupLabel[group],+ items: sections+ .filter((s) => s.group === group)+ .map((s) => ({+ key: s.key,+ label: sectionLabel[s.key],+ icon: <Icon d={SECTION_ICONS[s.key]} size={16} />,+ })),+ }),+ );++ return (+ <PagedDialog+ open={open}+ onClose={onClose}+ title={S.settings.systemSettings}+ groups={groups}+ active={current}+ onSelect={setActive}+ >+ {current === "general" && <GeneralSection />}+ {current === "appearance" && <AppearanceSection />}+ {current === "account" && <AccountSection />}+ {current === "proxy" && <ProxySection />}+ {current === "uploads" && <UploadsSection />}+ {current === "updates" && <UpdatesSection active={open} />}+ {current === "users" && <AdminUsersSection />}+ </PagedDialog>+ );+}diff --git a/packages/web/src/features/settings/updates-section.tsx b/packages/web/src/features/settings/updates-section.tsxnew file mode 100644index 00000000..d0813aae--- /dev/null+++ b/packages/web/src/features/settings/updates-section.tsx@@ -0,0 +1,100 @@+/**+ * Updates page of System settings: the running server version, one check-for-updates+ * action, and — once a newer release is known — the entry into UpdateDialog, which carries+ * the release-notes link and the admin-only self-update. Moved here from the sidebar user+ * menu's single update row; the row semantics are unchanged: check until a release is+ * known, then offer it. Never mounted in desktop mode (the section registry drops the+ * page), where updating is the desktop shell's job.+ *+ * Version + update state share useVersionInfo's module cache with the sidebar's reminder+ * dot, so the two surfaces never disagree about what is known.+ */+import { useState } from "react";+import { S } from "../../lib/strings";+import { useLocale } from "../../state/locale";+import { Button } from "../../components/ui/button";+import { UpdateDialog } from "../../components/account/update-dialog";+import { forceUpdateCheck, updateCheckOutcome, useVersionInfo } from "../../lib/use-version-info";+import { apiErrorText } from "../../lib/api-error";+import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";+import { formatMonthDay } from "../../lib/format";+import { useAuth } from "../../state/auth";+import { PrefRow } from "./setting-row";++export function UpdatesSection({ active }: { active: boolean }) {+ const { user } = useAuth();+ const { locale } = useLocale();+ const { version, update } = useVersionInfo(active);+ const [updateDialogOpen, setUpdateDialogOpen] = useState(false);+ const [updateChecking, setUpdateChecking] = useState(false);++ const updateAvailable = update?.updateAvailable === true;+ /** The newer release's version string, or null while none is known. */+ const newVersion = updateAvailable ? (update?.latestVersion ?? null) : null;+ const versionDate = version?.buildDate ?? null;++ /**+ * Manual update check: forces a lookup past the server's TTL cache and pushes the result+ * into the shared version-info store, so the sidebar's reminder dot appears immediately+ * when a newer release is found. Every outcome toasts — the check is fail-soft (failure+ * arrives as the `error` field, not an exception; the catch handles our own server being+ * unreachable).+ */+ const runUpdateCheck = async () => {+ if (updateChecking) return;+ setUpdateChecking(true);+ try {+ const outcome = updateCheckOutcome(await forceUpdateCheck());+ if (outcome.kind === "disabled") toastInfo(S.update.checkDisabled);+ else if (outcome.kind === "failed") toastError(S.update.checkFailed);+ else if (outcome.kind === "found") toastSuccess(S.update.foundNew(outcome.latestVersion));+ else toastSuccess(S.update.upToDate);+ } catch (e) {+ toastError(apiErrorText(e));+ } finally {+ setUpdateChecking(false);+ }+ };++ return (+ <div className="divide-y divide-gray-100 dark:divide-gray-800/60">+ <PrefRow+ label={newVersion !== null ? S.update.newVersion(newVersion) : S.update.checkNow}+ hint={+ versionDate !== null+ ? S.update.lastUpdated(formatMonthDay(versionDate, locale))+ : undefined+ }+ >+ <span className="flex items-center gap-3">+ {version !== null && (+ <span className="text-xs text-gray-400 dark:text-gray-500">{`v${version.version}`}</span>+ )}+ {newVersion !== null ? (+ <Button variant="primary" onClick={() => setUpdateDialogOpen(true)}>+ {S.update.newVersionBadge}+ </Button>+ ) : (+ <Button+ variant="secondary"+ disabled={updateChecking}+ onClick={() => void runUpdateCheck()}+ >+ {updateChecking ? S.update.checking : S.update.checkNow}+ </Button>+ )}+ </span>+ </PrefRow>+ <UpdateDialog+ open={updateDialogOpen}+ onClose={() => setUpdateDialogOpen(false)}+ latestVersion={newVersion}+ releaseUrl={update?.releaseUrl ?? null}+ canUpdate={user?.isAdmin === true}+ /* A finished self-update makes the known release stale — re-check silently so the+ row stops offering the version that is now running (see the old menu row). */+ onRunFinished={() => void forceUpdateCheck().catch(() => undefined)}+ />+ </div>+ );+}diff --git a/packages/web/src/features/settings/uploads-section.tsx b/packages/web/src/features/settings/uploads-section.tsxnew file mode 100644index 00000000..f16a48b9--- /dev/null+++ b/packages/web/src/features/settings/uploads-section.tsx@@ -0,0 +1,152 @@+/**+ * Upload limits (admin only, server-global), modelled on the proxy section beside it. Two+ * whole-MB numbers — the per-file attachment cap and the per-message total — written together+ * by a single PUT to /api/admin/settings, so a rejected value writes nothing.+ *+ * The bounds and the fixed limits quoted in the hint come from the server (`/api/me`+ * uploadLimits) rather than from constants here: the range is a statement about what the+ * server can survive, and a second copy of it in the browser would be a copy that goes stale.+ * A value outside it is refused by the server with `invalid_attachment_limit` and rendered+ * inline under the field, the same way the proxy section handles a bad address.+ *+ * Saving takes effect immediately — the attachment validators and the request body cap both+ * read the setting per request — so there is nothing to restart and nothing to warn about.+ */+import { useEffect, useState } from "react";+import type { ServerSettings } from "@prismshadow/penguin-server/api";+import * as api from "../../api/endpoints";+import { ApiError } from "../../api/client";+import { S } from "../../lib/strings";+import { apiErrorText } from "../../lib/api-error";+import { useAuth } from "../../state/auth";+import { Button } from "../../components/ui/button";+import { Input } from "../../components/ui/input";+import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";+import { SectionShell } from "./section-shell";++export function UploadsSection() {+ const { uploadLimits, refresh } = useAuth();+ /** Stored settings as hydrated on mount (null until then) — the no-change baseline. */+ const [settings, setSettings] = useState<ServerSettings | null>(null);+ // Kept as strings: a number input that clears to NaN cannot be typed into (backspacing the+ // last digit would snap the field back to a value the user is in the middle of replacing).+ const [maxMb, setMaxMb] = useState("");+ const [totalMb, setTotalMb] = useState("");+ /** Inline error under whichever field the server rejected. */+ const [limitError, setLimitError] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);++ /** Adopt server-side truth: the baseline and the drafts move together. */+ const adopt = (next: ServerSettings) => {+ setSettings(next);+ setMaxMb(String(next.attachmentMaxMb));+ setTotalMb(String(next.attachmentTotalMb));+ };++ useEffect(() => {+ let cancelled = false;+ void api+ .adminGetSettings()+ .then((res) => {+ if (!cancelled) adopt(res.settings);+ })+ .catch((e: unknown) => {+ // Controls stay disabled; leaving and returning to the section retries the fetch.+ if (!cancelled) toastError(apiErrorText(e));+ });+ return () => {+ cancelled = true;+ };+ }, []);++ const save = async () => {+ if (settings === null || busy) return;+ const parsedMax = Number(maxMb.trim());+ const parsedTotal = Number(totalMb.trim());+ // Shape-check locally so an empty or non-numeric field never becomes a NaN in the request+ // body; the RANGE is left to the server, which owns it (this form only reports its verdict).+ if (+ maxMb.trim() === "" ||+ totalMb.trim() === "" ||+ !Number.isInteger(parsedMax) ||+ !Number.isInteger(parsedTotal)+ ) {+ setLimitError(S.errors.byCode.invalid_attachment_limit);+ return;+ }+ if (parsedMax === settings.attachmentMaxMb && parsedTotal === settings.attachmentTotalMb) {+ toastInfo(S.common.noChangesToSave);+ return;+ }+ setBusy(true);+ setLimitError(null);+ try {+ const res = await api.adminPutSettings({+ attachmentMaxMb: parsedMax,+ attachmentTotalMb: parsedTotal,+ });+ adopt(res.settings);+ // The composer reads the limits from /api/me, so re-pull them: without this the tab that+ // just raised the cap would keep refusing files at the old number until the next reload.+ await refresh().catch(() => {});+ toastSuccess(S.common.saved);+ } catch (e) {+ if (e instanceof ApiError && e.code === "invalid_attachment_limit") {+ setLimitError(apiErrorText(e));+ } else {+ toastError(apiErrorText(e));+ }+ } finally {+ setBusy(false);+ }+ };++ const hydrated = settings !== null;+ return (+ <SectionShell+ actions={+ <Button variant="primary" disabled={!hydrated || busy} onClick={() => void save()}>+ {S.common.save}+ </Button>+ }+ >+ <Input+ label={S.settings.attachmentMaxMb}+ size="sm"+ type="number"+ inputMode="numeric"+ min={uploadLimits.attachmentLimitMinMb}+ max={uploadLimits.attachmentLimitMaxMb}+ value={maxMb}+ disabled={!hydrated}+ onChange={(e) => {+ setMaxMb(e.target.value);+ if (limitError !== null) setLimitError(null);+ }}+ />+ <Input+ label={S.settings.attachmentTotalMb}+ size="sm"+ type="number"+ inputMode="numeric"+ min={uploadLimits.attachmentLimitMinMb}+ max={uploadLimits.attachmentLimitMaxMb}+ value={totalMb}+ disabled={!hydrated}+ {...(limitError !== null ? { error: limitError } : {})}+ onChange={(e) => {+ setTotalMb(e.target.value);+ if (limitError !== null) setLimitError(null);+ }}+ />+ <p className="text-xs text-gray-500 dark:text-gray-400">+ {S.settings.uploadLimitsHint(+ uploadLimits.attachmentLimitMinMb,+ uploadLimits.attachmentLimitMaxMb,+ uploadLimits.attachmentMaxCount,+ uploadLimits.imageMaxMb,+ )}+ </p>+ </SectionShell>+ );+}diff --git a/packages/web/src/lib/settings-sections.ts b/packages/web/src/lib/settings-sections.tsnew file mode 100644index 00000000..40b076ea--- /dev/null+++ b/packages/web/src/lib/settings-sections.ts@@ -0,0 +1,91 @@+/**+ * The System settings dialog's pages, and who may see each one.+ *+ * Server-global pages write through /api/admin/settings (or the admin user routes) and+ * belong to admins alone; the personal pages are per-user preferences every signed-in user+ * owns. Two pages additionally depend on how this session runs: the account page only+ * exists where a password can be changed (see offersChangePassword), and updates / user+ * management disappear in desktop mode, where the app is single-user and updating is the+ * desktop shell's job. The rules live here rather than inside the dialog because this+ * package's vitest runs in Node with no DOM — a pure function is the only thing a test can+ * pin directly — and because rail and content have to apply the same rule to avoid a+ * visible-but-forbidden entry.+ *+ * A page the viewer may not open is dropped from the list entirely rather than rendered+ * disabled: a greyed-out "Proxy" row still tells a non-admin the setting exists and that+ * someone else can reach it.+ *+ * None of this is the boundary. The admin APIs answer a non-admin with 403 whatever the+ * browser chose to render.+ */+import { offersChangePassword } from "./account-menu";+import type { AccountMenuSession } from "./account-menu";++/** A page of the System settings dialog. */+export type SettingsSectionKey =+ "general" | "appearance" | "account" | "proxy" | "uploads" | "updates" | "users";++/** Rail heading a page sits under: the viewer's own preferences vs. the whole server's. */+export type SettingsGroupKey = "personal" | "server";++export interface SettingsSection {+ readonly key: SettingsSectionKey;+ readonly group: SettingsGroupKey;+}++/** Who is looking, and from where — the union of what the visibility rules consume. */+export interface SettingsViewer extends AccountMenuSession {+ readonly isAdmin: boolean;+}++/**+ * Every page in rail order, with its visibility rule. Pages of one group stay contiguous —+ * the rail renders this list top to bottom and starts a heading wherever the group changes.+ */+const SECTION_RULES: ReadonlyArray<SettingsSection & { visible(viewer: SettingsViewer): boolean }> =+ [+ { key: "general", group: "personal", visible: () => true },+ { key: "appearance", group: "personal", visible: () => true },+ // The desktop shell's own window has no password to change; a password-established+ // session against the same server still does. Same predicate as the old menu row.+ { key: "account", group: "personal", visible: (v) => offersChangePassword(v) },+ { key: "proxy", group: "server", visible: (v) => v.isAdmin },+ { key: "uploads", group: "server", visible: (v) => v.isAdmin },+ // Server updates: every non-desktop account may check; the dialog's self-update stays+ // admin-only inside. Desktop updates are the shell's job (electron-updater).+ { key: "updates", group: "server", visible: (v) => !v.desktopMode },+ // Single-user under the desktop shell: the server rejects the admin user routes there.+ { key: "users", group: "server", visible: (v) => v.isAdmin && !v.desktopMode },+ ];++/** The pages this viewer may open, in rail order. */+export function visibleSettingsSections(viewer: SettingsViewer): readonly SettingsSection[] {+ return SECTION_RULES.filter((section) => section.visible(viewer)).map(({ key, group }) => ({+ key,+ group,+ }));+}++/**+ * The group headings to draw for `sections`, in order and without repeats. A viewer left+ * with a single group gets one entry, which the rail takes as its cue to draw no heading+ * at all — a lone "Personal" heading implies the other group.+ */+export function settingsGroups(sections: readonly SettingsSection[]): readonly SettingsGroupKey[] {+ const seen: SettingsGroupKey[] = [];+ for (const section of sections) if (!seen.includes(section.group)) seen.push(section.group);+ return seen;+}++/**+ * Requested page -> the page to render. An unknown request and one naming a page this+ * viewer may not open resolve identically, to the first visible page: nothing about what a+ * different account would have found there leaks. Null only when nothing is visible.+ */+export function resolveSettingsSection(+ raw: string | null | undefined,+ sections: readonly SettingsSection[],+): SettingsSectionKey | null {+ if (sections.some((section) => section.key === raw)) return raw as SettingsSectionKey;+ return sections[0]?.key ?? null;+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 9f080aa1..10e34358 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -59,21 +59,34 @@ export const en: Strings = {settings: {language: "Language",+ languageHint: "Interface language; can follow the browser",+ /** Sidebar user-menu row opening the System settings dialog. */+ systemSettings: "System settings",+ /** Rail headings: the viewer's own preferences vs. the whole server's. */+ groupPersonal: "Personal",+ groupServer: "Server",+ /** Personal pages of the settings dialog. */+ generalTitle: "General",+ appearanceTitle: "Appearance",+ accountTitle: "Account",+ updatesTitle: "Updates",/** Sidebar Session list: also show CLI-created Sessions (default off — the list then never scans the Trace directories). */showCliSessions: "Show CLI sessions",- /** Admin-only user-menu row opening the proxy options dialog. */- proxyMenu: "Proxy options…",- proxyDialogTitle: "Proxy options",- /** The dialog's two switches: the server's own outbound traffic / agent command subprocess environments. */+ showCliSessionsHint:+ "Off, the conversation list holds only Sessions created in the Web App and is served straight from the database. On, the Trace directories are scanned too and CLI-created Sessions are listed alongside them. Applies to this account only.",+ /** Admin-only sub-page (server-global). */+ proxyTitle: "Proxy options",+ proxyHint:+ "Server-global, and in force the moment it is saved — nothing to restart. Loopback addresses always go direct.",+ /** The two switches: the server's own outbound traffic / agent command subprocess environments. */proxyForApp: "Application uses the proxy",proxyForAgent: "Agent environment uses the proxy",/** The shared explicit proxy address (empty = follow the proxy environment variables). */proxyAddress: "Proxy address",proxyAddressPlaceholder: "Empty = follow system proxy",- /** Admin-only user-menu row opening the upload-limits dialog. */- uploadLimitsMenu: "Upload limits…",- uploadLimitsDialogTitle: "Upload limits",- /** The dialog's two number fields, both in whole MB. */+ /** Admin-only sub-page (server-global). */+ uploadLimitsTitle: "Upload limits",+ /** Its two number fields, both in whole MB. */attachmentMaxMb: "Max attachment size (MB)",attachmentTotalMb: "Max total per message (MB)",/** Explains what the numbers govern and what stays fixed, so the form needs no separate docs trip. */@@ -83,18 +96,24 @@ export const en: Strings = {`${imageMb}MB limit that this setting does not raise — an inline image enters the ` +`conversation and the Trace, where its size is paid again on every history page and resume.`,theme: "Theme",+ themeHint: "Light or dark look of the app",themeLight: "Light",themeDark: "Dark",followSystem: "System",terminalTheme: "Terminal theme",+ terminalThemeHint: "Colors of the terminal panel; follows the app theme by default",followAppTheme: "App",langZh: "中文",langEn: "English",fontSize: "Font size",+ fontSizeHint: "Overall interface font size",fontSmall: "S",fontMedium: "M",fontLarge: "L",accent: "Accent",+ accentHint: "Interface accent color",+ currencyHint: "Display currency for prices; storage is always USD",+ changePasswordHint: "Change this account's sign-in password",accentNames: {neutral: "Neutral",blue: "Blue",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 9e1f8e64..0300cb98 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -61,21 +61,33 @@ export const zh = {settings: {language: "语言",+ languageHint: "界面语言,可跟随浏览器设置",+ /** Sidebar user-menu row opening the System settings dialog. */+ systemSettings: "系统设置",+ /** Rail headings: the viewer's own preferences vs. the whole server's. */+ groupPersonal: "个人",+ groupServer: "服务器",+ /** Personal pages of the settings dialog. */+ generalTitle: "通用",+ appearanceTitle: "外观",+ accountTitle: "账户",+ updatesTitle: "更新",/** Sidebar Session list: also show CLI-created Sessions (default off — the list then never scans the Trace directories). */showCliSessions: "显示 CLI 会话",- /** Admin-only user-menu row opening the proxy options dialog. */- proxyMenu: "代理选项",- proxyDialogTitle: "代理选项",- /** The dialog's two switches: the server's own outbound traffic / agent command subprocess environments. */+ showCliSessionsHint:+ "关闭时会话列表只列出在 Web 端创建的会话,直接由数据库返回;开启后会额外扫描轨迹目录,把 CLI 创建的会话一并列出。仅影响当前账号。",+ /** Admin-only sub-page (server-global). */+ proxyTitle: "代理选项",+ proxyHint: "服务器全局设置,保存后立即生效,无需重启。回环地址始终直连。",+ /** The two switches: the server's own outbound traffic / agent command subprocess environments. */proxyForApp: "应用程序使用代理",proxyForAgent: "Agent 环境使用代理",/** The shared explicit proxy address (empty = follow the proxy environment variables). */proxyAddress: "代理地址",proxyAddressPlaceholder: "留空 = 跟随系统代理",- /** Admin-only user-menu row opening the upload-limits dialog. */- uploadLimitsMenu: "上传限制",- uploadLimitsDialogTitle: "上传限制",- /** The dialog's two number fields, both in whole MB. */+ /** Admin-only sub-page (server-global). */+ uploadLimitsTitle: "上传限制",+ /** Its two number fields, both in whole MB. */attachmentMaxMb: "单个附件上限(MB)",attachmentTotalMb: "单条消息附件合计上限(MB)",/** Explains what the numbers govern and what stays fixed, so the form needs no separate docs trip. */@@ -83,18 +95,24 @@ export const zh = {`取值 ${min}–${max} MB,合计不得低于单个上限。一条消息最多 ${count} 个附件;` +`对话内嵌图片另有 ${imageMb}MB 上限,不随此设置变化——图片会进入对话与轨迹,每次翻阅历史与恢复会话都要重新付出它的体积。`,theme: "主题",+ themeHint: "应用的明暗外观",themeLight: "浅色",themeDark: "深色",followSystem: "跟随系统",terminalTheme: "终端主题",+ terminalThemeHint: "终端面板的配色,默认跟随应用主题",followAppTheme: "跟随主题",langZh: "中文",langEn: "English",fontSize: "字号",+ fontSizeHint: "界面整体字号",fontSmall: "小",fontMedium: "中",fontLarge: "大",accent: "主题色",+ accentHint: "界面强调色",+ currencyHint: "价格显示币种;存储始终为美元",+ changePasswordHint: "更改当前账号的登录密码",accentNames: {neutral: "灰白",blue: "蓝",diff --git a/packages/web/src/router.tsx b/packages/web/src/router.tsxindex c9354086..80c87135 100644--- a/packages/web/src/router.tsx+++ b/packages/web/src/router.tsx@@ -17,7 +17,6 @@ import { ModelsPage } from "./features/models/models-page";import { UsagePage } from "./features/usage/usage-page";import { TracesPage } from "./features/traces/traces-page";import { BenchmarkPage } from "./features/benchmark/benchmark-page";-import { AdminUsersPage } from "./features/admin/admin-users-page";import { TerminalPage } from "./features/terminal/terminal-page";/** Route guard: shows blank while initializing, redirects to /login when not authenticated. */@@ -76,7 +75,8 @@ export function AppRouter() {<Route path="/usage" element={<UsagePage />} /><Route path="/traces" element={<TracesPage />} /><Route path="/benchmark" element={<BenchmarkPage />} />- <Route path="/admin/users" element={<AdminUsersPage />} />+ {/* System settings and user management live in the settings dialog now (see+ SettingsDialog); their old routes fall through to the catch-all. */}<Route path="*" element={<Navigate to="/chat" replace />} /></Route></Routes>diff --git a/packages/web/src/state/theme.tsx b/packages/web/src/state/theme.tsxindex 3dd09630..2b8c700b 100644--- a/packages/web/src/state/theme.tsx+++ b/packages/web/src/state/theme.tsx@@ -6,10 +6,10 @@* - Font size: scales the root font-size (rem-based text-* utilities scale along with it).* - Theme color: html[data-accent] overrides --accent-bg/--accent-fg; defaults to neutral* (gray/white, follows light/dark).- * - Terminal theme: its own light/dark/follow-the-app setting, defaulting to dark — see- * TerminalThemeMode. It drives no class or variable here; the terminal reads- * `terminalDark` and paints itself, because Tailwind's dark: variant is anchored on- * html.dark and cannot express a light subtree inside a dark app.+ * - Terminal theme: its own light/dark/follow-the-app setting, following the app unless+ * explicitly pinned — see TerminalThemeMode. It drives no class or variable here; the+ * terminal reads `terminalDark` and paints itself, because Tailwind's dark: variant is+ * anchored on html.dark and cannot express a light subtree inside a dark app.* All preferences persist to localStorage.*/import { createContext, useCallback, useContext, useEffect, useState } from "react";@@ -19,10 +19,11 @@ export type ThemeMode = "light" | "dark" | "system";export type FontScale = "sm" | "md" | "lg";export type Accent = "neutral" | "blue" | "green" | "violet" | "rose" | "amber";/**- * The terminal's appearance, which is its own preference rather than a slice of the app's.- * A terminal is where people keep prompts, colour schemes and TUIs tuned for a dark- * screen, and plenty of them want exactly that inside an otherwise light app — so the- * default is "dark" regardless of the app, and "app" is the opt-in that couples the two.+ * The terminal's appearance. By default it follows the app ("app"): switching the app+ * between light and dark carries the terminal along. Pinning "light" or "dark" decouples+ * the two — for people whose prompts, colour schemes and TUIs are tuned for one screen+ * regardless of the app around it. An absent stored value reads as "app", so only an+ * explicit pin ever overrides the coupling.*/export type TerminalThemeMode = "light" | "dark" | "app";/** Display currency (prices are always stored as USD/million Tokens; conversion happens only for display and input). */@@ -89,7 +90,7 @@ function initialAccent(): Accent {function initialTerminalMode(): TerminalThemeMode {const stored = localStorage.getItem(TERMINAL_KEY);if (stored === "light" || stored === "dark" || stored === "app") return stored;- return "dark";+ return "app";}function initialCurrency(): Currency {diff --git a/packages/web/test/account-menu.test.ts b/packages/web/test/account-menu.test.tsindex 596c1834..0961028e 100644--- a/packages/web/test/account-menu.test.ts+++ b/packages/web/test/account-menu.test.ts@@ -49,22 +49,50 @@ describe("offersChangePassword", () => {});});+describe("the settings section registry", () => {+ const source = readFileSync(+ resolve(dirname(fileURLToPath(import.meta.url)), "../src/lib/settings-sections.ts"),+ "utf8",+ );++ it("gates the account page on the predicate rather than listing it always", () => {+ // The change-password row moved from the sidebar menu into the settings dialog; the+ // predicate now decides whether that page exists at all. Without this the predicate+ // could pass every test above while the registry ignored it.+ expect(source).toContain("offersChangePassword(v)");+ });+});+describe("the sidebar user menu", () => {const source = readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), "../src/components/layout/sidebar.tsx"),"utf8",);- it("gates its change-password entry on the predicate rather than rendering it always", () => {- // Without this the predicate could pass every test above while the menu ignored it,- // which is the exact regression this change guards against.- expect(source).toContain("offersChangePassword({ desktopMode, sessionVia })");+ it("keeps sign-out on its own desktopMode gate", () => {+ // Sign out is hidden for the whole desktop-mode server, not just the shell's window.+ expect(source).toContain("{!desktopMode && (");});- it("leaves the sibling entries on their own desktopMode gate", () => {- // Sign out and Users are hidden for the whole desktop-mode server, not just the- // shell's window; the narrower rule above must not be copied onto them by accident.- expect(source).toContain("{!desktopMode && (");- expect(source).toContain("{user?.isAdmin && !desktopMode && (");+ it("reaches the settings it no longer holds through one ungated System settings entry", () => {+ // The preference rows, change password, the update row and user management all moved+ // into the settings dialog, whose own section registry decides which pages this viewer+ // sees — so the row itself carries no isAdmin test, or a non-admin would lose the+ // personal pages along with the admin ones.+ expect(source).toContain("setSettingsOpen(true)");+ expect(source).not.toContain("offersChangePassword");+ expect(source).not.toContain("S.settings.showCliSessions");+ expect(source).not.toContain("S.settings.theme");+ expect(source).not.toContain('go("/settings")');+ expect(source).not.toContain('go("/admin/users")');+ });++ it("no longer mounts the dialogs whose surfaces moved into the settings dialog", () => {+ // A stale mount would be a build failure rather than a silent one, but the menu+ // keeping an opener for a surface reachable elsewhere is the regression worth naming.+ expect(source).not.toContain("ProxySettingsDialog");+ expect(source).not.toContain("UploadLimitsDialog");+ expect(source).not.toContain("ChangePasswordDialog");+ expect(source).not.toContain("UpdateDialog");});});diff --git a/packages/web/test/settings-sections.test.ts b/packages/web/test/settings-sections.test.tsnew file mode 100644index 00000000..b4e49e33--- /dev/null+++ b/packages/web/test/settings-sections.test.ts@@ -0,0 +1,153 @@+/**+ * settings-sections.ts unit tests: which System settings pages each viewer gets.+ *+ * The rule is pinned by value rather than by shape because both halves of it can fail+ * silently and separately: a rail that shows a forbidden entry leaks that the setting+ * exists, and an initialSection that is honoured without the same filter hands a+ * non-admin the form itself. Both go through these functions, so both are covered here.+ *+ * The client filter is convenience, not the boundary — the admin APIs answer a non-admin+ * with 403 either way (server/test/admin-settings.test.ts, "non-admin access is always+ * 403").+ *+ * vitest runs node-only here (`environment: "node"`, no jsdom), so this asserts against+ * the exported functions and, for the dialog's use of them, its source+ * (account-menu.test.ts convention).+ */+import { readFileSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";+import {+ resolveSettingsSection,+ settingsGroups,+ visibleSettingsSections,+} from "../src/lib/settings-sections";++/** Admin signed into a plain `penguin server` through the login form. */+const admin = visibleSettingsSections({+ isAdmin: true,+ desktopMode: false,+ sessionVia: "password",+});+/** Ordinary account on the same server. */+const plain = visibleSettingsSections({+ isAdmin: false,+ desktopMode: false,+ sessionVia: "password",+});+/** The desktop shell's own window: single-user, token session, no password to change. */+const shell = visibleSettingsSections({+ isAdmin: true,+ desktopMode: true,+ sessionVia: "desktop",+});+/** A browser signed into that same desktop-mode server over loopback, with a real password. */+const desktopBrowser = visibleSettingsSections({+ isAdmin: true,+ desktopMode: true,+ sessionVia: "password",+});++describe("visibleSettingsSections", () => {+ it("gives a web admin every page, in rail order", () => {+ expect(admin.map((s) => s.key)).toEqual([+ "general",+ "appearance",+ "account",+ "proxy",+ "uploads",+ "updates",+ "users",+ ]);+ });++ it("gives a non-admin their own pages and the update check, nothing server-global", () => {+ // Not "fewer pages" — the exact list. Proxy, upload limits and user management are+ // admin surfaces, and the whole point of dropping them is that a non-admin is never+ // told they exist. The updates page stays: any account may run the check; the+ // self-update inside stays admin-only.+ expect(plain.map((s) => s.key)).toEqual(["general", "appearance", "account", "updates"]);+ });++ it("strips the desktop shell's window down to what a token session can use", () => {+ // No account page (no password to change — see offersChangePassword), no updates+ // (electron-updater owns updating there), no user management (single-user server).+ expect(shell.map((s) => s.key)).toEqual(["general", "appearance", "proxy", "uploads"]);+ });++ it("keeps the account page for a password session against a desktop-mode server", () => {+ // Mirrors the old menu row's two-field rule: that session typed a real password and+ // can still change it, while updates and user management stay desktop-hidden.+ expect(desktopBrowser.map((s) => s.key)).toEqual([+ "general",+ "appearance",+ "account",+ "proxy",+ "uploads",+ ]);+ });+});++describe("settingsGroups", () => {+ it("lists an admin's groups once each, in page order", () => {+ expect(settingsGroups(admin)).toEqual(["personal", "server"]);+ });++ it("keeps both headings for a non-admin, whose updates page sits under Server", () => {+ expect(settingsGroups(plain)).toEqual(["personal", "server"]);+ });++ it("collapses to a single group when only one remains, the rail's cue to draw no heading", () => {+ // A lone "Personal" heading announces that some other group exists.+ expect(settingsGroups(plain.filter((s) => s.group === "personal"))).toEqual(["personal"]);+ });+});++describe("resolveSettingsSection", () => {+ it("passes through a page the viewer may open", () => {+ expect(resolveSettingsSection("proxy", admin)).toBe("proxy");+ expect(resolveSettingsSection("appearance", plain)).toBe("appearance");+ });++ it("sends a non-admin asking for an admin page to their own first page", () => {+ // Answering identically to an unknown request is the point: initialSection cannot be+ // used to find out that "users" is a real page.+ expect(resolveSettingsSection("users", plain)).toBe("general");+ expect(resolveSettingsSection("proxy", plain)).toBe("general");+ expect(resolveSettingsSection("no-such-section", plain)).toBe("general");+ });++ it("falls back to the first visible page for a missing request", () => {+ expect(resolveSettingsSection(null, admin)).toBe("general");+ expect(resolveSettingsSection(undefined, admin)).toBe("general");+ });++ it("returns null when nothing is visible, rather than inventing a page", () => {+ expect(resolveSettingsSection("general", [])).toBe(null);+ });+});++describe("the System settings dialog", () => {+ const source = readFileSync(+ resolve(+ dirname(fileURLToPath(import.meta.url)),+ "../src/features/settings/settings-dialog.tsx",+ ),+ "utf8",+ );++ it("builds its rail from the filtered list rather than the full one", () => {+ // Without this the functions above could pass every test while the dialog mapped over+ // the raw registry and rendered the admin rows to everyone.+ expect(source).toContain("visibleSettingsSections({");+ expect(source).not.toContain("SECTION_RULES");+ });++ it("resolves both the landing page and the rendered page through the same gate", () => {+ // initialSection is a request, not a right: an unknown or forbidden value must land on+ // the viewer's own first page, and the pane renders only what re-resolves.+ expect(source).toContain("resolveSettingsSection(initialSection, sections)");+ expect(source).toContain("resolveSettingsSection(active, sections)");+ });+});