A local-first multi-agent app development platform, built on PenguinHarness
feat(server,web,ui): 权限菜单给出具名沙箱预设(上游 #975 移植)
lmliheng2e9d53b64bd1
diff --git a/.agents/skills/penguin-harness-frontend/SKILL.md b/.agents/skills/penguin-harness-frontend/SKILL.mdindex 71ad3299..7a342fbc 100644--- a/.agents/skills/penguin-harness-frontend/SKILL.md+++ b/.agents/skills/penguin-harness-frontend/SKILL.md@@ -76,9 +76,9 @@ Two forms, and **a title decides between them, not taste**:- **A title is present** → `InfoPopover` (`@lmliheng/penguin-ui`). A circled "?"immediately after the section heading, the table column header, or the field label — the last of- those via `Field`/`Input`/`Textarea`/`PasswordInput`'s `info` prop. The "?" is an *anchored*- mark: it reads as help only because it modifies the title it sits against, and it borrows that- title's meaning instead of restating it.+ those via `Field`/`Input`/`Textarea`/`PasswordInput`/`Select`'s `info` prop. The "?" is an+ *anchored* mark: it reads as help only because it modifies the title it sits against, and it+ borrows that title's meaning instead of restating it.- **No title on the surface** → `HelpFold` (`@lmliheng/penguin-ui`). A compact row thatnames itself and expands its explanation inline underneath. This is the Agent settings tabs:their name lives in the tab bar and the panel does not repeat it, so a "?" at the top of thediff --git a/changelog/unreleased/2026-10-09-sandbox-named-presets.md b/changelog/unreleased/2026-10-09-sandbox-named-presets.mdnew file mode 100644index 00000000..8e6ebdd7--- /dev/null+++ b/changelog/unreleased/2026-10-09-sandbox-named-presets.md@@ -0,0 +1,101 @@+# The permission menu offers named presets++- **Date:** 2026-10-09+- **Type:** feature+- **Scope:** `server`, `web`, `ui`++[中文版](2026-10-09-sandbox-named-presets.zh.md)++The composer's permission button lists presets instead of three sections of levels: Full Access,+Always Ask, Workspace Write and Read Only, then More… for an administrator. Each preset is a+named file mode, network level and approval mode, and one pick saves all three on the Session.+This is ported from upstream PenguinHarness (#975, commit `9b170c61`).++- **What a preset does is in its tooltip.** Hovering a preset says what it blocks, what it+ allows, and whether this machine can enforce it. A preset no backend here can enforce stays+ listed, greyed out and marked "Not installed" or "Unavailable", as the levels were before.+- **The button names the Session's level by its preset.** A level no preset matches (set from+ the full settings, or by an older client) is shown as Custom, with its three values in the+ tooltip. When the Session also has masked paths or a read-only temp directory, the menu says+ "Advanced settings in effect".+- **The Sandbox card has a presets table.** More… opens the Sandbox card on the Settings+ dialog's Plugins page. At the top of the card is a table with one row per preset: the name,+ its file mode, network level and ask mode (the approval mode), and an "Action" group of icons — a pin for+ whether the menu lists it, a drag handle, and a "…" menu with Set as default and, on presets+ an administrator added, Delete. The default row reads "(Default)" after its name. Each name+ has a "?" saying what the row is for: a sentence per built-in preset (Workspace Write: for+ everyday coding), and for an added preset, or a built-in one whose values changed, what each+ of its three values does. The choice cells show the value's full title as text and open a small+ menu of the options. Dragging the handle lifts the row and shows where it will land; the+ arrow keys move a focused handle's row. That order is the composer's menu order. "Add preset"+ adds a row (Workspace write only, Full access, Ask every time, not pinned); only added rows+ can be deleted, and not while they are the default. Renaming keeps a row's mapping; Full+ Access can only be renamed, unpinned or made the default; a value stored for one of its+ locked cells by hand is ignored. Names wrap by words, and below the+ table's minimum width the table scrolls instead of crushing them.+- **Explanations sit behind a "?" beside their title** on every settings card: the card's+ description, each field's and the table's. A format rule (masked paths: one absolute path+ per line) stays on screen under its field.+- **New Sessions start from the default preset.** One row is the default, Workspace Write until+ changed. While the switch is on, a new Session and the composer's draft take that+ row's file mode, network and approval mode; a default that confines nothing (Full Access)+ starts Sessions unconfined. Changing the default reaches new Sessions only. The card no longer+ has its own confinement mode and network fields; settings stored before the default preset+ keep their mode and network until an administrator sets a default. The card marks as default+ the row that+ starts Sessions exactly where they do, or none, with a notice saying what is in effect (see+ [backward compatibility](2026-10-09-sandbox-switch-backward-compatibility.md)).+- **The Sandbox card has an Enable switch at the top.** It decides whether new Sessions start+ confined; a Session that exists keeps its own policy. Off, a new Session has full file and+ network access and is held only by its approval mode, and the composer's permission menu+ lists the four approval modes instead of the presets; a pick there changes only the+ Session's (or the draft's) approval mode, never its sandbox policy. The presets and the default are kept+ while it is off and apply again when it is turned on. A fresh install starts off. Settings+ saved before the switch existed read it as on when they confined anything (a mode other than+ Off, a network that is not open, or masked paths); see+ [backward compatibility](2026-10-09-sandbox-switch-backward-compatibility.md). While the+ switch is off, the card shows the switch alone: no presets table, no Advanced fold, no notice+ and no backend's own settings.+- **The temp directory and masked paths moved into an Advanced fold**, collapsed by default,+ under the switch and the presets table.+- **Turning the switch on offers to install a sandbox backend** when the machine has none for+ its OS: `@lmliheng/penguin-plugin-sandbox-bwrap` on Linux, `@lmliheng/penguin-plugin-sandbox-seatbelt` on+ macOS, `@lmliheng/penguin-plugin-sandbox-wsl` on Windows. The dialog wears a download mark. The+ choices are Install and Not now, with+ "Don't ask again", which this browser remembers per machine. Installing goes through the+ Plugins page's install, into the current Project for that machine; the switch stays on+ either way.+- Settings groups gain a `table` field type: fixed rows, columns of `string`, `boolean` or `enum`,+ and cells that can be locked. Only the cells that differ from the declaration are stored, and a+ refused cell is named `<field>.<row>.<column>`. An `unavailable` option can name a table+ column. A table can declare a `rowChoice`: a single choice of a row, stored in an `enum` field+ of the same group whose options are the row ids, drawn as its title in brackets after the+ chosen row's name and picked from the row's "…" menu; a `pin`: a boolean column drawn as a pin toggle with a tooltip per state; a `columnGroup`, a+ header over adjacent columns; and `extensible`: rows may be added (only those deleted) and all+ reordered, stored additively under `"$added"` and `"$order"`. A row choice may name an added+ row, or no row at all; a save that leaves it naming a row the table no longer has is refused. Columns, rows and+ `enum` options take a `description` (a row's and its options' are its "?"), and fields a `hint` (`hintZh`) for their format, shown under the+ field while the `description` goes behind the "?".+- Settings fields can be marked `advanced: true`; the Plugins page folds such fields on every+ card.+- The sandbox's settings entry gains `backend` (`installed`, `recommended`); its group gains+ `enabled` and `defaultPreset` and loses `mode` and `network`. A configuration may name a+ boolean field as its `switch`: while it is off, the page draws that field alone.+- **A non-admin sees which presets only an administrator can pick.** A preset wider than the+ server's sandbox settings (with the default Workspace Write: Full Access and Always Ask, whose+ file mode is Off) is greyed out for a non-admin and marked "Admin only", and its tooltip says it+ exceeds this server's sandbox ceiling; administrators, and the preset the Session is on, are+ unaffected. A refused pick leaves the Session as it was, and a toast says why.+- `ConfirmModal` (UI package) takes a `glyph` for its leading mark. A portaled `Dropdown` moves+ focus to its first item once the panel is placed; before, opening one from the keyboard left+ focus on the trigger and the arrow keys did nothing.+- The Session's `sandbox` object in the API gains three response-only fields: `presets` (the+ table, disabled rows included), `advanced`, and `switchOn` (the Sandbox switch). The chat+ defaults carry them too, plus `defaultApprovalMode`: the default preset's approval mode+ while the switch is on. A Session created without an approval mode takes it; the Sessions+ nobody watches keep `allow-all`: an organization's, a scheduled run's and a workflow's. Each preset row carries `aboveCeiling: true` when+ it is wider than the server's settings, by the same comparison that refuses a non-admin's+ pick with `403 sandbox_forbidden`.+- `PATCH /api/sessions/:sessionId` checks every field, the sandbox's ceiling and+ enforceability included, before it writes any: a refused request stores nothing. Before, it+ stored the approval mode first, so a refused preset pick left its approval-mode half saved.diff --git a/changelog/unreleased/2026-10-09-sandbox-named-presets.zh.md b/changelog/unreleased/2026-10-09-sandbox-named-presets.zh.mdnew file mode 100644index 00000000..13b43440--- /dev/null+++ b/changelog/unreleased/2026-10-09-sandbox-named-presets.zh.md@@ -0,0 +1,25 @@+# 权限菜单改为命名的预设++- **Date:** 2026-10-09+- **Type:** feature+- **Scope:** `server`, `web`, `ui`++[English](2026-10-09-sandbox-named-presets.md)++输入框的权限按钮不再分三段列出各档位,而是列出预设:Full Access、Always Ask、Workspace Write、Read Only,管理员还会看到「更多…」。每个预设是文件模式、网络与审批方式的一个命名组合,选一次就把三者一起保存到会话上。本次从上游 PenguinHarness 移植(#975,提交 `9b170c61`)。++- **预设做什么,写在它的悬停提示里。** 悬停在预设上会说明它封住什么、放开什么,以及本机能否实施。本机没有后端能实施的预设仍列出,但置灰并标注「未安装」或「不可用」,与此前的档位一致。+- **按钮用预设为会话的档位命名。** 没有预设匹配的档位(在完整设置里改出来的,或由旧版本客户端设置的)显示为「自定义」,提示里列出三个实际值。会话另有屏蔽路径或只读临时目录时,菜单顶部显示「高级设置生效中」。+- **沙盒卡片有一张预设表。** 「更多…」打开设置对话框插件页上的「沙盒」卡片,卡片顶部是一张表,每个预设一行:名称、文件模式、网络、询问模式(即审批方式),以及「操作」一组图标——图钉表示是否进菜单,拖动手柄,以及「…」菜单,内有「设为默认」和(仅新增预设上的)「删除」。默认行在名称后标「(默认)」。每个名称旁有「?」说明这一行的用途:内置预设各有一句(仅工作区可写:适合日常编码);新增的预设,或改过取值的内置预设,则逐项说明三个取值的作用。选择类单元格以文字显示取值的完整名称,点击后弹出选项小菜单。拖动手柄时该行浮起并显示落点;聚焦手柄后按上下方向键也可移动。这个顺序就是输入框权限菜单的顺序。「添加预设」新增一行(仅工作区可写、完全访问、每次询问、不固定);只有新增的行可以删除,且作为默认时不能删除。改名不改映射;Full Access 只能改名、取消固定或设为默认;手工为其锁定单元格写入的值会被忽略。名称按词换行;窗口窄于表格最小宽度时表格横向滚动,而不是挤压名称。+- **说明文字收进标题旁的「?」**,所有设置卡片一致:卡片说明、每个字段与表格的说明都如此。格式要求(屏蔽路径:每行一个绝对路径)仍显示在字段下方。+- **新会话从默认预设开始。** 表中一行为默认,未改动时为 Workspace Write。开关打开时,新会话与输入框草稿取该行的文件模式、网络与审批方式;默认行不做任何封禁时(Full Access),新会话不进入沙盒。改动默认只影响此后新建的会话。卡片不再有单独的封禁模式与网络字段;默认预设出现之前存下的设置,在管理员设定默认行之前继续按其封禁模式与网络执行。卡片把起点与之完全相同的那一行标为默认;没有这样的行时不标任何一行,并以一条提示写明实际生效的值(见[向后兼容](2026-10-09-sandbox-switch-backward-compatibility.zh.md))。+- **沙盒卡片顶部有「启用」开关。** 它决定新建会话是否进入沙盒;已有会话保留自己的策略。关闭时,新会话拥有完全的文件与网络访问,只受审批模式约束,输入框的权限菜单改为列出四种审批模式而不是预设;在这里选择只改会话(或草稿)的审批模式,不动其沙盒策略。关闭期间预设与默认都保留,重新打开后照旧生效。全新安装默认关闭。开关出现之前保存的设置,只要有任何封禁(封禁模式不是「关闭」、网络不是完全开放,或设置了屏蔽路径)即视为打开,见[向后兼容](2026-10-09-sandbox-switch-backward-compatibility.zh.md)。开关关闭时,卡片只显示这个开关:没有预设表、高级选项、提示,也没有后端自身的设置。+- **临时目录与屏蔽路径移入「高级选项」折叠区**,默认折叠,位于开关与预设表之下。+- **打开开关时,若本机没有适用于其操作系统的沙盒后端,会询问是否安装**:Linux 为 `@lmliheng/penguin-plugin-sandbox-bwrap`,macOS 为 `@lmliheng/penguin-plugin-sandbox-seatbelt`,Windows 为 `@lmliheng/penguin-plugin-sandbox-wsl`。对话框带下载标记,选项为「安装」与「暂不」,另有「不再询问」,由本浏览器按机器记住。安装走插件页的同一条安装路径,装到当前项目的该机器上;无论选哪项,开关都保持打开。+- 设置分组新增 `table` 字段类型:行固定,列可以是 `string`、`boolean` 或 `enum`,单元格可以锁定。只存与声明不同的单元格,被拒的单元格按 `<字段>.<行>.<列>` 点名。`unavailable` 可以指向表的某一列。表格可以声明 `rowChoice`:单选一行,存入同组中选项为各行 id 的 `enum` 字段,画作被选行名称后带括号的标题,在该行的「…」菜单里选定;`pin`:把一个布尔列画成图钉按钮,每种状态各有提示;`columnGroup`:相邻几列上方的分组标题;以及 `extensible`:可新增行(只有新增的行可删除)并调整所有行的顺序,以 `"$added"` 与 `"$order"` 增量存储。单选列可以指向新增的行,也可以不指向任何行;保存后若它指向表里已不存在的行,保存会被拒绝。列、行与 `enum` 选项可带 `description`(行及其选项的说明就是该行的「?」),字段可带格式提示 `hint`(`hintZh`),显示在字段下方,`description` 则收进「?」。+- 设置字段可以标记 `advanced: true`;插件页在每张卡片上都把这类字段收进折叠区。+- 沙盒的设置条目新增 `backend`(`installed`、`recommended`);其分组新增 `enabled` 与 `defaultPreset`,去掉 `mode` 与 `network`。配置可以把一个布尔字段声明为 `switch`:它关闭时,页面只画这一个字段。+- **非管理员能看出哪些预设只有管理员能选。** 比服务端沙盒设置更宽的预设(默认为 Workspace Write 时,即文件模式为关闭的 Full Access 与 Always Ask)对非管理员置灰并标「仅管理员」,悬停说明它超出了本服务器的沙盒上限;管理员不受影响,会话当前所在的预设也不受影响。被拒绝的选择不改动会话,由 toast 说明原因。+- UI 包的 `ConfirmModal` 新增 `glyph`,用于指定左侧标记。以 portal 方式弹出的 `Dropdown` 在面板定位后才把焦点移到第一项;此前用键盘打开时焦点留在触发按钮上,方向键也无效。+- API 中会话的 `sandbox` 对象新增三个只出现在响应里的字段:`presets`(整张表,含未固定的行)、`advanced` 与 `switchOn`(沙盒开关)。chat defaults 也带上它们,另加 `defaultApprovalMode`:开关打开时默认预设的审批方式。创建时未指定审批方式的会话取这一项;无人值守的会话仍为 `allow-all`:组织的会话、定时任务与工作流创建的会话。预设表的每一行在比服务端设置更宽时带 `aboveCeiling: true`,与以 `403 sandbox_forbidden` 拒绝非管理员选择的是同一次比较。+- `PATCH /api/sessions/:sessionId` 先完成全部校验(含沙盒的上限与可实施性)再写入任何字段:被拒的请求什么都不落盘。原先它先写审批方式,被拒的预设选择会只存下审批方式那一半。diff --git a/changelog/unreleased/2026-10-09-sandbox-switch-backward-compatibility.md b/changelog/unreleased/2026-10-09-sandbox-switch-backward-compatibility.mdnew file mode 100644index 00000000..44eaaa24--- /dev/null+++ b/changelog/unreleased/2026-10-09-sandbox-switch-backward-compatibility.md@@ -0,0 +1,29 @@+# Backward compatibility: sandbox settings saved before the switch++- **Date:** 2026-10-09+- **Type:** feature+- **Scope:** `server`++[中文版](2026-10-09-sandbox-switch-backward-compatibility.zh.md)++[The Sandbox card's switch](2026-10-09-sandbox-named-presets.md) is stored as `enabled` in the sandbox's settings document (`plugin-config:sandbox` in `web.db`). Documents saved before it have no `enabled`.+This is ported from upstream PenguinHarness (#975, commit `9b170c61`).++## The old shape: no `enabled`++Such a document reads the switch as **on when its policy confined anything**: a mode other than Off, a network that is not open, or masked paths. Otherwise it reads as off. The card shows that value and the server applies it, so a deployment that was confined stays confined and one that was not stays open. The document on disk is not rewritten; `enabled` is written only when an administrator changes the switch and saves the card.++## The old shape: `mode` and `network`, no `defaultPreset`++The card no longer has its own confinement mode and network: new Sessions start from the default preset. A stored document with its own `mode` or `network` (or masked paths, which the old Off mode stored alone) and no `defaultPreset` keeps starting new Sessions from its own `mode` and `network`, with its temp directory and masked paths, **until an administrator sets a row as the default**. The card shows that start as it is:++- **A row gives exactly the same start** — making it the default would change neither a new Session's policy (file mode, network, temp directory, masked paths) nor its approval mode. The card marks that row "(Default)" (the first in table order), and a save writes it as `defaultPreset`. In the shipped table those are Workspace Write and Read Only, each for the old mode of the same name with the network open.+- **No row does** — the old network was none or localhost only, or the old mode was Off with masked paths (Full Access confines nothing, so it does not match). No row is marked as the default, a notice at the top of the card names the values in effect and how to change them (set a row as the default from its "…" menu, or add a preset with those values and set it), and a save of other fields writes no `defaultPreset`: the start stays the old one.++A document without `mode` or `network` (a fresh install, or one saved only through the new card) is not of this shape: every save writes `defaultPreset`, Workspace Write unless another row is picked. A save of the card therefore never loosens a confined deployment on its own: the default preset decides new Sessions, and the ceiling for non-admins, only once an administrator has picked a row. Reads never rewrite the document.++Both apply to every data root, on start and on a hot push alike. **A user is not required to do anything.**++## When this can be removed++Both fallbacks live in `packages/server/src/sandbox/settings-policy.ts` (`sandboxEnabledOf`, `sandboxStartOf`). Because a save writes only the fields it changes, a document keeps lacking `enabled` until its switch is changed, and keeps lacking `defaultPreset` until a save pins a row (at once where a row matches, otherwise when an administrator picks one), so neither fallback expires on its own. The pre-preset reading also covers `prePresetStartOf` and the card's notice (`prePresetNotice`) in the same file, and the derive, saving and status hooks in `settings-status.ts` that use them. They can be removed once the maintainers choose either a one-time migration that writes `enabled` and `defaultPreset` into such documents, or an announced break that reads them with the switch off and the shipped default preset; until then they cost a few comparisons per read.diff --git a/changelog/unreleased/2026-10-09-sandbox-switch-backward-compatibility.zh.md b/changelog/unreleased/2026-10-09-sandbox-switch-backward-compatibility.zh.mdnew file mode 100644index 00000000..600f7746--- /dev/null+++ b/changelog/unreleased/2026-10-09-sandbox-switch-backward-compatibility.zh.md@@ -0,0 +1,28 @@+# 向后兼容:开关出现之前保存的沙盒设置++- **Date:** 2026-10-09+- **Type:** feature+- **Scope:** `server`++[English](2026-10-09-sandbox-switch-backward-compatibility.md)++[沙盒卡片的开关](2026-10-09-sandbox-named-presets.zh.md)存为沙盒设置文档(`web.db` 中的 `plugin-config:sandbox`)里的 `enabled`。此前保存的文档没有 `enabled`。本次从上游 PenguinHarness 移植(#975,提交 `9b170c61`)。++## 旧形态:没有 `enabled`++这类文档按**其策略是否有任何封禁**推出开关:封禁模式不是「关闭」、网络不是完全开放,或设置了屏蔽路径,即视为打开;否则视为关闭。卡片显示这个值,服务端也按它实施,因此原本处于封禁的部署保持封禁,原本开放的保持开放。磁盘上的文档不改写;只有管理员改动开关并保存卡片时才写入 `enabled`。++## 旧形态:有 `mode` 与 `network`,没有 `defaultPreset`++卡片不再有单独的封禁模式与网络,新会话从默认预设开始。带自身 `mode` 或 `network`(或设置了屏蔽路径——旧的「关闭」模式只存这一项)而没有 `defaultPreset` 的存量文档,**在管理员把一行设为默认之前**,新会话继续按其自身的 `mode` 与 `network`(连同临时目录与屏蔽路径)开始。卡片如实显示这个起点:++- **有一行给出完全相同的起点**——把它定为默认,新会话的策略(文件模式、网络、临时目录、屏蔽路径)与审批方式都不变:卡片在这一行名称后标「(默认)」(按表序取第一个),保存时把它写入 `defaultPreset`。出厂的表里是 Workspace Write 与 Read Only 两行,各对应网络完全开放的同名旧模式。+- **没有这样的行**——旧网络为无网络或仅本机,或旧模式为关闭而设了屏蔽路径(Full Access 不做任何封禁,对不上):不标任何一行为默认,卡片顶部的提示写明实际生效的值与改法(在一行的「…」菜单里把它设为默认,或先添加一条同值的预设再设为默认),保存其他字段也不写入 `defaultPreset`,起点仍是旧值。++没有 `mode` 或 `network` 的文档(全新安装,或只经新卡片保存过的)不属于此形态:每次保存都写入 `defaultPreset`,未选其他行时为 Workspace Write。因此保存卡片本身不会让原本封禁的部署放宽:只有管理员选定一行之后,新会话的起点与非管理员的上限才改由默认预设决定。读取从不改写文档。++两者适用于所有数据根,启动与热推送时都一样。**用户无需任何操作。**++## 何时可以移除++两处兜底都在 `packages/server/src/sandbox/settings-policy.ts`(`sandboxEnabledOf`、`sandboxStartOf`)。保存只写入改动过的字段,文档在开关被改动之前一直没有 `enabled`,在某次保存写入一行之前(有行对得上时即下一次保存,否则要等管理员选定)一直没有 `defaultPreset`,所以兜底不会自行失效。旧起点的读取还包括同一文件中的 `prePresetStartOf` 与卡片提示(`prePresetNotice`),以及 `settings-status.ts` 中用到它们的 derive、saving 与 status 钩子。维护者选定以下之一后即可移除:一次性迁移,把 `enabled` 与 `defaultPreset` 写入这类文档;或明确宣布不兼容,按开关关闭与出厂默认预设读取它们。在此之前,每次读取只多几次比较。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex f8d728f8..cbfedfa5 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -167,7 +167,9 @@ Two limits cannot be changed: the number of files per message (20) and the inlinA settings group is a contribution to `PluginConfigProvider.groups`; the sandbox's comes first. Each group in the list carries its schema (`configuration`), its stored values merged onto the defaults with secrets masked, the group whose card it is drawn inside (`parent`), and live status lines (`notices`).-Field types are `string`, `secret`, `boolean`, `number`, `enum` (with `options`) and `list` (one value per line, optional `maxItems`). A `number` may declare `minimum` and `maximum`, and a `string` or `list` a `pattern` (with `patternErrorMessage`) that every value or line must match.+Field types are `string`, `secret`, `boolean`, `number`, `enum` (with `options`) and `list` (one value per line, optional `maxItems`). A `number` may declare `minimum` and `maximum`, and a `string` or `list` a `pattern` (with `patternErrorMessage`) that every value or line must match. A field marked `advanced: true` is drawn in the card's Advanced fold, collapsed by default; it is stored and validated like any other. A field's `description` is what it means, drawn behind a "?" beside its title; its `hint` is the shape a value must take, shown under it. A `table` field has fixed `rows` and `columns` (`string`, `boolean` or `enum`, each with an optional `description` for its header's "?"), and may declare a `rowChoice` (a single choice of a row, stored in an `enum` field of the group, drawn as its title in brackets after the chosen row's name and picked from the row's "…" menu), a `pin` (a boolean column drawn as a pin toggle, with an `on` and `off` tooltip), a `columnGroup` (a header over adjacent columns) and `extensible` (rows may be added and reordered: stored under `"$added"` and `"$order"` beside the changed cells; only added rows may be deleted, and a row choice naming no row is refused). A row may carry a `description` and an `enum` option a `description`, both for the "?" after the row's name. A configuration may name a boolean field as its `switch`: while it is off, the card draws that field alone.++The sandbox's entry also carries `backend`: `installed` says whether a sandbox backend for this machine's OS is installed, and `recommended` names the package this OS defaults to (`@lmliheng/penguin-plugin-sandbox-bwrap` on Linux, `@lmliheng/penguin-plugin-sandbox-seatbelt` on macOS, `@lmliheng/penguin-plugin-sandbox-wsl` on Windows). Its `enabled` switch decides whether new Sessions start confined, and `defaultPreset` (the presets table's `rowChoice`, drawn as "(Default)" after the row's name) names the row whose mode, network and approval mode they start from. A document saved before the switch existed reads it as on when its old policy confined anything (a mode other than Off, a network that is not open, or masked paths); one saved before the default preset (with its own `mode` or `network`, or masked paths, and no `defaultPreset`) keeps starting new Sessions by its own `mode` and `network` until an administrator picks a default. For such a document `values.defaultPreset` is the first row whose start is exactly that one, and a save pins it; when no row gives it (a network of `none` or `local`, or Off with masked paths), `defaultPreset` is absent, a notice says what is in effect, and a save of other fields writes no `defaultPreset`. Neither is rewritten on read. A table's `rowChoice` may name no row: a save is not refused for that, only for leaving it on a row the table no longer has. The chat defaults' `sandbox.defaultApprovalMode` is the default preset's approval mode while the switch is on.On PUT, fields the request omits keep their value, `null` or `""` clears one, and a secret sent back as its mask keeps the stored value. A refused field returns `400` `plugin_config_invalid` naming it; a name no group answers to returns `404` `plugin_config_unknown`. The declaring module picks the change up itself, through its watch or at its next read, with no restart.@@ -680,7 +682,7 @@ Two conventions apply to every route here. A Session the caller cannot access al| Method | Path | Description || --- | --- | --- || GET | `/` | Session info |-| PATCH | `/` | Updates the Session: `{approvalMode?, thinkingLevel?, archived?, title?}` |+| PATCH | `/` | Updates the Session: `{approvalMode?, sandbox?, thinkingLevel?, archived?, title?}` || DELETE | `/` | Deletes the Session, with its Traces and scratch files || GET | `/messages` | The OmniMessage history, in full or as a window of Tasks || GET | `/trace-image?file=&ordinal=[&i=]` | One image of a Trace record, as a windowed `/messages` page references it |@@ -690,6 +692,7 @@ Two conventions apply to every route here. A Session the caller cannot access al| GET | `/goal` | The Session's most recent goal run |- `GET /` returns the Session's info. Unlike the list rows, the single-Session response also carries `tracePath`, the absolute path of the latest Trace file. `orgId` marks a Session that company mode's caches own (a desk session, or a session contributing to one of that organization's tickets); it is absent on every ordinary Session, and the list route sets it too.+- `PATCH /` checks every field before it writes any, the `sandbox` pick (`{mode?, network?}`) included: a non-admin's pick wider than the server's sandbox settings is `403` `sandbox_forbidden`, a level no backend here can enforce `400` `sandbox_unsupported`, and a refused request stores nothing — not its `approvalMode` or `title` either. The Session's `sandbox` view marks each row of its `presets` that is wider than the server's settings with `aboveCeiling: true` (response-only), by the same comparison: a non-admin's pick of such a row is refused.- `PATCH /` with `thinkingLevel` pins the level on this Session durably, from its very next LLM request. The thinking level is soft-limited: it can change mid-context, at the cost of the provider's cached context, which is why the level picker advises compacting first. The pinned level comes back as `SessionInfo.thinkingLevel`; when that is absent, no level was ever pinned and the agent config applies.- `GET /messages` without parameters returns the full OmniMessage history. `tailLimit=n` reads the newest n Task-aligned units instead, and `before=<cursor>&limit=n` reads the n units before a cursor. The two forms are exclusive, `n` is between 1 and 1000, and `limit` defaults to 200. A window also stays within 4 MiB of serialized messages: it stops before the unit that would pass that, but always holds at least one, so it can hold fewer units than asked for and still carry a `before` cursor. The bundled Web App opens a conversation on its latest 20 turns and loads 20 more each time you scroll to the top. A windowed response carries `page`, with the cursor for the next page (`before`), the number of turns before the window (`earlierTurns`), the cumulative stats before it (`prior`), and the model of the context the window starts in (`contextModel`): a Session can switch models between contexts, and a window that starts partway into one does not hold the `session_meta` that names its model. While a Task runs, the response also carries `live`; see [The live field on GET /messages](#the-live-field-on-get-messages).- A windowed page serves images by reference. In each record that carries a `tracePosition`, a PNG, JPEG, GIF or WebP `data:` URL, whether a user's `image_url` or an entry of a tool output's `images`, is replaced by `/api/sessions/:sessionId/trace-image?file=<fileIndex>&ordinal=<ordinal>`, with `&i=<k>` for the k-th entry of `images`. That route answers the decoded image with its own type, `Cache-Control: private, max-age=31536000, immutable` and `X-Content-Type-Options: nosniff`. It returns 404 `trace_image_not_found` when the record holds no such image, and 400 for a missing or malformed parameter. Subagent messages, other image types and the full read keep their `data:` URLs.diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 50d1d3f6..480f058b 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -167,7 +167,9 @@ PUT 按如下规则校验:设置分组是投给 `PluginConfigProvider.groups` 的 contribution,沙盒的排在最前。列表中的每个分组带有它的 schema(`configuration`)、合并到缺省值上的存储值(密钥掩码)、它被画在哪个分组的卡片里(`parent`),以及实时状态行(`notices`)。-字段类型有 `string`、`secret`、`boolean`、`number`、`enum`(带 `options`)和 `list`(每行一个值,可选 `maxItems`)。`number` 可声明 `minimum` 与 `maximum`;`string` 与 `list` 可声明每个值或每一行都须匹配的 `pattern`(配 `patternErrorMessage`)。+字段类型有 `string`、`secret`、`boolean`、`number`、`enum`(带 `options`)和 `list`(每行一个值,可选 `maxItems`)。`number` 可声明 `minimum` 与 `maximum`;`string` 与 `list` 可声明每个值或每一行都须匹配的 `pattern`(配 `patternErrorMessage`)。标记 `advanced: true` 的字段画在卡片默认折叠的「高级选项」里,存储与校验与其他字段相同。字段的 `description` 说明其含义,收在标题旁的「?」里;`hint` 是取值须符合的格式,显示在字段下方。`table` 字段有固定的 `rows` 与 `columns`(`string`、`boolean` 或 `enum`,各可带 `description`,用于列标题的「?」),并可声明 `rowChoice`(单选一行,存入该组的一个 `enum` 字段,画作被选行名称后带括号的标题,在该行的「…」菜单里选定)、`pin`(把一个布尔列画成图钉按钮,带 `on` 与 `off` 两种提示)、`columnGroup`(相邻几列上方的分组标题)与 `extensible`(可新增行并调整顺序,在改动的单元格旁存于 `"$added"` 与 `"$order"`;只有新增的行可删除,单选列不指向任何行的保存会被拒绝)。行可带 `description`,`enum` 的选项也可带 `description`,都用于行名称后的「?」。配置可把一个布尔字段声明为 `switch`:它关闭时,卡片只画这一个字段。++沙盒条目另带 `backend`:`installed` 表示是否装有适用于本机操作系统的沙盒后端,`recommended` 是本系统的默认后端包(Linux 为 `@lmliheng/penguin-plugin-sandbox-bwrap`,macOS 为 `@lmliheng/penguin-plugin-sandbox-seatbelt`,Windows 为 `@lmliheng/penguin-plugin-sandbox-wsl`)。其 `enabled` 开关决定新建 Session 是否进入沙盒,`defaultPreset`(预设表的 `rowChoice`,画作行名称后的「(默认)」)指定新 Session 取哪一行的封禁模式、网络与审批方式。开关出现之前保存的设置,旧策略有任何封禁(封禁模式不是「关闭」、网络不是完全开放,或设置了屏蔽路径)即视为打开;默认预设出现之前保存的设置(带自身的 `mode` 或 `network`、或设置了屏蔽路径,且没有 `defaultPreset`),新 Session 仍按其自身的 `mode` 与 `network` 开始,直到管理员选定默认行。对这类文档,`values.defaultPreset` 是起点与之完全相同的第一行,保存时写入它;没有这样的行时(网络为 `none` 或 `local`,或模式为关闭而设了屏蔽路径),`defaultPreset` 缺省,一条提示写明实际生效的值,保存别的字段也不写入 `defaultPreset`。读取时都不改写文档。表的 `rowChoice` 可以不指向任何一行:保存不因此被拒,只有让它指向表里已不存在的行时才被拒。chat defaults 的 `sandbox.defaultApprovalMode` 是开关打开时默认预设的审批方式。PUT 时,请求省略的字段保持原值,`null` 或 `""` 清除该字段,密钥按掩码原样送回即保持存储值。被拒的字段返回 `400` `plugin_config_invalid` 并点名该字段;没有分组叫这个名字时返回 `404` `plugin_config_unknown`。声明它的模块自己经 watch 或下次读取拿到改动,无需重启。@@ -680,7 +682,7 @@ Benchmark 属于 Project,不属于某个 Agent:一个 Benchmark 可以评估| 方法 | 路径 | 说明 || --- | --- | --- || GET | `/` | Session 信息 |-| PATCH | `/` | 更新 Session:`{approvalMode?, thinkingLevel?, archived?, title?}` |+| PATCH | `/` | 更新 Session:`{approvalMode?, sandbox?, thinkingLevel?, archived?, title?}` || DELETE | `/` | 删除 Session,连同它的 Trace 和暂存文件 || GET | `/messages` | OmniMessage 历史,全量或按 Task 窗口 || GET | `/trace-image?file=&ordinal=[&i=]` | Trace 记录中的一张图片,即分窗 `/messages` 页引用的图片 |@@ -690,6 +692,7 @@ Benchmark 属于 Project,不属于某个 Agent:一个 Benchmark 可以评估| GET | `/goal` | 当前 Session 最近一次目标运行 |- `GET /` 返回 Session 的信息。与列表行不同,单个 Session 的响应还带 `tracePath`,即最新 Trace 文件的绝对路径。`orgId` 标记公司模式缓存持有的会话(工位会话,或这个组织某个工单的贡献会话);普通 Session 一律不带这个字段,列表路由同样会设置它。+- `PATCH /` 先校验全部字段再写入任何一个,`sandbox` 选择(`{mode?, network?}`)也在其中:非管理员选的档位比服务端的沙盒设置更宽时为 `403` `sandbox_forbidden`,本机没有后端能实施的档位为 `400` `sandbox_unsupported`;被拒的请求什么都不落盘,`approvalMode` 与 `title` 也不例外。Session 的 `sandbox` 视图里,`presets` 中比服务端设置更宽的行带 `aboveCeiling: true`(只出现在响应里),与这条拒绝用同一次比较:非管理员选这样的行会被拒绝。- `PATCH /` 带 `thinkingLevel` 会把这个思考等级持久地固定到这个 Session,从下一次 LLM 请求开始生效。思考等级是软性限制:可以在上下文中途更改,代价是损失供应商已缓存的上下文,因此等级选择器会建议先压缩。固定后的等级以 `SessionInfo.thinkingLevel` 返回;没有这个字段说明从未固定等级,此时采用 Agent 配置。- `GET /messages` 不带参数时返回完整的 OmniMessage 历史。`tailLimit=n` 改为读取最新的 n 个按 Task 对齐的单元,`before=<cursor>&limit=n` 读取某个游标之前的 n 个单元。两种形式互斥,`n` 在 1 到 1000 之间,`limit` 默认为 200。窗口还受 4 MiB 的序列化大小约束:加入某个单元会超出时就在它之前收口,但至少包含一个单元,所以窗口的单元数可能少于请求的数量,此时同样带 `before` 游标。内置 Web App 打开一段对话时先显示最近 20 轮,每次滚动到顶部再加载 20 轮。窗口式响应带 `page`,包含下一页的游标(`before`)、窗口之前的轮数(`earlierTurns`)、此前累计的统计(`prior`),以及窗口起点所在上下文的模型(`contextModel`):Session 可以在上下文之间切换模型,而从某个上下文中途开始的窗口并不包含记录其模型的那条 `session_meta`。Task 运行期间,响应还会带 `live`;见 [GET /messages 上的 live 字段](#get-messages-上的-live-字段)。- 窗口式响应中的图片按引用下发。在带 `tracePosition` 的记录里,PNG、JPEG、GIF 或 WebP 的 `data:` URL(无论是用户的 `image_url`,还是工具输出 `images` 中的一项)会被替换为 `/api/sessions/:sessionId/trace-image?file=<fileIndex>&ordinal=<ordinal>`,`images` 的第 k 项再加 `&i=<k>`。这条路由返回解码后的图片,带图片自身的类型、`Cache-Control: private, max-age=31536000, immutable` 和 `X-Content-Type-Options: nosniff`。记录中没有对应图片时返回 404 `trace_image_not_found`,参数缺失或格式不对时返回 400。子 Agent 的消息、其他类型的图片以及全量读取都保留原来的 `data:` URL。diff --git a/packages/docs/content/settings.en.md b/packages/docs/content/settings.en.mdindex 36918a9c..29eaebdd 100644--- a/packages/docs/content/settings.en.md+++ b/packages/docs/content/settings.en.md@@ -269,10 +269,11 @@ The **Plugins** page is admin-only and server-global. It shows the options eachThe sandbox is the first card on the page. It sets the policy a new Session is confined under. One policy governs the commands the agent runs, the hook scripts its Session runs, the MCP Servers it starts over `stdio`, and the file tools (`read_file`, `edit_file`, `write_file`):-- **Confinement mode**: off (full access), workspace write only, or read-only. Workspace write allows writes to the Session's Workspace, its scratchpad (the plan file, a goal's state file, attachments) and the temporary directory; read-only allows the temporary directory only.-- **Network**: full access, local network (localhost only), or no network. It applies to the image URLs `read_file` fetches too. The local level needs a backend that can enforce it.-- **Temporary directory**: whether it stays writable. On by default, in either confining mode, because shells and most tools cannot start without one.-- **Masked paths**: paths hidden from the agent's commands, hook scripts, `stdio` MCP Servers and file tools, reads included; one absolute path per line, at most 64.+- **Enable**: the switch at the top. Off (a fresh install), a new Session has full file and network access and is held only by its approval mode, and the composer's permission menu lists the approval modes alone. While it is off, the card shows the switch alone: the presets, the Advanced fold, the backends' own settings and the card's notices come back when it is turned on, as they were.+- **Presets**: the table of what the permission menu offers, one row per preset: its name, file mode (off, workspace, read-only), network (full, localhost, none) and approval mode, and an **Action** group: a pin for whether the menu lists it, a drag handle, and a "…" menu with **Set as default** and, on presets you added, **Delete**. The default row reads "(Default)" after its name, and each name's "?" says what the row is for — for a preset you added, or a built-in one whose values you changed, what each of its values does. Each header's "?" says what the column (or each icon) means. Drag a row's handle (or press the arrow keys on it) to reorder; the order is the menu's. **Add preset** adds a row; only added rows can be deleted, and not while they are the default. Workspace allows writes to the Session's Workspace, its scratchpad (the plan file, a goal's state file, attachments) and the temporary directory; read-only allows the temporary directory only. The network level applies to the image URLs `read_file` fetches too, and localhost needs a backend that can enforce it. The default row is the one a new Session starts from while the switch is on — its file mode, network and approval mode; Workspace Write until changed. Settings saved before the presets table keep their own file mode and network until you set a default: the card marks as default the row that starts Sessions exactly where they do, and saving pins it. When no row does (a cut or localhost-only network, or masked paths with the file mode off), no row is marked, a notice at the top of the card says what is in effect, and saving other settings keeps it; set a row as default, or add a preset with those values and set it.+- Under **Advanced**, folded by default:+ - **Temporary directory**: whether it stays writable. On by default, in either confining mode, because shells and most tools cannot start without one.+ - **Masked paths**: paths hidden from the agent's commands, hook scripts, `stdio` MCP Servers and file tools, reads included; one absolute path per line, at most 64.Neither confining mode lets the agent write its Agent State: `AGENTS.md`, `system_config.yaml`, Skills, hook packages, memory, the vault and scheduled tasks. To let an agent write memory, write its own Skills or hook packages, or change its configuration, switch that conversation to full access with its **Permissions** button. An MCP Server started over `stdio` is confined the same way when it starts — at a context open or a reconnect — so a Server that must write outside those directories, or reach a network the level cuts, fails to connect in a confining Session; MCP Servers reached over `http` or `sse` are not processes of this machine and are not confined.diff --git a/packages/docs/content/settings.zh.md b/packages/docs/content/settings.zh.mdindex 0fbb03d5..da667079 100644--- a/packages/docs/content/settings.zh.md+++ b/packages/docs/content/settings.zh.md@@ -269,10 +269,11 @@ Trace 会成为该 Agent 的一段新对话。如果该 Agent 下已有相同 id沙盒是页面上的第一张卡片,设置新建 Session 所处的封禁策略。同一份策略约束 Agent 执行的命令、Session 运行的钩子脚本、它以 `stdio` 方式启动的 MCP Server,以及文件工具(`read_file`、`edit_file`、`write_file`):-- **封禁模式**:关闭(完全访问)、仅工作区可写或只读。仅工作区可写时,可写的是 Session 的 Workspace、它的 scratchpad(计划文件、goal 的状态文件与附件都在这里)和临时目录;只读时只有临时目录可写。-- **网络**:完全访问、本地网络(仅本机 localhost)或无网络。`read_file` 读取的图片 URL 同样受它约束。本地网络需要能实施它的后端。-- **临时目录**:是否保持可写。默认开启,两种封禁模式下都生效,因为 Shell 与大多数工具没有它就无法启动。-- **屏蔽路径**:对 Agent 的命令、钩子脚本、`stdio` MCP Server 和文件工具隐藏的路径,读取也不例外;每行一个绝对路径,最多 64 条。+- **启用**:卡片顶部的开关。关闭时(全新安装即如此),新 Session 拥有完全的文件与网络访问,只受审批模式约束,输入框的权限菜单只列出审批模式。关闭期间卡片只显示这个开关:预设表、高级选项、后端自身的设置与卡片的提示都在打开后原样恢复。+- **预设**:权限菜单提供的选项表,每个预设一行:名称、文件模式(关闭、仅工作区、只读)、网络(完全、仅本机、无)、审批方式,以及**操作**一组图标:图钉表示是否进菜单,拖动手柄,以及「…」菜单,内有**设为默认**和(仅新增预设上的)**删除**。默认行在名称后标有「(默认)」;每个名称旁的「?」说明这一行的用途——新增的预设,或改过取值的内置预设,则逐项说明各取值的作用。每个标题旁的「?」说明该列(或每个图标)的含义。拖动手柄(或在手柄上按上下方向键)调整顺序,菜单按此顺序列出。**添加预设**新增一行;只有新增的行可以删除,且不能是默认行。仅工作区时,可写的是 Session 的 Workspace、它的 scratchpad(计划文件、goal 的状态文件与附件都在这里)和临时目录;只读时只有临时目录可写。网络档位同样约束 `read_file` 读取的图片 URL,仅本机需要能实施它的后端。默认行是开关打开时新 Session 的起点——取该行的文件模式、网络与审批方式;未改动时为 Workspace Write。预设表出现之前保存的设置,在你设定默认行之前沿用自身的文件模式与网络:卡片把起点与之完全相同的那一行标为默认,保存时写入它。没有这样的行时(网络为无网络或仅本机,或文件模式为关闭而设了屏蔽路径),不标任何一行,卡片顶部的提示写明实际生效的值,保存其他设置也保留它;把一行设为默认,或先添加一条同值的预设再设为默认即可。+- 收在默认折叠的**高级选项**里:+ - **临时目录**:是否保持可写。默认开启,两种封禁模式下都生效,因为 Shell 与大多数工具没有它就无法启动。+ - **屏蔽路径**:对 Agent 的命令、钩子脚本、`stdio` MCP Server 和文件工具隐藏的路径,读取也不例外;每行一个绝对路径,最多 64 条。两种封禁模式都不允许 Agent 写自己的 Agent State:`AGENTS.md`、`system_config.yaml`、Skill、钩子包、记忆、vault 与定时任务。要让 Agent 写记忆、自行编写 Skill 或钩子包、修改自己的配置,用该对话的**权限**按钮把它切到完全访问。以 `stdio` 方式启动的 MCP Server 在启动时(上下文开启或重连)受同样的封禁:必须写这些目录之外、或访问网络档位所切断的网络的 Server,在封禁的 Session 里会连接失败;经 `http` / `sse` 访问的 MCP Server 不是本机进程,不在封禁之列。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 3b394306..d24c3a0a 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -1536,6 +1536,50 @@ export interface SessionSandbox {* composer marks the confining levels unavailable and gives the first one's reason.*/unavailableBackends?: UnavailableSandboxBackend[];+ /**+ * Response only, ignored in requests: the server's sandbox presets (the Sandbox card's table),+ * in table order, disabled rows included. The composer lists the enabled ones and names the+ * Session's level by the first row matching its mode, network and approval mode. A server+ * that does not report it gets the composer's built-in table.+ */+ presets?: SessionSandboxPreset[];+ /**+ * Response only, ignored in requests: true when this Session's policy holds something the+ * presets do not show — masked paths, or the temp directory not writable.+ */+ advanced?: boolean;+ /**+ * Response only, chat defaults only: the approval mode a new Session starts with when its+ * request names none — the Sandbox card's default preset's, while the switch is on. Absent:+ * the server's own fallback (`allow-all`).+ */+ defaultApprovalMode?: ApprovalMode;+ /**+ * Response only, ignored in requests: the Sandbox card's switch on this server — whether new+ * Sessions start confined. Off, the composer offers the approval modes alone (a Session keeps+ * its own policy either way). A server that does not report it is read as on.+ */+ switchOn?: boolean;+}++/** One sandbox preset: a named mode, network level and approval mode. */+export interface SessionSandboxPreset {+ id: string;+ /** The name an administrator gave it, or its declared English name. */+ name: string;+ /** Its declared Chinese name, while it has not been renamed. */+ nameZh?: string;+ /** Whether the composer's menu lists it. */+ enabled: boolean;+ mode: SessionSandboxMode;+ network: SessionSandboxNetwork;+ approvalMode: ApprovalMode;+ /**+ * Response-only: its file mode or network is wider than the server's sandbox settings (the+ * ceiling for non-admins), so a non-admin's pick of it is refused with `403 sandbox_forbidden`.+ * The same comparison as that refusal; absent when it is within them.+ */+ aboveCeiling?: true;}/** An enabled sandbox backend that is not in use on this server, and why. */@@ -5384,17 +5428,30 @@ export interface ContributionsResponse {* One field of a settings group a module declares (its `PluginConfigProvider.groups`* contribution's `properties.<name>`): what the Settings dialog draws for it. `secret` is* drawn as a password field and masked on the way out; `enum` is a choice among `options`;- * `list` is a list of strings, drawn one per line.+ * `list` is a list of strings, drawn one per line; `table` is a fixed set of `rows`, each a+ * value per one of its `columns`, drawn as a table.*/export interface PluginConfigField {- type: "string" | "secret" | "boolean" | "number" | "enum" | "list";+ type: "string" | "secret" | "boolean" | "number" | "enum" | "list" | "table";title: string;titleZh?: string;+ /** What the field means: disclosed behind a "?" beside its title. */description?: string;descriptionZh?: string;+ /**+ * The shape a value must take ("one absolute path per line"): shown under the field at all+ * times, since it is read while typing.+ */+ hint?: string;+ hintZh?: string;placeholder?: string;/** The value a package with nothing stored reads; also what an empty field falls back to. */default?: string | number | boolean | string[];+ /**+ * Drawn in the card's Advanced fold, collapsed by default, rather than among the basic+ * fields. Presentation only: it is stored, validated and read like any other field.+ */+ advanced?: boolean;/** A save that would leave this field empty is refused. */required?: boolean;/** `enum` only: the values it may take, in display order. */@@ -5408,6 +5465,114 @@ export interface PluginConfigField {pattern?: string;/** What a save refused by `pattern` says, after the field's name (e.g. "must be an absolute path"). */patternErrorMessage?: string;+ /**+ * `table` only: its columns, in display order, and its rows, in display order. The table+ * has no `default`: the rows' declared cells are its defaults, and what is stored is only+ * the cells that differ from them — `{ [row id]: { [column]: value } }`.+ */+ columns?: PluginConfigTableColumn[];+ rows?: PluginConfigTableRow[];+ /**+ * `table` only: a single choice of one row — the sandbox's default preset. The choice is+ * stored in `field`, an `enum` field of the same group whose options are the row ids (plus,+ * in an `extensible` table, the ids of the rows added to it); the page draws that field only+ * as its title in brackets after the chosen row's name ("(Default)"), and picks it from a+ * row's "…" menu.+ */+ rowChoice?: PluginConfigRowChoice;+ /**+ * `table` only: rows may be added (and only those deleted, from the row's "…" menu) and every+ * row reordered. A new row+ * starts from these values. What is stored, beside the declared rows' changed cells, is the+ * added rows under `"$added"` (`{ [row id]: { [column]: value } }`, every column present) and+ * the row order under `"$order"` (row ids); neither key can be a row id. A save sends either+ * key whole; a document without them reads as the declared rows in declared order.+ */+ extensible?: PluginConfigNewRow;+ /**+ * `table` only: a header drawn over adjacent columns that belong together (the sandbox's+ * Pin, under "Action"). `columns` names them. When the group ends the columns, the row's drag+ * handle and "…" menu join it.+ */+ columnGroup?: PluginConfigColumnGroup;+ /**+ * `table` only: a `boolean` column drawn as a pin toggle rather than a switch — a row pinned+ * to a list (the sandbox presets in the composer's menu). The texts are its tooltip in each+ * state. Declared on the table, not the column, so every column keeps one shape.+ */+ pin?: PluginConfigPinColumn;+}++/** A table's pin column: which boolean column, and its tooltip pinned and not. */+export interface PluginConfigPinColumn {+ column: string;+ on: string;+ onZh?: string;+ off: string;+ offZh?: string;+}++/**+ * A table's single choice of a row: the `enum` field it stores into, and its title, drawn in+ * brackets after the chosen row's name. The choice may name no row (nothing stored, and the+ * group's `derive` gives none): no row is marked and a save is not refused for it. A save that+ * leaves it naming a row the table no longer has is refused.+ */+export interface PluginConfigRowChoice {+ field: string;+ title: string;+ titleZh?: string;+}++/** One column of a `table` field: a scalar field type (`string`, `boolean`, or an `enum` with `options`). */+export interface PluginConfigTableColumn {+ name: string;+ type: "string" | "boolean" | "enum";+ title: string;+ titleZh?: string;+ /** What the column means: disclosed behind a "?" beside its header. */+ description?: string;+ descriptionZh?: string;+ options?: PluginConfigOption[];+}++/** One row of a `table` field: its id and its declared cells. */+export interface PluginConfigTableRow {+ id: string;+ /** Every column's declared value. */+ values: Record<string, string | boolean>;+ /** A string cell's declared value in Chinese, shown until a save changes the cell. */+ valuesZh?: Record<string, string>;+ /** Columns whose cell in this row a save may not change. */+ locked?: string[];+ /** A row added to an `extensible` table (not declared): the only kind that may be deleted. */+ added?: boolean;+ /**+ * What the row is for, disclosed behind a "?" beside its name while its `enum` cells hold+ * their declared values. A row without one, or whose choices changed, gets a "?" listing its+ * `enum` cells' values and what each does (the options' `description`s).+ */+ description?: string;+ descriptionZh?: string;+}++/** A header over adjacent table columns, with its own "?". */+export interface PluginConfigColumnGroup {+ title: string;+ titleZh?: string;+ description?: string;+ descriptionZh?: string;+ columns: string[];+}++/** The values a row added to an `extensible` table starts from. */+export interface PluginConfigNewRow {+ /** The add button's text ("Add preset"). */+ add?: string;+ addZh?: string;+ values: Record<string, string | boolean>;+ /** A string column's starting text in Chinese. */+ valuesZh?: Record<string, string>;}/** One choice of an `enum` field. */@@ -5415,6 +5580,9 @@ export interface PluginConfigOption {value: string;title: string;titleZh?: string;+ /** What picking it does: listed, for a table column's option, in a row's "?" (see the row's `description`). */+ description?: string;+ descriptionZh?: string;}/** A declared configuration: a titled group of fields, in declaration order. */@@ -5423,6 +5591,13 @@ export interface PluginConfiguration {titleZh?: string;description?: string;descriptionZh?: string;+ /**+ * A `boolean` field that turns the group on (the sandbox's `enabled`). While it is off, as+ * drafted, the card draws that field alone: no other field, notice or action, and none of the+ * groups drawn inside it. Turning it on in a group that reports a `backend` it lacks offers+ * to install one.+ */+ switch?: string;properties: Record<string, PluginConfigField>;}@@ -5453,11 +5628,28 @@ export interface PluginConfigEntry {actions?: PluginConfigActionDecl[];/** Enum options this machine cannot honour now: drawn greyed out with the reason; a save choosing one is refused. */unavailable?: PluginConfigUnavailableDecl[];+ /**+ * For a group whose settings a backend plugin enforces (the sandbox): whether one that+ * applies to this machine's OS is installed, and which package this OS defaults to. The card+ * offers to install `recommended` when the group's switch is turned on and none is installed.+ * Asked per read, like the notices; the client never guesses the OS.+ */+ backend?: PluginConfigBackend;+}++/** Whether a backend that applies to this machine is installed, and this OS's default one. */+export interface PluginConfigBackend {+ /** A backend for this OS is installed: loaded, or installed and failing its check. */+ installed: boolean;+ /** The npm package this OS defaults to; absent on an OS with no default backend. */+ recommended?: string;}/** One enum option a settings group cannot honour on this machine, and why. */export interface PluginConfigUnavailableDecl {field: string;+ /** A `table` field's column: the option is unavailable in every cell of that column. */+ column?: string;value: string;reason: string;reasonZh?: string;diff --git a/packages/server/src/http/routes/admin-plugin-config.ts b/packages/server/src/http/routes/admin-plugin-config.tsindex f79a6056..10ceb3a2 100644--- a/packages/server/src/http/routes/admin-plugin-config.ts+++ b/packages/server/src/http/routes/admin-plugin-config.ts@@ -12,7 +12,7 @@ import { Hono } from "hono";import type { PluginConfigActionResponse, PluginConfigResponse } from "../../api/types.js";import type { AppEnv } from "../../auth/middleware.js";import { PluginConfigError } from "../../plugin/config.js";-import type { PluginConfigAdmin } from "../../plugin/config.js";+import type { PluginConfigAdmin } from "../../plugin/config-page.js";import { HttpError } from "../errors.js";import { badRequest, readJson, requireString } from "../validate.js";diff --git a/packages/server/src/http/routes/admin.ts b/packages/server/src/http/routes/admin.tsindex c781ff8e..e7736f30 100644--- a/packages/server/src/http/routes/admin.ts+++ b/packages/server/src/http/routes/admin.ts@@ -14,7 +14,7 @@ import { Bind, Component, Use } from "@lmliheng/penguin-core/kernel";import type { Desktop, Proxy } from "../../hmr/capabilities.js";import { adminSettingsRoutes } from "./admin-settings.js";import { adminPluginConfigRoutes } from "./admin-plugin-config.js";-import { PluginConfigAdmin } from "../../plugin/config.js";+import { PluginConfigAdmin } from "../../plugin/config-page.js";import type { Admin } from "../../mechanisms/identity.js";import type { Settings } from "../../mechanisms/settings.js";diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.tsindex 47aec411..2004c3f0 100644--- a/packages/server/src/http/routes/sessions.ts+++ b/packages/server/src/http/routes/sessions.ts@@ -693,6 +693,13 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {"No updatable field provided (approvalMode / sandbox / thinkingLevel / archived / title).",);}+ // Every check before any write: the sandbox pick's (the non-admin ceiling, what this server+ // can enforce) included, so a refused request stores nothing — not the approval-mode half+ // of a preset whose sandbox half was refused.+ const nextSandbox =+ sandbox !== undefined+ ? deps.sessionService.pickSandbox(row, sandbox, c.var.user.isAdmin)+ : undefined;let updated: SessionRow = { ...row };if (title !== undefined) {// Manual renaming takes priority over auto-generation: TitleGenerator only ever replaces the fallback title it wrote itself, never a manual rename.@@ -712,10 +719,10 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {deps.sessionsRepo.updateApprovalMode(row.sessionId, approvalMode);updated = { ...updated, approvalMode };}- if (sandbox !== undefined) {+ if (nextSandbox !== undefined) {// Takes effect at the Session's next command: its confiner reads the row at every spawn.- const next = deps.sessionService.updateSandbox(row, sandbox, c.var.user.isAdmin);- updated = { ...updated, sandbox: next };+ deps.sessionService.updateSandbox(row.sessionId, nextSandbox);+ updated = { ...updated, sandbox: nextSandbox };}if (thinkingLevel !== undefined) {// The row is what the loader applies at load; a runtime already loaded is assigned@@ -1768,7 +1775,7 @@ export class SessionApiRoutes {agentConfigService,projectConfigService,access,- sandboxDefaults: () => sessionService.sandboxView(sessionService.defaultSandbox()),+ sandboxDefaults: () => sessionService.defaultsView(),});this.commandPolicyRoutes = commandPolicyRoutes({ projectConfigService, access });this.agentsRoutes = agentsRoutes({diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.tsindex fc0c13fd..2caa5b9c 100644--- a/packages/server/src/platform.ts+++ b/packages/server/src/platform.ts@@ -48,12 +48,8 @@ import { QQTransportProvider } from "./runtime/messaging/qq-connector.js";import { QQScanTransportProvider } from "./runtime/messaging/qq-scan.js";import { WeChatTransportProvider } from "./runtime/messaging/wechat-connector.js";import { WeChatScanTransportProvider } from "./runtime/messaging/wechat-scan.js";-import {- PluginConfig,- PluginConfigAdmin,- PluginConfigPage,- PluginConfigProvider,-} from "./plugin/config.js";+import { PluginConfig, PluginConfigProvider } from "./plugin/config.js";+import { PluginConfigAdmin, PluginConfigPage } from "./plugin/config-page.js";import {CoreSessionLoaders,DefaultTitleGenerators,@@ -114,7 +110,8 @@ import { MemoryService } from "./services/memory-service.js";import { BenchmarkService } from "./services/benchmark-service.js";import { ProjectsRoutes } from "./http/routes/dirs.js";import { SandboxModule } from "./sandbox/service.js";-import { SandboxSettings, SandboxSettingsStatus } from "./sandbox/settings-store.js";+import { SandboxSettings } from "./sandbox/settings-store.js";+import { SandboxSettingsStatus } from "./sandbox/settings-status.js";import { SchedulerRoutes } from "./http/routes/schedules.js";import { Machines, MachinesModule } from "./machines/service.js";import { OrganizationModule, OrgScheduler, OrgService } from "./runtime/organization/service.js";diff --git a/packages/server/src/plugin/config-page.ts b/packages/server/src/plugin/config-page.tsnew file mode 100644index 00000000..ee51926e--- /dev/null+++ b/packages/server/src/plugin/config-page.ts@@ -0,0 +1,244 @@+/**+ * The Plugins page's view of the settings groups: the stored entries (`PluginConfigEntries`,+ * config.ts) with what each group's status contributor reports live — notices, actions, enum+ * options this machine cannot honour, values derived for a document saved before a field+ * existed, and whether a backend the group needs is installed. A separate node from the store+ * for the ordering reason config.ts gives: a status contributor (the sandbox's, which reads the+ * sandbox service) is created before this page, and a sandbox backend reading its own group is+ * created after the provider.+ */+import { Interface, Module, Provide, Use } from "@lmliheng/penguin-core/kernel";+import type { ClassCtx, Slot } from "@lmliheng/penguin-core/kernel";+import type {+ PluginConfigBackend,+ PluginConfigEntry,+ PluginConfigNotice,+ PluginConfiguration,+} from "../api/types.js";+import {+ PluginConfig,+ PluginConfigEntries,+ PluginConfigError,+ TABLE_ADDED,+ isRecord,+ resolveTable,+} from "./config.js";++/**+ * The code half of a `status` contribution: a group's live notices, asked per read, and the+ * ACTIONS it offers.+ *+ * An action is for what a person cannot express as a field: something the deployment must DO+ * once, on the machine, before the settings above mean anything — the Windows sandbox's local+ * accounts, which need an administrator's consent. Naming the command in a notice puts the work+ * on whoever reads it; an action lets the module do it and report back.+ */+export interface SettingsGroupStatus {+ /**+ * The live notices, asked per read. `stored` and `configuration` are the group's document+ * whole and its declaration, as `derive` gets them, for a notice about what is stored.+ */+ notices(+ stored: Record<string, unknown>,+ configuration: PluginConfiguration,+ ): PluginConfigNotice[];+ /**+ * After a save of this group or of one drawn inside its card: does what that save sets in+ * motion beyond the group's own watchers, and resolves once it has settled, so the notices+ * the save answers with are current.+ */+ saved?(): Promise<void>;+ /** What this group offers to do, drawn as buttons beneath its notices. */+ actions?(): PluginConfigAction[];+ /**+ * Enum options this machine cannot honour right now: drawn greyed out with the reason, and a+ * save choosing one is refused. Asked per read, like the notices.+ */+ unavailable?(): PluginConfigUnavailable[];+ /** Runs one, by its id. Told what happened, in words the page shows as they are. */+ run?(action: string): Promise<PluginConfigActionResult>;+ /**+ * The values the page reads, with what the group derives for a document saved before one of+ * its fields existed (the sandbox's `enabled`, read off its old mode). Read-side only: the+ * document on disk is never rewritten, and the module applying the group derives the same way+ * from the document it reads. `stored` is that document whole — the stored keys merged onto+ * the defaults, including keys the schema no longer declares, which `values` leaves out;+ * `configuration` is the group's declaration (what `resolveTable` reads a table by).+ */+ derive?(+ values: Record<string, unknown>,+ stored: Record<string, unknown>,+ configuration: PluginConfiguration,+ ): Record<string, unknown>;+ /** For a group a backend plugin enforces: whether one for this OS is installed, and the default. */+ backend?(): PluginConfigBackend;+ /**+ * Completes a save of this group before it is validated and stored: what every save must+ * write besides the fields the page changed. `current` is the group's values as the page+ * reads them (`derive` applied) (the sandbox pins the default preset the card shows, which a+ * document saved before the default preset may not have).+ */+ saving?(+ update: Record<string, unknown>,+ current: Record<string, unknown>,+ ): Record<string, unknown>;+}++/** One enum option a settings group cannot honour on this machine, and why. */+export interface PluginConfigUnavailable {+ field: string;+ /** A `table` field's column: the option is unavailable in every cell of that column. */+ column?: string;+ value: string;+ reason: string;+ reasonZh?: string;+}++/** One thing a settings group can do, named for the button that runs it. */+export interface PluginConfigAction {+ id: string;+ title: string;+ titleZh?: string;+ /** What pressing it will do, shown beside the button — a person consents to what they read. */+ description?: string;+ descriptionZh?: string;+}++/** What an action reports: whether it did what it said, and what to tell the person. */+export interface PluginConfigActionResult {+ ok: boolean;+ message: string;+ messageZh?: string;+ /**+ * Work the action started and did not wait for, reported through `progress` notices; it+ * resolves when that work ends. The page node then settles the card the way a save does (a+ * sandbox backend the work made usable loads again). Never sent to the page.+ */+ settled?: Promise<void>;+}++/** What the settings page reads and writes. */+@Interface()+export abstract class PluginConfigAdmin {+ /** Every declared group, in order, with its live notices; values masked. */+ abstract describe(): PluginConfigEntry[];+ /** Validates and stores one update; answers that entry, masked, with its notices once its card's status has settled. */+ abstract set(name: string, update: Record<string, unknown>): Promise<PluginConfigEntry>;+ /** Runs one group's action and says what happened; throws PluginConfigError for an unknown one. */+ abstract run(name: string, action: string): Promise<PluginConfigActionResult>;+}++export interface PluginConfigAdminSlots {+ /** Live notices for a group that has any (`group` names it). */+ status: Slot<{ group: string }, SettingsGroupStatus>;+}++/** The page's view: the stored entries with the live notices their status contributors report. */+@Module()+export class PluginConfigPage {+ @Use() private readonly entries!: PluginConfigEntries;+ /** The stored documents whole, which a group's `derive` reads. */+ @Use() private readonly pluginConfig!: PluginConfig;+ @Provide() pluginConfigAdmin!: PluginConfigAdmin;+ setup({ contributions }: ClassCtx) {+ const entries = this.entries;+ const pluginConfig = this.pluginConfig;+ const status = new Map<string, SettingsGroupStatus>();+ for (const c of contributions.status ?? []) {+ status.set(c.data.group as string, c.code as SettingsGroupStatus);+ }+ const withStatus = (entry: PluginConfigEntry): PluginConfigEntry => {+ const group = status.get(entry.name);+ const stored = pluginConfig.get(entry.name);+ const notices = group?.notices(stored, entry.configuration) ?? [];+ const actions = group?.actions?.() ?? [];+ const unavailable = group?.unavailable?.() ?? [];+ const backend = group?.backend?.();+ return {+ ...entry,+ ...(group?.derive !== undefined+ ? { values: group.derive(entry.values, stored, entry.configuration) }+ : {}),+ ...(notices.length > 0 ? { notices } : {}),+ ...(actions.length > 0 ? { actions } : {}),+ ...(unavailable.length > 0 ? { unavailable } : {}),+ ...(backend !== undefined ? { backend } : {}),+ };+ };+ /** A group's values as the page reads them: stored onto defaults, then derived. */+ const readValues = (name: string, group: SettingsGroupStatus) => {+ const entry = entries.describe().find((e) => e.name === name);+ if (entry === undefined) return {};+ return (+ group.derive?.(entry.values, pluginConfig.get(name), entry.configuration) ?? entry.values+ );+ };+ this.pluginConfigAdmin = {+ describe: () => entries.describe().map(withStatus),+ set: async (name, sent) => {+ const group = status.get(name);+ const update =+ group?.saving === undefined ? sent : group.saving(sent, readValues(name, group));+ // An option this machine cannot honour is refused like an invalid value, naming it.+ for (const u of status.get(name)?.unavailable?.() ?? []) {+ if (u.column !== undefined) {+ // A table is saved whole: only a cell the save CHANGES to the value is refused, so+ // one already holding it (a backend went away since) does not block the others.+ const rows = update[u.field];+ const entry = entries.describe().find((e) => e.name === name);+ const field = entry?.configuration.properties[u.field];+ const current =+ field?.type === "table" ? resolveTable(field, entry!.values[u.field]) : [];+ const before = (id: string): Record<string, unknown> =>+ current.find((r) => r.id === id)?.values ?? {};+ // The declared rows' cells, and the added rows (stored whole, so every cell of+ // theirs is "sent").+ const sentRows = isRecord(rows)+ ? { ...rows, ...(isRecord(rows[TABLE_ADDED]) ? rows[TABLE_ADDED] : {}) }+ : {};+ const row = Object.entries(sentRows).find(+ ([id, cells]) =>+ isRecord(cells) &&+ cells[u.column!] === u.value &&+ before(id)[u.column!] !== u.value,+ );+ if (row !== undefined) {+ const at = `${u.field}.${row[0]}.${u.column}`;+ throw new PluginConfigError(+ u.field,+ `"${at}" cannot be "${u.value}" here: ${u.reason}`,+ );+ }+ continue;+ }+ if (update[u.field] === u.value) {+ throw new PluginConfigError(+ u.field,+ `"${u.field}" cannot be "${u.value}" here: ${u.reason}`,+ );+ }+ }+ const saved = entries.set(name, update);+ await status.get(saved.parent ?? name)?.saved?.();+ return withStatus(saved);+ },+ run: async (name, action) => {+ const group = status.get(name);+ const offered = group?.actions?.() ?? [];+ if (group?.run === undefined || !offered.some((a) => a.id === action)) {+ throw new PluginConfigError(null, `"${name}" offers no action "${action}".`);+ }+ const { settled, ...result } = await group.run(action);+ // What the action changed on the machine is settled like a save of its card: the+ // owner's status runs its follow-up (a backend that failed its check loads again).+ const owner = entries.describe().find((e) => e.name === name)?.parent ?? name;+ const settle = async () => {+ await status.get(owner)?.saved?.();+ };+ if (settled === undefined) await settle();+ else void settled.then(settle, settle).catch(() => {});+ return result;+ },+ };+ }+}diff --git a/packages/server/src/plugin/config.ts b/packages/server/src/plugin/config.tsindex 384eff4d..bb2da0c7 100644--- a/packages/server/src/plugin/config.ts+++ b/packages/server/src/plugin/config.ts@@ -8,7 +8,8 @@* can list and validate it without running the package. Its shape is VS Code's* `contributes.configuration` cut down to what a settings page can draw without knowing the* module — a titled group of fields (a string, a secret, a boolean, a number, a choice among- * options, or a list of lines) — plus a `parent` that draws the group inside another's card.+ * options, a list of lines, or a table of fixed rows) — plus a `parent` that draws the group+ * inside another's card.* The group's name is the contribution's id. A group whose status changes at run time (the* sandbox's backends) contributes that as code to `PluginConfigPage.status`.*@@ -26,8 +27,8 @@* boot (a data-only contribution), which is what lets one module both declare and require.** Two nodes, for the same ordering reason. `PluginConfigProvider` holds the values and takes- * the declarations; `PluginConfigPage` is what the admin API reads — the entries with their- * live notices — and takes the status code. A status contributor (the sandbox's, which reads+ * the declarations; `PluginConfigPage` (config-page.ts) is what the admin API reads — the+ * entries with their live notices — and takes the status code. A status contributor (the sandbox's, which reads* the sandbox service) is created before the page, and a sandbox backend reading its own* group is created after the provider: one node for both would close that circle.*/@@ -36,7 +37,10 @@ import type { ClassCtx, Slot } from "@lmliheng/penguin-core/kernel";import type {PluginConfigEntry,PluginConfigField,- PluginConfigNotice,+ PluginConfigOption,+ PluginConfigPinColumn,+ PluginConfigTableColumn,+ PluginConfigTableRow,PluginConfiguration,} from "../api/types.js";import { Settings } from "../mechanisms/settings.js";@@ -51,11 +55,351 @@ const FIELD_TYPES = new Set<PluginConfigField["type"]>(["number","enum","list",+ "table",]);/** A field name: what the manifest and the stored document are keyed by. */const FIELD_NAME = /^[A-Za-z][A-Za-z0-9_]*$/;+/** A table row's id: what its stored cells are keyed by. */+const ROW_ID = /^[a-z][a-z0-9-]*$/;++const COLUMN_TYPES = new Set<PluginConfigTableColumn["type"]>(["string", "boolean", "enum"]);++/** An enum's options, checked: every one a string value with a title. */+function parseOptions(options: unknown, where: string): PluginConfigOption[] {+ if (!Array.isArray(options) || options.length === 0) {+ throw new Error(`${where}.options must list the choices`);+ }+ return options.map((o, i) => {+ const opt = (o ?? {}) as Record<string, unknown>;+ if (typeof opt.value !== "string" || typeof opt.title !== "string") {+ throw new Error(`${where}.options[${i}] needs a string value and title`);+ }+ return {+ value: opt.value,+ title: opt.title,+ ...(typeof opt.titleZh === "string" ? { titleZh: opt.titleZh } : {}),+ ...describedBy(opt),+ };+ });+}++export const isRecord = (v: unknown): v is Record<string, unknown> =>+ v !== null && typeof v === "object" && !Array.isArray(v);++/** A column's (or row's, or option's) description, in both languages, where declared as text. */+function describedBy(c: Record<string, unknown>): { description?: string; descriptionZh?: string } {+ return {+ ...(typeof c.description === "string" ? { description: c.description } : {}),+ ...(typeof c.descriptionZh === "string" ? { descriptionZh: c.descriptionZh } : {}),+ };+}++/** A table's pin column: a boolean column of it, and its tooltip pinned and not. */+function parsePin(+ raw: unknown,+ columns: readonly PluginConfigTableColumn[],+ where: string,+): PluginConfigPinColumn {+ const p = (raw ?? {}) as Record<string, unknown>;+ if (typeof p.on !== "string" || typeof p.off !== "string") {+ throw new Error(`${where}.pin needs an on and an off text`);+ }+ if (columns.find((c) => c.name === p.column)?.type !== "boolean") {+ throw new Error(`${where}.pin.column must name a boolean column`);+ }+ return {+ column: p.column as string,+ on: p.on,+ off: p.off,+ ...(typeof p.onZh === "string" ? { onZh: p.onZh } : {}),+ ...(typeof p.offZh === "string" ? { offZh: p.offZh } : {}),+ };+}++/** Whether a value is of a table column's type. */+function cellFits(column: PluginConfigTableColumn, value: unknown): boolean {+ if (column.type === "boolean") return typeof value === "boolean";+ if (column.type === "enum") {+ return typeof value === "string" && (column.options ?? []).some((o) => o.value === value);+ }+ return typeof value === "string";+}++/** A `table` field's columns and rows, checked: every row declares every column, and fits it. */+function parseTable(+ f: Record<string, unknown>,+ where: string,+): { columns: PluginConfigTableColumn[]; rows: PluginConfigTableRow[] } {+ if (!Array.isArray(f.columns) || f.columns.length === 0) {+ throw new Error(`${where}.columns must list the columns`);+ }+ const columns = f.columns.map((raw, i): PluginConfigTableColumn => {+ const c = (raw ?? {}) as Record<string, unknown>;+ const at = `${where}.columns[${i}]`;+ if (typeof c.name !== "string" || !FIELD_NAME.test(c.name)) {+ throw new Error(`${at}.name is not a valid name`);+ }+ if (+ typeof c.type !== "string" ||+ !COLUMN_TYPES.has(c.type as PluginConfigTableColumn["type"])+ ) {+ throw new Error(`${at}.type must be one of ${[...COLUMN_TYPES].join(", ")}`);+ }+ if (typeof c.title !== "string" || c.title === "") throw new Error(`${at}.title is required`);+ return {+ name: c.name,+ type: c.type as PluginConfigTableColumn["type"],+ title: c.title,+ ...(typeof c.titleZh === "string" ? { titleZh: c.titleZh } : {}),+ ...describedBy(c),+ ...(c.type === "enum" ? { options: parseOptions(c.options, at) } : {}),+ };+ });+ if (!Array.isArray(f.rows) || f.rows.length === 0) {+ throw new Error(`${where}.rows must list the rows`);+ }+ const ids = new Set<string>();+ const rows = f.rows.map((raw, i): PluginConfigTableRow => {+ const r = (raw ?? {}) as Record<string, unknown>;+ const at = `${where}.rows[${i}]`;+ if (typeof r.id !== "string" || !ROW_ID.test(r.id) || ids.has(r.id)) {+ throw new Error(`${at}.id must be a unique lower-case id`);+ }+ ids.add(r.id);+ const values = isRecord(r.values) ? r.values : {};+ for (const column of columns) {+ if (!cellFits(column, values[column.name])) {+ throw new Error(`${at}.values.${column.name} does not fit its column`);+ }+ }+ const row: PluginConfigTableRow = {+ id: r.id,+ values: Object.fromEntries(columns.map((c) => [c.name, values[c.name] as string | boolean])),+ ...describedBy(r),+ };+ if (r.valuesZh !== undefined) {+ if (!isRecord(r.valuesZh)) throw new Error(`${at}.valuesZh must be an object`);+ for (const [name, v] of Object.entries(r.valuesZh)) {+ if (columns.find((c) => c.name === name)?.type !== "string" || typeof v !== "string") {+ throw new Error(`${at}.valuesZh.${name} must be a string column's text`);+ }+ }+ row.valuesZh = r.valuesZh as Record<string, string>;+ }+ if (r.locked !== undefined) {+ if (!Array.isArray(r.locked) || !r.locked.every((n) => columns.some((c) => c.name === n))) {+ throw new Error(`${at}.locked must list columns of the table`);+ }+ row.locked = r.locked as string[];+ }+ return row;+ });+ return { columns, rows };+}++/** Where an `extensible` table stores its added rows and its row order: never a row id. */+export const TABLE_ADDED = "$added";+export const TABLE_ORDER = "$order";++/** The rows added to an `extensible` table, as stored: each well-formed one, in stored order. */+function addedRowsOf(field: PluginConfigField, raw: unknown): PluginConfigTableRow[] {+ if (field.extensible === undefined || !isRecord(raw)) return [];+ const declared = new Set((field.rows ?? []).map((r) => r.id));+ const rows: PluginConfigTableRow[] = [];+ for (const [id, cells] of Object.entries(raw)) {+ if (!ROW_ID.test(id) || declared.has(id) || !isRecord(cells)) continue;+ const columns = field.columns ?? [];+ if (!columns.every((c) => cellFits(c, cells[c.name]))) continue;+ rows.push({+ id,+ values: Object.fromEntries(columns.map((c) => [c.name, cells[c.name] as string | boolean])),+ added: true,+ });+ }+ return rows;+}++/** Rows in the stored order: ids it names first, in that order, then the rest as they come. */+function inStoredOrder(rows: PluginConfigTableRow[], raw: unknown): PluginConfigTableRow[] {+ if (!Array.isArray(raw)) return rows;+ const rank = new Map<string, number>();+ for (const id of raw) if (typeof id === "string" && !rank.has(id)) rank.set(id, rank.size);+ return rows+ .map((row, i) => ({ row, at: rank.get(row.id) ?? rank.size + i }))+ .sort((a, b) => a.at - b.at)+ .map(({ row }) => row);+}++/**+ * A `table` field as read: every declared row with the stored cells laid over the declared+ * ones (never a locked cell's: a hand-edited document cannot remap one), then — in an `extensible` table — the rows added to it, all in the stored order. A cell+ * a save changed drops its Chinese text — the name an administrator gave is the name in every+ * language. Stored rows the table neither declares nor added are left out.+ */+export function resolveTable(field: PluginConfigField, stored: unknown): PluginConfigTableRow[] {+ const cells = isRecord(stored) ? stored : {};+ const declared = declaredRowsOf(field, cells);+ if (field.extensible === undefined) return declared;+ return inStoredOrder(+ [...declared, ...addedRowsOf(field, cells[TABLE_ADDED])],+ cells[TABLE_ORDER],+ );+}++function declaredRowsOf(+ field: PluginConfigField,+ cells: Record<string, unknown>,+): PluginConfigTableRow[] {+ return (field.rows ?? []).map((row) => {+ const own = isRecord(cells[row.id]) ? (cells[row.id] as Record<string, unknown>) : {};+ const values = { ...row.values };+ for (const column of field.columns ?? []) {+ const v = own[column.name];+ if (row.locked?.includes(column.name)) continue;+ if (v !== undefined && cellFits(column, v)) values[column.name] = v as string | boolean;+ }+ const zh = Object.entries(row.valuesZh ?? {}).filter(+ ([name]) => values[name] === row.values[name],+ );+ const { valuesZh: _declared, ...rest } = row;+ return { ...rest, values, ...(zh.length > 0 ? { valuesZh: Object.fromEntries(zh) } : {}) };+ });+}++/**+ * One update of a `table` field folded onto its stored cells. Each cell is checked against its+ * column and named `<field>.<row>.<column>` when refused; a cell set back to its declared value+ * (or sent empty) is dropped, so only the cells that differ are stored; a row the table does not+ * declare is dropped; a locked cell may not change.+ */+function applyTableUpdate(+ name: string,+ field: PluginConfigField,+ stored: unknown,+ update: unknown,+): Record<string, unknown> {+ if (!isRecord(update)) {+ throw new PluginConfigError(name, `"${name}" must be an object of rows`);+ }+ const before = isRecord(stored) ? stored : {};+ const next: Record<string, unknown> = {};+ for (const row of field.rows ?? []) {+ const cells: Record<string, string | boolean> = {};+ const kept = isRecord(before[row.id]) ? (before[row.id] as Record<string, unknown>) : {};+ for (const column of field.columns ?? []) {+ const v = kept[column.name];+ // A stored locked cell (a hand-edited document) is not carried over: reads ignore it.+ if (row.locked?.includes(column.name)) continue;+ if (v !== undefined && cellFits(column, v)) cells[column.name] = v as string | boolean;+ }+ const sent = update[row.id];+ if (sent !== undefined) {+ if (!isRecord(sent)) {+ throw new PluginConfigError(name, `"${name}.${row.id}" must be an object of cells`);+ }+ for (const [columnName, raw] of Object.entries(sent)) {+ const at = `${name}.${row.id}.${columnName}`;+ const column = (field.columns ?? []).find((c) => c.name === columnName);+ if (column === undefined) {+ throw new PluginConfigError(name, `"${at}" is not a column of this table`);+ }+ const value = typeof raw === "string" ? raw.trim() : raw;+ if (value === null || value === "" || value === row.values[columnName]) {+ delete cells[columnName];+ continue;+ }+ if (!cellFits(column, value)) {+ throw new PluginConfigError(+ name,+ column.type === "enum"+ ? `"${at}" must be one of ${(column.options ?? []).map((o) => o.value).join(", ")}`+ : `"${at}" must be a ${column.type}`,+ );+ }+ if (row.locked?.includes(columnName)) {+ throw new PluginConfigError(name, `"${at}" cannot be changed`);+ }+ cells[columnName] = value as string | boolean;+ }+ }+ if (Object.keys(cells).length > 0) next[row.id] = cells;+ }+ if (field.extensible !== undefined) {+ const added =+ update[TABLE_ADDED] !== undefined+ ? checkAddedRows(name, field, update[TABLE_ADDED])+ : Object.fromEntries(+ addedRowsOf(field, before[TABLE_ADDED]).map((row) => [row.id, row.values]),+ );+ if (Object.keys(added).length > 0) next[TABLE_ADDED] = added;+ const sentOrder = update[TABLE_ORDER];+ if (+ sentOrder !== undefined &&+ (!Array.isArray(sentOrder) || !sentOrder.every((id) => typeof id === "string"))+ ) {+ throw new PluginConfigError(name, `"${name}.${TABLE_ORDER}" must be a list of row ids`);+ }+ // Only ids of rows that exist, each once; a deleted row leaves the order with it.+ const ids = new Set([...(field.rows ?? []).map((r) => r.id), ...Object.keys(added)]);+ const listed: unknown = sentOrder ?? before[TABLE_ORDER];+ const order = [+ ...new Set(+ (Array.isArray(listed) ? listed : []).filter(+ (id): id is string => typeof id === "string" && ids.has(id),+ ),+ ),+ ];+ if (order.length > 0) next[TABLE_ORDER] = order;+ }+ return next;+}++/**+ * The added rows a save sends, checked: each id a lower-case row id the table does not declare,+ * each row every column's value; a text cell may not be empty. A refused cell is named+ * `<field>.<row>.<column>`.+ */+function checkAddedRows(+ name: string,+ field: PluginConfigField,+ sent: unknown,+): Record<string, Record<string, string | boolean>> {+ if (!isRecord(sent)) {+ throw new PluginConfigError(name, `"${name}.${TABLE_ADDED}" must be an object of rows`);+ }+ const declared = new Set((field.rows ?? []).map((r) => r.id));+ const out: Record<string, Record<string, string | boolean>> = {};+ for (const [id, raw] of Object.entries(sent)) {+ if (!ROW_ID.test(id) || declared.has(id)) {+ throw new PluginConfigError(name, `"${name}.${id}" is not an id a new row may take`);+ }+ if (!isRecord(raw)) {+ throw new PluginConfigError(name, `"${name}.${id}" must be an object of cells`);+ }+ const cells: Record<string, string | boolean> = {};+ for (const column of field.columns ?? []) {+ const at = `${name}.${id}.${column.name}`;+ const v = raw[column.name];+ const value = typeof v === "string" ? v.trim() : v;+ if (!cellFits(column, value) || value === "") {+ throw new PluginConfigError(+ name,+ column.type === "enum"+ ? `"${at}" must be one of ${(column.options ?? []).map((o) => o.value).join(", ")}`+ : value === ""+ ? `"${at}" may not be empty`+ : `"${at}" must be a ${column.type}`,+ );+ }+ cells[column.name] = value as string | boolean;+ }+ out[id] = cells;+ }+ return out;+}+/*** Validates a declared configuration. Undefined when there is none; a malformed one throws,* naming where it was declared — a schema the page cannot draw is@@ -98,7 +442,14 @@ export function parsePluginConfiguration(throw new Error(`${where}: configuration.properties.${name}.title is required`);}const field: PluginConfigField = { type: type as PluginConfigField["type"], title: f.title };- for (const key of ["titleZh", "description", "descriptionZh", "placeholder"] as const) {+ for (const key of [+ "titleZh",+ "description",+ "descriptionZh",+ "hint",+ "hintZh",+ "placeholder",+ ] as const) {const v = f[key];if (v === undefined) continue;if (typeof v !== "string") {@@ -107,23 +458,72 @@ export function parsePluginConfiguration(field[key] = v;}if (field.type === "enum") {- const options = f.options;- if (!Array.isArray(options) || options.length === 0) {- throw new Error(`${where}: configuration.properties.${name}.options must list the choices`);+ field.options = parseOptions(f.options, `${where}: configuration.properties.${name}`);+ }+ if (field.type === "table") {+ Object.assign(field, parseTable(f, `${where}: configuration.properties.${name}`));+ if (f.extensible !== undefined) {+ const e = (f.extensible ?? {}) as Record<string, unknown>;+ const at = `${where}: configuration.properties.${name}.extensible`;+ const values = isRecord(e.values) ? e.values : {};+ for (const column of field.columns ?? []) {+ if (!cellFits(column, values[column.name])) {+ throw new Error(`${at}.values.${column.name} does not fit its column`);+ }+ }+ field.extensible = {+ ...(typeof e.add === "string" ? { add: e.add } : {}),+ ...(typeof e.addZh === "string" ? { addZh: e.addZh } : {}),+ values: Object.fromEntries(+ (field.columns ?? []).map((c) => [c.name, values[c.name] as string | boolean]),+ ),+ ...(isRecord(e.valuesZh) ? { valuesZh: e.valuesZh as Record<string, string> } : {}),+ };}- field.options = options.map((o, i) => {- const opt = (o ?? {}) as Record<string, unknown>;- if (typeof opt.value !== "string" || typeof opt.title !== "string") {+ if (f.columnGroup !== undefined) {+ const g = (f.columnGroup ?? {}) as Record<string, unknown>;+ const at = `${where}: configuration.properties.${name}.columnGroup`;+ const known = new Set((field.columns ?? []).map((c) => c.name));+ if (+ typeof g.title !== "string" ||+ !Array.isArray(g.columns) ||+ g.columns.length === 0 ||+ !g.columns.every((c) => typeof c === "string" && known.has(c))+ ) {+ throw new Error(`${at} needs a title and columns of the table`);+ }+ field.columnGroup = {+ title: g.title,+ ...(typeof g.titleZh === "string" ? { titleZh: g.titleZh } : {}),+ ...describedBy(g),+ columns: g.columns as string[],+ };+ }+ if (f.pin !== undefined) {+ field.pin = parsePin(+ f.pin,+ field.columns ?? [],+ `${where}: configuration.properties.${name}`,+ );+ }+ if (f.rowChoice !== undefined) {+ const c = (f.rowChoice ?? {}) as Record<string, unknown>;+ if (typeof c.field !== "string" || typeof c.title !== "string" || c.title === "") {throw new Error(- `${where}: configuration.properties.${name}.options[${i}] needs a string value and title`,+ `${where}: configuration.properties.${name}.rowChoice needs a field and a title`,);}- return {- value: opt.value,- title: opt.title,- ...(typeof opt.titleZh === "string" ? { titleZh: opt.titleZh } : {}),+ field.rowChoice = {+ field: c.field,+ title: c.title,+ ...(typeof c.titleZh === "string" ? { titleZh: c.titleZh } : {}),};- });+ }+ if (f.default !== undefined) {+ throw new Error(+ `${where}: configuration.properties.${name}.default: a table's rows are its defaults`,+ );+ }}if (field.type === "list" && f.maxItems !== undefined) {if (typeof f.maxItems !== "number" || !Number.isInteger(f.maxItems) || f.maxItems < 1) {@@ -170,6 +570,12 @@ export function parsePluginConfiguration(}field.required = f.required;}+ if (f.advanced !== undefined) {+ if (typeof f.advanced !== "boolean") {+ throw new Error(`${where}: configuration.properties.${name}.advanced must be a boolean`);+ }+ if (f.advanced) field.advanced = true;+ }if (f.default !== undefined) {if (!valueFits(field, f.default) || valueViolation(name, field, f.default) !== undefined) {throw new Error(@@ -180,11 +586,34 @@ export function parsePluginConfiguration(}properties[name] = field;}+ const switchOf = (sw: string) => {+ if (properties[sw]?.type !== "boolean") {+ throw new Error(`${where}: configuration.switch must name a boolean field`);+ }+ return sw;+ };+ // A row choice stores into an enum of the same group whose options are exactly the row ids.+ for (const [name, field] of Object.entries(properties)) {+ if (field.rowChoice === undefined) continue;+ const target = properties[field.rowChoice.field];+ const ids = (field.rows ?? []).map((r) => r.id);+ const values = (target?.options ?? []).map((o) => o.value);+ if (+ target?.type !== "enum" ||+ values.length !== ids.length ||+ !ids.every((id) => values.includes(id))+ ) {+ throw new Error(+ `${where}: configuration.properties.${name}.rowChoice.field must name an enum of this group whose options are the row ids`,+ );+ }+ }return {...(str("title") !== undefined ? { title: str("title")! } : {}),...(str("titleZh") !== undefined ? { titleZh: str("titleZh")! } : {}),...(str("description") !== undefined ? { description: str("description")! } : {}),...(str("descriptionZh") !== undefined ? { descriptionZh: str("descriptionZh")! } : {}),+ ...(str("switch") !== undefined ? { switch: switchOf(str("switch")!) } : {}),properties,};}@@ -200,6 +629,8 @@ export function valueFits(field: PluginConfigField, value: unknown): boolean {return typeof value === "string" && (field.options ?? []).some((o) => o.value === value);case "list":return Array.isArray(value) && value.every((v) => typeof v === "string");+ case "table":+ return isRecord(value);default:return typeof value === "string";}@@ -282,6 +713,11 @@ export function applyUpdate(update: Record<string, unknown>,): Record<string, unknown> {const next = { ...stored };+ const rowChoiceTargets = new Map(+ Object.entries(schema.properties).flatMap(([table, f]) =>+ f.rowChoice !== undefined ? [[f.rowChoice.field, table] as const] : [],+ ),+ );for (const [name, value] of Object.entries(update)) {const field = schema.properties[name];if (field === undefined)@@ -294,6 +730,18 @@ export function applyUpdate(const current = stored[name];if (typeof current === "string" && current !== "" && value === maskApiKey(current)) continue;}+ if (field.type === "table") {+ const cells = applyTableUpdate(name, field, stored[name], value);+ if (Object.keys(cells).length === 0) delete next[name];+ else next[name] = cells;+ continue;+ }+ // A row choice's field names a row, which may be one added to the table: checked below,+ // against the table as this save leaves it.+ if (rowChoiceTargets.has(name) && typeof value === "string") {+ next[name] = value;+ continue;+ }if (!valueFits(field, value)) {throw new PluginConfigError(name,@@ -323,6 +771,16 @@ export function applyUpdate(const violation = valueViolation(name, field, next[name]);if (violation !== undefined) throw new PluginConfigError(name, violation);}+ for (const [target, table] of rowChoiceTargets) {+ const chosen = next[target];+ const field = schema.properties[table]!;+ if (chosen !== undefined && !resolveTable(field, next[table]).some((r) => r.id === chosen)) {+ throw new PluginConfigError(+ target,+ `"${target}" must name a row of "${table}": "${String(chosen)}" is not one (choose another row before deleting it)`,+ );+ }+ }for (const [name, field] of Object.entries(schema.properties)) {if (field.required === true && next[name] === undefined && field.default === undefined) {throw new PluginConfigError(name, `"${name}" is required`);@@ -346,65 +804,6 @@ export interface SettingsGroup {parent?: string;}-/**- * The code half of a `status` contribution: a group's live notices, asked per read, and the- * ACTIONS it offers.- *- * An action is for what a person cannot express as a field: something the deployment must DO- * once, on the machine, before the settings above mean anything — the Windows sandbox's local- * accounts, which need an administrator's consent. Naming the command in a notice puts the work- * on whoever reads it; an action lets the module do it and report back.- */-export interface SettingsGroupStatus {- notices(): PluginConfigNotice[];- /**- * After a save of this group or of one drawn inside its card: does what that save sets in- * motion beyond the group's own watchers, and resolves once it has settled, so the notices- * the save answers with are current.- */- saved?(): Promise<void>;- /** What this group offers to do, drawn as buttons beneath its notices. */- actions?(): PluginConfigAction[];- /**- * Enum options this machine cannot honour right now: drawn greyed out with the reason, and a- * save choosing one is refused. Asked per read, like the notices.- */- unavailable?(): PluginConfigUnavailable[];- /** Runs one, by its id. Told what happened, in words the page shows as they are. */- run?(action: string): Promise<PluginConfigActionResult>;-}--/** One enum option a settings group cannot honour on this machine, and why. */-export interface PluginConfigUnavailable {- field: string;- value: string;- reason: string;- reasonZh?: string;-}--/** One thing a settings group can do, named for the button that runs it. */-export interface PluginConfigAction {- id: string;- title: string;- titleZh?: string;- /** What pressing it will do, shown beside the button — a person consents to what they read. */- description?: string;- descriptionZh?: string;-}--/** What an action reports: whether it did what it said, and what to tell the person. */-export interface PluginConfigActionResult {- ok: boolean;- message: string;- messageZh?: string;- /**- * Work the action started and did not wait for, reported through `progress` notices; it- * resolves when that work ends. The page node then settles the card the way a save does (a- * sandbox backend the work made usable loads again). Never sent to the page.- */- settled?: Promise<void>;-}-/** What a module reads: the group it declared, and a watch on it. */@Interface()export abstract class PluginConfig {@@ -414,6 +813,8 @@ export abstract class PluginConfig {abstract watch(name: string, cb: (values: Record<string, unknown>) => void): () => void;/** Whether anything was ever saved under `name` — what tells a default from a choice. */abstract saved(name: string): boolean;+ /** The configuration `name` was declared with (what `resolveTable` reads a table by); undefined for none. */+ abstract schema(name: string): PluginConfiguration | undefined;}export interface PluginConfigSlots {@@ -428,22 +829,6 @@ export abstract class PluginConfigEntries {abstract set(name: string, update: Record<string, unknown>): PluginConfigEntry;}-/** What the settings page reads and writes. */-@Interface()-export abstract class PluginConfigAdmin {- /** Every declared group, in order, with its live notices; values masked. */- abstract describe(): PluginConfigEntry[];- /** Validates and stores one update; answers that entry, masked, with its notices once its card's status has settled. */- abstract set(name: string, update: Record<string, unknown>): Promise<PluginConfigEntry>;- /** Runs one group's action and says what happened; throws PluginConfigError for an unknown one. */- abstract run(name: string, action: string): Promise<PluginConfigActionResult>;-}--export interface PluginConfigAdminSlots {- /** Live notices for a group that has any (`group` names it). */- status: Slot<{ group: string }, SettingsGroupStatus>;-}-export interface PluginConfigStoreDeps {settings: Pick<Settings, "get" | "set">;groups: () => readonly SettingsGroup[];@@ -481,6 +866,10 @@ export class PluginConfigStore {return this.deps.settings.get(`plugin-config:${name}`) !== null;}+ schema(name: string): PluginConfiguration | undefined {+ return this.group(name)?.configuration;+ }+watch(name: string, cb: (values: Record<string, unknown>) => void): () => void {const set = this.watchers.get(name) ?? new Set();set.add(cb);@@ -556,63 +945,3 @@ export class PluginConfigProvider {this.pluginConfigEntries = store;}}--/** The page's view: the stored entries with the live notices their status contributors report. */-@Module()-export class PluginConfigPage {- @Use() private readonly entries!: PluginConfigEntries;- @Provide() pluginConfigAdmin!: PluginConfigAdmin;- setup({ contributions }: ClassCtx) {- const entries = this.entries;- const status = new Map<string, SettingsGroupStatus>();- for (const c of contributions.status ?? []) {- status.set(c.data.group as string, c.code as SettingsGroupStatus);- }- const withStatus = (entry: PluginConfigEntry): PluginConfigEntry => {- const group = status.get(entry.name);- const notices = group?.notices() ?? [];- const actions = group?.actions?.() ?? [];- const unavailable = group?.unavailable?.() ?? [];- return {- ...entry,- ...(notices.length > 0 ? { notices } : {}),- ...(actions.length > 0 ? { actions } : {}),- ...(unavailable.length > 0 ? { unavailable } : {}),- };- };- this.pluginConfigAdmin = {- describe: () => entries.describe().map(withStatus),- set: async (name, update) => {- // An option this machine cannot honour is refused like an invalid value, naming it.- for (const u of status.get(name)?.unavailable?.() ?? []) {- if (update[u.field] === u.value) {- throw new PluginConfigError(- u.field,- `"${u.field}" cannot be "${u.value}" here: ${u.reason}`,- );- }- }- const saved = entries.set(name, update);- await status.get(saved.parent ?? name)?.saved?.();- return withStatus(saved);- },- run: async (name, action) => {- const group = status.get(name);- const offered = group?.actions?.() ?? [];- if (group?.run === undefined || !offered.some((a) => a.id === action)) {- throw new PluginConfigError(null, `"${name}" offers no action "${action}".`);- }- const { settled, ...result } = await group.run(action);- // What the action changed on the machine is settled like a save of its card: the- // owner's status runs its follow-up (a backend that failed its check loads again).- const owner = entries.describe().find((e) => e.name === name)?.parent ?? name;- const settle = async () => {- await status.get(owner)?.saved?.();- };- if (settled === undefined) await settle();- else void settled.then(settle, settle).catch(() => {});- return result;- },- };- }-}diff --git a/packages/server/src/runtime/scheduler.ts b/packages/server/src/runtime/scheduler.tsindex b423227e..b502a042 100644--- a/packages/server/src/runtime/scheduler.ts+++ b/packages/server/src/runtime/scheduler.ts@@ -59,6 +59,11 @@ export interface ScheduleSessionCreatorShape {workspace?: string;modelId?: string;provider?: string;+ /**+ * Unattended creators pass `allow-all`: nobody is there to answer an ask the default+ * preset's approval mode would bring.+ */+ approvalMode?: "allow-all";source?: "schedule";}): Promise<{ sessionId: string }>;}@@ -434,6 +439,8 @@ export class Scheduler implements Scheduling {...(def.workspace !== undefined ? { workspace: def.workspace } : {}),...(def.modelId !== undefined ? { modelId: def.modelId } : {}),...(def.provider !== undefined ? { provider: def.provider } : {}),+ // Unattended: the Sandbox card's default preset may ask, and nobody would answer.+ approvalMode: "allow-all",source: "schedule",});await this.send(projectId, agentId, def, state, info.sessionId);diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.tsindex be08e4d8..c471c556 100644--- a/packages/server/src/runtime/session-manager.ts+++ b/packages/server/src/runtime/session-manager.ts@@ -92,6 +92,9 @@ import { Component, Interface, Module, Provide, Use } from "@lmliheng/penguin-coimport type { SessionService as SessionServiceImpl } from "../services/session-service.js";import type { ClassCtx, Opaque } from "@lmliheng/penguin-core/kernel";import { Sandbox, SandboxModule } from "../sandbox/service.js";+import { SANDBOX_GROUP } from "../sandbox/settings-store.js";+import { sandboxEnabledOf, sandboxPresetsOf, sandboxStartOf } from "../sandbox/settings-policy.js";+import { PluginConfig } from "../plugin/config.js";import { SessionService } from "../services/session-service.js";import { ModelScopeAuth } from "../services/modelscope-auth-service.js";import { TitleGenerator } from "./title-generator.js";@@ -2532,6 +2535,7 @@ export abstract class SessionServiceIface extends Interface<| "sessionStats"| "createSession"| "defaultSandbox"+ | "pickSandbox"| "updateSandbox"| "latestTracePath"| "adoptUnmanagedTraceSessions"@@ -2567,6 +2571,8 @@ export class SessionsModule {@Use() private readonly traceIndex!: TraceIndex;@Use() private readonly traceStore!: TraceIndexStore;@Use(SandboxModule) private readonly sandbox!: Sandbox;+ /** The Sandbox card's presets live in the sandbox's settings group. */+ @Use() private readonly pluginConfig!: PluginConfig;@Use() private readonly projectEvents!: ProjectEvents;@Use() private readonly messagingRepo!: MessagingBindings;/** Company-mode caches: which organization owns a Session (read at every command spawn). */@@ -2584,6 +2590,7 @@ export class SessionsModule {const errors = this.errors;const projectConfig = this.projectConfig;const sandbox = this.sandbox as SandboxService;+ const pluginConfig = this.pluginConfig;const orgCache = this.orgCache;const modelScopeAuth = this.modelScopeAuth;@@ -2705,6 +2712,14 @@ export class SessionsModule {sandboxDefaults: () => sandbox.currentSettings(),sandboxDimensions: () => [...new Set(sandbox.backends().flatMap((b) => b.dimensions))],sandboxUnavailable: () => sandbox.failures(),+ // The Sandbox card's presets, read per view: a rename there reaches the next read.+ sandboxPresets: () =>+ sandboxPresetsOf(pluginConfig.schema(SANDBOX_GROUP), pluginConfig.get(SANDBOX_GROUP)),+ sandboxSwitchOn: () => sandboxEnabledOf(pluginConfig.get(SANDBOX_GROUP)),+ // The default preset's approval mode, while the switch is on.+ sandboxDefaultApproval: () =>+ sandboxStartOf(pluginConfig.schema(SANDBOX_GROUP), pluginConfig.get(SANDBOX_GROUP))+ .approvalMode,});this.manager = manager;this.sessionService = sessionService;diff --git a/packages/server/src/sandbox/settings-policy.ts b/packages/server/src/sandbox/settings-policy.tsnew file mode 100644index 00000000..5708b89a--- /dev/null+++ b/packages/server/src/sandbox/settings-policy.ts@@ -0,0 +1,226 @@+/**+ * What the sandbox's settings document (settings-store.ts declares it) means for a NEW Session:+ * whether the switch is on, and the policy and approval mode the Session starts with, and the+ * card's notice when that start is one no preset gives. Pure reads of the stored document —+ * nothing here writes it.+ *+ * With the switch off, a new Session starts unconfined and its approval mode is the request's+ * (or the server's fallback). With it on, it starts from the card's default preset: that row's+ * file mode, network and approval mode, plus the card's temp-directory and masked-path+ * settings. A preset with the file system Off and the network open confines nothing, so a+ * Session started from it (Full Access, Always Ask) is unconfined. A document stored before the+ * card had a default preset starts Sessions by its own mode and network until one is picked.+ */+import type { SandboxMode, SandboxSettings as Policy } from "@lmliheng/penguin-core/plugin";+import type {+ ApprovalMode,+ PluginConfigNotice,+ PluginConfiguration,+ SessionSandboxPreset,+} from "../api/types.js";+import { resolveTable } from "../plugin/config.js";+import { requestedDimensions } from "./dimensions.js";++/** The preset a new Session starts from while the card has never chosen one. */+export const DEFAULT_PRESET = "workspace-write";++const MODES: readonly SandboxMode[] = ["read-only", "workspace-write", "danger-full-access"];++const UNCONFINED: Policy = { mode: "danger-full-access" };++/**+ * Whether the switch is on in a stored document (defaults merged). A document saved before the+ * switch existed has no `enabled`: it reads as on exactly when its policy confined anything — a+ * mode other than Off, a network that is not open, or masked paths — so a deployment that was+ * confined stays confined, and one that was not stays open. The document is never rewritten+ * for it.+ * TODO(sandbox-switch-compat): a save writes only the fields it changes, so a pre-switch+ * document keeps lacking `enabled` until its switch is toggled; the fallback can go only when+ * the maintainers choose a one-time migration or an announced break for such documents (see+ * the 2026-10-02 backward-compatibility changelog entry).+ */+export function sandboxEnabledOf(doc: Record<string, unknown>): boolean {+ if (typeof doc.enabled === "boolean") return doc.enabled;+ const policy = legacyPolicyOf(doc);+ return policy.mode !== "danger-full-access" || requestedDimensions(policy).length > 1;+}++/** What a new Session starts with: its policy, and its approval mode when the card sets one. */+export interface SandboxStart {+ policy: Policy;+ approvalMode?: ApprovalMode;+}++/**+ * What a new Session starts with under a stored document. A document stored before the card had+ * a default preset keeps starting Sessions by its own `mode` and `network` (`prePresetStartOf`)+ * until an administrator sets a row as the default.+ * TODO(sandbox-switch-compat): the pre-preset reading stays while documents saved before the+ * default preset can be on disk; it goes with the switch's fallback above, by the same+ * decision (see the 2026-10-02 backward-compatibility changelog entry).+ */+export function sandboxStartOf(+ schema: PluginConfiguration | undefined,+ doc: Record<string, unknown>,+): SandboxStart {+ if (!sandboxEnabledOf(doc)) return { policy: UNCONFINED };+ if (isPrePreset(doc)) return { policy: legacyPolicyOf(doc) };+ const presets = sandboxPresetsOf(schema, doc);+ const preset =+ presets.find((p) => p.id === doc.defaultPreset) ?? presets.find((p) => p.id === DEFAULT_PRESET);+ return preset === undefined ? { policy: UNCONFINED } : presetStartOf(preset, doc);+}++/**+ * Whether a document predates the default preset: it names none, and holds what the old card+ * saved — its own `mode` or `network`, or masked paths (the old card's Off mode, its default,+ * stored nothing of its own). A save pins `defaultPreset` (`SandboxSettingsStatus.saving`)+ * whenever a row gives the start such a document holds, or an administrator picks one; until+ * then it keeps this shape.+ */+function isPrePreset(doc: Record<string, unknown>): boolean {+ return (+ doc.defaultPreset === undefined &&+ (doc.mode !== undefined || doc.network !== undefined || maskPathsOf(doc).length > 0)+ );+}++/** A pre-preset document's start, and the row that gives exactly the same one, if any. */+export interface PrePresetStart {+ policy: Policy;+ /** The first row, in table order, whose start equals it; absent when none does. */+ row?: string;+}++/**+ * A pre-preset document's start (the policy its own `mode` and `network` describe, with the+ * card's temp directory and masked paths), and the first row in table order that gives the same+ * start: pinning that row as the default would change neither a new Session's policy nor its+ * approval mode. The card shows that row as the default and a save pins it; with no such row the+ * card marks none, says what is in effect, and a save leaves the start as it is. Undefined for a+ * document that is not pre-preset.+ * TODO(sandbox-switch-compat): goes with `sandboxStartOf`'s pre-preset branch, by the same+ * decision.+ */+export function prePresetStartOf(+ schema: PluginConfiguration | undefined,+ doc: Record<string, unknown>,+): PrePresetStart | undefined {+ if (!isPrePreset(doc)) return undefined;+ const policy = legacyPolicyOf(doc);+ // A pre-preset start names no approval mode: a new Session takes its request's, else the+ // server's fallback, allow-all (session-service's startApproval). A row matches only with+ // that one.+ const row = sandboxPresetsOf(schema, doc).find((p) => {+ const start = presetStartOf(p, doc);+ return start.approvalMode === "allow-all" && samePolicy(start.policy, policy);+ });+ return { policy, ...(row !== undefined ? { row: row.id } : {}) };+}++/** The start one row gives: its file mode and network with the card's extras, and its approval mode. */+function presetStartOf(preset: SessionSandboxPreset, doc: Record<string, unknown>): SandboxStart {+ const { approvalMode } = preset;+ if (preset.mode === "danger-full-access" && preset.network === "open") {+ return { policy: UNCONFINED, approvalMode };+ }+ return {+ policy: {+ mode: preset.mode,+ ...(preset.network !== "open" ? { network: preset.network } : {}),+ ...extrasOf(doc),+ },+ approvalMode,+ };+}++/** Whether two policies confine alike: mode, network, temp directory and masked paths. */+function samePolicy(a: Policy, b: Policy): boolean {+ const masks = (p: Policy) => p.maskPaths ?? [];+ return (+ a.mode === b.mode &&+ (a.network ?? "open") === (b.network ?? "open") &&+ (a.writableTemp === false) === (b.writableTemp === false) &&+ masks(a).length === masks(b).length &&+ masks(a).every((path, i) => path === masks(b)[i])+ );+}++/** The card's temp-directory and masked-path settings, as policy fields. */+function extrasOf(doc: Record<string, unknown>): Pick<Policy, "maskPaths" | "writableTemp"> {+ const maskPaths = maskPathsOf(doc);+ return {+ ...(maskPaths.length > 0 ? { maskPaths } : {}),+ ...(doc.writableTemp === false ? { writableTemp: false } : {}),+ };+}++function maskPathsOf(doc: Record<string, unknown>): string[] {+ return Array.isArray(doc.maskPaths)+ ? doc.maskPaths.filter((p): p is string => typeof p === "string" && p !== "")+ : [];+}++/** The policy a document's own `mode` and `network` describe — fields the card no longer has. */+function legacyPolicyOf(doc: Record<string, unknown>): Policy {+ const mode = MODES.includes(doc.mode as SandboxMode)+ ? (doc.mode as SandboxMode)+ : "danger-full-access";+ return {+ mode,+ ...(doc.network === "none" || doc.network === "local" ? { network: doc.network } : {}),+ ...extrasOf(doc),+ };+}++/**+ * The card's notice for a document saved before the default preset whose start no row gives:+ * no row is marked as the default, so the card says what new Sessions start from and how to+ * choose a default. Values are named by the presets table's own option titles.+ * TODO(sandbox-switch-compat): goes with the pre-preset reading above.+ */+export function prePresetNotice(+ stored: Record<string, unknown>,+ configuration: PluginConfiguration,+): PluginConfigNotice | undefined {+ const start = prePresetStartOf(configuration, stored);+ if (start === undefined || start.row !== undefined) return undefined;+ const option = (column: string, value: string) =>+ configuration.properties.presets?.columns+ ?.find((c) => c.name === column)+ ?.options?.find((o) => o.value === value);+ const named = (column: string, value: string) => {+ const o = option(column, value);+ return { en: o?.title ?? value, zh: o?.titleZh ?? o?.title ?? value };+ };+ const mode = named("mode", start.policy.mode);+ const network = named("network", start.policy.network ?? "open");+ const approval = named("approvalMode", "allow-all");+ return {+ tone: "attention",+ text: `While the sandbox is on, new sessions start from the settings saved before the presets: files ${mode.en}, network ${network.en}, ask mode ${approval.en}. No preset has these values, so no row is the default, and saving the card keeps them. To change that, set a row as the default from its "…" menu, or add a preset with these values and set it.`,+ textZh: `沙盒打开时,新会话从预设出现之前保存的设置开始:文件「${mode.zh}」、网络「${network.zh}」、询问模式「${approval.zh}」。没有预设与之相同,因此没有一行是默认,保存卡片也会保留这些值。要改变它,在一行的「…」菜单里把它设为默认,或先添加一条同值的预设再设为默认。`,+ };+}++/**+ * The group's presets table as the composer reads it: every row in table order, disabled ones+ * included. `schema` is the group's declared configuration, `doc` its stored document — the+ * table's cells are stored only where they differ from the declaration.+ */+export function sandboxPresetsOf(+ schema: PluginConfiguration | undefined,+ doc: Record<string, unknown>,+): SessionSandboxPreset[] {+ const field = schema?.properties.presets;+ if (field?.type !== "table") return [];+ return resolveTable(field, doc.presets).map(({ id, values, valuesZh }) => ({+ id,+ name: values.name as string,+ ...(valuesZh?.name !== undefined ? { nameZh: valuesZh.name } : {}),+ enabled: values.enabled === true,+ mode: values.mode as SessionSandboxPreset["mode"],+ network: values.network as SessionSandboxPreset["network"],+ approvalMode: values.approvalMode as SessionSandboxPreset["approvalMode"],+ }));+}diff --git a/packages/server/src/sandbox/settings-status.ts b/packages/server/src/sandbox/settings-status.tsnew file mode 100644index 00000000..a3a766cf--- /dev/null+++ b/packages/server/src/sandbox/settings-status.ts@@ -0,0 +1,142 @@+/**+ * The Sandbox card's live status (`PluginConfigPage.status`): whether the saved policy can be+ * enforced, which backends are in use, and why each other one is not — a backend that failed to+ * load, failed its check or runs on another platform is named with its reason, never left out —+ * plus the enum options no backend here can honour and the backend package this OS defaults+ * to. A code contribution, so it must not require plugin configuration itself.+ */+import { Bind, Component, Use } from "@lmliheng/penguin-core/kernel";+import type { PluginConfigNotice } from "../api/types.js";+import type { SettingsGroupStatus } from "../plugin/config-page.js";+import { Sandbox, SandboxModule } from "./service.js";+import { requestedDimensions } from "./dimensions.js";+import {+ DEFAULT_PRESET,+ prePresetNotice,+ prePresetStartOf,+ sandboxEnabledOf,+} from "./settings-policy.js";++/**+ * The backend package each OS defaults to: what the card offers to install when the switch is+ * turned on and no backend for this OS is installed. sandbox-dsh serves every OS but is never+ * the default, because it confines the file system only.+ */+const DEFAULT_BACKEND: Partial<Record<NodeJS.Platform, string>> = {+ linux: "@lmliheng/penguin-plugin-sandbox-bwrap",+ darwin: "@lmliheng/penguin-plugin-sandbox-seatbelt",+ win32: "@lmliheng/penguin-plugin-sandbox-wsl",+};++/**+ * The sandbox card's live notices: a warning when the saved mode needs isolation no usable+ * backend implements (every command would be refused), the backends in use, and each backend+ * that failed to load, with its reason. A backend that declined because this host is not its+ * platform is no fault of the deployment — it is named only when nothing else serves, where+ * it explains why.+ */+@Component({+ contributes: {+ "PluginConfigPage.status": [{ id: "sandbox.status", group: "sandbox" }],+ },+})+export class SandboxSettingsStatus {+ @Use(SandboxModule) private readonly sandbox!: Sandbox;+ @Bind("sandbox.status") status!: SettingsGroupStatus;+ setup() {+ const sandbox = this.sandbox;+ this.status = {+ // The switch and the default as the card shows them, for a document saved before they+ // existed: the switch off its old policy; the default the row that gives that document's+ // start, or none when no row does.+ derive: (values, stored, configuration) => {+ // Read off the whole document: a pre-switch one's mode and network are not fields.+ const prePreset = prePresetStartOf(configuration, stored);+ const { defaultPreset: chosen, ...rest } = values;+ const defaultPreset = prePreset !== undefined ? prePreset.row : (chosen ?? DEFAULT_PRESET);+ return {+ ...rest,+ enabled: sandboxEnabledOf(stored),+ ...(defaultPreset !== undefined ? { defaultPreset } : {}),+ };+ },+ // A save pins the default the card shows, so what new Sessions start from changes only+ // when an administrator picks a row. A document saved before the default preset that no+ // row matches shows none: the save writes none, and its own start stays (settings-policy.ts).+ saving: (update, current) =>+ update.defaultPreset !== undefined || current.defaultPreset === undefined+ ? update+ : { ...update, defaultPreset: current.defaultPreset },+ // A backend for this OS is installed when it is in use or failed (to load, or its check):+ // one that declined is for another OS. Installing the default would not fix a failure.+ backend: () => {+ const recommended = DEFAULT_BACKEND[process.platform];+ return {+ installed: sandbox.backends().length > 0 || sandbox.failures().length > 0,+ ...(recommended !== undefined ? { recommended } : {}),+ };+ },+ // A backend reads its own group (drawn inside this card) at load: after a save of the+ // card, one that failed its check — a wrong program path — loads again, no restart.+ saved: () => sandbox.retryFailed(),+ // The local level needs a backend that declares it; where none does, the option is+ // shown greyed out and a save choosing it is refused.+ unavailable: () => {+ if (sandbox.backends().some((b) => b.dimensions.includes("network-local"))) return [];+ const why = {+ value: "local",+ reason: "no sandbox backend on this host supports it",+ reasonZh: "本机的沙盒后端不支持",+ };+ return [{ field: "presets", column: "network", ...why }];+ },+ notices: (stored, configuration): PluginConfigNotice[] => {+ const notices: PluginConfigNotice[] = [];+ const prePreset = prePresetNotice(stored, configuration);+ if (prePreset !== undefined) notices.push(prePreset);+ const backends = sandbox.backends();+ const settings = sandbox.currentSettings();+ if (settings.mode !== "danger-full-access") {+ const required = requestedDimensions(settings);+ const served = backends.some((b) => required.every((d) => b.dimensions.includes(d)));+ if (!served) {+ const needs = required.join(" + ");+ notices.push({+ tone: "attention",+ text: `The saved mode needs ${needs}, and no usable backend implements it: every agent command and hook script is refused until one does.`,+ textZh: `当前保存的模式需要 ${needs},但没有可用的后端实现它:在有后端能实施之前,Agent 的每条命令与钩子脚本都会被拒绝。`,+ });+ }+ }+ if (backends.length === 0) {+ const declined = sandbox.declined();+ const elsewhere =+ declined.length === 0+ ? ""+ : ` ${declined.join(", ")} ${declined.length === 1 ? "is" : "are"} installed, but for another platform.`;+ const elsewhereZh =+ declined.length === 0 ? "" : `已安装 ${declined.join("、")},但它们适用于其他平台。`;+ notices.push({+ tone: "attention",+ text: `This deployment has no usable sandbox backend: until one for this platform is installed from the Plugins page, every mode but Off refuses every agent command and hook script.${elsewhere}`,+ textZh: `当前部署没有可用的沙盒后端:在插件页安装适用于本平台的后端之前,除「关闭」外的任何模式都会拒绝 Agent 的每条命令与钩子脚本。${elsewhereZh}`,+ });+ } else {+ const list = backends.map((b) => `${b.name} (${b.dimensions.join(", ")})`).join(" · ");+ notices.push({ tone: "muted", text: `Backends: ${list}`, textZh: `后端:${list}` });+ }+ // A failure while another backend serves is worth saying, but it is not the card's+ // headline — confinement works. With nothing serving it is the headline.+ const tone = backends.length === 0 ? "attention" : "muted";+ for (const { name, reason } of sandbox.failures()) {+ notices.push({+ tone,+ text: `${name} is not in use: ${reason}`,+ textZh: `${name} 未启用:${reason}`,+ });+ }+ return notices;+ },+ };+ }+}diff --git a/packages/server/src/sandbox/settings-store.ts b/packages/server/src/sandbox/settings-store.tsindex 0ffbb7f6..b70592f2 100644--- a/packages/server/src/sandbox/settings-store.ts+++ b/packages/server/src/sandbox/settings-store.ts@@ -9,40 +9,19 @@* and after every save. The service stays on the capability-free floor (a bare kernel boots* it with no database), and its parked context still carries the settings across a hot swap:* on boot a saved document wins, and with none saved the service keeps what the swap carried.- * `SandboxSettingsStatus` reports, as live notices, whether the saved policy can be enforced,- * which backends are in use, and why each other one is not — a backend that failed to load,- * failed its check or runs on another platform is named with its reason, never left out. It is- * a code contribution, so it must not require plugin configuration itself.+ * The card's live status (whether the saved policy can be enforced, which backends are in use+ * and why each other one is not) is `SandboxSettingsStatus`, in settings-status.ts.*/import { Bind, Component, Use } from "@lmliheng/penguin-core/kernel";import type { SandboxMode, SandboxSettings as Policy } from "@lmliheng/penguin-core/plugin";import type { PluginConfigNotice } from "../api/types.js";import { PluginConfig } from "../plugin/config.js";-import type { SettingsGroupStatus } from "../plugin/config.js";import { Sandbox, SandboxModule } from "./service.js";-import { requestedDimensions } from "./dimensions.js";+import { sandboxStartOf } from "./settings-policy.js";/** The sandbox's group name (its contribution id), and the parent a backend's group names. */export const SANDBOX_GROUP = "sandbox";-const MODES: readonly SandboxMode[] = ["read-only", "workspace-write", "danger-full-access"];--/** A stored document (defaults merged) as the service's policy. */-export function sandboxPolicyOf(doc: Record<string, unknown>): Policy {- const mode = MODES.includes(doc.mode as SandboxMode)- ? (doc.mode as SandboxMode)- : "danger-full-access";- const maskPaths = Array.isArray(doc.maskPaths)- ? doc.maskPaths.filter((p): p is string => typeof p === "string" && p !== "")- : [];- return {- mode,- ...(doc.network === "none" || doc.network === "local" ? { network: doc.network } : {}),- ...(maskPaths.length > 0 ? { maskPaths } : {}),- ...(doc.writableTemp === false ? { writableTemp: false } : {}),- };-}-@Component({contributes: {"PluginConfigProvider.groups": [@@ -55,43 +34,308 @@ export function sandboxPolicyOf(doc: Record<string, unknown>): Policy {"The confinement new sessions start with, enforced by a sandbox backend plugin. A session keeps the policy it started with; change it from that session's permission button.",descriptionZh:"新建会话的初始封禁策略,由沙盒后端插件实施。已有会话保留创建时的策略,可在该会话的权限按钮中修改。",+ // Off, the card shows the switch alone: the presets, notices and backends' own settings+ // matter only to a confined Session.+ switch: "enabled",properties: {- mode: {- type: "enum",- title: "Confinement mode",- titleZh: "封禁模式",- default: "danger-full-access",- options: [+ // No default: a document saved before the switch derives it (sandboxEnabledOf), and+ // with nothing saved that reads as off, the default mode being Off.+ enabled: {+ type: "boolean",+ title: "Enable",+ titleZh: "启用",+ description:+ "Whether new sessions start in the sandbox. On: from the default preset. Off: with full file and network access, held only by their ask mode. Sessions that already exist keep their own policy.",+ descriptionZh:+ "新会话是否进入沙盒。打开:从默认预设开始。关闭:拥有完全的文件与网络访问,只受询问模式约束。已有会话保留各自的策略。",+ },+ // The composer's menu: each preset a named mode, network level and approval mode, and+ // the default (marked after its name): the row a new Session starts from while on.+ // Full Access keeps its promise (nothing confined, everything approved): only its+ // name, whether the menu lists it and whether it is the default can change.+ presets: {+ type: "table",+ title: "Presets",+ titleZh: "预设",+ description:+ "Named combinations of file access, network and ask mode. The pinned ones are what the composer's permission menu offers, and the one marked (Default) is what a new session starts from while the sandbox is on; changing it reaches new sessions only. A session keeps its own three values, and the menu names it by the first row that matches. Each name's \"?\" says what the row is for.",+ descriptionZh:+ "文件访问、网络与询问模式的命名组合。固定的行出现在输入框的权限菜单里;沙盒打开时,新会话从标有(默认)的行开始,改动只影响此后新建的会话。会话只保存自己的三项取值,菜单按第一个匹配的行为它命名。每个名称旁的「?」说明这一行的用途。",+ rowChoice: { field: "defaultPreset", title: "Default", titleZh: "默认" },+ columnGroup: {+ title: "Action",+ titleZh: "操作",+ description:+ "Pin: listed in the composer's permission menu. Handle: drag to reorder (or focus it and use the arrow keys); the order is the menu's. …: set the row as the default, or delete a preset you added (built-in ones can only be unpinned).",+ descriptionZh:+ "图钉:列在输入框的权限菜单里。手柄:拖动调整顺序(或聚焦后按上下方向键),菜单按此顺序列出。…:设为默认,或删除你新增的预设(内置预设只能取消固定)。",+ columns: ["enabled"],+ },+ // Presets an administrator adds: only those can be deleted; every row can be moved,+ // and the order is the composer's menu order.+ extensible: {+ add: "Add preset",+ addZh: "添加预设",+ values: {+ name: "New preset",+ enabled: false,+ mode: "workspace-write",+ network: "open",+ approvalMode: "always-ask",+ },+ valuesZh: { name: "新预设" },+ },+ pin: {+ column: "enabled",+ on: "Pinned to the menu",+ onZh: "已固定到菜单",+ off: "Not in the menu",+ offZh: "不在菜单中",+ },+ columns: [+ {+ name: "name",+ type: "string",+ title: "Name",+ titleZh: "名称",+ description:+ "What the menu and the permission button call this row. A rename keeps what the row does; clear the box to restore the original name.",+ descriptionZh:+ "菜单与权限按钮显示的名称。改名不改变该行的作用;清空输入框即恢复原名。",+ },+ {+ name: "mode",+ type: "enum",+ title: "Files",+ titleZh: "文件",+ description:+ "What a confined command may write. Off: anywhere. Workspace: the session's workspace, its scratchpad and the temp directory. Read-only: the temp directory only. Needs a sandbox backend unless Off.",+ descriptionZh:+ "被封禁的命令能写哪里。关闭:任何位置。仅工作区:会话的工作区、scratchpad 与临时目录。只读:只有临时目录。除「关闭」外都需要沙盒后端。",+ options: [+ {+ value: "danger-full-access",+ title: "Off (full access)",+ titleZh: "关闭(完全访问)",+ description: "Commands and file tools may write anywhere.",+ descriptionZh: "命令与文件工具可以写任何位置。",+ },+ {+ value: "workspace-write",+ title: "Workspace write only",+ titleZh: "仅工作区可写",+ description:+ "Commands and file tools may write only the workspace, the session's scratchpad and the temp directory.",+ descriptionZh: "命令与文件工具只能写工作区、会话的 scratchpad 与临时目录。",+ },+ {+ value: "read-only",+ title: "Read-only",+ titleZh: "只读",+ description:+ "Commands and file tools may write nothing but the temp directory.",+ descriptionZh: "命令与文件工具除临时目录外什么都不能写。",+ },+ ],+ },+ {+ name: "network",+ type: "enum",+ title: "Network",+ titleZh: "网络",+ description:+ "What a confined command, hook script or read_file URL may reach. Localhost allows only this machine, and needs a backend that can enforce it.",+ descriptionZh:+ "被封禁的命令、钩子脚本与 read_file 的 URL 能访问的网络。仅本机只允许访问本机,需要能实施它的后端。",+ options: [+ {+ value: "open",+ title: "Full access",+ titleZh: "完全访问",+ description: "Any address can be reached.",+ descriptionZh: "可以访问任何地址。",+ },+ {+ value: "local",+ title: "Localhost only",+ titleZh: "仅本机",+ description: "Only this machine can be reached.",+ descriptionZh: "只能访问本机。",+ },+ {+ value: "none",+ title: "No network",+ titleZh: "无网络",+ description: "Nothing can be reached.",+ descriptionZh: "无法访问任何网络。",+ },+ ],+ },+ {+ name: "approvalMode",+ type: "enum",+ title: "Ask mode",+ titleZh: "询问模式",+ description:+ "Which tool calls run without asking: all of them, only the ones that read, none (each asks first), or none at all (every call is denied).",+ descriptionZh:+ "哪些工具调用无需询问即可执行:全部、仅读取类、都要先询问,或全部拒绝。",+ options: [+ {+ value: "allow-all",+ title: "Approve everything",+ titleZh: "全部批准",+ description: "Every tool call runs without asking.",+ descriptionZh: "每个工具调用都直接执行,不询问。",+ },+ {+ value: "read-only",+ title: "Approve read-only",+ titleZh: "批准只读",+ description: "Calls that only read run; every other call asks you first.",+ descriptionZh: "只读的调用直接执行,其余调用先询问你。",+ },+ {+ value: "always-ask",+ title: "Ask every time",+ titleZh: "每次询问",+ description: "Every tool call asks you first.",+ descriptionZh: "每个工具调用都先询问你。",+ },+ {+ value: "deny-all",+ title: "Deny everything",+ titleZh: "全部拒绝",+ description: "Every tool call is refused.",+ descriptionZh: "每个工具调用都被拒绝。",+ },+ ],+ },+ {+ name: "enabled",+ type: "boolean",+ title: "Pin",+ titleZh: "固定",+ description:+ "Whether the composer's permission menu lists this row. An unpinned row can still be the default.",+ descriptionZh: "权限菜单是否列出这一行。未固定的行仍可作为默认。",+ },+ ],+ rows: [+ {+ id: "full-access",+ values: {+ name: "Full Access",+ enabled: true,+ mode: "danger-full-access",+ network: "open",+ approvalMode: "allow-all",+ },+ valuesZh: { name: "完全访问" },+ description:+ "No sandbox and nothing asked: the agent writes files, runs commands and uses the network freely. For work you trust and watch.",+ descriptionZh:+ "不进沙盒,也不询问:Agent 可以随意写文件、执行命令、联网。适合你信任并在旁照看的工作。",+ locked: ["mode", "network", "approvalMode"],+ },{- value: "danger-full-access",- title: "Off (full access)",- titleZh: "关闭(完全访问)",+ id: "always-ask",+ values: {+ name: "Always Ask",+ enabled: true,+ mode: "danger-full-access",+ network: "open",+ approvalMode: "always-ask",+ },+ valuesZh: { name: "每次询问" },+ description:+ "No sandbox, but every tool call waits for your approval. For approving the work step by step.",+ descriptionZh: "不进沙盒,但每个工具调用都要等你批准。适合一步步审批。",+ },+ {+ id: "workspace-write",+ values: {+ name: "Workspace Write",+ enabled: true,+ mode: "workspace-write",+ network: "open",+ approvalMode: "allow-all",+ },+ valuesZh: { name: "仅工作区可写" },+ description:+ "Commands and file tools change files only inside the workspace; the network is open and calls run without asking. For everyday coding.",+ descriptionZh:+ "命令与文件工具只能改工作区内的文件;网络不受限,调用无需询问。适合日常编码。",+ },+ {+ id: "read-only",+ values: {+ name: "Read Only",+ enabled: true,+ mode: "read-only",+ network: "open",+ approvalMode: "allow-all",+ },+ valuesZh: { name: "只读" },+ description:+ "Nothing can be written but the temp directory; the network is open and calls run without asking. For exploring, reviewing and answering questions.",+ descriptionZh:+ "除临时目录外什么都不能写;网络不受限,调用无需询问。适合浏览代码、审阅与答疑。",+ },+ {+ id: "workspace-write-ask",+ values: {+ name: "Workspace Write with Ask",+ enabled: false,+ mode: "workspace-write",+ network: "open",+ approvalMode: "always-ask",+ },+ valuesZh: { name: "仅工作区可写并询问" },+ description:+ "Like Workspace Write, but every tool call asks you first. For careful edits.",+ descriptionZh: "与「仅工作区可写」相同,但每个工具调用都先询问你。适合谨慎的修改。",+ },+ {+ id: "denied-all",+ values: {+ name: "Denied All",+ enabled: false,+ mode: "danger-full-access",+ network: "open",+ approvalMode: "deny-all",+ },+ valuesZh: { name: "全部拒绝" },+ description:+ "Every tool call is refused, so the agent can only talk. For a conversation with no tool use.",+ descriptionZh: "每个工具调用都被拒绝,Agent 只能对话。适合不使用工具的纯对话。",},- { value: "workspace-write", title: "Workspace write only", titleZh: "仅工作区可写" },- { value: "read-only", title: "Read-only", titleZh: "只读" },],},- network: {+ // The row a new Session starts from while the switch is on, drawn only as the table's+ // "(Default)" marker. No declared default: the derive hook shows DEFAULT_PRESET, or for a+ // document stored before it the row giving that document's start, else none+ // (settings-policy.ts, prePresetStartOf).+ defaultPreset: {type: "enum",- title: "Network",- titleZh: "网络",- description:- "What a confined command, hook script or read_file URL may reach. Local network allows only this machine's localhost, and needs a backend that can enforce it.",- descriptionZh:- "被封禁的命令、钩子脚本与 read_file 的 URL 能访问的网络。本地网络只允许访问本机 localhost,需要能实施它的后端。",- default: "open",+ title: "Default preset",+ titleZh: "默认预设",options: [- { value: "open", title: "Full access", titleZh: "完全访问" },+ { value: "full-access", title: "Full Access", titleZh: "完全访问" },+ { value: "always-ask", title: "Always Ask", titleZh: "每次询问" },+ { value: "workspace-write", title: "Workspace Write", titleZh: "仅工作区可写" },+ { value: "read-only", title: "Read Only", titleZh: "只读" },{- value: "local",- title: "Local network (localhost only)",- titleZh: "本地网络(仅本机 localhost)",+ value: "workspace-write-ask",+ title: "Workspace Write with Ask",+ titleZh: "仅工作区可写并询问",},- { value: "none", title: "No network", titleZh: "无网络" },+ { value: "denied-all", title: "Denied All", titleZh: "全部拒绝" },],},writableTemp: {type: "boolean",+ advanced: true,title: "Temporary directory writable",titleZh: "临时目录可写",description:@@ -102,11 +346,14 @@ export function sandboxPolicyOf(doc: Record<string, unknown>): Policy {},maskPaths: {type: "list",+ advanced: true,title: "Masked paths",titleZh: "屏蔽路径",description:- "One absolute path per line, hidden from confined commands, hook scripts and file tools (reads included).",- descriptionZh: "每行一个绝对路径,对被封禁的命令、钩子脚本与文件工具隐藏(包括读取)。",+ "Paths hidden from confined commands, hook scripts and file tools, reads included.",+ descriptionZh: "对被封禁的命令、钩子脚本与文件工具隐藏的路径,读取也不例外。",+ hint: "One absolute path per line, at most 64.",+ hintZh: "每行一个绝对路径,最多 64 条。",maxItems: 64,// POSIX `/…`, Windows `C:\…` or `C:/…`, or a UNC `\\server\…`.pattern: "^(?:/|[A-Za-z]:[\\\\/]|\\\\\\\\)",@@ -124,92 +371,12 @@ export class SandboxSettings {const { pluginConfig, sandbox } = this;// A saved document wins; with none saved the service keeps what the swap carried —// applying the defaults here would un-confine a deployment on every hot update.+ const schema = () => pluginConfig.schema(SANDBOX_GROUP);if (pluginConfig.saved(SANDBOX_GROUP)) {- sandbox.configure(sandboxPolicyOf(pluginConfig.get(SANDBOX_GROUP)));+ sandbox.configure(sandboxStartOf(schema(), pluginConfig.get(SANDBOX_GROUP)).policy);}- pluginConfig.watch(SANDBOX_GROUP, (doc) => sandbox.configure(sandboxPolicyOf(doc)));- }-}--/**- * The sandbox card's live notices: a warning when the saved mode needs isolation no usable- * backend implements (every command would be refused), the backends in use, and each backend- * that failed to load, with its reason. A backend that declined because this host is not its- * platform is no fault of the deployment — it is named only when nothing else serves, where- * it explains why.- */-@Component({- contributes: {- "PluginConfigPage.status": [{ id: "sandbox.status", group: "sandbox" }],- },-})-export class SandboxSettingsStatus {- @Use(SandboxModule) private readonly sandbox!: Sandbox;- @Bind("sandbox.status") status!: SettingsGroupStatus;- setup() {- const sandbox = this.sandbox;- this.status = {- // A backend reads its own group (drawn inside this card) at load: after a save of the- // card, one that failed its check — a wrong program path — loads again, no restart.- saved: () => sandbox.retryFailed(),- // The local level needs a backend that declares it; where none does, the option is- // shown greyed out and a save choosing it is refused.- unavailable: () =>- sandbox.backends().some((b) => b.dimensions.includes("network-local"))- ? []- : [- {- field: "network",- value: "local",- reason: "no sandbox backend on this host supports it",- reasonZh: "本机的沙盒后端不支持",- },- ],- notices: (): PluginConfigNotice[] => {- const notices: PluginConfigNotice[] = [];- const backends = sandbox.backends();- const settings = sandbox.currentSettings();- if (settings.mode !== "danger-full-access") {- const required = requestedDimensions(settings);- const served = backends.some((b) => required.every((d) => b.dimensions.includes(d)));- if (!served) {- const needs = required.join(" + ");- notices.push({- tone: "attention",- text: `The saved mode needs ${needs}, and no usable backend implements it: every agent command and hook script is refused until one does.`,- textZh: `当前保存的模式需要 ${needs},但没有可用的后端实现它:在有后端能实施之前,Agent 的每条命令与钩子脚本都会被拒绝。`,- });- }- }- if (backends.length === 0) {- const declined = sandbox.declined();- const elsewhere =- declined.length === 0- ? ""- : ` ${declined.join(", ")} ${declined.length === 1 ? "is" : "are"} installed, but for another platform.`;- const elsewhereZh =- declined.length === 0 ? "" : `已安装 ${declined.join("、")},但它们适用于其他平台。`;- notices.push({- tone: "attention",- text: `This deployment has no usable sandbox backend: until one for this platform is installed from the Plugins page, every mode but Off refuses every agent command and hook script.${elsewhere}`,- textZh: `当前部署没有可用的沙盒后端:在插件页安装适用于本平台的后端之前,除「关闭」外的任何模式都会拒绝 Agent 的每条命令与钩子脚本。${elsewhereZh}`,- });- } else {- const list = backends.map((b) => `${b.name} (${b.dimensions.join(", ")})`).join(" · ");- notices.push({ tone: "muted", text: `Backends: ${list}`, textZh: `后端:${list}` });- }- // A failure while another backend serves is worth saying, but it is not the card's- // headline — confinement works. With nothing serving it is the headline.- const tone = backends.length === 0 ? "attention" : "muted";- for (const { name, reason } of sandbox.failures()) {- notices.push({- tone,- text: `${name} is not in use: ${reason}`,- textZh: `${name} 未启用:${reason}`,- });- }- return notices;- },- };+ pluginConfig.watch(SANDBOX_GROUP, (doc) =>+ sandbox.configure(sandboxStartOf(schema(), doc).policy),+ );}}diff --git a/packages/server/src/services/sandbox-ceiling.ts b/packages/server/src/services/sandbox-ceiling.tsnew file mode 100644index 00000000..451250e3--- /dev/null+++ b/packages/server/src/services/sandbox-ceiling.ts@@ -0,0 +1,39 @@+/**+ * The non-admin ceiling on a Session's sandbox: the server's settings. A non-admin may tighten a+ * Session's policy but never give it more file or network access than those settings+ * (`applySandboxPick`), and the composer greys out the presets wider than them+ * (`SessionSandboxPreset.aboveCeiling`) — both by this one comparison, so the menu never offers+ * a non-admin what the server will refuse.+ */+import type { SandboxSettings } from "@lmliheng/penguin-core/plugin";+import type { SessionSandbox } from "../api/types.js";++const SANDBOX_MODE_RANK: Record<SandboxSettings["mode"], number> = {+ "read-only": 0,+ "workspace-write": 1,+ "danger-full-access": 2,+};++const SANDBOX_NETWORK_RANK: Record<SessionSandbox["network"], number> = {+ none: 0,+ local: 1,+ open: 2,+};++/** A file mode and network level, as the composer names them. */+export type SandboxLevel = Pick<SessionSandbox, "mode" | "network">;++/**+ * Which dimension of `level` is wider than `ceiling` — the file mode first — or null when+ * neither is.+ */+export function aboveSandboxCeiling(+ level: SandboxLevel,+ ceiling: SandboxLevel,+): "mode" | "network" | null {+ if (SANDBOX_MODE_RANK[level.mode] > SANDBOX_MODE_RANK[ceiling.mode]) return "mode";+ if (SANDBOX_NETWORK_RANK[level.network] > SANDBOX_NETWORK_RANK[ceiling.network]) {+ return "network";+ }+ return null;+}diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.tsindex 03c60b6a..79bd6f97 100644--- a/packages/server/src/services/session-service.ts+++ b/packages/server/src/services/session-service.ts@@ -28,6 +28,7 @@ import type {SessionCategoryCounts,SessionInfo,SessionSandbox,+ SessionSandboxPreset,SessionSource,ServerEvent,UnavailableSandboxBackend,@@ -43,18 +44,7 @@ import type { TraceIndex, TraceIndexStore } from "../mechanisms/traces.js";import type { SessionIndex, SessionOrigins } from "../mechanisms/sessions.js";import type { ProjectConfigStore } from "../mechanisms/projects.js";import type { SandboxDimension, SandboxSettings } from "@lmliheng/penguin-core/plugin";--const SANDBOX_MODE_RANK: Record<SandboxSettings["mode"], number> = {- "read-only": 0,- "workspace-write": 1,- "danger-full-access": 2,-};--const SANDBOX_NETWORK_RANK: Record<SessionSandbox["network"], number> = {- none: 0,- local: 1,- open: 2,-};+import { aboveSandboxCeiling } from "./sandbox-ceiling.js";/** A stored policy's network level as the composer names it. */function networkOf(policy: SandboxSettings): SessionSandbox["network"] {@@ -66,12 +56,24 @@ function networkOf(policy: SandboxSettings): SessionSandbox["network"] {* `dimensions` is what the mounted sandbox backends implement between them — none on a* deployment that has not installed one. `unavailable` is each backend that is enabled but* failed to load or failed its check, with why; one for another platform is not among them.+ * `presets` is the Sandbox card's table the composer names levels by, when there is one; the+ * policy is `advanced` when it holds what no preset shows (masked paths, a read-only temp).+ * `switchOn` is the card's switch, when the server reports it. Given the server's settings+ * (`ceiling`), each preset wider than them is marked `aboveCeiling`, by the comparison+ * `applySandboxPick` refuses a non-admin's pick with.*/export function sessionSandboxOf(policy: SandboxSettings,dimensions: readonly SandboxDimension[] = [],unavailable: readonly UnavailableSandboxBackend[] = [],+ presets?: readonly SessionSandboxPreset[],+ switchOn?: boolean,+ ceiling?: SandboxSettings,): SessionSandbox {+ const advanced = (policy.maskPaths ?? []).length > 0 || policy.writableTemp === false;+ const above = (p: SessionSandboxPreset) =>+ ceiling !== undefined &&+ aboveSandboxCeiling(p, { mode: ceiling.mode, network: networkOf(ceiling) }) !== null;return {mode: policy.mode,network: networkOf(policy),@@ -79,6 +81,11 @@ export function sessionSandboxOf(noNetworkSupported: dimensions.includes("network"),localNetworkSupported: dimensions.includes("network-local"),unavailableBackends: unavailable.map(({ name, reason }) => ({ name, reason })),+ ...(presets !== undefined+ ? { presets: presets.map((p) => ({ ...p, ...(above(p) ? { aboveCeiling: true } : {}) })) }+ : {}),+ ...(advanced ? { advanced: true } : {}),+ ...(switchOn !== undefined ? { switchOn } : {}),};}@@ -106,14 +113,18 @@ export function applySandboxPick();}if (!isAdmin) {- if (SANDBOX_MODE_RANK[mode] > SANDBOX_MODE_RANK[defaults.mode]) {+ const above = aboveSandboxCeiling(+ { mode, network },+ { mode: defaults.mode, network: networkOf(defaults) },+ );+ if (above === "mode") {throw new HttpError(403,"sandbox_forbidden",`Only an administrator can give a Session more filesystem access than the server's sandbox settings (${defaults.mode}).`,);}- if (SANDBOX_NETWORK_RANK[network] > SANDBOX_NETWORK_RANK[networkOf(defaults)]) {+ if (above === "network") {throw new HttpError(403,"sandbox_forbidden",@@ -204,6 +215,12 @@ export interface SessionServiceDeps {sandboxDimensions?: () => readonly SandboxDimension[];/** The enabled sandbox backends that failed to load or failed their check, with why. */sandboxUnavailable?: () => readonly UnavailableSandboxBackend[];+ /** The Sandbox card's presets table, in table order (absent: the view carries none). */+ sandboxPresets?: () => readonly SessionSandboxPreset[];+ /** The Sandbox card's switch: whether new Sessions start confined (absent: not reported). */+ sandboxSwitchOn?: () => boolean;+ /** The approval mode a new Session starts with when its request names none (the default preset's). */+ sandboxDefaultApproval?: () => ApprovalMode | undefined;}export class SessionService {@@ -229,25 +246,58 @@ export class SessionService {policy,this.sandboxDimensions(),this.deps.sandboxUnavailable?.() ?? [],+ this.deps.sandboxPresets?.(),+ this.deps.sandboxSwitchOn?.(),+ this.defaultSandbox(),);}+ /**+ * What a new Session starts from, as the composer's draft reads it (the chat defaults): the+ * settings' policy, plus the approval mode the default preset gives a request naming none.+ */+ defaultsView(): SessionSandbox {+ const approval = this.deps.sandboxDefaultApproval?.();+ return {+ ...this.sandboxView(this.defaultSandbox()),+ ...(approval !== undefined ? { defaultApprovalMode: approval } : {}),+ };+ }++ /**+ * The approval mode a Session created without one starts with. An organization's Session+ * keeps `allow-all`: its runtime names the mode it wants, and nobody is there to answer an+ * ask a preset might bring. The other unattended creators — a scheduled run, a workflow —+ * pass `allow-all` themselves (scheduler.ts, workflows/service.ts).+ */+ private startApproval(requested: ApprovalMode | undefined, client?: string): ApprovalMode {+ if (requested !== undefined) return requested;+ if (client === "org") return "allow-all";+ return this.deps.sandboxDefaultApproval?.() ?? "allow-all";+ }+/** A Session's policy: its snapshot, or — for a row from before snapshots — the settings. */sandboxOf(row: SessionRow): SandboxSettings {return row.sandbox ?? this.defaultSandbox();}- /** Changes one Session's policy (its next command runs under it); returns the new policy. */- updateSandbox(row: SessionRow, pick: Partial<SessionSandbox>, isAdmin: boolean): SandboxSettings {- const next = applySandboxPick(+ /**+ * The policy a pick would give one Session, checked — the non-admin ceiling and what this+ * server can enforce — and not written: a PATCH checks every field before it writes any.+ */+ pickSandbox(row: SessionRow, pick: Partial<SessionSandbox>, isAdmin: boolean): SandboxSettings {+ return applySandboxPick(this.sandboxOf(row),pick,this.defaultSandbox(),isAdmin,this.localNetworkSupported(),);- this.deps.sessions.updateSandbox(row.sessionId, next);- return next;+ }++ /** Stores one Session's policy (`pickSandbox`'s): its next command runs under it. */+ updateSandbox(sessionId: string, policy: SandboxSettings): void {+ this.deps.sessions.updateSandbox(sessionId, policy);}/**@@ -618,7 +668,7 @@ export class SessionService {provider: session.provider,modelId: session.modelId,workspace: session.workspaceDir,- approvalMode: args.approvalMode ?? "allow-all",+ approvalMode: this.startApproval(args.approvalMode, args.client),sandbox,title: null,// The creator's hint: "cli" when the CLI created this Session through the API,diff --git a/packages/server/src/workflows/service.ts b/packages/server/src/workflows/service.tsindex abc03d6a..681f5af2 100644--- a/packages/server/src/workflows/service.ts+++ b/packages/server/src/workflows/service.ts@@ -583,7 +583,12 @@ export class WorkflowService implements Workflows {if (!service.agents.exists(projectId, target)) {throw new Error(`createSession: this Project has no Agent '${target}'`);}- return service.sessions.createSession({ projectId, agentId: target });+ // Unattended, like a scheduled run: allow-all, whatever the default preset asks.+ return service.sessions.createSession({+ projectId,+ agentId: target,+ approvalMode: "allow-all",+ });},async run(sessionId: string, input: WorkflowInput[]) {service.ownSession(projectId, sessionId, "run");diff --git a/packages/server/test/plugin-config.test.ts b/packages/server/test/plugin-config.test.tsindex d573cf6a..56107bc7 100644--- a/packages/server/test/plugin-config.test.ts+++ b/packages/server/test/plugin-config.test.ts@@ -9,11 +9,12 @@ import { parseManifest } from "@lmliheng/penguin-core/kernel";import type { PluginConfigResponse } from "../src/api/types.js";import {PluginConfigError,- PluginConfigPage,PluginConfigStore,applyUpdate,parsePluginConfiguration,+ resolveTable,} from "../src/plugin/config.js";+import { PluginConfigPage } from "../src/plugin/config-page.js";import { PluginHost } from "../src/plugin/host.js";import { apiClient, createTestApp, loginAdmin, provisionUser } from "./helpers.js";import type { TestApp } from "./helpers.js";@@ -86,6 +87,23 @@ describe("parsePluginConfiguration", () => {expect(bad({ a: { type: "string", title: "A", pattern: "(" } })).toThrow(/\.a\.pattern is not a valid regular expression/,);+ expect(bad({ a: { type: "string", title: "A", advanced: "yes" } })).toThrow(+ /\.a\.advanced must be a boolean/,+ );+ });++ it("keeps a field's advanced mark, and leaves it off a field not marked", () => {+ const schema = parsePluginConfiguration(+ {+ properties: {+ basic: { type: "boolean", title: "Basic", advanced: false },+ tuned: { type: "number", title: "Tuned", advanced: true },+ },+ },+ "acme/package.json",+ )!;+ expect(schema.properties.tuned).toEqual({ type: "number", title: "Tuned", advanced: true });+ expect(schema.properties.basic).toEqual({ type: "boolean", title: "Basic" });});});@@ -343,3 +361,314 @@ describe("PluginConfigPage actions", () => {expect(saves).toEqual(["sandbox"]);});});++const parse = (config: Record<string, unknown>) =>+ parsePluginConfiguration(config, "acme/package.json");+const NAME = { name: "name", type: "string", title: "Name" };+const LEVEL = {+ name: "level",+ type: "enum",+ title: "Level",+ options: [+ { value: "low", title: "Low", description: "Quiet", descriptionZh: "安静" },+ { value: "high", title: "High" },+ ],+};+/** What a refused update throws, or null. */+const refusal = (fn: () => unknown) => {+ try {+ fn();+ } catch (e) {+ return e;+ }+ return null;+};++describe("a table field", () => {+ const TABLE = parse({+ properties: {+ presets: {+ type: "table",+ title: "Presets",+ columns: [NAME, { name: "enabled", type: "boolean", title: "In menu" }, LEVEL],+ rows: [+ {+ id: "fixed",+ values: { name: "Fixed", enabled: true, level: "high" },+ valuesZh: { name: "固定" },+ locked: ["level"],+ },+ {+ id: "free",+ values: { name: "Free", enabled: false, level: "low" },+ description: "For quiet work",+ descriptionZh: "适合安静的工作",+ },+ ],+ pin: { column: "enabled", on: "Pinned", off: "Not pinned" },+ },+ },+ })!;+ const field = TABLE.properties.presets!;+ const FREE = {+ id: "free",+ values: { name: "Free", enabled: false, level: "low" },+ description: "For quiet work",+ descriptionZh: "适合安静的工作",+ };++ const on = [{ name: "on", type: "boolean", title: "On" }];+ const row = { id: "a", values: { on: true } };+ it.each([+ [{ rows: [] }, /presets\.columns must list the columns/],+ [{ columns: on, rows: [] }, /presets\.rows must list the rows/],+ [{ columns: [{ name: "n", type: "list", title: "N" }], rows: [] }, /columns\[0\]\.type must/],+ [{ columns: on, rows: [{ id: "a", values: {} }] }, /rows\[0\]\.values\.on does not fit/],+ [{ columns: on, rows: [{ ...row, locked: ["off"] }] }, /rows\[0\]\.locked must list columns/],+ [{ columns: on, rows: [row, row] }, /rows\[1\]\.id must be a unique/],+ [{ columns: on, rows: [{ ...row, id: "$added" }] }, /rows\[0\]\.id must be a unique lower/],+ [{ columns: on, rows: [row], default: {} }, /a table's rows are its defaults/],+ [{ columns: on, rows: [row], pin: { column: "on", on: "P" } }, /needs an on and an off text/],+ [+ {+ columns: [NAME],+ rows: [{ id: "a", values: { name: "A" } }],+ pin: { column: "name", on: "P", off: "N" },+ },+ /pin\.column must name a boolean column/,+ ],+ [{ columns: on, rows: [row], rowChoice: { field: "x" } }, /needs a field and a title/],+ ])("refuses a table the page could not draw (%#)", (presets, error) => {+ expect(() =>+ parse({ properties: { presets: { type: "table", title: "P", ...presets } } }),+ ).toThrow(error);+ });++ it("keeps the pin, and a row's and an option's description for the \"?\"", () => {+ expect(field.pin).toEqual({ column: "enabled", on: "Pinned", off: "Not pinned" });+ expect(field.columns![2]!.options![0]).toEqual(LEVEL.options[0]);+ });++ it("reads as its declared rows when nothing is stored, and lays stored cells over them", () => {+ expect(resolveTable(field, undefined)).toEqual([+ {+ id: "fixed",+ values: { name: "Fixed", enabled: true, level: "high" },+ valuesZh: { name: "固定" },+ locked: ["level"],+ },+ FREE,+ ]);+ // A renamed row is called that in every language; a stored row it does not declare is left out.+ const read = resolveTable(field, { fixed: { name: "Mine" }, gone: { name: "x" } });+ expect(read.map((r) => r.id)).toEqual(["fixed", "free"]);+ expect(read[0]).toEqual({+ id: "fixed",+ values: { name: "Mine", enabled: true, level: "high" },+ locked: ["level"],+ });+ });++ it("ignores a stored value for a locked cell: a hand-edited document cannot remap it", () => {+ const stored = { fixed: { name: "Mine", level: "low" } };+ expect(resolveTable(field, stored)[0]!.values.level).toBe("high");+ // A save of another cell does not carry the stored locked value along.+ expect(+ applyUpdate(TABLE, { presets: stored }, { presets: { free: { enabled: true } } }),+ ).toEqual({ presets: { fixed: { name: "Mine" }, free: { enabled: true } } });+ });++ it("stores only the cells that differ from the declaration", () => {+ const next = applyUpdate(+ TABLE,+ {},+ {+ presets: {+ fixed: { name: " Mine ", enabled: true, level: "high" },+ free: { name: "Free", enabled: true, level: "low" },+ },+ },+ );+ expect(next).toEqual({ presets: { fixed: { name: "Mine" }, free: { enabled: true } } });+ // A cell set back to its declared value, or emptied, is dropped; nothing left, nothing stored.+ expect(+ applyUpdate(TABLE, next, { presets: { fixed: { name: "" }, free: { enabled: false } } }),+ ).toEqual({});+ expect(applyUpdate(TABLE, next, { presets: null })).toEqual({});+ });++ it.each([+ [{ free: { level: "max" } }, '"presets.free.level" must be one of low, high'],+ [{ free: { enabled: "yes" } }, '"presets.free.enabled" must be a boolean'],+ [{ free: { colour: "red" } }, '"presets.free.colour" is not a column of this table'],+ [{ free: "on" }, '"presets.free" must be an object of cells'],+ [[], '"presets" must be an object of rows'],+ [{ fixed: { level: "low" } }, '"presets.fixed.level" cannot be changed'],+ ])("refuses the update %j, naming the cell", (cells, message) => {+ expect(refusal(() => applyUpdate(TABLE, {}, { presets: cells }))).toEqual(+ new PluginConfigError("presets", message),+ );+ });++ it("takes a locked cell's own value, and drops rows it does not declare", () => {+ const update = { fixed: { level: "high", name: "A" }, ghost: { name: "B" } };+ expect(applyUpdate(TABLE, {}, { presets: update })).toEqual({+ presets: { fixed: { name: "A" } },+ });+ });+});++describe("a table's row choice", () => {+ const table = (rowChoice: unknown, options: string[]) =>+ parse({+ properties: {+ rows: {+ type: "table",+ title: "Rows",+ columns: [NAME],+ rows: [+ { id: "a", values: { name: "A" } },+ { id: "b", values: { name: "B" } },+ ],+ rowChoice,+ },+ pick: {+ type: "enum",+ title: "Pick",+ options: options.map((value) => ({ value, title: value })),+ },+ },+ });++ it("names an enum of the group whose options are the row ids, kept as a marker", () => {+ const choice = {+ field: "pick",+ title: "Default",+ titleZh: "默认",+ description: "x",+ before: "name",+ };+ expect(table(choice, ["b", "a"])!.properties.rows!.rowChoice).toEqual({+ field: "pick",+ title: "Default",+ titleZh: "默认",+ });+ });++ it.each([+ ["nope", ["a", "b"]],+ ["pick", ["a"]],+ ])("refuses a choice of %s over options %j", (target, options) => {+ expect(() => table({ field: target, title: "Default" }, options)).toThrow(+ /rowChoice\.field must name an enum/,+ );+ });+});++describe("a group's switch", () => {+ const group = (sw: unknown) =>+ parse({+ switch: sw,+ properties: {+ on: { type: "boolean", title: "Enable" },+ note: { type: "string", title: "Note" },+ },+ });++ it("names a boolean field of the group, or is absent", () => {+ expect(group("on")!.switch).toBe("on");+ expect(group(undefined)!.switch).toBeUndefined();+ });++ it.each([+ ["note", /switch must name a boolean field/],+ ["nope", /switch must name a boolean field/],+ [1, /switch must be a string/],+ ])("refuses the switch %j", (sw, error) => {+ expect(() => group(sw)).toThrow(error);+ });+});++describe("an extensible table's save", () => {+ const SCHEMA_X = parse({+ properties: {+ rows: {+ type: "table",+ title: "Rows",+ columns: [NAME, LEVEL],+ rows: [+ { id: "a", values: { name: "A", level: "low" } },+ { id: "b", values: { name: "B", level: "high" } },+ ],+ rowChoice: { field: "pick", title: "Default" },+ extensible: { add: "Add", values: { name: "New", level: "low" } },+ },+ pick: {+ type: "enum",+ title: "Pick",+ options: [+ { value: "a", title: "A" },+ { value: "b", title: "B" },+ ],+ },+ },+ })!;+ const field = SCHEMA_X.properties.rows!;+ const MINE = { mine: { name: "Mine", level: "high" } };++ it("keeps well-formed added rows, trimmed, and an order of ids that exist", () => {+ const next = applyUpdate(+ SCHEMA_X,+ {},+ {+ rows: {+ $added: { mine: { name: " Mine ", level: "high" } },+ $order: ["mine", "ghost", "b", "mine"],+ },+ },+ );+ expect(next).toEqual({ rows: { $added: MINE, $order: ["mine", "b"] } });+ // Rows the order does not list follow it, in their own order.+ const read = resolveTable(field, next.rows);+ expect(read.map((r) => r.id)).toEqual(["mine", "b", "a"]);+ expect(read[0]).toEqual({ id: "mine", values: MINE.mine, added: true });+ });++ it.each([+ [{ mine: { name: "Mine" } }, '"rows.mine.level" must be one of low, high'],+ [{ mine: { name: "Mine", level: "max" } }, '"rows.mine.level" must be one of low, high'],+ [{ mine: { name: " ", level: "low" } }, '"rows.mine.name" may not be empty'],+ [{ $order: { name: "X", level: "low" } }, '"rows.$order" is not an id a new row may take'],+ [{ $added: { name: "X", level: "low" } }, '"rows.$added" is not an id a new row may take'],+ [{ a: { name: "X", level: "low" } }, '"rows.a" is not an id a new row may take'],+ ])("refuses the added rows %j", (added, message) => {+ expect(() => applyUpdate(SCHEMA_X, {}, { rows: { $added: added } })).toThrow(message);+ });++ it("drops a malformed added row on read (stored by hand, or by an older table)", () => {+ const $added = {+ bad: { name: "Bad" },+ worse: { name: "W", level: "max" },+ ok: { name: "Ok", level: "low" },+ };+ expect(resolveTable(field, { $added }).map((r) => r.id)).toEqual(["a", "b", "ok"]);+ });++ it("refuses a save that leaves the row choice pointing at a removed row", () => {+ const stored = applyUpdate(SCHEMA_X, {}, { rows: { $added: MINE }, pick: "mine" });+ expect(stored.pick).toBe("mine");+ expect(refusal(() => applyUpdate(SCHEMA_X, stored, { rows: { $added: {} } }))).toEqual(+ new PluginConfigError(+ "pick",+ '"pick" must name a row of "rows": "mine" is not one (choose another row before deleting it)',+ ),+ );+ // Choosing another row in the same save lets the deletion through; no choice at all is fine.+ expect(applyUpdate(SCHEMA_X, stored, { rows: { $added: {} }, pick: "a" })).toEqual({+ pick: "a",+ });+ expect(applyUpdate(SCHEMA_X, {}, { rows: { a: { name: "Renamed" } } })).toEqual({+ rows: { a: { name: "Renamed" } },+ });+ });+});diff --git a/packages/server/test/project-chat-defaults.test.ts b/packages/server/test/project-chat-defaults.test.tsindex df57ba80..1c5e7c3b 100644--- a/packages/server/test/project-chat-defaults.test.ts+++ b/packages/server/test/project-chat-defaults.test.ts@@ -38,6 +38,10 @@ const SERVED = {noNetworkSupported: false,localNetworkSupported: false,unavailableBackends: [],+ // The Sandbox card's presets table rides beside it (session-sandbox.test.ts pins its rows).+ presets: expect.any(Array),+ // Nothing saved: the Sandbox card's switch is off.+ switchOn: false,},};diff --git a/packages/server/test/sandbox-ceiling.test.ts b/packages/server/test/sandbox-ceiling.test.tsnew file mode 100644index 00000000..a83ff001--- /dev/null+++ b/packages/server/test/sandbox-ceiling.test.ts@@ -0,0 +1,69 @@+/**+ * The non-admin ceiling on a Session's sandbox: a non-admin may tighten but never loosen past the+ * server's settings; an admin may. The composer's `aboveCeiling` mark is the same comparison.+ */+import { describe, expect, it } from "vitest";+import type { SandboxSettings } from "@lmliheng/penguin-core/plugin";+import { aboveSandboxCeiling } from "../src/services/sandbox-ceiling.js";+import { applySandboxPick, sessionSandboxOf } from "../src/services/session-service.js";++describe("the non-admin ceiling on a Session's sandbox", () => {+ const settings: SandboxSettings = {+ mode: "workspace-write",+ network: "none",+ maskPaths: ["/secret"],+ writableTemp: false,+ };+ const local: SandboxSettings = { mode: "workspace-write", network: "local" };++ it.each([+ ["danger-full-access", "open", "mode"],+ ["read-only", "open", "network"],+ ["workspace-write", "local", null],+ ["read-only", "none", null],+ ] as const)("ranks %s/%s against workspace-write/local: %s", (mode, network, wider) => {+ expect(+ aboveSandboxCeiling({ mode, network }, { mode: "workspace-write", network: "local" }),+ ).toBe(wider);+ });++ it.each([+ [settings, { mode: "danger-full-access" }],+ [settings, { network: "open" }],+ [settings, { network: "local" }],+ [local, { network: "open" }],+ ] as const)("a non-admin cannot loosen %j by %j", (base, pick) => {+ expect(() => applySandboxPick(base, pick, base, false, true)).toThrow(/Only an administrator/);+ });++ it("refuses the local level where no backend supports it", () => {+ expect(() => applySandboxPick(settings, { network: "local" }, settings, true)).toThrow(+ /localhost/,+ );+ });++ it("a non-admin may tighten and come back, and pick local under open settings", () => {+ const tightened = applySandboxPick(settings, { mode: "read-only" }, settings, false);+ expect(applySandboxPick(tightened, { mode: "workspace-write" }, settings, false).mode).toBe(+ "workspace-write",+ );+ expect(applySandboxPick(local, { network: "none" }, local, false, true).network).toBe("none");+ const open: SandboxSettings = { mode: "workspace-write" };+ const picked = applySandboxPick(open, { network: "local" }, open, false, true);+ expect(sessionSandboxOf(picked, ["fs-write", "network", "network-local"])).toMatchObject({+ network: "local",+ localNetworkSupported: true,+ });+ });++ it("an admin may go past the settings", () => {+ const opened = applySandboxPick(+ settings,+ { mode: "danger-full-access", network: "open" },+ settings,+ true,+ );+ expect(opened.mode).toBe("danger-full-access");+ expect(opened.network).toBeUndefined();+ });+});diff --git a/packages/server/test/sandbox-settings.test.ts b/packages/server/test/sandbox-settings.test.tsindex b7bfe54c..22526186 100644--- a/packages/server/test/sandbox-settings.test.ts+++ b/packages/server/test/sandbox-settings.test.ts@@ -103,9 +103,10 @@ describe("sandbox settings group", () => {const entries = await list();const sandbox = entries.find((e) => e.name === "sandbox")!;expect(entries[0]).toBe(sandbox);+ // Nothing saved: the switch reads off, and the default preset is the shipped one.expect(sandbox.values).toEqual({- mode: "danger-full-access",- network: "open",+ enabled: false,+ defaultPreset: "workspace-write",writableTemp: true,});expect(sandbox.notices).toEqual([@@ -124,16 +125,42 @@ describe("sandbox settings group", () => {apps.push(t);const entry = (await list()).find((e) => e.name === "sandbox")!;expect(entry.unavailable).toEqual([- expect.objectContaining({ field: "network", value: "local" }),+ // The presets' network column, in every row.+ expect.objectContaining({ field: "presets", column: "network", value: "local" }),]);- const refused = await admin.put("/api/admin/plugin-config", {+ const refusedCell = await admin.put("/api/admin/plugin-config", {name: "sandbox",- values: { mode: "workspace-write", network: "local" },+ values: { presets: { "read-only": { network: "local" } } },});- expect(refused.status).toBe(400);- expect(await refused.text()).toContain("network");+ expect(refusedCell.status).toBe(400);+ expect(await refusedCell.text()).toContain("presets.read-only.network");// Nothing was stored: the service still runs the defaults.expect(sandbox.currentSettings()).toEqual({ mode: "danger-full-access" });+ expect((await list()).find((e) => e.name === "sandbox")!.values.presets).toBeUndefined();+ });++ it("starts new Sessions from the default preset, with the card's temp and masked paths beside it", async () => {+ const { t, admin, sandbox } = await appWith([]);+ apps.push(t);+ const save = (values: Record<string, unknown>) =>+ admin.put("/api/admin/plugin-config", { name: "sandbox", values });+ expect(+ (await save({ enabled: true, defaultPreset: "read-only", maskPaths: ["/secret"] })).status,+ ).toBe(200);+ expect(sandbox.currentSettings()).toEqual({ mode: "read-only", maskPaths: ["/secret"] });+ // A remapped default row is what new Sessions get.+ expect(+ (await save({ presets: { "read-only": { mode: "workspace-write", network: "none" } } }))+ .status,+ ).toBe(200);+ expect(sandbox.currentSettings()).toEqual({+ mode: "workspace-write",+ network: "none",+ maskPaths: ["/secret"],+ });+ // A default that confines nothing (Full Access) starts Sessions unconfined.+ expect((await save({ defaultPreset: "full-access" })).status).toBe(200);+ expect(sandbox.currentSettings()).toEqual({ mode: "danger-full-access" });});it("applies a saved policy to the next spawn; the backend reads its own saved group", async () => {@@ -142,7 +169,12 @@ describe("sandbox settings group", () => {apps.push(t);const saved = await admin.put("/api/admin/plugin-config", {name: "sandbox",- values: { mode: "workspace-write", network: "none", maskPaths: [" /etc/x ", "/etc/x", ""] },+ values: {+ enabled: true,+ defaultPreset: "workspace-write",+ presets: { "workspace-write": { network: "none" } },+ maskPaths: [" /etc/x ", "/etc/x", ""],+ },});expect(saved.status).toBe(200);expect(sandbox.currentSettings()).toEqual({@@ -172,7 +204,7 @@ describe("sandbox settings group", () => {await admin.put("/api/admin/plugin-config", {name: "sandbox",- values: { mode: "read-only", network: "open", maskPaths: [], writableTemp: false },+ values: { defaultPreset: "read-only", maskPaths: [], writableTemp: false },});expect(sandbox.currentSettings()).toEqual({ mode: "read-only", writableTemp: false });spawn();@@ -181,7 +213,7 @@ describe("sandbox settings group", () => {const refused = await admin.put("/api/admin/plugin-config", {name: "sandbox",- values: { mode: "wide-open" },+ values: { defaultPreset: "wide-open" },});expect(refused.status).toBe(400);// A relative masked path would resolve against the server's working directory.@@ -230,7 +262,7 @@ describe("sandbox settings group", () => {await t.deps.tree.api<SandboxService>("SandboxModule", "sandbox").whenReady();await admin.put("/api/admin/plugin-config", {name: "sandbox",- values: { mode: "workspace-write" },+ values: { enabled: true },});const entries = ((await (await admin.get("/api/admin/plugin-config")).json()) as PluginConfigResponse@@ -341,7 +373,7 @@ describe("sandbox settings group", () => {const first = await appWith([], dbPath);await first.admin.put("/api/admin/plugin-config", {name: "sandbox",- values: { mode: "read-only" },+ values: { enabled: true, defaultPreset: "read-only" },});await first.admin.put("/api/admin/plugin-config", {name: "sandbox-test",diff --git a/packages/server/test/sandbox-switch.test.ts b/packages/server/test/sandbox-switch.test.tsnew file mode 100644index 00000000..2f4ac085--- /dev/null+++ b/packages/server/test/sandbox-switch.test.ts@@ -0,0 +1,329 @@+/**+ * The Sandbox card's switch (whether new Sessions start confined) and its default preset:+ * settings saved before either existed keep their start, a new Session starts from the default+ * preset while the switch is on and unconfined while it is off, and the card reports whether+ * this OS has a sandbox backend.+ */+import fs from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { parseManifest } from "@lmliheng/penguin-core/kernel";+import type { ModuleDef } from "@lmliheng/penguin-core/kernel";+import type { PluginConfigEntry, PluginConfigResponse, SessionSandbox } from "../src/api/types.js";+import { PluginHost } from "../src/plugin/host.js";+import type { SandboxService } from "../src/sandbox/service.js";+import { apiClient, createTestApp, loginAdmin, provisionUser } from "./helpers.js";+import type { TestApp } from "./helpers.js";++/** What the server defaults to on the OS the suite runs on. */+const recommended = (+ {+ linux: "@lmliheng/penguin-plugin-sandbox-bwrap",+ darwin: "@lmliheng/penguin-plugin-sandbox-seatbelt",+ win32: "@lmliheng/penguin-plugin-sandbox-wsl",+ } as Partial<Record<NodeJS.Platform, string>>+)[process.platform];++/** A backend plugin whose providers resolve as given: a provider, null (declined), or a failure. */+function backendPlugin(bind: Record<string, unknown>): PluginHost {+ const module: ModuleDef = {+ manifest: parseManifest({+ name: "SwitchTestBackend",+ requires: {},+ provides: {},+ contributes: {+ "SandboxModule.providers": Object.keys(bind).map((id) => ({+ id,+ name: id.replace(/\.provider$/, ""),+ dimensions: ["fs-write", "network"],+ })),+ },+ children: [],+ }),+ create: () => ({ api: {}, bind }),+ };+ const host = new PluginHost();+ host.use({ specifier: "switch-test-backend", modules: [module], replaces: [] });+ return host;+}++const PROVIDER = {+ dimensions: ["fs-write", "network"],+ confine: (argv: readonly string[]) => ({+ argv: ["confined", ...argv],+ enforcement: "full" as const,+ denialSignatures: [],+ runnerFailureRules: [],+ }),+};+const fakeBackend = () => backendPlugin({ "fake.provider": PROVIDER });++type Doc = Record<string, unknown>;+type View = { sandbox: SessionSandbox };+type Created = { session: { sessionId: string; approvalMode: string } & View };++const apps: TestApp[] = [];+afterEach(async () => {+ for (const t of apps.splice(0)) await t.cleanup();+});++async function boot(opts: { plugins?: PluginHost; dbPath?: string } = {}) {+ const t = await createTestApp({+ ...(opts.plugins ? { plugins: opts.plugins } : {}),+ ...(opts.dbPath ? { config: { dbPath: opts.dbPath } } : {}),+ });+ apps.push(t);+ const admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);+ const sandbox = t.deps.tree.api<SandboxService>("SandboxModule", "sandbox");+ await sandbox.whenReady();+ const card = async (): Promise<PluginConfigEntry> =>+ (+ (await (await admin.get("/api/admin/plugin-config")).json()) as PluginConfigResponse+ ).plugins.find((e) => e.name === "sandbox")!;+ const save = (values: Doc) => admin.put("/api/admin/plugin-config", { name: "sandbox", values });+ const store = (doc: Doc) =>+ t.deps.serverSettingsRepo.set("plugin-config:sandbox", JSON.stringify(doc));+ const onDisk = () => JSON.parse(t.deps.serverSettingsRepo.get("plugin-config:sandbox")!) as Doc;+ return { t, sandbox, card, save, store, onDisk };+}++/** A member's Project with a model, and the calls a composer makes in it. */+async function ownerProject(t: TestApp, id: string) {+ const owner = apiClient(t.app, (await provisionUser(t.app, "owner")).cookie);+ const res = await owner.post("/api/projects", { projectId: id, name: "project" });+ const projectId = ((await res.json()) as { project: { projectId: string } }).project.projectId;+ const model = { provider: "anthropic", modelId: "claude-sonnet-4-6" };+ await owner.put(`/api/projects/${projectId}/models`, {+ defaultModel: model,+ models: [{ ...model, contextWindow: 128000 }],+ });+ return {+ owner,+ create: async () =>+ (await (+ await owner.post(`/api/projects/${projectId}/agents/default_agent/sessions`, {})+ ).json()) as Created,+ read: async (sessionId: string) =>+ ((await (await owner.get(`/api/sessions/${sessionId}`)).json()) as Created).session.sandbox,+ draft: async () =>+ ((await (await owner.get(`/api/projects/${projectId}/chat-defaults`)).json()) as View)+ .sandbox,+ };+}++describe("the sandbox switch", () => {+ // Settings saved before the switch read as on exactly when they confined anything.+ it.each([+ [{ mode: "read-only", network: "none" }, true, { mode: "read-only", network: "none" }],+ [+ { mode: "danger-full-access", network: "none" },+ true,+ { mode: "danger-full-access", network: "none" },+ ],+ [{ mode: "danger-full-access", maskPaths: [] }, false, { mode: "danger-full-access" }],+ ])(+ "reads pre-switch settings %j as on=%s, applies them, and leaves the disk alone",+ async (doc, on, applied) => {+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), "penguin-sandbox-switch-"));+ try {+ const dbPath = path.join(dir, "web.db");+ const first = await boot({ plugins: fakeBackend(), dbPath });+ first.store(doc);+ await apps.pop()!.cleanup();+ const next = await boot({ plugins: fakeBackend(), dbPath });+ expect((await next.card()).values.enabled).toBe(on);+ expect(next.sandbox.currentSettings()).toEqual(applied);+ expect(next.t.deps.serverSettingsRepo.get("plugin-config:sandbox")).toBe(+ JSON.stringify(doc),+ );+ } finally {+ for (const t of apps.splice(0)) await t.cleanup();+ await fs.rm(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });+ }+ },+ );++ it("shows the row a pre-preset document matches as the default, and none when no row matches", async () => {+ const { card, store } = await boot();+ const prePresetNotice = (entry: PluginConfigEntry) =>+ entry.notices?.find((n) => n.text.includes("saved before the presets"));+ // Nothing saved is no pre-preset document: the shipped default.+ expect((await card()).values.defaultPreset).toBe("workspace-write");++ const cut = {+ name: "Cut",+ enabled: false,+ mode: "read-only",+ network: "none",+ approvalMode: "allow-all",+ };+ // Same mode and network, approving everything; masked paths lie over every row; added rows count.+ for (const [doc, row] of [+ [{ mode: "read-only" }, "read-only"],+ [{ mode: "workspace-write", network: "open" }, "workspace-write"],+ [{ mode: "workspace-write", maskPaths: ["/secret"] }, "workspace-write"],+ [{ mode: "read-only", network: "none", presets: { $added: { cut } } }, "cut"],+ ] as const) {+ store(doc);+ const entry = await card();+ expect(entry.values.defaultPreset, JSON.stringify(doc)).toBe(row);+ expect(prePresetNotice(entry)).toBeUndefined();+ }++ // No row starts there (Off with masked paths confines nothing): no default, and a notice.+ for (const doc of [+ { mode: "workspace-write", network: "local" },+ { maskPaths: ["/secret"] },+ { mode: "danger-full-access", maskPaths: ["/secret"] },+ { mode: "read-only", network: "none" },+ ]) {+ store(doc);+ const entry = await card();+ expect(entry.values.defaultPreset, JSON.stringify(doc)).toBeUndefined();+ expect(entry.values.enabled).toBe(true);+ expect(prePresetNotice(entry), JSON.stringify(doc)).toMatchObject({ tone: "attention" });+ }+ // The notice says what is in effect (the last document's start).+ expect(prePresetNotice(await card())?.text).toContain("files Read-only, network No network");+ });++ it("keeps a pre-preset document's start across a save that picks no default", async () => {+ const { save, sandbox, store, onDisk } = await boot();+ const rename = { presets: { "read-only": { name: "Look only" } } };++ // No row matches: an unrelated save writes no default; an administrator's pick moves it.+ store({ mode: "read-only", network: "none" });+ expect((await save(rename)).status).toBe(200);+ expect(onDisk().defaultPreset).toBeUndefined();+ expect(sandbox.currentSettings()).toEqual({ mode: "read-only", network: "none" });+ expect((await save({ defaultPreset: "workspace-write" })).status).toBe(200);+ expect(onDisk().defaultPreset).toBe("workspace-write");+ expect(sandbox.currentSettings()).toEqual({ mode: "workspace-write" });++ // A row matches: the save pins it, and the start is what it was.+ store({ mode: "read-only" });+ expect((await save(rename)).status).toBe(200);+ expect(onDisk().defaultPreset).toBe("read-only");+ expect(sandbox.currentSettings()).toEqual({ mode: "read-only" });+ });++ it("on, a new Session starts from the default preset; off, unconfined; existing Sessions keep theirs", async () => {+ const { t, card, save, sandbox } = await boot({ plugins: fakeBackend() });+ // Fresh install: off.+ expect((await card()).values.enabled).toBe(false);+ const { create, read, draft } = await ownerProject(t, "owner-switch");++ const remapped = { "read-only": { network: "none", approvalMode: "always-ask" } };+ const onSave = await save({ enabled: true, defaultPreset: "read-only", presets: remapped });+ expect(onSave.status).toBe(200);+ const confined = await create();+ expect(confined.session.approvalMode).toBe("always-ask");+ const readOnly = { mode: "read-only", network: "none" };+ expect(confined.session.sandbox).toMatchObject({ ...readOnly, switchOn: true });+ expect(await draft()).toMatchObject({ ...readOnly, defaultApprovalMode: "always-ask" });++ // Another default reaches new Sessions only.+ expect((await save({ defaultPreset: "workspace-write" })).status).toBe(200);+ const next = await create();+ expect(next.session.approvalMode).toBe("allow-all");+ expect(next.session.sandbox).toMatchObject({ mode: "workspace-write", network: "open" });+ expect(await read(confined.session.sessionId)).toMatchObject(readOnly);++ // Off: unconfined, no approval mode from the presets; the default stays recorded.+ const off = await save({ enabled: false });+ const offCard = ((await off.json()) as PluginConfigResponse).plugins.find(+ (e) => e.name === "sandbox",+ )!;+ expect(offCard.values).toMatchObject({ enabled: false, defaultPreset: "workspace-write" });+ expect(sandbox.currentSettings()).toEqual({ mode: "danger-full-access" });+ const unconfined = await create();+ expect(unconfined.session.approvalMode).toBe("allow-all");+ expect(unconfined.session.sandbox).toMatchObject({+ mode: "danger-full-access",+ network: "open",+ switchOn: false,+ });+ const offDraft = await draft();+ expect(offDraft).toMatchObject({ mode: "danger-full-access", switchOn: false });+ expect(offDraft.defaultApprovalMode).toBeUndefined();+ expect(await read(confined.session.sessionId)).toMatchObject({ ...readOnly, switchOn: false });++ // On again: the default preset applies again, to new Sessions only.+ expect((await save({ enabled: true })).status).toBe(200);+ expect(sandbox.currentSettings()).toEqual({ mode: "workspace-write" });+ expect(await read(unconfined.session.sessionId)).toMatchObject({ mode: "danger-full-access" });+ });++ it("serves the card's presets to the composer in the stored order, added ones included, and a pick applies", async () => {+ const { t, save } = await boot();+ const { owner, create, draft } = await ownerProject(t, "owner-order");+ const order = ["mine", "read-only", "full-access", "always-ask", "workspace-write"];+ const mine = {+ name: "Mine",+ enabled: true,+ mode: "read-only",+ network: "open",+ approvalMode: "always-ask",+ };+ const saved = await save({+ enabled: true,+ defaultPreset: "mine",+ presets: { $added: { mine }, $order: order },+ });+ expect(saved.status).toBe(200);+ const sandbox = await draft();+ // The stored order first, then the rows it does not name, as declared.+ expect(sandbox.presets?.map((p) => p.id)).toEqual([+ ...order,+ "workspace-write-ask",+ "denied-all",+ ]);+ expect(sandbox.presets?.[0]).toMatchObject({ name: "Mine", enabled: true });+ expect(sandbox).toMatchObject({ switchOn: true, defaultApprovalMode: "always-ask" });++ const created = await create();+ expect(created.session.approvalMode).toBe("always-ask");+ expect(created.session.sandbox.presets?.map((p) => p.id).slice(0, 5)).toEqual(order);+ // A preset picked from the menu: its three values land on the Session.+ const pick = { approvalMode: "allow-all", sandbox: { mode: "read-only", network: "open" } };+ const picked = await owner.patch(`/api/sessions/${created.session.sessionId}`, pick);+ expect(picked.status).toBe(200);+ expect(((await picked.json()) as Created).session).toMatchObject(pick);+ });++ it("reports no backend for this OS, the OS's default package, and names its switch", async () => {+ const entry = await (await boot()).card();+ expect(entry.backend).toEqual({ installed: false, ...(recommended ? { recommended } : {}) });+ expect(+ entry.notices?.find((n) => n.text.startsWith("This deployment has no usable")),+ ).toMatchObject({ tone: "attention" });+ expect(entry.configuration.switch).toBe("enabled");+ });++ it("explains every preset row and every value a row's choice can take, in both languages", async () => {+ const presets = (await (await boot()).card()).configuration.properties.presets!;+ const described = { description: expect.any(String), descriptionZh: expect.any(String) };+ for (const row of presets.rows!) expect(row, row.id).toMatchObject(described);+ for (const column of presets.columns!.filter((c) => c.type === "enum"))+ for (const option of column.options!)+ expect(option, `${column.name}.${option.value}`).toMatchObject(described);+ });++ it.each([+ ["declined only", { "elsewhere.provider": Promise.resolve(null) }, false],+ [+ "installed and failing",+ {+ "elsewhere.provider": Promise.resolve(null),+ // A loader, so the failure is not an unhandled rejection before the service asks.+ "broken.provider": () => Promise.reject(new Error("'bwrap' is missing")),+ },+ true,+ ],+ ["in use", { "fake.provider": PROVIDER }, true],+ ])("counts a backend %s as installed: %s", async (_, bind, installed) => {+ const { card } = await boot({ plugins: backendPlugin(bind) });+ expect((await card()).backend?.installed).toBe(installed);+ });+});diff --git a/packages/server/test/scheduler.test.ts b/packages/server/test/scheduler.test.tsindex 2a375784..0a748dc0 100644--- a/packages/server/test/scheduler.test.ts+++ b/packages/server/test/scheduler.test.ts@@ -49,6 +49,7 @@ describe("scheduler", () => {workspace?: string;provider?: string;modelId?: string;+ approvalMode?: "allow-all";source?: "schedule";}>;let events: Array<{ userId: string; event: ScheduleServerEvent }>;@@ -409,6 +410,8 @@ describe("scheduler", () => {workspace: "/tmp/ws",provider: "custom",modelId: "m-bench",+ // Unattended: allow-all, whatever approval mode the Sandbox card's default preset gives.+ approvalMode: "allow-all",source: "schedule",});expect(started.map((s) => s.sessionId)).toEqual(["session-new-1", "session-new-2"]);diff --git a/packages/server/test/session-sandbox.test.ts b/packages/server/test/session-sandbox.test.tsindex 923a58a5..4c32eb8b 100644--- a/packages/server/test/session-sandbox.test.ts+++ b/packages/server/test/session-sandbox.test.ts@@ -11,6 +11,7 @@ import { migrate } from "../src/db/migrations.js";import { SCHEMA_SQL } from "../src/db/schema.js";import { SessionsRepo } from "../src/db/repos/sessions.js";import type { SessionRow } from "../src/db/repos/sessions.js";+import type { SessionSandbox } from "../src/api/types.js";import { SandboxService } from "../src/sandbox/index.js";import { applySandboxPick, sessionSandboxOf } from "../src/services/session-service.js";@@ -24,6 +25,36 @@ const NO_BACKEND = {unavailableBackends: [],};+/** The Sandbox card's presets table as a Session's view carries it with nothing saved. */+const DEFAULT_PRESETS = (+ [+ ["full-access", "Full Access", "完全访问", true, "danger-full-access", "allow-all"],+ ["always-ask", "Always Ask", "每次询问", true, "danger-full-access", "always-ask"],+ ["workspace-write", "Workspace Write", "仅工作区可写", true, "workspace-write", "allow-all"],+ ["read-only", "Read Only", "只读", true, "read-only", "allow-all"],+ [+ "workspace-write-ask",+ "Workspace Write with Ask",+ "仅工作区可写并询问",+ false,+ "workspace-write",+ "always-ask",+ ],+ ["denied-all", "Denied All", "全部拒绝", false, "danger-full-access", "deny-all"],+ ] as const+).map(([id, name, nameZh, enabled, mode, approvalMode]) => ({+ id,+ name,+ nameZh,+ enabled,+ mode,+ network: "open",+ approvalMode,+}));++/** Served beside a policy on a server with no backend: the presets, and the switch on. */+const SERVED = { ...NO_BACKEND, presets: DEFAULT_PRESETS, switchOn: true };+const ROW: SessionRow = {sessionId: "session-1",projectId: "p",@@ -48,13 +79,24 @@ describe("picking a Session's sandbox from the composer", () => {it("keeps the snapshot's mask paths and temp choice, and lays the picks over it", () => {const next = applySandboxPick(settings, { mode: "read-only" }, settings, false);expect(next).toEqual({ ...settings, mode: "read-only" });+ // Masked paths and a read-only temp are what no preset shows: the view says so.expect(sessionSandboxOf(next)).toEqual({mode: "read-only",network: "none",...NO_BACKEND,+ advanced: true,});});+ it("is advanced only while the policy holds what no preset shows, and carries the presets it is given", () => {+ expect(sessionSandboxOf({ mode: "workspace-write" }).advanced).toBeUndefined();+ expect(sessionSandboxOf({ mode: "workspace-write", writableTemp: false }).advanced).toBe(true);+ expect(sessionSandboxOf({ mode: "workspace-write", maskPaths: ["/k"] }).advanced).toBe(true);+ expect(sessionSandboxOf({ mode: "workspace-write" }).presets).toBeUndefined();+ const view = sessionSandboxOf({ mode: "read-only" }, [], [], DEFAULT_PRESETS as never);+ expect(view.presets).toEqual(DEFAULT_PRESETS);+ });+it("says which levels the mounted backends can enforce, and none without a backend", () => {const policy: SandboxSettings = { mode: "danger-full-access" };expect(sessionSandboxOf(policy)).toEqual({@@ -93,59 +135,6 @@ describe("picking a Session's sandbox from the composer", () => {],});});-- it("a non-admin cannot loosen past the server's settings, in either dimension", () => {- expect(() =>- applySandboxPick(settings, { mode: "danger-full-access" }, settings, false),- ).toThrow(/Only an administrator/);- expect(() => applySandboxPick(settings, { network: "open" }, settings, false)).toThrow(- /Only an administrator/,- );- });-- it("the local level is refused where no backend supports it, and ranks between none and open", () => {- expect(() => applySandboxPick(settings, { network: "local" }, settings, true)).toThrow(- /localhost/,- );- const open: SandboxSettings = { mode: "workspace-write" };- const local = applySandboxPick(open, { network: "local" }, open, false, true);- expect(local.network).toBe("local");- expect(sessionSandboxOf(local, ["fs-write", "network", "network-local"])).toEqual({- mode: "workspace-write",- network: "local",- confinementSupported: true,- noNetworkSupported: true,- localNetworkSupported: true,- unavailableBackends: [],- });- // Under settings of "local", a non-admin may cut the network but not open it.- const localDefaults: SandboxSettings = { mode: "workspace-write", network: "local" };- expect(- applySandboxPick(localDefaults, { network: "none" }, localDefaults, false, true).network,- ).toBe("none");- expect(() =>- applySandboxPick(localDefaults, { network: "open" }, localDefaults, false, true),- ).toThrow(/Only an administrator/);- // Under settings of "none", "local" is already looser.- expect(() => applySandboxPick(settings, { network: "local" }, settings, false, true)).toThrow(- /Only an administrator/,- );- });-- it("a non-admin who tightened may come back to the settings; an admin may go past them", () => {- const tightened = applySandboxPick(settings, { mode: "read-only" }, settings, false);- expect(applySandboxPick(tightened, { mode: "workspace-write" }, settings, false).mode).toBe(- "workspace-write",- );- const opened = applySandboxPick(- settings,- { mode: "danger-full-access", network: "open" },- settings,- true,- );- expect(opened.mode).toBe("danger-full-access");- expect(opened.network).toBeUndefined();- });});describe("the snapshot on the Session's row", () => {@@ -211,69 +200,205 @@ describe("confining under a Session's own policy", () => {});});+type ApiSession = { sessionId: string; approvalMode: string; sandbox: SessionSandbox };++/** A fresh app, an admin, and an owner's Project with a model, to create Sessions in. */+async function ownerProject(id: string) {+ const { apiClient, createTestApp, loginAdmin, provisionUser } = await import("./helpers.js");+ const t = await createTestApp();+ const admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);+ const owner = apiClient(t.app, (await provisionUser(t.app, "owner")).cookie);+ const projectId = (+ (await (await owner.post("/api/projects", { projectId: id, name: "project" })).json()) as {+ project: { projectId: string };+ }+ ).project.projectId;+ await owner.put(`/api/projects/${projectId}/models`, {+ defaultModel: { provider: "anthropic", modelId: "claude-sonnet-4-6" },+ models: [{ provider: "anthropic", modelId: "claude-sonnet-4-6", contextWindow: 128000 }],+ });+ const body = async (res: Response) => ((await res.json()) as { session: ApiSession }).session;+ return {+ t,+ admin,+ owner,+ projectId,+ body,+ settings: (values: Record<string, unknown>) =>+ admin.put("/api/admin/plugin-config", { name: "sandbox", values }),+ post: (sandbox?: unknown) =>+ owner.post(+ `/api/projects/${projectId}/agents/default_agent/sessions`,+ sandbox ? { sandbox } : {},+ ),+ create: async () =>+ body(await owner.post(`/api/projects/${projectId}/agents/default_agent/sessions`, {})),+ read: async (sessionId: string) => body(await owner.get(`/api/sessions/${sessionId}`)),+ defaults: async () =>+ (+ (await (await owner.get(`/api/projects/${projectId}/chat-defaults`)).json()) as {+ sandbox: SessionSandbox;+ }+ ).sandbox,+ };+}+describe("the API: settings seed new Sessions, and never reach existing ones", () => {it("snapshots at creation, keeps the snapshot across a settings change, and bounds non-admins", async () => {- const { apiClient, createTestApp, loginAdmin, provisionUser } = await import("./helpers.js");- const t = await createTestApp();+ const { t, owner, settings, post, create, read, body } = await ownerProject("owner-sandbox");try {- const admin = apiClient(t.app, (await loginAdmin(t.app)).cookie);- const owner = apiClient(t.app, (await provisionUser(t.app, "owner")).cookie);- const project = (await (- await owner.post("/api/projects", { projectId: "owner-sandbox", name: "project" })- ).json()) as { project: { projectId: string } };- const projectId = project.project.projectId;- await owner.put(`/api/projects/${projectId}/models`, {- defaultModel: { provider: "anthropic", modelId: "claude-sonnet-4-6" },- models: [{ provider: "anthropic", modelId: "claude-sonnet-4-6", contextWindow: 128000 }],- });- const settings = (values: Record<string, unknown>) =>- admin.put("/api/admin/plugin-config", { name: "sandbox", values });- const create = async (body: Record<string, unknown> = {}) =>- owner.post(`/api/projects/${projectId}/agents/default_agent/sessions`, body);- type Created = { session: { sessionId: string; sandbox: unknown } };-- expect((await settings({ mode: "workspace-write", network: "none" })).status).toBe(200);- const first = (await (await create()).json()) as Created;- expect(first.session.sandbox).toEqual({- mode: "workspace-write",- network: "none",- ...NO_BACKEND,+ const served = (mode: string, network: string) => ({+ mode,+ network,+ ...SERVED,+ presets: expect.any(Array),});+ // A new Session starts from the default preset, here remapped to cut the network.+ const remap = {+ enabled: true,+ defaultPreset: "workspace-write",+ presets: { "workspace-write": { network: "none" } },+ };+ expect((await settings(remap)).status).toBe(200);+ const first = await create();+ expect(first.sandbox).toEqual(served("workspace-write", "none"));// The settings change: a new Session starts from it, the existing one does not move.- expect((await settings({ mode: "read-only", network: "open" })).status).toBe(200);- const again = (await (- await owner.get(`/api/sessions/${first.session.sessionId}`)- ).json()) as Created;- expect(again.session.sandbox).toEqual({- mode: "workspace-write",- network: "none",- ...NO_BACKEND,- });- const second = (await (await create()).json()) as Created;- expect(second.session.sandbox).toEqual({- mode: "read-only",- network: "open",- ...NO_BACKEND,- });+ expect((await settings({ defaultPreset: "read-only" })).status).toBe(200);+ expect((await read(first.sessionId)).sandbox).toEqual(served("workspace-write", "none"));+ const second = await create();+ expect(second.sandbox).toEqual(served("read-only", "open"));// A non-admin tightens freely, and may not loosen past the settings.- const tightened = await owner.patch(`/api/sessions/${first.session.sessionId}`, {- sandbox: { mode: "read-only" },- });- expect(tightened.status).toBe(200);- expect(((await tightened.json()) as Created).session.sandbox).toEqual({- mode: "read-only",- network: "none",- ...NO_BACKEND,- });- const loosened = await owner.patch(`/api/sessions/${second.session.sessionId}`, {- sandbox: { mode: "danger-full-access" },- });+ const patch = (id: string, mode: string) =>+ owner.patch(`/api/sessions/${id}`, { sandbox: { mode } });+ const tightened = await patch(first.sessionId, "read-only");+ expect((await body(tightened)).sandbox).toEqual(served("read-only", "none"));+ const loosened = await patch(second.sessionId, "danger-full-access");expect(loosened.status).toBe(403);expect(await loosened.json()).toMatchObject({ error: { code: "sandbox_forbidden" } });- expect((await create({ sandbox: { mode: "workspace-write" } })).status).toBe(403);- expect((await create({ sandbox: { mode: "nope" } })).status).toBe(400);+ expect((await post({ mode: "workspace-write" })).status).toBe(403);+ expect((await post({ mode: "nope" })).status).toBe(400);+ } finally {+ await t.cleanup();+ }+ });++ it("carries the Sandbox card's presets, read back after a save, and says when the policy is advanced", async () => {+ const { t, settings, create, read, defaults } = await ownerProject("owner-presets");+ try {+ const first = await create();+ expect(first.sandbox.presets).toEqual(DEFAULT_PRESETS);+ expect(first.sandbox.advanced).toBeUndefined();++ // The table names levels, it is not part of a Session's policy: a save reaches existing ones.+ const edits = {+ "read-only": { name: "Look only", network: "none" },+ "denied-all": { enabled: true },+ };+ expect((await settings({ presets: edits })).status).toBe(200);+ const presets = (await read(first.sessionId)).sandbox.presets!;+ expect(presets.map((p) => p.id)).toEqual(DEFAULT_PRESETS.map((p) => p.id));+ // A saved row reads without its shipped Chinese name.+ const readOnly = {+ id: "read-only",+ enabled: true,+ mode: "read-only",+ approvalMode: "allow-all",+ };+ expect(presets[3]).toEqual({ ...readOnly, name: "Look only", network: "none" });+ expect(presets[5]?.enabled).toBe(true);+ expect((await defaults()).presets).toEqual(presets);++ // A Session created under masked paths holds what no preset shows.+ await settings({ maskPaths: ["/secret"] });+ expect((await create()).sandbox.advanced).toBe(true);+ expect((await read(first.sessionId)).sandbox.advanced).toBeUndefined();+ } finally {+ await t.cleanup();+ }+ });++ it("a refused pick stores nothing: not the sandbox, nor the title or approval mode beside it", async () => {+ const { t, owner, settings, create } = await ownerProject("owner-refused");+ try {+ await settings({ enabled: true, defaultPreset: "workspace-write-ask" });+ const created = await create();+ const confined = {+ approvalMode: "always-ask",+ sandbox: { mode: "workspace-write", network: "open" },+ };+ expect(created).toMatchObject(confined);+ const before = t.deps.sessionsRepo.findById(created.sessionId);+ const cases = [+ // Past the server's settings for a non-admin.+ [+ {+ title: "Renamed",+ approvalMode: "allow-all",+ sandbox: { mode: "danger-full-access", network: "open" },+ },+ 403,+ "sandbox_forbidden",+ ],+ // A level this server cannot enforce.+ [{ approvalMode: "allow-all", sandbox: { network: "local" } }, 400, "sandbox_unsupported"],+ ] as const;+ for (const [patch, status, code] of cases) {+ const res = await owner.patch(`/api/sessions/${created.sessionId}`, patch);+ expect(res.status).toBe(status);+ expect(await res.json()).toMatchObject({ error: { code } });+ expect(t.deps.sessionsRepo.findById(created.sessionId)).toEqual(before);+ }+ } finally {+ await t.cleanup();+ }+ });++ it("an approval-mode change alone leaves the policy unchecked and untouched", async () => {+ const { t, owner, create, body } = await ownerProject("owner-modeonly");+ try {+ const id = (await create()).sessionId;+ // Localhost-only networking no backend here enforces (picked while one was installed).+ const held = {+ ...t.deps.sessionService.sandboxOf(t.deps.sessionsRepo.findById(id)!),+ network: "local" as const,+ };+ t.deps.sessionService.updateSandbox(id, held);+ const res = await owner.patch(`/api/sessions/${id}`, { approvalMode: "read-only" });+ expect(res.status, await res.clone().text()).toBe(200);+ expect(await body(res)).toMatchObject({+ approvalMode: "read-only",+ sandbox: { network: "local" },+ });+ expect(t.deps.sessionsRepo.findById(id)!.sandbox).toEqual(held);+ } finally {+ await t.cleanup();+ }+ });++ it("marks the presets wider than the server's settings as above the ceiling", async () => {+ const { t, owner, settings, create, read, defaults } = await ownerProject("owner-ceiling");+ try {+ const aboveIds = (sandbox: SessionSandbox) =>+ (sandbox.presets ?? []).filter((p) => p.aboveCeiling === true).map((p) => p.id);+ // On, from Workspace Write: the presets whose file mode is Off are above it.+ expect((await settings({ enabled: true })).status).toBe(200);+ const created = await create();+ const above = ["full-access", "always-ask", "denied-all"];+ expect(aboveIds(created.sandbox)).toEqual(above);+ expect(aboveIds(await defaults())).toEqual(above);+ // The mark is the refusal's own comparison: a marked row is refused, an unmarked one is not.+ const pick = (mode: string) =>+ owner.patch(`/api/sessions/${created.sessionId}`, { sandbox: { mode, network: "open" } });+ expect((await pick("danger-full-access")).status).toBe(403);+ expect((await pick("read-only")).status).toBe(200);++ // Off: the server's settings confine nothing, so no row is above them.+ expect((await settings({ enabled: false })).status).toBe(200);+ const after = (await read(created.sessionId)).sandbox;+ expect(after.presets).toHaveLength(DEFAULT_PRESETS.length);+ expect(aboveIds(after)).toEqual([]);} finally {await t.cleanup();}diff --git a/packages/server/test/workflows.test.ts b/packages/server/test/workflows.test.tsindex d8418f77..0f182f1f 100644--- a/packages/server/test/workflows.test.ts+++ b/packages/server/test/workflows.test.ts@@ -7,7 +7,8 @@* under ui/ (no default document, nothing outside it) and dispatches to its handler, and its* state persists on disk across a reload.* - Its own state write is not an edit: the revision holds and nothing is left staged.- * - It opens and runs Sessions the SDK's way, inside its own Project only.+ * - It opens and runs Sessions the SDK's way, inside its own Project only, with allow-all:+ * nobody is there to answer an ask.* - A handler takes any body (a form only from the app's own pages) and sends back any* content type, a stream as it is produced and a redirect relative to its mount, never the* app's cookies; JSON stays the default.@@ -30,7 +31,7 @@* compile; each editing case needs a folder of its own to break, which it gets in an Agent of* its own within the editing group's one app.*/-import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";import fs from "node:fs/promises";import path from "node:path";import { agentDir } from "@lmliheng/penguin-core";@@ -265,10 +266,19 @@ describe("a loaded workflow", { timeout: 30_000 }, () => {ran: "run: this Project has no Session 'not-a-session'",agents: [AGENT],});- const own = await (await owner.get(`${BASE}/demo/api/open`)).json();- // Its own Agent passes the Project check and reaches the session runtime, which in this- // fixture has no model key to open a Session with.- expect(own).toMatchObject({ opened: expect.stringContaining("API key") });+ const create = vi.spyOn(t.deps.sessionService, "createSession");+ try {+ const own = await (await owner.get(`${BASE}/demo/api/open`)).json();+ // Its own Agent passes the Project check and reaches the session runtime, which in this+ // fixture has no model key to open a Session with.+ expect(own).toMatchObject({ opened: expect.stringContaining("API key") });+ // Unattended: allow-all, whatever approval mode the Sandbox card's default preset gives.+ expect(create).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: AGENT, approvalMode: "allow-all" }),+ );+ } finally {+ create.mockRestore();+ }});it("hands a handler any body and sends back any content type; JSON stays the default", async () => {diff --git a/packages/ui/src/components/forms/select/select.tsx b/packages/ui/src/components/forms/select/select.tsxindex b8d58483..71c79ce9 100644--- a/packages/ui/src/components/forms/select/select.tsx+++ b/packages/ui/src/components/forms/select/select.tsx@@ -28,6 +28,10 @@ export interface SelectProps extends Omit<SelectHTMLAttributes<HTMLSelectElementerror?: string;/** Same size tier as Input: sm is for filter bars, keeps the toolbar from growing taller. */size?: ControlSize;+ /** Semantic explanation behind a "?" beside the label (see Field's `info`). */+ info?: ReactNode;+ /** Accessible name for that "?" (defaults to the generic "More info"). */+ infoLabel?: string;}interface Opt {@@ -59,6 +63,8 @@ export function Select({error,required,size = "sm",+ info,+ infoLabel,className,children,value,@@ -73,6 +79,8 @@ export function Select({const current = String(value ?? "");const selected = options.find((o) => o.value === current);const errorId = useId();+ // The info layout associates the label by htmlFor (see Field), so the trigger needs an id.+ const controlId = useId();const [open, setOpen] = useState(false);const { triggerRef, panelRef, position } = usePortalPanel({@@ -94,6 +102,7 @@ export function Select({<buttonref={triggerRef}type="button"+ {...(info !== undefined ? { id: controlId } : {})}disabled={disabled}aria-haspopup="listbox"aria-expanded={open}@@ -148,7 +157,16 @@ export function Select({);return (- <Field label={label} hint={hint} error={error} errorId={errorId} required={required}>+ <Field+ label={label}+ hint={hint}+ error={error}+ errorId={errorId}+ required={required}+ info={info}+ {...(infoLabel !== undefined ? { infoLabel } : {})}+ controlId={controlId}+ >{control}</Field>);diff --git a/packages/ui/src/components/icons/icons.ts b/packages/ui/src/components/icons/icons.tsindex c340452c..6d9ab903 100644--- a/packages/ui/src/components/icons/icons.ts+++ b/packages/ui/src/components/icons/icons.ts@@ -108,6 +108,11 @@ export const ICONS = {gear: "M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2zM15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0z",/** A pushpin (lucide pin): head, body and stem. */pin: "M12 17v5M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1z",+ /**+ * A five-pointed star with softened points (lucide star). Drawn with `GlyphIcon`'s `filled`+ * mode for its "on" state: the solid star is a favourite, the outline the way to make one.+ */+ star: "M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",/** A wrench. */wrench: "M14.7 6.3a4 4 0 0 0-5 5L4 17v3h3l5.7-5.7a4 4 0 0 0 5-5l-2.5 2.5-2-2 2.5-2.5z",/** A key: a round bow, the shaft and two teeth (feather key). */diff --git a/packages/ui/src/components/overlays/confirm-modal/confirm-modal.tsx b/packages/ui/src/components/overlays/confirm-modal/confirm-modal.tsxindex 4783970b..677e3fa2 100644--- a/packages/ui/src/components/overlays/confirm-modal/confirm-modal.tsx+++ b/packages/ui/src/components/overlays/confirm-modal/confirm-modal.tsx@@ -26,12 +26,8 @@ import { Modal } from "../modal/modal";* overwrite or save. The tone is carried by the glyph's ink alone, on the same neutral disc for* both — an icon never sits in a tint of its own tone.*/-function ToneMark({ tone }: { tone: "danger" | "primary" }) {- const glyph =- tone === "danger"- ? ICONS.triangleAlert- : // Pencil-line (lucide): writing changes down.- "M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z";+function ToneMark({ tone, glyph: own }: { tone: "danger" | "primary"; glyph?: string }) {+ const glyph = own ?? (tone === "danger" ? ICONS.triangleAlert : ICONS.penLine);return (<spanaria-hidden@@ -73,6 +69,11 @@ export interface ConfirmModalProps {onSecondary?: () => void;/** Confirm button variant: danger for deletions, primary for saves and other overwrites. */tone?: "danger" | "primary";+ /**+ * The leading mark's drawing (an `ICONS` path) when the tone's default does not say what the+ * action does — a download for an install, say. The tone still picks its ink.+ */+ glyph?: string;busy?: boolean;children: ReactNode;}@@ -88,13 +89,14 @@ export function ConfirmModal({secondaryLabel,onSecondary,tone = "danger",+ glyph,busy = false,children,}: ConfirmModalProps) {return (<Modal open={open} title={title} onClose={onClose} headerless widthClass="sm:max-w-sm"><div className="flex items-start gap-3">- <ToneMark tone={tone} />+ <ToneMark tone={tone} {...(glyph !== undefined ? { glyph } : {})} /><div className="min-w-0 flex-1 pt-1.5">{children}</div></div>{/* Wraps rather than overflows: three choices with long labels don't fit one row insidediff --git a/packages/ui/src/components/overlays/dropdown/dropdown.tsx b/packages/ui/src/components/overlays/dropdown/dropdown.tsxindex 0babd189..a956cee0 100644--- a/packages/ui/src/components/overlays/dropdown/dropdown.tsx+++ b/packages/ui/src/components/overlays/dropdown/dropdown.tsx@@ -151,15 +151,18 @@ export function Dropdown({);// Opening moves focus into the panel (first item), so the menu is operable from the- // keyboard at all. Runs after the panel has mounted, portal or in-flow alike.- // Read through a ref so the effect still depends on `open` alone: a caller that flips+ // keyboard at all. Runs after the panel has mounted, portal or in-flow alike — a portaled+ // panel once it is placed: until then it is laid out `visibility: hidden`, and a hidden+ // element cannot take focus, which would leave focus on the trigger and the arrows dead.+ // Read through a ref so the effect still depends on opening alone: a caller that flips// focusOnOpen while the menu is open must not make focus jump into the panel.const focusOnOpenRef = useRef(focusOnOpen);focusOnOpenRef.current = focusOnOpen;+ const placed = !portal || pos !== null;useEffect(() => {- if (!open || focusOnOpenRef.current === false) return;+ if (!open || !placed || focusOnOpenRef.current === false) return;panelItems()[0]?.focus();- }, [open, panelItems]);+ }, [open, placed, panelItems]);/*** Up/Down walk the panel's items, wrapping at both ends (the standard menu idiom) —diff --git a/packages/ui/test/dropdown.test.ts b/packages/ui/test/dropdown.test.tsindex b96ad86e..fc03432c 100644--- a/packages/ui/test/dropdown.test.ts+++ b/packages/ui/test/dropdown.test.ts@@ -4,7 +4,8 @@** The panel mounts only while open, and its portal mode reaches for `document.body`, which a* static render has none of; the in-flow panel renders, and what the portal path must keep doing- * (share the dialogs' focusable set and Escape stack) is pinned against the source. How the app's+ * (share the dialogs' focusable set and Escape stack, and focus its first item once placed) is+ * pinned against the source. How the app's* menus consult the scroll rule is `context-menu.test.ts`; that dialogs and menus share one* focusable selector is the web app's `modal-focus.test.ts`.*/@@ -80,6 +81,16 @@ describe("Dropdown", () => {// Portaled panels clear a dialog's overlay; in-flow ones stay on the menu tier.expect(source).toContain('${portal ? "z-[60]" : "z-40"}');});++ // A source pin (no DOM here): a hidden, unplaced portaled panel cannot take focus.+ it("source pin: the first-item focus effect waits for a portaled panel to be placed", () => {+ const source = readFileSync(join(SRC_DIR, "components/overlays/dropdown/dropdown.tsx"), "utf8");+ expect(source).toContain("const placed = !portal || pos !== null;");+ expect(source).toMatch(+ /if \(!open \|\| !placed \|\| focusOnOpenRef\.current === false\) return;\s*panelItems\(\)\[0\]\?\.focus\(\);\s*\}, \[open, placed, panelItems\]\);/,+ );+ expect(source).toContain('visibility: "hidden" as const');+ });});describe("FormPicker", () => {diff --git a/packages/web/src/features/chat/builtin-dock-panels.tsx b/packages/web/src/features/chat/builtin-dock-panels.tsxindex ea482da0..f3dbf9e8 100644--- a/packages/web/src/features/chat/builtin-dock-panels.tsx+++ b/packages/web/src/features/chat/builtin-dock-panels.tsx@@ -52,8 +52,7 @@ function AgentsPanelBody() {subagentFocus,subagentTaskScope,models,- onChangeApprovalMode,- onChangeSandbox,+ onChangePermission,modeSaving,parentThinkingLevel,} = useChatDock();@@ -74,8 +73,7 @@ function AgentsPanelBody() {models={models?.models ?? []}approvalMode={selected.approvalMode}approvalModes={approvalModeChoices(selected.client, selected.approvalMode)}- onChangeApprovalMode={onChangeApprovalMode}- onChangeSandbox={onChangeSandbox}+ onChangePermission={onChangePermission}modeSaving={modeSaving}parentThinkingLevel={parentThinkingLevel}/>diff --git a/packages/web/src/features/chat/chat-dock-context.tsx b/packages/web/src/features/chat/chat-dock-context.tsxindex 94677d2a..2145e224 100644--- a/packages/web/src/features/chat/chat-dock-context.tsx+++ b/packages/web/src/features/chat/chat-dock-context.tsx@@ -8,12 +8,8 @@*/import { createContext, useContext } from "react";import type { ReactNode } from "react";-import type {- ApprovalMode,- ModelsResponse,- SessionInfo,- SessionSandbox,-} from "@lmliheng/penguin-server/api";+import type { ModelsResponse, SessionInfo } from "@lmliheng/penguin-server/api";+import type { PermissionPick } from "../../lib/permission-level";import type { StreamModel } from "../../lib/omni/stream-model";import type { MemoryChangeRow, MemoryLocateTarget } from "../../lib/omni/memory-changes";import type { ComposerReference } from "../../lib/workspace-tree";@@ -43,8 +39,8 @@ export interface ChatDockState {/** The Task the agents tab shows: null = the latest; an anchor pins the one with that child. */subagentTaskScope: { anchorSessionId: string } | null;models: ModelsResponse | null;- onChangeApprovalMode: (mode: ApprovalMode) => void;- onChangeSandbox: (pick: Partial<SessionSandbox>) => void;+ /** A permission pick: the approval mode and the Session's sandbox, saved in one PATCH. */+ onChangePermission: (pick: PermissionPick) => void | Promise<unknown>;/** An approval-mode or sandbox save is in flight. */modeSaving: boolean;/** The Session's effective thinking level ("" = unknown): a child composer's display fallback. */diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsxindex af79852f..de540e13 100644--- a/packages/web/src/features/chat/chat-input.tsx+++ b/packages/web/src/features/chat/chat-input.tsx@@ -127,6 +127,7 @@ import { useLocale } from "../../state/locale";import { useAuth } from "../../state/auth";import { agentDisplayName } from "../../state/project";import { PermissionSelect } from "./permission-select";+import type { PermissionPick } from "../../lib/permission-level";import { SkillIcon } from "../skills/skill-icon-view";import { SkillPickList } from "../skills/skill-pick-list";import { toggleSkillName } from "../skills/skill-selection";@@ -621,9 +622,8 @@ export function ChatInput({vision,approvalMode,approvalModes,- onChangeApprovalMode,sandbox,- onChangeSandbox,+ onChangePermission,modeSaving,autoFocus,agents,@@ -797,16 +797,16 @@ export function ChatInput({vision: boolean;approvalMode: ApprovalMode;/**- * The modes the permission button's Approval section lists, in order (`approvalModeChoices`):- * all four, except that an organization's Session leaves out `always-ask` unless it is the- * current value. The button's level and title follow `approvalMode` whatever the list holds.+ * The approval modes the permission button may offer, in order (`approvalModeChoices`): all+ * four, except that an organization's Session leaves out `always-ask` unless it is the current+ * value. A preset whose approval mode is not listed is left out of the menu, unless it is the+ * current preset. The button's level and title follow `approvalMode` whatever the list holds.*/approvalModes: readonly ApprovalMode[];- /** A returned promise keeps the permission button's pick on screen until the save settles. */- onChangeApprovalMode: (mode: ApprovalMode) => void | Promise<unknown>;/** The Session's own sandbox policy (the draft's pick before there is a Session). */sandbox: SessionSandbox;- onChangeSandbox: (pick: Partial<SessionSandbox>) => void | Promise<unknown>;+ /** Saves a preset's approval mode and sandbox together; a returned promise keeps the permission button's pick on screen until the save settles. */+ onChangePermission: (pick: PermissionPick) => void | Promise<unknown>;modeSaving: boolean;autoFocus?: boolean;/** Agent list of the current Project: the `/agent` command's candidates (without any, the command isn't offered). */@@ -2476,8 +2476,7 @@ export function ChatInput({approvalMode={approvalMode}approvalModes={approvalModes}sandbox={sandbox}- onChangeApprovalMode={onChangeApprovalMode}- onChangeSandbox={onChangeSandbox}+ onChange={onChangePermission}disabled={modeSaving}direction={models && onChangeModel ? "down" : "up"}/>diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex 30c915cd..6c082870 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -21,12 +21,10 @@ import type { ReactNode } from "react";import { useLocation, useNavigate, useParams } from "react-router";import type {AgentSummary,- ApprovalMode,ModelRefDto,ModelsResponse,SessionInfo,SessionPatchRequest,- SessionSandbox,SessionProcessInfo,SessionStatus,SkillMetadataItem,@@ -59,6 +57,7 @@ import { ApiError } from "../../api/client";import { S } from "../../lib/strings";import { useWorkflowTabs, WorkflowFrame, WorkflowTabStrip } from "../workflows/workflow-tabs";import { apiErrorText } from "../../lib/api-error";+import type { PermissionPick } from "../../lib/permission-level";import { configuredCompactionLimit } from "../../lib/context";import { useDocumentTitle } from "../../lib/use-document-title";import {@@ -100,6 +99,7 @@ import type { ForkTarget } from "./task-stats-line";import { latestTaskHasSubagent, modelTaskStartCount, taskStartCount } from "./agent-topology";import { ChatInput } from "./chat-input";import type { ComposerControl } from "./chat-input";+import { onPluginConfigSaved } from "../../lib/plugin-config-event";import { approvalModeChoices } from "./approval-mode";import type { ComposerReference } from "../../lib/workspace-tree";import {@@ -1513,7 +1513,7 @@ export function ChatPage() {// Pins a picked level on the Session so it outlives this tab: PATCH, then swap the// returned row into the session store (the picker reads it back from there); it applies// from the next LLM request (the picker's menu advises compacting first). Modeled on- // onChangeApprovalMode — a failed write surfaces as a toast and leaves the level as it+ // onChangePermission — a failed write surfaces as a toast and leaves the level as it// was, rather than showing a level the server does not have.const applyTurnThinkingLevel = useCallback((level: string) => {@@ -1597,41 +1597,41 @@ export function ChatPage() {[selected],);- const onChangeApprovalMode = useCallback(- (mode: ApprovalMode) => {+ // A preset from the permission button: the approval mode and the Session's own sandbox+ // policy in one PATCH, applied from the next tool call and command. A refused change (a+ // non-admin loosening past the server's settings) stores nothing — the route checks every+ // field before writing any — so the Session is as it was, and the toast says why.+ const onChangePermission = useCallback(+ (pick: PermissionPick) => {if (!selected || modeSaving) return;setModeSaving(true);// Returned so the permission button keeps the pick on screen until the save settles.return api- .patchSession(selected.sessionId, { approvalMode: mode })- .then((res) => replace(res.session))- .catch((e: unknown) => {- toastError(apiErrorText(e));+ .patchSession(selected.sessionId, {+ approvalMode: pick.approvalMode,+ // Absent for an approval-mode pick: the Session's policy is left as it is.+ ...(pick.sandbox !== undefined ? { sandbox: pick.sandbox } : {}),})- .finally(() => setModeSaving(false));- },- [selected, modeSaving, replace],- );-- // The Session's own sandbox policy: saved on the Session and applied from its next command.- // The same save shape as the approval mode — a refused change (a non-admin loosening past- // the server's settings) is a toast, and the button keeps showing what the server has.- const onChangeSandbox = useCallback(- (pick: Partial<SessionSandbox>) => {- if (!selected || modeSaving) return;- setModeSaving(true);- // Returned so the permission button keeps the pick on screen until the save settles.- return api- .patchSession(selected.sessionId, { sandbox: pick }).then((res) => replace(res.session))- .catch((e: unknown) => {- toastError(apiErrorText(e));- })+ .catch((e: unknown) => toastError(apiErrorText(e))).finally(() => setModeSaving(false));},[selected, modeSaving, replace],);+ // The Sandbox card was saved: the open Session's view (switch, presets) is read again, so the+ // permission menu shows what the card now says.+ const selectedId = selected?.sessionId;+ useEffect(() => {+ if (selectedId === undefined) return;+ return onPluginConfigSaved("sandbox", () => {+ void api.getSession(selectedId).then(+ (res) => replace(res.session),+ () => undefined,+ );+ });+ }, [selectedId, replace]);+// Starts a context compaction — the single path to the server for it (the composer's// /compact command and the thinking-switch dialog's "compact, then switch" both come// through here). Returns whether the request was ACCEPTED: the endpoint answers 202 and@@ -1980,8 +1980,7 @@ export function ChatPage() {subagentFocus,subagentTaskScope,models,- onChangeApprovalMode,- onChangeSandbox,+ onChangePermission,modeSaving,parentThinkingLevel: sessionThinkingLevel(turnThinkingLevel, agentThinkingLevel),fileOpenRequest,@@ -2095,9 +2094,8 @@ export function ChatPage() {approvalMode={selected.approvalMode}// An organization's Session is not offered always-ask: nobody is there to be asked.approvalModes={approvalModeChoices(selected.client, selected.approvalMode)}- onChangeApprovalMode={onChangeApprovalMode}sandbox={selected.sandbox}- onChangeSandbox={onChangeSandbox}+ onChangePermission={onChangePermission}modeSaving={modeSaving}autoFocusagents={agents}diff --git a/packages/web/src/features/chat/draft-view.tsx b/packages/web/src/features/chat/draft-view.tsxindex 0344b24c..d6827dbc 100644--- a/packages/web/src/features/chat/draft-view.tsx+++ b/packages/web/src/features/chat/draft-view.tsx@@ -62,7 +62,8 @@ import {} from "@lmliheng/penguin-ui";import * as api from "../../api/endpoints";import { S } from "../../lib/strings";-import { UNCONFINED } from "../../lib/permission-level";+import { UNCONFINED, draftSandboxAfter } from "../../lib/permission-level";+import type { PermissionPick } from "../../lib/permission-level";import { formatMonthDay } from "../../lib/format";import { apiErrorText } from "../../lib/api-error";import { rememberSessionMachine } from "../../lib/session-machines";@@ -94,6 +95,7 @@ import {type ChatDefaultsChangedDetail,} from "./chat-defaults-event";import { newChatAgentId } from "./new-chat";+import { onPluginConfigSaved } from "../../lib/plugin-config-event";import { effectiveThinkingLevel } from "./thinking-level";import { WorkspaceSelect, pillClass } from "./workspace-select";import { FilesPanelToggle } from "./dock-toggles";@@ -374,12 +376,10 @@ export function DraftView({) {setWorkspace(chatDefaults.workspace);}- if (- chatDefaults.approvalMode !== undefined &&- cached.approvalMode === undefined &&- !touchedRef.current.approval- ) {- setApprovalMode(chatDefaults.approvalMode);+ // The Project's own default wins; else the Sandbox card's default preset, while it is on.+ const seeded = chatDefaults.approvalMode ?? chatDefaults.sandbox?.defaultApprovalMode;+ if (seeded !== undefined && cached.approvalMode === undefined && !touchedRef.current.approval) {+ setApprovalMode(seeded);}}, [chatDefaults, stateWorkspace, cached.workspace, cached.approvalMode]);@@ -416,7 +416,7 @@ export function DraftView({setChatDefaults(d);touchedRef.current = { workspace: false, approval: false };setWorkspace(d.workspace ?? "");- setApprovalMode(d.approvalMode ?? "allow-all");+ setApprovalMode(d.approvalMode ?? d.sandbox?.defaultApprovalMode ?? "allow-all");// The Agent a fresh mount would now start on (the new block's default while it names// an Agent, then default_agent, then the first).setAgentId(newChatAgentId(agents, d));@@ -431,6 +431,25 @@ export function DraftView({/** Latest-closure mirror for the window listener (same convention as persistRef). */const onDefaultsChangedRef = useRef(onDefaultsChanged);onDefaultsChangedRef.current = onDefaultsChanged;+ // The Sandbox card was saved (from the composer's More…, say): the permission menu reads the+ // sandbox view again, and an approval mode nobody picked follows the new default preset.+ useEffect(+ () =>+ onPluginConfigSaved("sandbox", () => {+ void api.getChatDefaults(projectId).then(+ (res) => {+ setChatDefaults((prev) => ({+ ...(prev ?? {}),+ ...(res.sandbox !== undefined ? { sandbox: res.sandbox } : {}),+ }));+ const seeded = res.approvalMode ?? res.sandbox?.defaultApprovalMode;+ if (seeded !== undefined && !touchedRef.current.approval) setApprovalMode(seeded);+ },+ () => undefined,+ );+ }),+ [projectId],+ );useEffect(() => {const onEvent = (e: Event) => {const detail = chatDefaultsChangedDetail(e, projectId);@@ -709,12 +728,12 @@ export function DraftView({// home, or the next Session would be created on the machine the previous pick named.setWorkspaceMachine(machineId ?? null);}, []);- const changeApprovalMode = useCallback((mode: ApprovalMode) => {+ // A preset sets both halves of the draft's level at once, as it does on a Session; an+ // approval-mode pick (switch off) leaves the sandbox half unpicked, so the settings decide it.+ const changePermission = useCallback((pick: PermissionPick) => {touchedRef.current.approval = true;- setApprovalMode(mode);- }, []);- const changeSandbox = useCallback((pick: Partial<SessionSandbox>) => {- setSandboxPick((prev) => ({ ...prev, ...pick }));+ setApprovalMode(pick.approvalMode);+ setSandboxPick((prev) => draftSandboxAfter(prev, pick));}, []);// Synchronous in-flight guard for the one send entry point (the composer): a second@@ -875,9 +894,8 @@ export function DraftView({approvalMode={approvalMode}// A draft becomes an ordinary conversation, never an organization's: every mode.approvalModes={APPROVAL_MODES}- onChangeApprovalMode={changeApprovalMode}sandbox={{ ...(chatDefaults?.sandbox ?? UNCONFINED), ...sandboxPick }}- onChangeSandbox={changeSandbox}+ onChangePermission={changePermission}modeSaving={false}autoFocusagents={agents}diff --git a/packages/web/src/features/chat/permission-select.tsx b/packages/web/src/features/chat/permission-select.tsxindex 7a7dec3f..69d3ff4b 100644--- a/packages/web/src/features/chat/permission-select.tsx+++ b/packages/web/src/features/chat/permission-select.tsx@@ -1,28 +1,40 @@/*** The composer's permission button: an icon-only square like the + button, wearing lucide's* shield icon for the level (see lib/permission-level.ts) — a different icon per level, coloured- * by it, so the level never depends on colour alone. The menu has three sections — Filesystem, Network and Approval — and, for an- * administrator, More…, which opens the Settings page's Sandbox card.+ * by it, so the level never depends on colour alone. The menu lists the server's sandbox presets+ * that are in the menu — each a named mode, network level and approval mode — and, for an+ * administrator, More…, which opens the Settings page's Sandbox card, where the presets are+ * renamed, remapped and put in or out of the menu, and where the full settings stay.*- * Filesystem and Network edit the Session's own sandbox policy: a Session keeps the policy it- * was created with, so the Settings page only decides what NEW Sessions start from. The menu is- * the same on every platform; a level this server cannot enforce is greyed out rather than- * hidden — with no sandbox backend installed, every level short of full access, marked so.+ * A pick edits the Session's own policy and approval mode in one save: a Session keeps the+ * policy it was created with, so the Settings page only decides what NEW Sessions start from.+ * The Session stores the three values, never the preset: the button names it by the first row+ * matching them, and says custom when none does. A preset this server cannot enforce is greyed+ * out rather than hidden, marked with why — with no sandbox backend installed, every preset+ * that confines. So is, for a non-admin, a preset wider than the server's sandbox settings+ * (`aboveCeiling`), which the server would refuse: marked admin-only, unless it is the current one.*- * Approval lists the modes the composer passes in (see approval-mode.ts): an organization's- * Session is not offered `always-ask` unless it is the current value.+ * With the server's Sandbox switch off, new Sessions start unconfined and the menu lists the+ * approval modes alone (permissionMenu); a pick changes only the approval mode.+ *+ * The menu offers only presets whose approval mode is among the modes the composer passes in+ * (see approval-mode.ts): an organization's Session is not offered an `always-ask` preset unless+ * it is the current one.** Popup direction depends on context: the draft card has room below and opens downward; the* chat input docked at the bottom of the screen opens upward.*/import { useState } from "react";-import type { ApprovalMode, SessionSandbox } from "@lmliheng/penguin-server/api";+import type {+ ApprovalMode,+ SessionSandbox,+ SessionSandboxPreset,+} from "@lmliheng/penguin-server/api";import {Dropdown,GlyphIcon,Menu,MenuItem,- MenuLabel,MenuRadioItem,MenuSeparator,} from "@lmliheng/penguin-ui";@@ -31,71 +43,72 @@ import { toneInk } from "../../lib/tone";import {PERMISSION_LEVEL_GLYPH,PERMISSION_LEVEL_TONE,+ approvalModePick,firstUnavailableBackend,- fsModeBlock,- networkBlock,+ matchPreset,permissionLevel,+ permissionMenu,+ presetBlock,+ presetEffects,+ presetPick,+ presetsOf,+ sandboxSwitchOff,} from "../../lib/permission-level";-import type { LevelBlock } from "../../lib/permission-level";+import type { PermissionPick, PresetBlock } from "../../lib/permission-level";import { useAuth } from "../../state/auth";+import { useLocale } from "../../state/locale";+import { localizedText } from "./skill-use";import { SettingsDialog } from "../settings/settings-dialog";-const FS_MODES: SessionSandbox["mode"][] = ["read-only", "workspace-write", "danger-full-access"];-const NETWORK_MODES: SessionSandbox["network"][] = ["open", "local", "none"];-/**- * One choice row: its text, and a check when it is the current value. An unavailable choice- * stays listed, greyed out, with a short note (`note`, "Not supported" unless given) and the- * reason in its title (`unavailable`).+ * One preset row: its name, and a check when it is the Session's level. Its tooltip says what+ * it blocks and allows and whether this machine can enforce it; an unenforceable one stays+ * listed, greyed out, with a short note.*/function Choice({label,selected,onPick,+ hint,unavailable,note,}: {label: string;selected: boolean;onPick: () => void;- unavailable?: string;+ hint: string;+ unavailable: boolean;note?: string;}) {- const off = unavailable !== undefined;return (<MenuRadioItemlabel={label}checked={selected}- disabled={off}- data-tooltip={unavailable}- trailing={off ? (note ?? S.chat.permission.unsupported) : undefined}+ disabled={unavailable}+ data-tooltip={hint}+ trailing={unavailable ? (note ?? S.chat.permission.unsupported) : undefined}onSelect={onPick}/>);}-/** A pick not yet confirmed by its save: shown at once, dropped when the save settles. */-interface PendingPick {- approvalMode?: ApprovalMode;- sandbox?: Partial<SessionSandbox>;-}-export function PermissionSelect({approvalMode: savedApprovalMode,approvalModes,sandbox: savedSandbox,- onChangeApprovalMode,- onChangeSandbox,+ onChange,disabled,direction = "up",}: {approvalMode: ApprovalMode;- /** The modes the Approval section lists, in order (`approvalModeChoices`). */+ /**+ * The approval modes the Session may be given, in order (`approvalModeChoices`): a preset+ * holding any other is not offered, unless it is the current one.+ */approvalModes: readonly ApprovalMode[];sandbox: SessionSandbox;- /** A save that returns a promise keeps the pick on screen until it settles. */- onChangeApprovalMode: (mode: ApprovalMode) => void | Promise<unknown>;- onChangeSandbox: (pick: Partial<SessionSandbox>) => void | Promise<unknown>;+ /** Saves a preset's three values together; a returned promise keeps the pick on screen until it settles. */+ onChange: (pick: PermissionPick) => void | Promise<unknown>;/** Blocks a second pick while one saves; deliberately NOT drawn dimmed (that read as a flicker). */disabled: boolean;direction?: "up" | "down";@@ -104,28 +117,40 @@ export function PermissionSelect({// The pick shows the moment it is made: waiting for the server's row would draw the old// level, then the new one — the flicker. When the save settles the saved values take over// (on a refusal those are the old ones, and the toast says why).- const [pending, setPending] = useState<PendingPick | null>(null);+ const [pending, setPending] = useState<PermissionPick | null>(null);const approvalMode = pending?.approvalMode ?? savedApprovalMode;const sandbox: SessionSandbox = { ...savedSandbox, ...pending?.sandbox };const [settingsOpen, setSettingsOpen] = useState(false);// The Sandbox card lives on the Plugins page, which only an administrator can open.const isAdmin = useAuth().user?.isAdmin === true;+ const { locale } = useLocale();const P = S.chat.permission;- // A level this server cannot enforce stays listed, greyed out, saying why — with no backend- // mounted, that is every level short of full access: not installed, or enabled but failing- // its check, with the first such backend's reason.+ const nameOf = (p: SessionSandboxPreset) => localizedText(locale, p.name, p.nameZh);+ const presets = presetsOf(sandbox);+ const current = matchPreset(presets, approvalMode, sandbox);+ // A preset this server cannot enforce stays listed, greyed out, saying why — with no backend+ // mounted, every preset that confines: not installed, or enabled but failing its check, with+ // the first such backend's reason.const failed = firstUnavailableBackend(sandbox);- const blocked = (block: LevelBlock | null) =>- block === null- ? {}+ const blockText = (block: PresetBlock): { reason: string; note?: string } =>+ block === "above-ceiling"+ ? { reason: P.aboveCeiling, note: P.adminOnly }: block === "no-backend"- ? { unavailable: P.noBackend, note: P.notInstalled }+ ? { reason: P.noBackend, note: P.notInstalled }: block === "unavailable" && failed !== null- ? { unavailable: P.backendUnavailable(failed.name, failed.reason), note: P.notAvailable }- : {- unavailable:- block === "local-unsupported" ? P.localUnsupported : P.noNetworkUnsupported,- };+ ? { reason: P.backendUnavailable(failed.name, failed.reason), note: P.notAvailable }+ : { reason: block === "local-unsupported" ? P.localUnsupported : P.noNetworkUnsupported };+ const hintOf = (p: SessionSandboxPreset, block: PresetBlock | null) => {+ const { blocks, allows } = presetEffects(p);+ const list = (effects: string[]) =>+ effects.length === 0 ? P.nothing : effects.map((e) => P.effects[e] ?? e).join(", ");+ const confines = p.mode !== "danger-full-access" || p.network !== "open";+ return [+ `${P.blocks}: ${list(blocks)}`,+ `${P.allows}: ${list(allows)}`,+ block !== null ? blockText(block).reason : confines ? P.enforceable : P.needsNoBackend,+ ].join("\n");+ };const level = permissionLevel(approvalMode, sandbox);// The swap animation plays only for a CHANGE of level, never on the first paint — React's// "adjust state while rendering" pattern for information from the previous render.@@ -135,16 +160,37 @@ export function PermissionSelect({setShownLevel(level);setAnimate(true);}- const levelName = P.levels[level] ?? level;+ // With the Sandbox switch off the menu is the approval modes, so the button names the mode.+ const switchOff = sandboxSwitchOff(sandbox);+ const levelName = switchOff+ ? (S.chat.approvalModeNames[approvalMode] ?? approvalMode)+ : current !== null+ ? nameOf(current)+ : P.custom;const summary = [`${P.fs}: ${P.fsModes[sandbox.mode] ?? sandbox.mode}`,`${P.network}: ${P.networkModes[sandbox.network] ?? sandbox.network}`,`${P.approval}: ${S.chat.approvalModeNames[approvalMode] ?? approvalMode}`,].join(" · ");- const pick = (next: PendingPick, save: () => void | Promise<unknown>) => {+ const pick = (p: SessionSandboxPreset) => {+ if (current?.id === p.id) {+ setOpen(false);+ return;+ }+ save(presetPick(p));+ };+ // Switch off: only the approval mode changes; the pick carries no policy (see PermissionPick).+ const pickMode = (mode: ApprovalMode) => {+ if (mode === approvalMode) {+ setOpen(false);+ return;+ }+ save(approvalModePick(mode));+ };+ const save = (next: PermissionPick) => {setOpen(false);setPending(next);- const saved = save();+ const saved = onChange(next);if (saved instanceof Promise) void saved.finally(() => setPending(null));else setPending(null);};@@ -179,53 +225,49 @@ export function PermissionSelect({</button>}>- <Menu label={P.label} density="sm" className="pb-1">- <MenuLabel>{P.fs}</MenuLabel>- {FS_MODES.map((mode) => (- <Choice- key={mode}- label={P.fsModes[mode] ?? mode}- selected={sandbox.mode === mode}- {...blocked(fsModeBlock(sandbox, mode))}- onPick={() =>- mode === sandbox.mode- ? setOpen(false)- : pick({ sandbox: { mode } }, () => onChangeSandbox({ mode }))- }- />- ))}- <MenuLabel>{P.network}</MenuLabel>- {NETWORK_MODES.map((network) => (- <Choice- key={network}- label={P.networkModes[network] ?? network}- selected={sandbox.network === network}- {...blocked(networkBlock(sandbox, network))}- onPick={() =>- network === sandbox.network- ? setOpen(false)- : pick({ sandbox: { network } }, () => onChangeSandbox({ network }))- }- />- ))}- <MenuLabel>{P.approval}</MenuLabel>- {approvalModes.map((mode) => (- <Choice- key={mode}- label={S.chat.approvalModes[mode] ?? mode}- selected={approvalMode === mode}- onPick={() =>- mode === approvalMode- ? setOpen(false)- : pick({ approvalMode: mode }, () => onChangeApprovalMode(mode))- }- />- ))}+ <Menu label={P.label} density="sm" className="py-1">+ {/* The two views say the same policy: what the presets cannot show is flagged here. */}+ {sandbox.advanced === true && !switchOff && (+ <div+ role="presentation"+ data-tooltip={P.advancedHint}+ className="px-3 pt-1 pb-1.5 text-xs font-medium text-fg-subtle"+ >+ {P.advancedActive}+ </div>+ )}+ {permissionMenu(sandbox, approvalModes, current).map((row) => {+ if (row.kind === "approval") {+ return (+ <MenuRadioItem+ key={row.mode}+ label={S.chat.approvalModeNames[row.mode] ?? row.mode}+ checked={row.mode === approvalMode}+ onSelect={() => pickMode(row.mode)}+ />+ );+ }+ const p = row.preset;+ const block = presetBlock(sandbox, p, { isAdmin, current });+ return (+ <Choice+ key={p.id}+ label={nameOf(p)}+ selected={current?.id === p.id}+ hint={hintOf(p, block)}+ unavailable={block !== null}+ {...(block !== null && blockText(block).note !== undefined+ ? { note: blockText(block).note }+ : {})}+ onPick={() => pick(p)}+ />+ );+ })}{isAdmin && (<><MenuSeparator />- {/* More…: the rest of the sandbox (masked paths, the temp directory, the backend)- is on the Settings page's Sandbox card, where this opens. */}+ {/* More…: the presets table and the full settings (masked paths, the temp+ directory, the backends) are on the Settings page's Sandbox card. */}<MenuItemlabel={P.more}onSelect={() => {diff --git a/packages/web/src/features/chat/subagents-view.tsx b/packages/web/src/features/chat/subagents-view.tsxindex e42ddcbe..689014a3 100644--- a/packages/web/src/features/chat/subagents-view.tsx+++ b/packages/web/src/features/chat/subagents-view.tsx@@ -49,6 +49,7 @@ import { S } from "../../lib/strings";import type { NestedSessionMeta, StreamModel } from "../../lib/omni/stream-model";import { ChatInput } from "./chat-input";import type { ComposerControl } from "./chat-input";+import type { PermissionPick } from "../../lib/permission-level";import { noteSessionSeen } from "../../lib/session-seen";import { useProject } from "../../state/project";import { useSessions } from "../../state/sessions";@@ -83,8 +84,7 @@ export function SubagentsView({models,approvalMode,approvalModes,- onChangeApprovalMode,- onChangeSandbox,+ onChangePermission,modeSaving,parentThinkingLevel,}: {@@ -104,11 +104,10 @@ export function SubagentsView({models: ModelInfo[];/** The PARENT session's approval mode — child approvals are judged by it (the same value the main composer edits). */approvalMode: ApprovalMode;- /** The modes the picker lists for the PARENT session (the main composer's list). */+ /** The approval modes the picker may offer for the PARENT session (the main composer's list). */approvalModes: readonly ApprovalMode[];- onChangeApprovalMode: (mode: ApprovalMode) => void;- /** Edits the PARENT session's sandbox policy — a child runs under its root's. */- onChangeSandbox: (pick: Partial<SessionSandbox>) => void;+ /** Edits the PARENT session's approval mode and sandbox policy — a child runs under its root's. */+ onChangePermission: (pick: PermissionPick) => void | Promise<unknown>;modeSaving: boolean;/** The parent session's effective thinking level ("" = unknown): the child composer's display fallback — a child inherits it at spawn unless the spawning call pinned its own. */parentThinkingLevel: string;@@ -307,9 +306,8 @@ export function SubagentsView({models={models}approvalMode={approvalMode}approvalModes={approvalModes}- onChangeApprovalMode={onChangeApprovalMode}sandbox={session.sandbox}- onChangeSandbox={onChangeSandbox}+ onChangePermission={onChangePermission}modeSaving={modeSaving}fallbackThinkingLevel={activeNode?.spawnThinkingLevel ?? parentThinkingLevel}/>@@ -352,9 +350,8 @@ function SubagentComposer({models,approvalMode,approvalModes,- onChangeApprovalMode,sandbox,- onChangeSandbox,+ onChangePermission,modeSaving,fallbackThinkingLevel,}: {@@ -369,11 +366,10 @@ function SubagentComposer({models: ModelInfo[];approvalMode: ApprovalMode;approvalModes: readonly ApprovalMode[];- onChangeApprovalMode: (mode: ApprovalMode) => void;/** The PARENT session's sandbox policy. */sandbox: SessionSandbox;- /** Edits the PARENT session's sandbox policy — a child runs under its root's. */- onChangeSandbox: (pick: Partial<SessionSandbox>) => void;+ /** Edits the PARENT session's approval mode and sandbox policy — a child runs under its root's. */+ onChangePermission: (pick: PermissionPick) => void | Promise<unknown>;modeSaving: boolean;/** Display fallback for the thinking picker while the user hasn't picked: the spawn call's explicit level, else the parent session's effective level (what the child inherited). */fallbackThinkingLevel: string;@@ -475,9 +471,8 @@ function SubagentComposer({vision={false}approvalMode={approvalMode}approvalModes={approvalModes}- onChangeApprovalMode={onChangeApprovalMode}sandbox={sandbox}- onChangeSandbox={onChangeSandbox}+ onChangePermission={onChangePermission}modeSaving={modeSaving}agents={[]}skills={skills}diff --git a/packages/web/src/features/settings/advanced-fold.tsx b/packages/web/src/features/settings/advanced-fold.tsxnew file mode 100644index 00000000..16727765--- /dev/null+++ b/packages/web/src/features/settings/advanced-fold.tsx@@ -0,0 +1,39 @@+/**+ * A settings card's Advanced fold: the fields a group marks `advanced`, collapsed by default+ * under one row, so the card leads with what most people change. It follows the WAI-ARIA+ * disclosure pattern like `HelpFold`: a real button carrying `aria-expanded` and+ * `aria-controls`, and a panel that stays in the DOM, `hidden` while collapsed, so the+ * reference always resolves. Inline flow, so no portal.+ */+import { useId, useState } from "react";+import type { ReactNode } from "react";+import { Chevron, ICON_GAP, ICON_SIZE } from "@lmliheng/penguin-ui";+import { S } from "../../lib/strings";++export function AdvancedFold({+ children,+ defaultOpen = false,+}: {+ children: ReactNode;+ defaultOpen?: boolean;+}) {+ const [open, setOpen] = useState(defaultOpen);+ const panelId = useId();+ return (+ <div className="border-t border-line-muted pt-2">+ <button+ type="button"+ aria-expanded={open}+ aria-controls={panelId}+ onClick={() => setOpen((v) => !v)}+ className={`flex items-center rounded-md py-1 text-xs font-medium text-fg-muted transition-colors duration-150 hover:text-fg ${ICON_GAP.row}`}+ >+ <Chevron open={open} size={ICON_SIZE.chevronDense} />+ {S.settings.pluginAdvanced}+ </button>+ <div id={panelId} hidden={!open} className="space-y-3 pt-2">+ {children}+ </div>+ </div>+ );+}diff --git a/packages/web/src/features/settings/plugin-config-draft.ts b/packages/web/src/features/settings/plugin-config-draft.tsnew file mode 100644index 00000000..0ef90b61--- /dev/null+++ b/packages/web/src/features/settings/plugin-config-draft.ts@@ -0,0 +1,166 @@+/**+ * A settings card's drafts: what each field's control holds between the stored value and the+ * card's Save, and what a Save sends. Only a field whose draft differs from its stored value is+ * sent — an untouched field would store its default as a value, pinning it against a later+ * change of the default.+ */+import type { PluginConfigEntry, PluginConfigField } from "@lmliheng/penguin-server/api";++type Cells = Record<string, string | boolean>;++/**+ * A `table` field's draft: the declared rows' cells, the rows added to an `extensible` table+ * (whole), and every row's id in drawing order.+ */+export interface TableDraft {+ rows: Record<string, Cells>;+ added: Record<string, Cells>;+ order: string[];+}++/** Where an `extensible` table's added rows and order are stored (server `plugin/config.ts`). */+const ADDED = "$added";+const ORDER = "$order";++const isRecord = (v: unknown): v is Record<string, unknown> =>+ v !== null && typeof v === "object" && !Array.isArray(v);++/** An added row's id (server `plugin/config.ts` ROW_ID). */+const ROW_ID = /^[a-z][a-z0-9-]*$/;++type Column = NonNullable<PluginConfigField["columns"]>[number];++/** Whether a stored value fits its column — the server's `cellFits`, repeated with the reading. */+function cellFits(column: Column, value: unknown): boolean {+ if (column.type === "boolean") return typeof value === "boolean";+ if (column.type === "enum") {+ return typeof value === "string" && (column.options ?? []).some((o) => o.value === value);+ }+ return typeof value === "string";+}++/**+ * A table's draft from its stored value. A declared row's text cell is what was saved into it,+ * empty for the declared text; every other cell is its value. A locked cell, or a stored value+ * that does not fit its column, reads as declared. Added rows are taken whole when well formed+ * (an id no declared row has, every column fitting) and dropped otherwise, and the order is the+ * stored one with any row it does not name after it — the server's reading (`resolveTable`),+ * repeated here because the page draws the draft, not the server's rows.+ */+export function tableDraftOf(field: PluginConfigField, stored: unknown): TableDraft {+ const saved = isRecord(stored) ? stored : {};+ const columns = field.columns ?? [];+ const rows = Object.fromEntries(+ (field.rows ?? []).map((row) => {+ const own = isRecord(saved[row.id]) ? (saved[row.id] as Record<string, unknown>) : {};+ return [+ row.id,+ Object.fromEntries(+ columns.map((c) => {+ const v = row.locked?.includes(c.name) === true ? undefined : own[c.name];+ if (c.type === "string") return [c.name, typeof v === "string" ? v : ""];+ return [c.name, cellFits(c, v) ? (v as string | boolean) : row.values[c.name]!];+ }),+ ),+ ];+ }),+ );+ const added: Record<string, Cells> = {};+ if (field.extensible !== undefined && isRecord(saved[ADDED])) {+ const declared = new Set((field.rows ?? []).map((r) => r.id));+ for (const [id, cells] of Object.entries(saved[ADDED] as Record<string, unknown>)) {+ if (!ROW_ID.test(id) || declared.has(id) || !isRecord(cells)) continue;+ if (!columns.every((c) => cellFits(c, cells[c.name]))) continue;+ added[id] = Object.fromEntries(+ columns.map((c) => [c.name, cells[c.name] as string | boolean]),+ );+ }+ }+ const ids = [...Object.keys(rows), ...Object.keys(added)];+ const listed = field.extensible !== undefined && Array.isArray(saved[ORDER]) ? saved[ORDER] : [];+ const first = [+ ...new Set((listed as unknown[]).filter((id): id is string => ids.includes(id as string))),+ ];+ return { rows, added, order: [...first, ...ids.filter((id) => !first.includes(id))] };+}++/** What a table's draft sends: the declared rows' cells, and an extensible table's rows and order. */+function tableValueOf(field: PluginConfigField, draft: TableDraft): Record<string, unknown> {+ return field.extensible === undefined+ ? { ...draft.rows }+ : { ...draft.rows, [ADDED]: draft.added, [ORDER]: draft.order };+}++/**+ * A field's draft: strings and numbers as typed (a number stays the string in the box until+ * Save, so "1." or "-" survives the keystroke), booleans as values; a secret's clear box+ * beside it.+ */+export type Draft = Record<string, unknown>;++/** The draft a plugin's form starts from: every non-secret value as stored, every secret empty. */+export function draftOf(entry: PluginConfigEntry): Draft {+ const out: Draft = {};+ for (const [name, field] of Object.entries(entry.configuration.properties)) {+ if (field.type === "secret") continue;+ if (field.type === "table") {+ out[name] = tableDraftOf(field, entry.values[name]);+ continue;+ }+ const v = entry.values[name];+ if (v === undefined) continue;+ out[name] =+ field.type === "number"+ ? String(v)+ : field.type === "list"+ ? (Array.isArray(v) ? v : []).join("\n")+ : v;+ }+ return out;+}++/** What a field's saved value is compared with, in the terms a save sends. */+export function baselineOf(field: PluginConfigField, stored: unknown): unknown {+ return field.type === "table" ? tableValueOf(field, tableDraftOf(field, stored)) : stored;+}++/** The value a draft sends for a field: a number parsed from its box, a list split into lines, everything else as is. */+export function valueOf(field: PluginConfigField, draft: unknown): unknown {+ if (field.type === "table") {+ return draft === undefined ? null : tableValueOf(field, draft as TableDraft);+ }+ if (field.type === "list") {+ const lines = (typeof draft === "string" ? draft : "")+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => line !== "");+ return lines.length === 0 ? null : lines;+ }+ if (field.type !== "number") return draft ?? null;+ const text = typeof draft === "string" ? draft.trim() : "";+ return text === "" ? null : Number(text);+}++/** Whether two field values are the same (lists compared by content). */+export const sameValue = (a: unknown, b: unknown) =>+ JSON.stringify(a ?? null) === JSON.stringify(b ?? null);++/** Whether an entry's `switch` field is off as drafted: its card then draws the switch alone. */+export function switchedOff(entry: PluginConfigEntry, draft: Record<string, unknown> | undefined) {+ const sw = entry.configuration.switch;+ return sw !== undefined && draft?.[sw] !== true;+}++/**+ * The fields a card draws, in declaration order: the switch alone while it is off, else every+ * field but one a table's row choice stores into (drawn only as that table's marker).+ */+export function drawnFields(+ entry: PluginConfigEntry,+ draft: Record<string, unknown> | undefined,+): Array<[string, PluginConfigField]> {+ const all = Object.entries(entry.configuration.properties);+ if (switchedOff(entry, draft)) return all.filter(([n]) => n === entry.configuration.switch);+ const choices = new Set(all.flatMap(([, f]) => (f.rowChoice ? [f.rowChoice.field] : [])));+ return all.filter(([n]) => !choices.has(n));+}diff --git a/packages/web/src/features/settings/plugin-config-enum-cell.tsx b/packages/web/src/features/settings/plugin-config-enum-cell.tsxnew file mode 100644index 00000000..d045deb9--- /dev/null+++ b/packages/web/src/features/settings/plugin-config-enum-cell.tsx@@ -0,0 +1,73 @@+/**+ * A table's choice cell without select chrome: the current option's full title as plain text,+ * wrapping when long. Pressing it opens a small menu of the options — the UI package's portaled+ * `Dropdown` with the `Menu` family's rows, like every other menu in the app — so no scrolling+ * ancestor clips it; an option this machine cannot honour stays listed, greyed out, with the+ * reason. Keyboard (the Dropdown's): opening focuses the first row, the arrow keys move, Enter+ * picks, Esc closes this menu only, not an enclosing dialog.+ */+import { useState } from "react";+import { Dropdown, Menu, MenuRadioItem } from "@lmliheng/penguin-ui";++export interface EnumCellOption {+ value: string;+ title: string;+ /** Why this machine cannot honour it; set, the option is listed but cannot be picked. */+ unavailable?: string;+}++export function EnumCell({+ label,+ value,+ options,+ disabled,+ onChange,+}: {+ label: string;+ value: string;+ options: EnumCellOption[];+ disabled: boolean;+ onChange: (value: string) => void;+}) {+ const [open, setOpen] = useState(false);+ const current = options.find((o) => o.value === value);+ const pick = (option: EnumCellOption) => {+ setOpen(false);+ if (option.value !== value) onChange(option.value);+ };+ return (+ <Dropdown+ open={open}+ setOpen={setOpen}+ menuClass="w-56"+ portal={{ direction: "down", align: "left" }}+ button={+ <button+ type="button"+ aria-label={`${label}: ${current?.title ?? value}`}+ aria-haspopup="menu"+ aria-expanded={open}+ disabled={disabled}+ onClick={() => setOpen(!open)}+ // Plain text that wraps; the hover wash and the focus ring say it can be pressed.+ className="w-full rounded-md px-1.5 py-1 text-left text-xs leading-snug break-words text-fg transition-colors duration-150 hover:bg-surface-muted focus-visible:ring-2 focus-visible:ring-accent/40 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-60"+ >+ {current?.title ?? value}+ </button>+ }+ >+ <Menu label={label} density="sm" className="py-1">+ {options.map((o) => (+ <MenuRadioItem+ key={o.value}+ label={o.title}+ checked={o.value === value}+ disabled={o.unavailable !== undefined}+ {...(o.unavailable !== undefined ? { description: o.unavailable } : {})}+ onSelect={() => pick(o)}+ />+ ))}+ </Menu>+ </Dropdown>+ );+}diff --git a/packages/web/src/features/settings/plugin-config-field-cell.tsx b/packages/web/src/features/settings/plugin-config-field-cell.tsxnew file mode 100644index 00000000..e1fed82e--- /dev/null+++ b/packages/web/src/features/settings/plugin-config-field-cell.tsx@@ -0,0 +1,188 @@+/**+ * One field cell of a settings table's row, by its column's type: a `string` cell is a box+ * holding the effective text (an empty override shows the declared text, in the page's+ * language; clearing it or typing the declared text back restores it), which wraps; a `boolean`+ * cell is a switch, or a pin toggle for the column the table's `pin` names; an `enum` cell is its+ * value's full title as text, which opens a menu of the options (plugin-config-enum-cell.tsx). A+ * cell the row locks is the value's text alone, with "locked" in its tooltip and in visually+ * hidden text.+ *+ * The row's name cell also carries the row's marks after the name: the chosen row's marker+ * ("(Default)") and the "?" saying what the row is for.+ */+import type { ReactNode } from "react";+import type {+ PluginConfigEntry,+ PluginConfigField,+ PluginConfigTableColumn,+ PluginConfigTableRow,+} from "@lmliheng/penguin-server/api";+import { InfoPopover, Switch } from "@lmliheng/penguin-ui";+import { S } from "../../lib/strings";+import { EnumCell } from "./plugin-config-enum-cell";+import { PinToggle, WrappingNameBox } from "./plugin-config-table-cells";++/** A row as drawn: its declared form (absent for an added row) and its cells. */+export interface DrawnRow {+ id: string;+ declared?: PluginConfigTableRow;+ cells: Record<string, string | boolean>;+}++/** What follows the name in a row's name cell. */+export interface RowMarks {+ /** The chosen row's marker, "(Default)". */+ marker?: string;+ /** What the row is for, behind a "?" named after the row. */+ help?: ReactNode;+}++/**+ * What a row is for: its declared `description` while every `enum` cell holds its declared+ * value; otherwise (an added row, or one whose choices changed) a line per `enum` column with+ * its value and what that option does. Undefined for a row with neither.+ */+export function rowHelp(+ columns: readonly PluginConfigTableColumn[],+ row: DrawnRow,+ localized: (en: string, zh: string | undefined) => string,+): string | string[] | undefined {+ const choices = columns.filter((c) => c.type === "enum");+ const d = row.declared;+ if (+ d?.description !== undefined &&+ choices.every((c) => row.cells[c.name] === d.values[c.name])+ ) {+ return localized(d.description, d.descriptionZh);+ }+ if (choices.length === 0) return undefined;+ return choices.map((c) => {+ const o = c.options?.find((x) => x.value === row.cells[c.name]);+ return S.settings.pluginTableRowValue(+ localized(c.title, c.titleZh),+ o !== undefined ? localized(o.title, o.titleZh) : String(row.cells[c.name]),+ o?.description !== undefined ? localized(o.description, o.descriptionZh) : undefined,+ );+ });+}++export function Cell({+ entry,+ name,+ column: c,+ row,+ rowName,+ pinned,+ marks,+ localized,+ disabled,+ onCell,+}: {+ entry: PluginConfigEntry;+ name: string;+ column: PluginConfigTableColumn;+ row: DrawnRow;+ rowName: string;+ pinned: PluginConfigField["pin"];+ /** Set on the row's name cell only. */+ marks?: RowMarks;+ localized: (en: string, zh: string | undefined) => string;+ disabled: boolean;+ onCell: (value: string | boolean) => void;+}) {+ const cell = row.cells[c.name];+ const locked = row.declared?.locked?.includes(c.name) === true;+ // The declared text, in the page's language; an added row has none (its text is its own).+ const declared =+ row.declared !== undefined+ ? localized(String(row.declared.values[c.name] ?? ""), row.declared.valuesZh?.[c.name])+ : "";+ const cellLabel = `${rowName} · ${localized(c.title, c.titleZh)}`;+ const optionTitle = (value: unknown) => {+ const option = c.options?.find((o) => o.value === value);+ return option !== undefined ? localized(option.title, option.titleZh) : String(value);+ };+ const shown =+ c.type === "enum"+ ? optionTitle(cell)+ : c.type === "string"+ ? cell === ""+ ? declared+ : String(cell)+ : cell === true+ ? S.settings.pluginCellOn+ : S.settings.pluginCellOff;+ const body = locked ? (+ // The value alone: no control to suggest it could change. "Locked" is in the tooltip and,+ // for a screen reader, in visually hidden text after the value — an aria-label on a span+ // without a role is not announced.+ <span+ data-tooltip={S.settings.pluginCellLocked}+ className="block px-1.5 text-xs break-words text-fg-muted"+ >+ {shown}+ <span className="sr-only"> ({S.settings.pluginCellLocked})</span>+ </span>+ ) : c.type === "boolean" ? (+ pinned !== undefined ? (+ <PinToggle+ label={cellLabel}+ pinned={cell === true}+ tooltip={+ cell === true ? localized(pinned.on, pinned.onZh) : localized(pinned.off, pinned.offZh)+ }+ disabled={disabled}+ onChange={onCell}+ />+ ) : (+ <Switch+ aria-label={cellLabel}+ checked={cell === true}+ disabled={disabled}+ onChange={onCell}+ />+ )+ ) : c.type === "enum" ? (+ <EnumCell+ label={cellLabel}+ value={typeof cell === "string" ? cell : ""}+ disabled={disabled}+ onChange={onCell}+ options={(c.options ?? []).map((option) => {+ const off = entry.unavailable?.find(+ (u) => u.field === name && u.column === c.name && u.value === option.value,+ );+ return {+ value: option.value,+ title: localized(option.title, option.titleZh),+ ...(off !== undefined ? { unavailable: localized(off.reason, off.reasonZh) } : {}),+ };+ })}+ />+ ) : (+ <WrappingNameBox+ label={cellLabel}+ // The effective text: an empty override is the declared text, in the page's language.+ // Typing it back, or clearing the box, restores it.+ value={typeof cell === "string" && cell !== "" ? cell : declared}+ disabled={disabled}+ onChange={(value) => onCell(row.declared !== undefined && value === declared ? "" : value)}+ />+ );+ return (+ <td className={`px-1 py-1.5 align-middle ${c.type === "boolean" ? "text-center" : ""}`}>+ {marks === undefined ? (+ body+ ) : (+ // The name first, then its marks; a long name takes the line and the marks wrap under.+ <div className="flex flex-wrap items-center gap-x-1">+ {body}+ {marks.marker !== undefined && (+ <span className="text-xs whitespace-nowrap text-fg-muted">{marks.marker}</span>+ )}+ {marks.help !== undefined && <InfoPopover label={rowName}>{marks.help}</InfoPopover>}+ </div>+ )}+ </td>+ );+}diff --git a/packages/web/src/features/settings/plugin-config-field.tsx b/packages/web/src/features/settings/plugin-config-field.tsxnew file mode 100644index 00000000..56db91c2--- /dev/null+++ b/packages/web/src/features/settings/plugin-config-field.tsx@@ -0,0 +1,203 @@+/**+ * One field of a settings group, drawn from its declared type: a text box, a password box with+ * the stored value's mask and a clear box, a switch, a number box, a select (its options this+ * machine cannot honour greyed out with the reason), a list of lines, or a table+ * (plugin-config-table.tsx). It shows the draft it is handed and reports each edit; the page+ * owns the drafts, the errors and what a change sets in motion.+ */+import type { PluginConfigEntry, PluginConfigField } from "@lmliheng/penguin-server/api";+import { Checkbox, Input, PasswordInput, Select, Textarea, ToggleRow } from "@lmliheng/penguin-ui";+import { S } from "../../lib/strings";+import type { Locale } from "../../state/locale";+import { localizedText } from "../chat/skill-use";+import { ConfigTable } from "./plugin-config-table";+import type { TableDraft } from "./plugin-config-draft";++export function ConfigField({+ entry,+ name,+ field,+ value,+ error,+ tableErrors,+ choice,+ onChoice,+ clearing,+ onChange,+ onClearingChange,+ disabled,+ locale,+}: {+ entry: PluginConfigEntry;+ name: string;+ field: PluginConfigField;+ /** The field's draft: a string as typed, a boolean, a list as its lines, a table's cells. */+ value: unknown;+ error: string | undefined;+ /** A table's refused cells, each named `<field>.<row>.<column>` by the server. */+ tableErrors: string[];+ /** A table's single-choice column: the chosen row as drafted, and its setter. */+ choice?: unknown;+ onChoice?: (row: string) => void;+ /** A secret field: whether the next save drops the stored value. */+ clearing: boolean;+ onChange: (value: unknown) => void;+ onClearingChange: (on: boolean) => void;+ disabled: boolean;+ locale: Locale;+}) {+ const localized = (en: string | undefined, zh: string | undefined) =>+ en === undefined ? undefined : localizedText(locale, en, zh);+ const label = localized(field.title, field.titleZh) ?? name;+ // What the field means sits behind a "?" beside its title; the shape a value must take (the+ // hint) stays on screen, since it is read while typing.+ const info = localized(field.description, field.descriptionZh);+ const hint = localized(field.hint, field.hintZh);+ const disclosed = info !== undefined ? { info, infoLabel: label } : {};+ switch (field.type) {+ case "table": {+ const table = (value as TableDraft | undefined) ?? { rows: {}, added: {}, order: [] };+ return (+ <ConfigTable+ key={name}+ entry={entry}+ name={name}+ field={field}+ table={table}+ onChange={onChange}+ errors={tableErrors}+ choice={choice}+ {...(onChoice !== undefined ? { onChoice } : {})}+ disabled={disabled}+ locale={locale}+ />+ );+ }+ case "enum":+ return (+ <Select+ key={name}+ size="sm"+ label={label}+ {...(hint !== undefined ? { hint } : {})}+ {...disclosed}+ {...(error !== undefined ? { error } : {})}+ value={typeof value === "string" ? (value as string) : ""}+ disabled={disabled}+ onChange={(e) => onChange(e.target.value)}+ >+ {(field.options ?? []).map((option) => {+ // An option this machine cannot honour stays listed, greyed out, with the reason.+ const off = entry.unavailable?.find(+ (u) => u.field === name && u.value === option.value,+ );+ const title = localized(option.title, option.titleZh);+ return (+ <option key={option.value} value={option.value} disabled={off !== undefined}>+ {off === undefined+ ? title+ : S.settings.pluginOptionUnavailable(+ title ?? option.value,+ localized(off.reason, off.reasonZh) ?? off.reason,+ )}+ </option>+ );+ })}+ </Select>+ );+ case "list":+ return (+ <Textarea+ key={name}+ label={label}+ rows={3}+ {...(hint !== undefined ? { hint } : {})}+ {...disclosed}+ {...(error !== undefined ? { error } : {})}+ value={typeof value === "string" ? (value as string) : ""}+ placeholder={field.placeholder ?? ""}+ disabled={disabled}+ onChange={(e) => onChange(e.target.value)}+ />+ );+ case "boolean":+ return (+ <ToggleRow+ key={name}+ variant="plain"+ label={label}+ {...(hint !== undefined ? { hint } : {})}+ {...(info !== undefined ? { info } : {})}+ checked={value === true}+ onChange={onChange}+ disabled={disabled}+ />+ );+ case "secret": {+ const masked = typeof entry.values[name] === "string" ? (entry.values[name] as string) : "";+ const typed = typeof value === "string" ? (value as string) : "";+ return (+ <div key={name} className="space-y-1">+ <PasswordInput+ size="sm"+ label={label}+ {...(hint !== undefined ? { hint } : {})}+ {...disclosed}+ {...disclosed}+ {...(error !== undefined ? { error } : {})}+ value={typed}+ placeholder={+ masked !== "" ? S.settings.pluginSecretKeepHint : (field.placeholder ?? "")+ }+ disabled={disabled}+ autoComplete="off"+ onChange={(e) => onChange(e.target.value)}+ />+ {masked !== "" && typed === "" && (+ <div className="flex items-center gap-x-3 text-xs text-fg-muted">+ <span className="font-mono">{masked}</span>+ <Checkbox+ checked={clearing}+ disabled={disabled}+ label={S.settings.pluginSecretClear}+ onChange={onClearingChange}+ />+ </div>+ )}+ </div>+ );+ }+ case "number":+ return (+ <Input+ key={name}+ size="sm"+ type="number"+ label={label}+ {...(hint !== undefined ? { hint } : {})}+ {...disclosed}+ {...(error !== undefined ? { error } : {})}+ value={typeof value === "string" ? (value as string) : ""}+ placeholder={field.placeholder ?? ""}+ disabled={disabled}+ onChange={(e) => onChange(e.target.value)}+ />+ );+ default:+ return (+ <Input+ key={name}+ size="sm"+ label={label}+ {...(hint !== undefined ? { hint } : {})}+ {...disclosed}+ {...(error !== undefined ? { error } : {})}+ value={typeof value === "string" ? (value as string) : ""}+ placeholder={field.placeholder ?? ""}+ disabled={disabled}+ autoComplete="off"+ onChange={(e) => onChange(e.target.value)}+ />+ );+ }+}diff --git a/packages/web/src/features/settings/plugin-config-heading.tsx b/packages/web/src/features/settings/plugin-config-heading.tsxnew file mode 100644index 00000000..954c37f1--- /dev/null+++ b/packages/web/src/features/settings/plugin-config-heading.tsx@@ -0,0 +1,92 @@+/**+ * A settings entry's head: its title with its description behind a "?", its store name, the+ * actions it offers+ * (what the deployment must do once on the machine, as buttons beside what each will do) and+ * its live notices — a spinner for work in progress, a strip for what needs attention, quiet+ * text for the rest. While the group's switch is off (as drafted), only the title is drawn:+ * the actions and notices concern the group in use.+ */+import type { PluginConfigEntry } from "@lmliheng/penguin-server/api";+import { Button, InfoPopover, NoticeStrip, Spinner } from "@lmliheng/penguin-ui";+import { S } from "../../lib/strings";+import { toneInk } from "../../lib/tone";+import type { Locale } from "../../state/locale";+import { localizedText } from "../chat/skill-use";+import { switchedOff } from "./plugin-config-draft";++export function ConfigHeading({+ entry,+ draft,+ nested,+ disabled,+ onAction,+ locale,+}: {+ entry: PluginConfigEntry;+ /** The entry's draft: with its `switch` field off, the actions and notices are hidden. */+ draft: Record<string, unknown> | undefined;+ /** Drawn inside another entry's card (a sandbox backend's group): a step smaller. */+ nested: boolean;+ disabled: boolean;+ onAction: (action: string) => void;+ locale: Locale;+}) {+ const localized = (en: string | undefined, zh: string | undefined) =>+ en === undefined ? undefined : localizedText(locale, en, zh);+ const title = localized(entry.configuration.title, entry.configuration.titleZh) ?? entry.name;+ // What the group is for sits behind a "?" beside its title.+ const description = localized(entry.configuration.description, entry.configuration.descriptionZh);+ const live = !switchedOff(entry, draft);+ return (+ <div className="space-y-1.5">+ <div>+ <p+ className={`inline-flex items-center gap-1 ${nested ? "text-xs font-semibold" : "text-sm font-semibold"}`}+ >+ {title}+ {description !== undefined && <InfoPopover label={title}>{description}</InfoPopover>}+ </p>+ <p className="font-mono text-xs text-fg-muted">{entry.name}</p>+ </div>+ {live && (entry.actions ?? []).length > 0 && (+ <div className="space-y-2">+ {(entry.actions ?? []).map((action) => {+ const description = localized(action.description, action.descriptionZh);+ return (+ <div key={action.id} className="flex items-start gap-3">+ <Button+ size="sm"+ variant="secondary"+ disabled={disabled}+ onClick={() => onAction(action.id)}+ >+ {localized(action.title, action.titleZh) ?? action.title}+ </Button>+ {description !== undefined && (+ <p className="text-xs text-fg-muted">{description}</p>+ )}+ </div>+ );+ })}+ </div>+ )}+ {live &&+ (entry.notices ?? []).map((notice, i) =>+ notice.tone === "progress" ? (+ <p key={i} className={`flex items-center gap-2 text-xs ${toneInk.busy}`}>+ <Spinner size="sm" label={S.common.loading} />+ <span className="min-w-0 break-words">{localized(notice.text, notice.textZh)}</span>+ </p>+ ) : notice.tone === "attention" ? (+ <NoticeStrip tone="attention" as="p" key={i} className="rounded-md px-3 py-2 text-xs">+ {localized(notice.text, notice.textZh)}+ </NoticeStrip>+ ) : (+ <p key={i} className="text-xs text-fg-muted">+ {localized(notice.text, notice.textZh)}+ </p>+ ),+ )}+ </div>+ );+}diff --git a/packages/web/src/features/settings/plugin-config-row-menu.tsx b/packages/web/src/features/settings/plugin-config-row-menu.tsxnew file mode 100644index 00000000..d3709222--- /dev/null+++ b/packages/web/src/features/settings/plugin-config-row-menu.tsx@@ -0,0 +1,118 @@+/**+ * A table row's "…" menu: the operations a row needs less often than its pin and handle —+ * making it the table's chosen row (the sandbox's default preset) and deleting a row an+ * administrator added. Declared rows have no Delete, and the chosen row cannot be deleted+ * (its item stays, disabled, saying why). The panel is the UI package's portaled `Dropdown` with+ * the `Menu` family's rows, like every other menu in the app: opening focuses the first item,+ * the arrow keys move, Enter picks, Esc closes this menu only.+ */+import { useState } from "react";+import { Dropdown, GlyphIcon, ICONS, ICON_SIZE, Menu, MenuItem } from "@lmliheng/penguin-ui";+import { S } from "../../lib/strings";+import { ICON_BUTTON } from "./plugin-config-table-cells";++/** One item of a row's menu; `blocked` says why it cannot be used now. */+export interface RowAction {+ id: "choose" | "delete";+ label: string;+ glyph: string;+ danger?: boolean;+ blocked?: string;+ run: () => void;+}++/**+ * The items a row's menu offers: Set as default where the table has a row choice, and Delete+ * on an added row. Empty when the row has neither.+ */+export function rowActions({+ chosen,+ canChoose,+ added,+ onChoose,+ onDelete,+}: {+ /** The row is the table's chosen one. */+ chosen: boolean;+ /** The table has a row choice. */+ canChoose: boolean;+ /** The row was added to an extensible table, so it may be deleted. */+ added: boolean;+ onChoose: () => void;+ onDelete: () => void;+}): RowAction[] {+ const actions: RowAction[] = [];+ if (canChoose) {+ actions.push({+ id: "choose",+ label: S.settings.pluginTableChoose,+ glyph: ICONS.star,+ ...(chosen ? { blocked: S.settings.pluginTableChosen } : {}),+ run: onChoose,+ });+ }+ if (added) {+ actions.push({+ id: "delete",+ label: S.settings.pluginTableDelete,+ glyph: ICONS.trash,+ danger: true,+ ...(chosen ? { blocked: S.settings.pluginTableDeleteChosen } : {}),+ run: onDelete,+ });+ }+ return actions;+}++export function RowMenu({+ row,+ actions,+ disabled,+}: {+ /** The row's name, for the button's accessible name. */+ row: string;+ actions: RowAction[];+ disabled: boolean;+}) {+ const [open, setOpen] = useState(false);+ if (actions.length === 0) return null;+ return (+ <Dropdown+ open={open}+ setOpen={setOpen}+ menuClass="w-56"+ portal={{ direction: "down", align: "right" }}+ button={+ <button+ type="button"+ aria-label={S.settings.pluginTableRowMenu(row)}+ aria-haspopup="menu"+ aria-expanded={open}+ // No tooltip while the menu is open: it would sit on top of the panel.+ data-tooltip={open ? undefined : S.settings.pluginTableRowMenuHint}+ disabled={disabled}+ onClick={() => setOpen(!open)}+ className={ICON_BUTTON}+ >+ <GlyphIcon d={ICONS.ellipsis} size={ICON_SIZE.iconButton} filled />+ </button>+ }+ >+ <Menu label={S.settings.pluginTableRowMenu(row)} density="sm" className="py-1">+ {actions.map((a) => (+ <MenuItem+ key={a.id}+ glyph={a.glyph}+ label={a.label}+ {...(a.danger === true ? { danger: true } : {})}+ {...(a.blocked !== undefined ? { disabled: true, description: a.blocked } : {})}+ onSelect={() => {+ setOpen(false);+ a.run();+ }}+ />+ ))}+ </Menu>+ </Dropdown>+ );+}diff --git a/packages/web/src/features/settings/plugin-config-table-cells.tsx b/packages/web/src/features/settings/plugin-config-table-cells.tsxnew file mode 100644index 00000000..5f1d6ce5--- /dev/null+++ b/packages/web/src/features/settings/plugin-config-table-cells.tsx@@ -0,0 +1,197 @@+/**+ * The presets table's own cell controls: the pin toggle, the wrapping name box and the row's+ * drag handle.+ */+import { useLayoutEffect, useRef } from "react";+import { GlyphIcon, ICONS, ICON_SIZE, Textarea } from "@lmliheng/penguin-ui";+import { S } from "../../lib/strings";++/** The one box every icon control in a table row takes, so a row's icons line up. */+export const ICON_BUTTON =+ "inline-flex size-6 items-center justify-center rounded-md align-middle text-fg-subtle transition-colors duration-150 hover:bg-surface-muted hover:text-fg disabled:cursor-not-allowed disabled:opacity-60";++/**+ * An icon toggle: the glyph, filled while pressed. A real button with `aria-pressed`; its+ * tooltip says the state in words.+ */+export function IconToggle({+ label,+ pressed,+ glyph,+ tooltip,+ disabled,+ onPress,+}: {+ label: string;+ pressed: boolean;+ glyph: string;+ tooltip: string;+ disabled: boolean;+ onPress: () => void;+}) {+ return (+ <button+ type="button"+ aria-label={label}+ aria-pressed={pressed}+ data-tooltip={tooltip}+ disabled={disabled}+ onClick={onPress}+ className={`${ICON_BUTTON} ${pressed ? "!text-fg" : ""}`}+ >+ <GlyphIcon d={glyph} size={ICON_SIZE.iconButton} filled={pressed} />+ </button>+ );+}++/** A pin toggle: the pin glyph, filled while pinned (see IconToggle). */+export function PinToggle({+ label,+ pinned,+ tooltip,+ disabled,+ onChange,+}: {+ label: string;+ pinned: boolean;+ tooltip: string;+ disabled: boolean;+ onChange: (pinned: boolean) => void;+}) {+ return (+ <IconToggle+ label={label}+ pressed={pinned}+ glyph={ICONS.pin}+ tooltip={tooltip}+ disabled={disabled}+ onPress={() => onChange(!pinned)}+ />+ );+}++/**+ * A one-line text value that wraps instead of clipping: a name longer than the column (a+ * "Workspace Write with Ask") reads whole on two lines, where an <input> could only cut it off.+ * The box grows to its content; Enter and pasted line breaks never put a newline in the value.+ * Borderless until pointed at or focused: the row reads as a table of names, and the box shows+ * itself when it is about to be edited.+ */+export function WrappingNameBox({+ label,+ value,+ disabled,+ onChange,+}: {+ label: string;+ value: string;+ disabled: boolean;+ onChange: (value: string) => void;+}) {+ const ref = useRef<HTMLTextAreaElement>(null);+ // Sized to its content on every change of the text AND of its width: the fixed table settles+ // its column widths after the first paint, and a height measured at the wider first width+ // would cut the wrapped name's last line off.+ useLayoutEffect(() => {+ const box = ref.current;+ if (box === null) return;+ const fit = () => {+ box.style.height = "auto";+ box.style.height = `${box.scrollHeight}px`;+ };+ fit();+ if (typeof ResizeObserver === "undefined") return;+ let width = box.clientWidth;+ const observer = new ResizeObserver(() => {+ if (box.clientWidth === width) return;+ width = box.clientWidth;+ fit();+ });+ observer.observe(box);+ return () => observer.disconnect();+ }, [value]);+ return (+ <Textarea+ ref={ref}+ size="sm"+ rows={1}+ aria-label={label}+ value={value}+ disabled={disabled}+ autoComplete="off"+ spellCheck={false}+ // As wide as the name, so a mark after it (the default's) sits right beside it; never wider+ // than the cell, where it wraps. A browser without `field-sizing` gives it the whole cell.+ className="!w-auto max-w-full min-w-8 resize-none overflow-hidden ![field-sizing:content] !px-1 !py-1 !leading-snug break-words whitespace-pre-wrap !border-transparent !bg-transparent hover:!border-line focus:!border-fg-muted supports-[not(field-sizing:content)]:!w-full"+ onKeyDown={(e) => {+ if (e.key === "Enter") e.preventDefault();+ }}+ onChange={(e) => onChange(e.target.value.replace(/[\r\n]+/g, " "))}+ />+ );+}++/**+ * A row's drag handle (three lines). Pressed, it takes the pointer capture and reports the drag+ * to the table, which moves the row by transform and reorders only on the drop — so this button+ * never moves in the DOM while it holds the capture. Losing the capture or a cancelled pointer+ * puts the row back. Focused, the up and down arrow keys move the row one place. `touch-none`+ * keeps a touch drag from scrolling the page instead.+ */+export function RowGrip({+ row,+ disabled,+ onStep,+ onDragStart,+ onDragMove,+ onDragEnd,+ gripRef,+}: {+ /** The row's name, for the accessible name. */+ row: string;+ disabled: boolean;+ onStep: (by: -1 | 1) => void;+ onDragStart: (clientY: number) => void;+ onDragMove: (clientY: number) => void;+ /** `true` drops the row where it is; `false` puts it back. */+ onDragEnd: (commit: boolean) => void;+ gripRef: (el: HTMLButtonElement | null) => void;+}) {+ const dragging = useRef(false);+ const end = (commit: boolean) => {+ if (!dragging.current) return;+ dragging.current = false;+ onDragEnd(commit);+ };+ return (+ <button+ ref={gripRef}+ type="button"+ aria-label={S.settings.pluginTableMove(row)}+ data-tooltip={S.settings.pluginTableMoveHint}+ disabled={disabled}+ onKeyDown={(e) => {+ if (e.key === "ArrowUp" || e.key === "ArrowDown") {+ e.preventDefault();+ onStep(e.key === "ArrowUp" ? -1 : 1);+ }+ }}+ onPointerDown={(e) => {+ if (disabled || e.button !== 0) return;+ e.preventDefault();+ e.currentTarget.setPointerCapture(e.pointerId);+ dragging.current = true;+ onDragStart(e.clientY);+ }}+ onPointerMove={(e) => {+ if (dragging.current) onDragMove(e.clientY);+ }}+ onPointerUp={() => end(true)}+ onPointerCancel={() => end(false)}+ onLostPointerCapture={() => end(true)}+ className={`${ICON_BUTTON} cursor-grab touch-none active:cursor-grabbing`}+ >+ <GlyphIcon d={ICONS.menu} size={ICON_SIZE.iconButton} />+ </button>+ );+}diff --git a/packages/web/src/features/settings/plugin-config-table.tsx b/packages/web/src/features/settings/plugin-config-table.tsxnew file mode 100644index 00000000..2d3a53cf--- /dev/null+++ b/packages/web/src/features/settings/plugin-config-table.tsx@@ -0,0 +1,436 @@+/**+ * A settings group's `table` field (the Sandbox card's presets), drawn inside a rounded,+ * hairline-bordered box. The layout is fixed: every `enum` column gets the same width, the+ * small columns (a pin, the handle, the "…" menu) get just their control, and the text column+ * takes the rest and wraps. On a screen too narrow for that the box scrolls sideways.+ *+ * The table's title, every column header and a column group's header carry a "?" disclosing+ * what they mean (the schema's `description`s), never a paragraph on screen.+ *+ * Cells by column type are plugin-config-field-cell.tsx's. The row's name (its `name` column)+ * is followed by the chosen row's marker ("(Default)", the `rowChoice`'s title) and a "?" saying+ * what the row is for: its declared `description` while its choices are the declared ones, else+ * each choice's value and what that option does.+ *+ * An `extensible` table ends every row with a drag handle (the arrow keys move a focused one),+ * and has an add button under it. A drag lifts the row and moves it with the pointer, shows a+ * line where it will land, and reorders once, on the drop; Esc puts it back. A row's "…" menu+ * (plugin-config-row-menu.tsx) holds what is used less often: Set as default, and Delete on an+ * added row. The handle and the menu join the column group when it ends the columns. Every+ * control is named "<row> · <column>" (or after its action) for a screen reader, the row's name+ * in the page's language.+ */+import { useEffect, useRef, useState } from "react";+import type {+ PluginConfigEntry,+ PluginConfigField,+ PluginConfigTableColumn,+} from "@lmliheng/penguin-server/api";+import { Button, InfoPopover } from "@lmliheng/penguin-ui";+import { S } from "../../lib/strings";+import { toneInk } from "../../lib/tone";+import type { Locale } from "../../state/locale";+import { localizedText } from "../chat/skill-use";+import type { TableDraft } from "./plugin-config-draft";+import { Cell, rowHelp } from "./plugin-config-field-cell";+import type { DrawnRow } from "./plugin-config-field-cell";+import { RowMenu, rowActions } from "./plugin-config-row-menu";+import { RowGrip } from "./plugin-config-table-cells";++/** The column a row is named by: its text is the row's name, followed by the row's marks. */+const NAME_COLUMN = "name";++/**+ * Column widths, in the table's fixed layout. Equal for every choice column so none reads wider+ * than its siblings, one width for every icon column (the action group), and a floor under the+ * name (and its marks): below the table's minimum width its box scrolls sideways rather than+ * crushing names.+ */+const WIDTH = {+ enum: "w-[6.25rem]",+ icon: "w-7",+ boolean: "w-[3.25rem]",+} as const;+/** Name floor (7.75rem) + three choice columns + three icon columns. */+const TABLE_MIN = "min-w-[31.75rem]";++const TH = "px-1 py-2 text-left text-xs font-medium text-fg-muted";++/** A header's title and its "?" — the title is the "?"'s anchor, so they share one element. */+function HeaderTitle({ title, info }: { title: string; info: string | undefined }) {+ return (+ <span className="inline-flex items-center gap-1 whitespace-nowrap">+ {title}+ {info !== undefined && <InfoPopover label={title}>{info}</InfoPopover>}+ </span>+ );+}++/** One drawn column: a field column, an extensible table's handle, or the row's "…" menu. */+type Slot =+ { kind: "column"; column: PluginConfigTableColumn } | { kind: "move" } | { kind: "more" };++/**+ * A drag in progress: the row, how far the pointer has moved, and where the row would land+ * among the others (an index into the order without it). Nothing is reordered until the drop,+ * so the handle holding the pointer capture never moves in the DOM.+ */+interface Drag {+ id: string;+ startY: number;+ dy: number;+ /** The other rows' vertical midpoints, measured once when the drag starts. */+ mids: number[];+ /** The dragged row's own midpoint at the start. */+ mid: number;+ target: number;+}++/** A fresh id for an added row: lower-case, never a declared one. */+const newRowId = () => `added-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;++export function ConfigTable({+ entry,+ name,+ field,+ table,+ onChange,+ choice,+ onChoice,+ errors,+ disabled,+ locale,+}: {+ entry: PluginConfigEntry;+ name: string;+ field: PluginConfigField;+ table: TableDraft;+ onChange: (next: TableDraft) => void;+ /** The row the table's single choice (`rowChoice`) holds, as drafted. */+ choice?: unknown;+ onChoice?: (row: string) => void;+ /** The refused cells' messages, listed under the table. */+ errors: string[];+ disabled: boolean;+ locale: Locale;+}) {+ const localized = (en: string, zh: string | undefined) => localizedText(locale, en, zh);+ const described = (d: { description?: string; descriptionZh?: string }) =>+ d.description !== undefined ? localized(d.description, d.descriptionZh) : undefined;+ const label = localized(field.title, field.titleZh);+ const info = described(field);+ const { rowChoice, pin, columnGroup, extensible } = field;++ // The columns in drawing order: an extensible table's handle and the "…" menu come last —+ // inside the column group when it ends there.+ const slots = (field.columns ?? []).map((column): Slot => ({ kind: "column", column }));+ const lastField = slots.length - 1;+ if (extensible !== undefined) slots.push({ kind: "move" });+ if (extensible !== undefined || rowChoice !== undefined) slots.push({ kind: "more" });+ const slotKey = (slot: Slot) => (slot.kind === "column" ? slot.column.name : slot.kind);+ const isIcon = (slot: Slot) => slot.kind !== "column" || pin?.column === slot.column.name;+ const grouped = (slot: Slot, i: number) => {+ if (columnGroup === undefined) return false;+ if (slot.kind !== "column") {+ // The row controls join the group when the group is what the field columns end with.+ const last = slots[lastField];+ return last !== undefined && columnGroup.columns.includes(slotKey(last)) && i > lastField;+ }+ return columnGroup.columns.includes(slotKey(slot));+ };+ const widthOf = (slot: Slot) =>+ isIcon(slot)+ ? WIDTH.icon+ : slot.kind === "column" && slot.column.type === "enum"+ ? WIDTH.enum+ : slot.kind === "column" && slot.column.type === "boolean"+ ? WIDTH.boolean+ : "";+ const slotTitle = (slot: Slot) =>+ slot.kind === "column" ? localized(slot.column.title, slot.column.titleZh) : "";+ const slotInfo = (slot: Slot) => (slot.kind === "column" ? described(slot.column) : undefined);++ const declared = new Map((field.rows ?? []).map((r) => [r.id, r]));+ const rows: DrawnRow[] = table.order.flatMap((id): DrawnRow[] => {+ const row = declared.get(id);+ if (row !== undefined) return [{ id, declared: row, cells: table.rows[id] ?? {} }];+ const added = table.added[id];+ return added !== undefined ? [{ id, cells: added }] : [];+ });+ const rowName = (row: DrawnRow) => {+ const typed = row.cells[NAME_COLUMN];+ if (typeof typed === "string" && typed !== "") return typed;+ return row.declared !== undefined+ ? localized(+ String(row.declared.values[NAME_COLUMN] ?? row.id),+ row.declared.valuesZh?.[NAME_COLUMN],+ )+ : row.id;+ };+ /** What a row is for, behind the "?" after its name: one line, or a line per choice. */+ const helpOf = (row: DrawnRow) => {+ const help = rowHelp(field.columns ?? [], row, localized);+ return Array.isArray(help)+ ? help.map((line, i) => (+ <span key={i} className="block">+ {line}+ </span>+ ))+ : help;+ };++ const setCell = (row: DrawnRow, column: string, value: string | boolean) =>+ onChange(+ row.declared !== undefined+ ? { ...table, rows: { ...table.rows, [row.id]: { ...row.cells, [column]: value } } }+ : { ...table, added: { ...table.added, [row.id]: { ...row.cells, [column]: value } } },+ );+ /** Puts a row at `index` of the order without it. */+ const placeAt = (id: string, index: number) => {+ const rest = table.order.filter((x) => x !== id);+ const at = Math.max(0, Math.min(rest.length, index));+ if (table.order.indexOf(id) === at) return;+ rest.splice(at, 0, id);+ onChange({ ...table, order: rest });+ };+ const remove = (row: DrawnRow) => {+ const { [row.id]: _gone, ...added } = table.added;+ onChange({ ...table, added, order: table.order.filter((x) => x !== row.id) });+ };+ const add = () => {+ if (extensible === undefined) return;+ const id = newRowId();+ const values = Object.fromEntries(+ (field.columns ?? []).map((c) => [+ c.name,+ c.type === "string"+ ? localized(String(extensible.values[c.name] ?? ""), extensible.valuesZh?.[c.name])+ : extensible.values[c.name]!,+ ]),+ );+ onChange({ ...table, added: { ...table.added, [id]: values }, order: [...table.order, id] });+ };++ // Rows by id, to measure them when a drag starts; a handle that moved its row by keyboard+ // keeps the focus after the rows re-render in their new order.+ const rowEls = useRef(new Map<string, HTMLTableRowElement>());+ const grips = useRef(new Map<string, HTMLButtonElement>());+ const refocus = useRef<string | null>(null);+ useEffect(() => {+ if (refocus.current === null) return;+ grips.current.get(refocus.current)?.focus();+ refocus.current = null;+ });+ const [drag, setDrag] = useState<Drag | null>(null);+ const dragRef = useRef<Drag | null>(null);+ dragRef.current = drag;+ const midOf = (id: string) => {+ const box = rowEls.current.get(id)?.getBoundingClientRect();+ return box === undefined ? 0 : box.top + box.height / 2;+ };+ const startDrag = (id: string, clientY: number) => {+ const others = table.order.filter((x) => x !== id);+ const next: Drag = {+ id,+ startY: clientY,+ dy: 0,+ mids: others.map(midOf),+ mid: midOf(id),+ target: table.order.indexOf(id),+ };+ setDrag(next);+ };+ const moveDrag = (clientY: number) => {+ const d = dragRef.current;+ if (d === null) return;+ const dy = clientY - d.startY;+ // Where the dragged row's middle now sits among the others' middles.+ const target = d.mids.filter((m) => m < d.mid + dy).length;+ setDrag({ ...d, dy, target });+ };+ const endDrag = (commit: boolean) => {+ const d = dragRef.current;+ setDrag(null);+ if (commit && d !== null) placeAt(d.id, d.target);+ };+ // Esc puts a dragged row back where it was.+ useEffect(() => {+ if (drag === null) return;+ const onKey = (e: KeyboardEvent) => {+ if (e.key !== "Escape") return;+ e.preventDefault();+ e.stopPropagation();+ endDrag(false);+ };+ window.addEventListener("keydown", onKey, true);+ return () => window.removeEventListener("keydown", onKey, true);+ });+ // The drop line: on top of the row the dragged one would land before, or under the last.+ const others = drag === null ? [] : table.order.filter((x) => x !== drag.id);+ const dropBefore = drag === null ? null : (others[drag.target] ?? null);+ const dropAfterLast = drag !== null && drag.target >= others.length;++ const groupSlots = slots.filter(grouped);+ const groupTitle =+ columnGroup !== undefined ? localized(columnGroup.title, columnGroup.titleZh) : "";++ return (+ <div className="space-y-1.5">+ <p className="inline-flex items-center gap-1 text-sm font-medium">+ {label}+ {info !== undefined && <InfoPopover label={label}>{info}</InfoPopover>}+ </p>+ {field.hint !== undefined && (+ <p className="text-xs text-fg-muted">{localized(field.hint, field.hintZh)}</p>+ )}+ <div className="overflow-x-auto rounded-lg border border-line">+ <table className={`w-full ${TABLE_MIN} table-fixed border-collapse text-sm`}>+ <colgroup>+ {slots.map((slot) => (+ <col key={slotKey(slot)} className={widthOf(slot)} />+ ))}+ </colgroup>+ <thead className="bg-surface-muted">+ <tr>+ {slots.map((slot, i) => {+ if (grouped(slot, i)) {+ // The group's header stands once, over its first column, spanning them all:+ // its "?" says what each icon in it does.+ if (slots.findIndex(grouped) !== i) return null;+ return (+ <th+ key="group"+ scope="colgroup"+ colSpan={groupSlots.length}+ className={`${TH} text-center`}+ >+ <HeaderTitle title={groupTitle} info={described(columnGroup!)} />+ </th>+ );+ }+ if (slot.kind !== "column") return <th key={slot.kind} aria-hidden />;+ return (+ <th+ key={slotKey(slot)}+ scope="col"+ className={`${TH} ${isIcon(slot) ? "text-center" : ""}`}+ >+ <HeaderTitle title={slotTitle(slot)} info={slotInfo(slot)} />+ </th>+ );+ })}+ </tr>+ </thead>+ <tbody>+ {rows.map((row) => {+ const rowLabel = rowName(row);+ const dy = drag !== null && drag.id === row.id ? drag.dy : null;+ const dragging = dy !== null;+ const lineAbove = dropBefore === row.id;+ const lineBelow = dropAfterLast && row.id === others[others.length - 1];+ const chosen = choice === row.id;+ return (+ <tr+ key={row.id}+ ref={(el) => {+ if (el === null) rowEls.current.delete(row.id);+ else rowEls.current.set(row.id, el);+ }}+ // Lifted while dragged: it follows the pointer by transform, above the rest.+ style={+ dragging+ ? { transform: `translateY(${dy}px)`, position: "relative", zIndex: 1 }+ : undefined+ }+ className={`border-t border-line-muted ${dragging ? "bg-surface shadow-lg" : "transition-colors duration-150 hover:bg-surface-muted/60"} ${lineAbove ? "[&>td]:border-t-2 [&>td]:border-t-accent" : ""} ${lineBelow ? "[&>td]:border-b-2 [&>td]:border-b-accent" : ""}`}+ >+ {slots.map((slot) => {+ if (slot.kind === "move") {+ return (+ <td key="move" className="px-0.5 py-1.5 text-center align-middle">+ <RowGrip+ row={rowLabel}+ disabled={disabled}+ gripRef={(el) => {+ if (el === null) grips.current.delete(row.id);+ else grips.current.set(row.id, el);+ }}+ onStep={(by) => {+ refocus.current = row.id;+ placeAt(row.id, table.order.indexOf(row.id) + by);+ }}+ onDragStart={(y) => startDrag(row.id, y)}+ onDragMove={moveDrag}+ onDragEnd={endDrag}+ />+ </td>+ );+ }+ if (slot.kind === "more") {+ // The cell stays on a row with nothing to offer, empty, so the icons line up.+ return (+ <td key="more" className="px-0.5 py-1.5 text-center align-middle">+ <RowMenu+ row={rowLabel}+ disabled={disabled}+ actions={rowActions({+ chosen,+ canChoose: rowChoice !== undefined,+ added: extensible !== undefined && row.declared === undefined,+ onChoose: () => onChoice?.(row.id),+ onDelete: () => remove(row),+ })}+ />+ </td>+ );+ }+ return (+ <Cell+ key={slot.column.name}+ entry={entry}+ name={name}+ column={slot.column}+ row={row}+ rowName={rowLabel}+ pinned={pin?.column === slot.column.name ? pin : undefined}+ {...(slot.column.name === NAME_COLUMN+ ? {+ marks: {+ ...(chosen && rowChoice !== undefined+ ? {+ marker: S.settings.pluginTableChosenMarker(+ localized(rowChoice.title, rowChoice.titleZh),+ ),+ }+ : {}),+ help: helpOf(row),+ },+ }+ : {})}+ localized={localized}+ disabled={disabled}+ onCell={(value) => setCell(row, slot.column.name, value)}+ />+ );+ })}+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ {extensible !== undefined && (+ <Button size="sm" variant="secondary" disabled={disabled} onClick={add}>+ {extensible.add !== undefined+ ? localized(extensible.add, extensible.addZh)+ : S.settings.pluginTableAdd}+ </Button>+ )}+ {errors.map((text, i) => (+ <p key={i} className={`text-xs ${toneInk.danger}`}>+ {text}+ </p>+ ))}+ </div>+ );+}diff --git a/packages/web/src/features/settings/plugins-section.tsx b/packages/web/src/features/settings/plugins-section.tsxindex fcdb4f9e..9136829e 100644--- a/packages/web/src/features/settings/plugins-section.tsx+++ b/packages/web/src/features/settings/plugins-section.tsx@@ -1,8 +1,12 @@/*** Plugin options (admin only, server-global): one card per settings entry — a group a module* contributes (the sandbox) or a loaded plugin's declared configuration — drawn from its- * schema: a string, a secret, a boolean, a number, a choice or a list of- * lines per field, so the page knows nothing about any particular entry. An entry naming a+ * schema: a string, a secret, a boolean, a number, a choice, a list of lines or a table (a+ * row per preset, say; plugin-config-table.tsx) per field, so the page knows nothing about any+ * particular entry. Fields a group marks `advanced` sit in a fold under the others, collapsed+ * by default (advanced-fold.tsx). A group with a `switch` draws that field alone while it is+ * off, and one that reports a `backend` it lacks offers to install it when the switch is turned+ * on (sandbox-backend-prompt.tsx). An entry naming a* `parent` is drawn inside that card (a sandbox backend's own options inside the sandbox's) and* saved with it; notices the entry reports sit under its title. Each card saves on its own;* nothing is written until its Save, which sends each changed entry of the card in one PUT. A secret field always starts empty and shows@@ -27,70 +31,38 @@ import { S } from "../../lib/strings";import { useLocale } from "../../state/locale";import { localizedText } from "../chat/skill-use";import { apiErrorText } from "../../lib/api-error";-import { toneInk } from "../../lib/tone";import { useSessions } from "../../state/sessions";+import { useProject } from "../../state/project";+import {+ THIS_SERVER_KEY,+ backendToOffer,+ dismissBackendPrompt,+} from "../../lib/sandbox-backend-prompt";+import { dispatchPluginConfigSaved } from "../../lib/plugin-config-event";import { MachinePicker } from "../machines/machine-picker";+import { AdvancedFold } from "./advanced-fold";+import {+ baselineOf,+ draftOf,+ drawnFields,+ sameValue,+ switchedOff,+ valueOf,+} from "./plugin-config-draft";+import type { Draft } from "./plugin-config-draft";+import { ConfigField } from "./plugin-config-field";+import { ConfigHeading } from "./plugin-config-heading";+import { SandboxBackendPrompt } from "./sandbox-backend-prompt";import {Button,- Checkbox,- Input,+ ConfirmModal,NoticeStrip,- PasswordInput,- Select,SettingsSection,- Spinner,- Textarea,- ToggleRow,toastError,toastInfo,toastSuccess,} from "@lmliheng/penguin-ui";-/** The picker's value for this server; a machine id is never this short. */-const THIS_SERVER = "*";--/**- * A field's draft: strings and numbers as typed (a number stays the string in the box until- * Save, so "1." or "-" survives the keystroke), booleans as values; a secret's clear box- * beside it.- */-type Draft = Record<string, unknown>;--/** The draft a plugin's form starts from: every non-secret value as stored, every secret empty. */-function draftOf(entry: PluginConfigEntry): Draft {- const out: Draft = {};- for (const [name, field] of Object.entries(entry.configuration.properties)) {- if (field.type === "secret") continue;- const v = entry.values[name];- if (v === undefined) continue;- out[name] =- field.type === "number"- ? String(v)- : field.type === "list"- ? (Array.isArray(v) ? v : []).join("\n")- : v;- }- return out;-}--/** The value a draft sends for a field: a number parsed from its box, a list split into lines, everything else as is. */-function valueOf(field: PluginConfigField, draft: unknown): unknown {- if (field.type === "list") {- const lines = (typeof draft === "string" ? draft : "")- .split("\n")- .map((line) => line.trim())- .filter((line) => line !== "");- return lines.length === 0 ? null : lines;- }- if (field.type !== "number") return draft ?? null;- const text = typeof draft === "string" ? draft.trim() : "";- return text === "" ? null : Number(text);-}--/** Whether two field values are the same (lists compared by content). */-const sameValue = (a: unknown, b: unknown) =>- JSON.stringify(a ?? null) === JSON.stringify(b ?? null);-/*** Brings one card into view once the list has loaded — an opening that names a card (the* composer's permission menu names `sandbox`) lands on it rather than on the top of the page.@@ -122,12 +94,25 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {const [clearing, setClearing] = useState<Set<string>>(new Set());const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});const [busy, setBusy] = useState<string | null>(null);+ /**+ * A group action awaiting confirmation, with its own title. A plugin cannot mark an action+ * as dangerous, so every one asks before it runs on the machine.+ */+ const [pendingAction, setPendingAction] = useState<{+ entry: PluginConfigEntry;+ id: string;+ title: string;+ } | null>(null);const { machineIds, machineLabels } = useSessions();/** The machine whose settings the page shows and saves: null for this server. */const [machine, setMachine] = useState<string | null>(null);/** Why the picked machine's settings could not be read, when they could not. */const [loadError, setLoadError] = useState<string | null>(null);const nameOf = (id: string) => machineLabels.get(id) ?? id;+ const projectId = useProject().currentProject?.projectId ?? null;+ /** The backend package the install prompt offers, while it is open. */+ const [offered, setOffered] = useState<string | null>(null);+ const [installing, setInstalling] = useState(false);const adopt = (list: PluginConfigEntry[]) => {setEntries(list);@@ -245,7 +230,7 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {}// Only what changed: sending an untouched field would store its default as a value,// pinning it against a later change of the default.- if (sameValue(v, entry.values[name])) continue;+ if (sameValue(v, baselineOf(field, entry.values[name]))) continue;values[name] = v;changed = true;}@@ -287,6 +272,10 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {}}toastSuccess(S.common.saved);+ // Pages showing what the card configures (the composer's permission menu) read it again.+ for (const [entry] of updates) {+ dispatchPluginConfigSaved({ group: entry.name, card: card.name });+ }} finally {setBusy(null);}@@ -298,6 +287,16 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {* knows what happened, this page does not — and the groups it answers with replace ours,* because a setup that worked changes what the card says about itself.*/+ /** A group action's button: asks first, with the action's own title (see pendingAction). */+ const askAction = (entry: PluginConfigEntry, id: string) => {+ const action = entry.actions?.find((a) => a.id === id);+ setPendingAction({+ entry,+ id,+ title: (action && localized(action.title, action.titleZh)) ?? action?.title ?? id,+ });+ };+const runAction = async (entry: PluginConfigEntry, action: string) => {setBusy(`${entry.name}\0${action}`);try {@@ -313,6 +312,62 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {}};+ /**+ * The switch was turned on: if the machine reports no sandbox backend for its OS, ask whether+ * to install its default one. The switch stays on in the draft whatever the answer.+ */+ const offerBackend = (entry: PluginConfigEntry) => {+ const pkg = backendToOffer(entry, machine ?? THIS_SERVER_KEY);+ if (pkg !== null) setOffered(pkg);+ };+ const closePrompt = (dontAskAgain: boolean) => {+ if (dontAskAgain) dismissBackendPrompt(machine ?? THIS_SERVER_KEY);+ setOffered(null);+ };++ /**+ * Installs the offered backend the way the Plugins page does: into this Project's table for+ * the machine on screen only — this server's own machine id when the card shows this server,+ * so no other machine is asked to run it. Afterwards the card's live parts (notices, the+ * backend report) are read again; drafts being edited are kept.+ */+ const installOffered = async (dontAskAgain: boolean) => {+ if (offered === null || installing) return;+ if (projectId === null) {+ toastError(S.settings.sandboxBackendPrompt.noProject);+ return;+ }+ const pkg = offered;+ setInstalling(true);+ try {+ const target = machine ?? (await api.getInstalledPlugins(projectId)).machineId;+ const res = await api.installPlugin(projectId, pkg, target);+ const row = res.plugins.find((p) => p.specifier === pkg);+ if (row?.error !== undefined) toastError(S.plugins.deploymentFailedToast(pkg, row.error));+ else toastSuccess(S.plugins.deploymentInstalledToast(pkg));+ closePrompt(dontAskAgain);+ const config = await api.adminGetPluginConfig(machine);+ setEntries((prev) =>+ (prev ?? []).map((e) => {+ const next = config.plugins.find((p) => p.name === e.name);+ if (next === undefined) return e;+ const { notices: _n, actions: _a, backend: _b, unavailable: _u, ...rest } = e;+ return {+ ...rest,+ ...(next.notices !== undefined ? { notices: next.notices } : {}),+ ...(next.actions !== undefined ? { actions: next.actions } : {}),+ ...(next.backend !== undefined ? { backend: next.backend } : {}),+ ...(next.unavailable !== undefined ? { unavailable: next.unavailable } : {}),+ };+ }),+ );+ } catch (e) {+ toastError(apiErrorText(e));+ } finally {+ setInstalling(false);+ }+ };+// Only when there is another machine to pick: a single server has nothing to switch to.const picker =machineIds.length > 0 ? (@@ -320,12 +375,12 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {<MachinePickeraria-label={S.settings.pluginConfigMachine}choices={[- { value: THIS_SERVER, label: S.plugins.thisServer },+ { value: THIS_SERVER_KEY, label: S.plugins.thisServer },...machineIds.map((id) => ({ value: id, label: nameOf(id) })),]}- value={machine ?? THIS_SERVER}+ value={machine ?? THIS_SERVER_KEY}onChange={(v) => {- if (busy === null) setMachine(v === THIS_SERVER ? null : v);+ if (busy === null) setMachine(v === THIS_SERVER_KEY ? null : v);}}/></div>@@ -343,205 +398,60 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {};const control = (entry: PluginConfigEntry, name: string, field: PluginConfigField) => {- const draft = drafts[entry.name] ?? {};const key = `${entry.name}\0${name}`;- const error = fieldErrors[key];- const label = localized(field.title, field.titleZh) ?? name;- const hint = localized(field.description, field.descriptionZh);- const disabled = busy !== null;- switch (field.type) {- case "enum":- return (- <Select- key={name}- size="sm"- label={label}- {...(hint !== undefined ? { hint } : {})}- {...(error !== undefined ? { error } : {})}- value={typeof draft[name] === "string" ? (draft[name] as string) : ""}- disabled={disabled}- onChange={(e) => patch(entry.name, name, e.target.value)}- >- {(field.options ?? []).map((option) => {- // An option this machine cannot honour stays listed, greyed out, with the reason.- const off = entry.unavailable?.find(- (u) => u.field === name && u.value === option.value,- );- const title = localized(option.title, option.titleZh);- return (- <option key={option.value} value={option.value} disabled={off !== undefined}>- {off === undefined- ? title- : S.settings.pluginOptionUnavailable(- title ?? option.value,- localized(off.reason, off.reasonZh) ?? off.reason,- )}- </option>- );- })}- </Select>- );- case "list":- return (- <Textarea- key={name}- label={label}- rows={3}- {...(hint !== undefined ? { hint } : {})}- {...(error !== undefined ? { error } : {})}- value={typeof draft[name] === "string" ? (draft[name] as string) : ""}- placeholder={field.placeholder ?? ""}- disabled={disabled}- onChange={(e) => patch(entry.name, name, e.target.value)}- />- );- case "boolean":- return (- <ToggleRow- key={name}- variant="plain"- label={label}- hint={hint}- checked={draft[name] === true}- onChange={(v) => patch(entry.name, name, v)}- disabled={disabled}- />- );- case "secret": {- const masked = typeof entry.values[name] === "string" ? (entry.values[name] as string) : "";- const typed = typeof draft[name] === "string" ? (draft[name] as string) : "";- return (- <div key={name} className="space-y-1">- <PasswordInput- size="sm"- label={label}- {...(hint !== undefined ? { hint } : {})}- {...(error !== undefined ? { error } : {})}- value={typed}- placeholder={- masked !== "" ? S.settings.pluginSecretKeepHint : (field.placeholder ?? "")- }- disabled={disabled}- autoComplete="off"- onChange={(e) => {- patch(entry.name, name, e.target.value);- setClearing((prev) => {- const next = new Set(prev);- next.delete(key);- return next;- });- }}- />- {masked !== "" && typed === "" && (- <div className="flex items-center gap-x-3 text-xs text-gray-500 dark:text-gray-400">- <span className="font-mono">{masked}</span>- <Checkbox- checked={clearing.has(key)}- disabled={disabled}- label={S.settings.pluginSecretClear}- onChange={(on) =>- setClearing((prev) => {- const next = new Set(prev);- if (on) next.add(key);- else next.delete(key);- return next;- })- }- />- </div>- )}- </div>- );- }- case "number":- return (- <Input- key={name}- size="sm"- type="number"- label={label}- {...(hint !== undefined ? { hint } : {})}- {...(error !== undefined ? { error } : {})}- value={typeof draft[name] === "string" ? (draft[name] as string) : ""}- placeholder={field.placeholder ?? ""}- disabled={disabled}- onChange={(e) => patch(entry.name, name, e.target.value)}- />- );- default:- return (- <Input- key={name}- size="sm"- label={label}- {...(hint !== undefined ? { hint } : {})}- {...(error !== undefined ? { error } : {})}- value={typeof draft[name] === "string" ? (draft[name] as string) : ""}- placeholder={field.placeholder ?? ""}- disabled={disabled}- autoComplete="off"- onChange={(e) => patch(entry.name, name, e.target.value)}- />- );- }+ const choiceField = field.rowChoice?.field;+ return (+ <ConfigField+ key={name}+ entry={entry}+ name={name}+ field={field}+ value={drafts[entry.name]?.[name]}+ error={fieldErrors[key]}+ // A refused cell is named `<field>.<row>.<column>`; the table lists them under itself.+ tableErrors={Object.entries(fieldErrors)+ .filter(([k]) => k === key || k.startsWith(`${key}.`))+ .map(([, text]) => text)}+ {...(choiceField !== undefined+ ? {+ choice: drafts[entry.name]?.[choiceField],+ onChoice: (row: string) => patch(entry.name, choiceField, row),+ }+ : {})}+ clearing={clearing.has(key)}+ onChange={(value) => {+ patch(entry.name, name, value);+ // Typing a new secret is not also clearing it.+ if (field.type === "secret") setClearingKey(key, false);+ if (value === true && name === entry.configuration.switch) {+ offerBackend(entry);+ }+ }}+ onClearingChange={(on) => setClearingKey(key, on)}+ disabled={busy !== null}+ locale={locale}+ />+ );};+ const setClearingKey = (key: string, on: boolean) =>+ setClearing((prev) => {+ const next = new Set(prev);+ if (on) next.add(key);+ else next.delete(key);+ return next;+ });- /** An entry's title, its store name, its description and its notices. */- const heading = (entry: PluginConfigEntry, nested: boolean) => {- const description = localized(- entry.configuration.description,- entry.configuration.descriptionZh,- );+ /** An entry's fields in declaration order: the basic ones, then the Advanced fold, if any. */+ const fields = (entry: PluginConfigEntry) => {+ const all = drawnFields(entry, drafts[entry.name]);+ const advanced = all.filter(([, field]) => field.advanced === true);return (- <div className="space-y-1.5">- <div>- <p className={nested ? "text-xs font-semibold" : "text-sm font-semibold"}>- {localized(entry.configuration.title, entry.configuration.titleZh) ?? entry.name}- </p>- <p className="font-mono text-xs text-gray-500 dark:text-gray-400">{entry.name}</p>- {description !== undefined && (- <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">{description}</p>- )}- </div>- {(entry.actions ?? []).length > 0 && (- <div className="space-y-2">- {(entry.actions ?? []).map((action) => {- const description = localized(action.description, action.descriptionZh);- return (- <div key={action.id} className="flex items-start gap-3">- <Button- size="sm"- variant="secondary"- disabled={busy !== null}- onClick={() => void runAction(entry, action.id)}- >- {localized(action.title, action.titleZh) ?? action.title}- </Button>- {description !== undefined && (- <p className="text-xs text-gray-500 dark:text-gray-400">{description}</p>- )}- </div>- );- })}- </div>- )}- {(entry.notices ?? []).map((notice, i) =>- notice.tone === "progress" ? (- <p key={i} className={`flex items-center gap-2 text-xs ${toneInk.busy}`}>- <Spinner size="sm" label={S.common.loading} />- <span className="min-w-0 break-words">{localized(notice.text, notice.textZh)}</span>- </p>- ) : notice.tone === "attention" ? (- <NoticeStrip tone="attention" as="p" key={i} className="rounded-md px-3 py-2 text-xs">- {localized(notice.text, notice.textZh)}- </NoticeStrip>- ) : (- <p key={i} className="text-xs text-gray-500 dark:text-gray-400">- {localized(notice.text, notice.textZh)}- </p>- ),+ <>+ {all.filter(([, field]) => field.advanced !== true).map(([n, f]) => control(entry, n, f))}+ {advanced.length > 0 && (+ <AdvancedFold>{advanced.map(([n, f]) => control(entry, n, f))}</AdvancedFold>)}- </div>+ </>);};@@ -566,19 +476,29 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {data-plugin-config={card.name}className="space-y-3 rounded-md border border-gray-200 p-4 dark:border-gray-800">- {heading(card, false)}- {Object.entries(card.configuration.properties).map(([name, field]) =>- control(card, name, field),- )}- {children.map((child) => (+ <ConfigHeading+ entry={card}+ draft={drafts[card.name]}+ nested={false}+ disabled={busy !== null}+ onAction={(action) => askAction(card, action)}+ locale={locale}+ />+ {fields(card)}+ {(switchedOff(card, drafts[card.name]) ? [] : children).map((child) => (<divkey={child.name}className="space-y-3 border-t border-gray-100 pt-3 dark:border-gray-800/60">- {heading(child, true)}- {Object.entries(child.configuration.properties).map(([name, field]) =>- control(child, name, field),- )}+ <ConfigHeading+ entry={child}+ draft={drafts[child.name]}+ nested+ disabled={busy !== null}+ onAction={(action) => askAction(child, action)}+ locale={locale}+ />+ {fields(child)}</div>))}<div className="flex justify-end">@@ -594,6 +514,36 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {</section>);})}+ <ConfirmModal+ open={pendingAction !== null}+ title={S.settings.pluginActionTitle}+ tone="primary"+ onClose={() => setPendingAction(null)}+ onConfirm={() => {+ if (pendingAction !== null) void runAction(pendingAction.entry, pendingAction.id);+ setPendingAction(null);+ }}+ confirmLabel={S.settings.pluginActionRun}+ cancelLabel={S.common.cancel}+ >+ <p className="text-sm text-gray-600 dark:text-gray-300">+ {pendingAction !== null+ ? S.settings.pluginActionConfirm(+ pendingAction.title,+ machine === null ? null : nameOf(machine),+ )+ : ""}+ </p>+ </ConfirmModal>+ <SandboxBackendPrompt+ pkg={offered}+ machineName={machine === null ? S.plugins.thisServer : nameOf(machine)}+ busy={installing}+ onInstall={(dontAskAgain) => void installOffered(dontAskAgain)}+ onLater={(dontAskAgain) => {+ if (!installing) closePrompt(dontAskAgain);+ }}+ /></SettingsSection>);}diff --git a/packages/web/src/features/settings/sandbox-backend-prompt.tsx b/packages/web/src/features/settings/sandbox-backend-prompt.tsxnew file mode 100644index 00000000..a3fcd795--- /dev/null+++ b/packages/web/src/features/settings/sandbox-backend-prompt.tsx@@ -0,0 +1,50 @@+/**+ * The question the Sandbox card asks when its switch is turned on and the machine has no+ * sandbox backend for its OS: install this OS's default one? Install / Not now, plus "Don't+ * ask again" for this machine (lib/sandbox-backend-prompt.ts keeps that in this browser).+ *+ * The answer never touches the switch: it stays on in the card either way, and the card's Save+ * stores it. Installing goes through the Plugins page's own install, so it carries that page's+ * cost, which the body says: the App is re-assembled, stopping runs in progress.+ */+import { useState } from "react";+import { Checkbox, ConfirmModal, ICONS } from "@lmliheng/penguin-ui";+import { S } from "../../lib/strings";++export function SandboxBackendPrompt({+ pkg,+ machineName,+ busy,+ onInstall,+ onLater,+}: {+ /** The package to offer; null keeps the dialog closed. */+ pkg: string | null;+ /** The machine the card is editing, as the picker names it. */+ machineName: string;+ busy: boolean;+ onInstall: (dontAskAgain: boolean) => void;+ onLater: (dontAskAgain: boolean) => void;+}) {+ const [dontAsk, setDontAsk] = useState(false);+ const P = S.settings.sandboxBackendPrompt;+ return (+ <ConfirmModal+ open={pkg !== null}+ title={P.title}+ tone="primary"+ glyph={ICONS.download}+ busy={busy}+ confirmLabel={busy ? P.installing : P.install}+ cancelLabel={P.later}+ onConfirm={() => onInstall(dontAsk)}+ onClose={() => onLater(dontAsk)}+ >+ <div className="space-y-2 text-sm">+ <p>{P.body(machineName, pkg ?? "")}</p>+ <p className="text-xs text-fg-muted">{P.cost}</p>+ <Checkbox checked={dontAsk} disabled={busy} label={P.dontAsk} onChange={setDontAsk} />+ </div>+ </ConfirmModal>+ );+}diff --git a/packages/web/src/lib/install-scope.ts b/packages/web/src/lib/install-scope.tsindex 7e28b43b..e6aedbbd 100644--- a/packages/web/src/lib/install-scope.ts+++ b/packages/web/src/lib/install-scope.ts@@ -271,6 +271,12 @@ export const KEY_RULES: readonly KeyRule[] = [scope: "install",why: "The Sessions each machine was last seen holding, shown until its connection is held again. Project id and machine id in the key, Session ids in the value — a new root knows none of them.",},+ {+ kind: "exact",+ key: "penguin.sandboxBackendPromptDismissed",+ scope: "install",+ why: "The machines whose Sandbox card no longer offers to install a backend — machine ids of this root.",+ },{kind: "family",key: "penguin.machineAgents.",diff --git a/packages/web/src/lib/permission-level.ts b/packages/web/src/lib/permission-level.tsindex 81499827..5ab6e1d1 100644--- a/packages/web/src/lib/permission-level.ts+++ b/packages/web/src/lib/permission-level.ts@@ -9,7 +9,12 @@* tool call approved without asking.* - `partial`: some write permission, with something still holding it back.*/-import type { ApprovalMode, SessionSandbox } from "@lmliheng/penguin-server/api";+import type {+ ApprovalMode,+ SessionSandbox,+ SessionSandboxPreset,+} from "@lmliheng/penguin-server/api";+import { ICONS } from "@lmliheng/penguin-ui";import type { Tone } from "./tone";export type PermissionLevel = "all" | "partial" | "read-only" | "off";@@ -100,3 +105,252 @@ export function networkBlock(/** What a Session starts from when the server has not said: confinement off, network open. */export const UNCONFINED: SessionSandbox = { mode: "danger-full-access", network: "open" };++/**+ * One pick from the composer's menu: a preset's three values, saved together — or, with the+ * Sandbox switch off, the approval mode alone (`sandbox` absent). An approval-mode pick never+ * carries the policy: echoing the current one back would pin it in a draft (a later switch-on+ * then sends an unconfined level a member may not have) and re-check it on a Session (one+ * holding `local` on a server that cannot enforce it could not change its mode at all).+ */+export interface PermissionPick {+ approvalMode: ApprovalMode;+ sandbox?: Pick<SessionSandbox, "mode" | "network">;+}++/** A preset's pick: its approval mode and its policy together. */+export function presetPick(p: SessionSandboxPreset): PermissionPick {+ return { approvalMode: p.approvalMode, sandbox: { mode: p.mode, network: p.network } };+}++/** An approval-mode pick (switch off): the mode alone, the policy untouched. */+export function approvalModePick(mode: ApprovalMode): PermissionPick {+ return { approvalMode: mode };+}++/** A draft's sandbox pick after `pick`: only a preset pick changes it. */+export function draftSandboxAfter(+ prev: Partial<SessionSandbox>,+ pick: PermissionPick,+): Partial<SessionSandbox> {+ return pick.sandbox === undefined ? prev : { ...prev, ...pick.sandbox };+}++/**+ * The presets a server that does not report its own gets: the Sandbox card's declared table+ * (server `sandbox/settings-store.ts`), copied because an older server cannot send it. Kept+ * in step with that declaration by hand; it only matters until every server reports `presets`.+ */+export const BUILTIN_PRESETS: readonly SessionSandboxPreset[] = [+ {+ id: "full-access",+ name: "Full Access",+ nameZh: "完全访问",+ enabled: true,+ mode: "danger-full-access",+ network: "open",+ approvalMode: "allow-all",+ },+ {+ id: "always-ask",+ name: "Always Ask",+ nameZh: "每次询问",+ enabled: true,+ mode: "danger-full-access",+ network: "open",+ approvalMode: "always-ask",+ },+ {+ id: "workspace-write",+ name: "Workspace Write",+ nameZh: "仅工作区可写",+ enabled: true,+ mode: "workspace-write",+ network: "open",+ approvalMode: "allow-all",+ },+ {+ id: "read-only",+ name: "Read Only",+ nameZh: "只读",+ enabled: true,+ mode: "read-only",+ network: "open",+ approvalMode: "allow-all",+ },+ {+ id: "workspace-write-ask",+ name: "Workspace Write with Ask",+ nameZh: "仅工作区可写并询问",+ enabled: false,+ mode: "workspace-write",+ network: "open",+ approvalMode: "always-ask",+ },+ {+ id: "denied-all",+ name: "Denied All",+ nameZh: "全部拒绝",+ enabled: false,+ mode: "danger-full-access",+ network: "open",+ approvalMode: "deny-all",+ },+];++/** The presets the composer offers and names levels by: the server's, else the built-in table. */+export function presetsOf(sandbox: SessionSandbox): readonly SessionSandboxPreset[] {+ return sandbox.presets ?? BUILTIN_PRESETS;+}++/**+ * The preset a Session's level is: the first row, in table order, holding all three of its+ * values — a disabled row counts too. Null when none does (a level set from the full settings+ * or by an older client), which the composer shows as custom rather than rounding it to a row.+ */+export function matchPreset(+ presets: readonly SessionSandboxPreset[],+ approval: ApprovalMode,+ sandbox: Pick<SessionSandbox, "mode" | "network">,+): SessionSandboxPreset | null {+ return (+ presets.find(+ (p) =>+ p.approvalMode === approval && p.mode === sandbox.mode && p.network === sandbox.network,+ ) ?? null+ );+}++/**+ * The rows the composer's menu lists, in table order: the enabled presets whose approval mode+ * the Session may be given (`approvalModes`, from `approvalModeChoices`). An organization's+ * Session leaves out `always-ask`, so its presets are not offered there either — except the+ * current preset, which stays listed and ticked rather than leaving the menu with nothing+ * selected, the same exception the approval-mode list makes for its current value.+ */+export function menuPresets(+ presets: readonly SessionSandboxPreset[],+ approvalModes: readonly ApprovalMode[],+ current: SessionSandboxPreset | null,+): SessionSandboxPreset[] {+ return presets.filter(+ (p) => p.enabled && (p.id === current?.id || approvalModes.includes(p.approvalMode)),+ );+}++/**+ * Whether the server's Sandbox switch is off: new Sessions start unconfined, and the menu+ * offers the approval modes alone. Only an explicit false counts — a server that does not+ * report the switch keeps the presets menu it always had.+ */+export function sandboxSwitchOff(sandbox: Pick<SessionSandbox, "switchOn">): boolean {+ return sandbox.switchOn === false;+}++/** One row of the composer's permission menu. */+export type PermissionMenuRow =+ { kind: "preset"; preset: SessionSandboxPreset } | { kind: "approval"; mode: ApprovalMode };++/**+ * What the composer's permission menu lists. With the Sandbox switch on, the presets+ * (`menuPresets`); with it off, the approval modes the Session may be given, in the picker's+ * order — a pick then changes only the approval mode and keeps the Session's own policy, which+ * a Session created while the switch was on still holds.+ */+export function permissionMenu(+ sandbox: SessionSandbox,+ approvalModes: readonly ApprovalMode[],+ current: SessionSandboxPreset | null,+): PermissionMenuRow[] {+ if (sandboxSwitchOff(sandbox)) {+ return approvalModes.map((mode) => ({ kind: "approval", mode }));+ }+ return menuPresets(presetsOf(sandbox), approvalModes, current).map((preset) => ({+ kind: "preset",+ preset,+ }));+}++/**+ * Why a preset cannot be picked: a `LevelBlock` (this server cannot enforce it), or+ * `above-ceiling` — wider than the server's sandbox settings, which only an administrator may go+ * past (the server marks such a row `aboveCeiling` and refuses a non-admin's pick of it).+ */+export type PresetBlock = LevelBlock | "above-ceiling";++/** Who is picking: whether an administrator, and the preset the Session is on, if any. */+export interface PresetPicker {+ isAdmin: boolean;+ current: SessionSandboxPreset | null;+}++/**+ * Why a preset cannot be picked, or null when it can: its mode's enforcement block, else its+ * network's, else — given who is picking — the ceiling, which holds a non-admin only and never on+ * the preset the Session is already on (picking it changes nothing).+ */+export function presetBlock(+ sandbox: SessionSandbox,+ preset: Pick<SessionSandboxPreset, "mode" | "network"> &+ Partial<Pick<SessionSandboxPreset, "id" | "aboveCeiling">>,+ picker?: PresetPicker,+): PresetBlock | null {+ const enforce = fsModeBlock(sandbox, preset.mode) ?? networkBlock(sandbox, preset.network);+ if (enforce !== null) return enforce;+ if (+ picker !== undefined &&+ !picker.isAdmin &&+ preset.aboveCeiling === true &&+ preset.id !== picker.current?.id+ ) {+ return "above-ceiling";+ }+ return null;+}++/** One thing a preset holds back or lets through, as the hover text names it. */+export type PresetEffect =+ | "write-outside-workspace"+ | "write-anywhere"+ | "network"+ | "network-beyond-localhost"+ | "unasked-calls"+ | "unasked-writes"+ | "every-call"+ | "files-everywhere"+ | "files-in-workspace"+ | "read-files"+ | "network-open"+ | "localhost"+ | "calls-unasked"+ | "reads-unasked";++/** What a preset blocks and what it allows, from its three values, for the hover text. */+export function presetEffects(+ preset: Pick<SessionSandboxPreset, "mode" | "network" | "approvalMode">,+): {+ blocks: PresetEffect[];+ allows: PresetEffect[];+} {+ const blocks: PresetEffect[] = [];+ const allows: PresetEffect[] = [];+ if (preset.mode === "workspace-write") {+ blocks.push("write-outside-workspace");+ allows.push("files-in-workspace");+ } else if (preset.mode === "read-only") {+ blocks.push("write-anywhere");+ allows.push("read-files");+ } else allows.push("files-everywhere");+ if (preset.network === "none") blocks.push("network");+ else if (preset.network === "local") {+ blocks.push("network-beyond-localhost");+ allows.push("localhost");+ } else allows.push("network-open");+ if (preset.approvalMode === "deny-all") blocks.push("every-call");+ else if (preset.approvalMode === "always-ask") blocks.push("unasked-calls");+ else if (preset.approvalMode === "read-only") {+ blocks.push("unasked-writes");+ allows.push("reads-unasked");+ } else allows.push("calls-unasked");+ return { blocks, allows };+}diff --git a/packages/web/src/lib/plugin-config-event.ts b/packages/web/src/lib/plugin-config-event.tsnew file mode 100644index 00000000..01dcecce--- /dev/null+++ b/packages/web/src/lib/plugin-config-event.ts@@ -0,0 +1,31 @@+/**+ * Same-tab notification that a settings group was saved on the Plugins page. The composer's+ * permission menu is drawn from the Sandbox card (its switch, presets, default preset), but+ * reaches it through the Session's and the chat defaults' sandbox view, which a page reads+ * once: without this, a draft or an open conversation kept the menu it had before the save —+ * approval modes only after the switch was turned on, the old presets after an edit — until+ * the page was reloaded. The Plugins page dispatches after its PUT lands; a mounted draft and+ * conversation read their view again.+ */+export const PLUGIN_CONFIG_SAVED_EVENT = "penguin:plugin-config-saved";++export interface PluginConfigSavedDetail {+ /** The saved group's name (`sandbox`), and the card it is drawn in. */+ group: string;+ card: string;+}++export function dispatchPluginConfigSaved(detail: PluginConfigSavedDetail): void {+ window.dispatchEvent(+ new CustomEvent<PluginConfigSavedDetail>(PLUGIN_CONFIG_SAVED_EVENT, { detail }),+ );+}++/** Calls `cb` after every save of the card named `card`; returns the unsubscribe. */+export function onPluginConfigSaved(card: string, cb: () => void): () => void {+ const listener = (e: Event) => {+ if ((e as CustomEvent<PluginConfigSavedDetail>).detail?.card === card) cb();+ };+ window.addEventListener(PLUGIN_CONFIG_SAVED_EVENT, listener);+ return () => window.removeEventListener(PLUGIN_CONFIG_SAVED_EVENT, listener);+}diff --git a/packages/web/src/lib/sandbox-backend-prompt.ts b/packages/web/src/lib/sandbox-backend-prompt.tsnew file mode 100644index 00000000..a4e26d20--- /dev/null+++ b/packages/web/src/lib/sandbox-backend-prompt.ts@@ -0,0 +1,79 @@+/**+ * When the Sandbox card offers to install a sandbox backend: the admin turned the switch on,+ * the machine reports no backend for its OS, it names a package to suggest, and nobody ticked+ * "Don't ask again" for that machine in this browser.+ *+ * The OS and the package come from the server (`PluginConfigEntry.backend`); this module never+ * guesses either. "Don't ask again" is remembered per machine in this browser only — it is a+ * question about this person's prompts, not a setting of the machine — so it is never sent to+ * a server. Storage that is unavailable or throws (a private window, blocked site data) reads+ * as "never dismissed" and drops the write: the prompt then asks again, which is the safe side.+ */+import type { PluginConfigEntry } from "@lmliheng/penguin-server/api";++/** localStorage key: a JSON array of the machine keys whose prompt was dismissed for good. */+export const BACKEND_PROMPT_DISMISSED_KEY = "penguin.sandboxBackendPromptDismissed";++/**+ * The key for the server this page is served from, which has no machine id: the Plugins page's+ * machine-picker value for it too (a machine id is never this short).+ */+export const THIS_SERVER_KEY = "*";++/** The storage this reads and writes — localStorage, or a stub in tests. */+export type PromptStorage = Pick<Storage, "getItem" | "setItem">;++function defaultStorage(): PromptStorage | null {+ try {+ return typeof localStorage === "undefined" ? null : localStorage;+ } catch {+ return null;+ }+}++function dismissedIn(storage: PromptStorage | null): string[] {+ try {+ const raw = storage?.getItem(BACKEND_PROMPT_DISMISSED_KEY);+ const list: unknown = raw ? JSON.parse(raw) : [];+ return Array.isArray(list) ? list.filter((v): v is string => typeof v === "string") : [];+ } catch {+ return [];+ }+}++/** Whether "Don't ask again" was ticked for this machine in this browser. */+export function backendPromptDismissed(+ machine: string,+ storage: PromptStorage | null = defaultStorage(),+): boolean {+ return dismissedIn(storage).includes(machine);+}++/** Remembers "Don't ask again" for this machine; a storage that refuses the write is ignored. */+export function dismissBackendPrompt(+ machine: string,+ storage: PromptStorage | null = defaultStorage(),+): void {+ const list = dismissedIn(storage);+ if (list.includes(machine)) return;+ try {+ storage?.setItem(BACKEND_PROMPT_DISMISSED_KEY, JSON.stringify([...list, machine]));+ } catch {+ // Not remembered: the next switch-on asks again.+ }+}++/**+ * The package to offer when the switch is turned on for this entry on this machine, or null+ * when there is nothing to ask: a backend for the OS is installed, the OS has no default, the+ * server does not report it, or the prompt was dismissed for this machine.+ */+export function backendToOffer(+ entry: Pick<PluginConfigEntry, "backend">,+ machine: string,+ storage: PromptStorage | null = defaultStorage(),+): string | null {+ const report = entry.backend;+ if (report === undefined || report.installed || report.recommended === undefined) return null;+ return backendPromptDismissed(machine, storage) ? null : report.recommended;+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex f5bbc4c2..f2902683 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -445,6 +445,12 @@ export const en: Strings = {pluginSecretClear: "Clear stored value",/** The Plugins settings page's machine picker: each server keeps its own plugin settings. */pluginConfigMachine: "Machine",+ /** A plugin group's action: it runs once on the picked machine, and only the plugin knows what it does. */+ pluginActionTitle: "Run plugin action",+ pluginActionRun: "Run",+ /** `machine` is the picked machine's name, null for this server. */+ pluginActionConfirm: (action: string, machine: string | null): string =>+ `Run "${action}" on ${machine ?? "this server"}? It runs on that machine right away; what it does is up to the plugin.`,/** Under a number field whose box does not parse; the save is not sent. */pluginFieldNotNumber: "Must be a number",uploadLimitsTitle: "Upload limits",@@ -461,6 +467,42 @@ export const en: Strings = {`conversation keep a separate ${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.`,+ /** The fold holding the fields a settings group marks advanced. */+ pluginAdvanced: "Advanced",+ /** A table cell its row does not let change, beside the lock mark. */+ pluginCellLocked: "Locked: this row keeps this value",+ pluginCellOn: "On",+ pluginCellOff: "Off",+ /** A table row's drag handle: what it moves, and how. */+ pluginTableMove: (row: string) => `Move ${row}`,+ pluginTableMoveHint: "Drag, or press the up and down arrow keys",+ /** The add button under an extensible table that names none of its own. */+ pluginTableAdd: "Add a row",+ /** After the chosen row's name (the sandbox's default preset): the row choice's title. */+ pluginTableChosenMarker: (title: string) => `(${title})`,+ /** A table row's "…" button: its accessible name and tooltip. */+ pluginTableRowMenu: (row: string) => `More actions: ${row}`,+ pluginTableRowMenuHint: "More actions",+ /** The row menu's items: make the row the chosen one, and delete a row an administrator added. */+ pluginTableChoose: "Set as default",+ pluginTableChosen: "Already the default",+ pluginTableDelete: "Delete",+ pluginTableDeleteChosen: "Set another row as default first",+ /** One line of a row's "?" that lists its values: a choice column's value, and what it does. */+ pluginTableRowValue: (column: string, value: string, does: string | undefined) =>+ does === undefined ? `${column}: ${value}` : `${column}: ${value}. ${does}`,+ /** Asked when the Sandbox switch is turned on and the machine has no sandbox backend. */+ sandboxBackendPrompt: {+ title: "Install a sandbox backend",+ body: (machine: string, pkg: string) =>+ `${machine} has no sandbox backend for its operating system, so new sessions cannot be confined yet. Install ${pkg}?`,+ cost: "Installing reloads the server's plugins, which stops agent runs in progress in every Project. The switch stays on either way.",+ install: "Install",+ installing: "Installing…",+ later: "Not now",+ dontAsk: "Don't ask again for this machine",+ noProject: "Open a Project first: the backend is installed into the current Project.",+ },theme: "Theme",themeInfo:"The app's overall style: layout, lines, type and motion change with it; content and every other setting stay as they are.",@@ -2760,10 +2802,42 @@ export const en: Strings = {noNetworkUnsupported: "No sandbox backend on this machine can cut the network off",/** The short note beside a level whose enabled backend failed its check. */notAvailable: "Unavailable",+ /** The short note beside a preset wider than the server's sandbox settings, for a non-admin. */+ adminOnly: "Admin only",+ aboveCeiling:+ "Exceeds this server's sandbox ceiling: only an administrator can give a Session this much access.",backendUnavailable: (name: string, reason: string) =>`The sandbox backend ${name} is enabled but not in use: ${reason}. An administrator can fix this on the Sandbox card (More…).`,more: "More…",approval: "Approval",+ /** The button's name for a level no preset matches (set from the full settings, or by an older client). */+ custom: "Custom",+ /** The menu's top line when the Session's policy holds what no preset shows. */+ advancedActive: "Advanced settings in effect",+ advancedHint:+ "This Session also has masked paths or a read-only temp directory, set from the Sandbox card; picking a preset keeps them.",+ /** A preset's hover text: what it blocks, what it allows, and whether this machine can enforce it. */+ blocks: "Blocks",+ allows: "Allows",+ nothing: "nothing",+ enforceable: "This machine can enforce it.",+ needsNoBackend: "Needs no sandbox backend.",+ effects: {+ "write-outside-workspace": "writing outside the workspace",+ "write-anywhere": "writing any file",+ network: "all network access",+ "network-beyond-localhost": "network beyond localhost",+ "unasked-calls": "tool calls without asking (each one asks first)",+ "unasked-writes": "writes without asking (a call that may write asks first)",+ "every-call": "every tool call (all denied)",+ "files-everywhere": "reading and writing any file",+ "files-in-workspace": "writing inside the workspace",+ "read-files": "reading files",+ "network-open": "the full network",+ localhost: "this machine's localhost",+ "calls-unasked": "every tool call, unasked",+ "reads-unasked": "read-only calls, unasked",+ } as Record<string, string>,},approvalModeNames: {"allow-all": "Approve everything",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 9e660e06..39520fa6 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -510,6 +510,12 @@ export const zh = {pluginSecretClear: "清除已存值",/** The Plugins settings page's machine picker: each server keeps its own plugin settings. */pluginConfigMachine: "机器",+ /** A plugin group's action: it runs once on the picked machine, and only the plugin knows what it does. */+ pluginActionTitle: "执行插件操作",+ pluginActionRun: "执行",+ /** `machine` is the picked machine's name, null for this server. */+ pluginActionConfirm: (action: string, machine: string | null): string =>+ `在${machine === null ? "本机" : ` ${machine} `}上执行「${action}」?它会立即在那台机器上运行,具体做什么由插件决定。`,/** Under a number field whose box does not parse; the save is not sent. */pluginFieldNotNumber: "必须是数字",uploadLimitsTitle: "上传限制",@@ -524,6 +530,42 @@ export const zh = {uploadLimitsInfo: (count: number, imageMb: number): string =>`一条消息最多 ${count} 个附件;对话内嵌图片另有 ${imageMb}MB 上限,不随此设置变化——` +`图片会进入对话与轨迹,每次翻阅历史与恢复会话都要重新付出它的体积。`,+ /** The fold holding the fields a settings group marks advanced. */+ pluginAdvanced: "高级选项",+ /** A table cell its row does not let change, beside the lock mark. */+ pluginCellLocked: "已锁定:此行保持这个取值",+ pluginCellOn: "开",+ pluginCellOff: "关",+ /** A table row's drag handle: what it moves, and how. */+ pluginTableMove: (row: string) => `移动 ${row}`,+ pluginTableMoveHint: "拖动,或按上下方向键",+ /** The add button under an extensible table that names none of its own. */+ pluginTableAdd: "添加一行",+ /** After the chosen row's name (the sandbox's default preset): the row choice's title. */+ pluginTableChosenMarker: (title: string) => `(${title})`,+ /** A table row's "…" button: its accessible name and tooltip. */+ pluginTableRowMenu: (row: string) => `更多操作:${row}`,+ pluginTableRowMenuHint: "更多操作",+ /** The row menu's items: make the row the chosen one, and delete a row an administrator added. */+ pluginTableChoose: "设为默认",+ pluginTableChosen: "已是默认",+ pluginTableDelete: "删除",+ pluginTableDeleteChosen: "请先把其他行设为默认",+ /** One line of a row's "?" that lists its values: a choice column's value, and what it does. */+ pluginTableRowValue: (column: string, value: string, does: string | undefined) =>+ does === undefined ? `${column}:${value}` : `${column}:${value}。${does}`,+ /** Asked when the Sandbox switch is turned on and the machine has no sandbox backend. */+ sandboxBackendPrompt: {+ title: "安装沙盒后端",+ body: (machine: string, pkg: string) =>+ `${machine} 没有适用于其操作系统的沙盒后端,新会话暂时无法进入沙盒。是否安装 ${pkg}?`,+ cost: "安装会重新装载服务器的插件,所有项目中正在进行的 Agent 运行都会停止。无论是否安装,开关都保持打开。",+ install: "安装",+ installing: "正在安装…",+ later: "暂不",+ dontAsk: "此机器不再询问",+ noProject: "请先打开一个项目:后端会安装到当前项目。",+ },theme: "主题",themeInfo: "应用的整体风格:布局、线条、字体与动效随之改变,内容与其他设置不受影响。",/** Display names of the three themes; the ids stay github / modern / geek. */@@ -2815,10 +2857,36 @@ export const zh = {"本服务器没有安装沙盒后端,命令无法被封禁。管理员可在插件页启用适用于本平台的后端(更多…)。",noNetworkUnsupported: "本机的沙盒后端不支持断开网络",notAvailable: "不可用",+ adminOnly: "仅管理员",+ aboveCeiling: "超出了本服务器的沙盒上限:只有管理员可以给会话这么大的权限。",backendUnavailable: (name: string, reason: string) =>`沙盒后端 ${name} 已启用但未在用:${reason}。管理员可在「更多…」里的沙盒卡片处理。`,more: "更多…",approval: "审批",+ custom: "自定义",+ advancedActive: "高级设置生效中",+ advancedHint: "本会话另有屏蔽路径或只读的临时目录,来自沙盒卡片;选择预设会保留它们。",+ blocks: "封住",+ allows: "放开",+ nothing: "无",+ enforceable: "本机可以实施。",+ needsNoBackend: "不需要沙盒后端。",+ effects: {+ "write-outside-workspace": "写工作区之外",+ "write-anywhere": "写任何文件",+ network: "全部网络",+ "network-beyond-localhost": "本机 localhost 之外的网络",+ "unasked-calls": "不经询问的工具调用(每次调用先问)",+ "unasked-writes": "不经询问的写入(可能写入的调用先问)",+ "every-call": "每一次工具调用(全部拒绝)",+ "files-everywhere": "读写任何文件",+ "files-in-workspace": "写工作区之内",+ "read-files": "读取文件",+ "network-open": "完整网络",+ localhost: "本机 localhost",+ "calls-unasked": "所有工具调用,不经询问",+ "reads-unasked": "只读调用,不经询问",+ } as Record<string, string>,},/** Short description (the trigger button shows only the description, not the mode id). */approvalModeNames: {diff --git a/packages/web/test/advanced-fold.test.ts b/packages/web/test/advanced-fold.test.tsnew file mode 100644index 00000000..095aa87e--- /dev/null+++ b/packages/web/test/advanced-fold.test.ts@@ -0,0 +1,26 @@+// The settings card's Advanced fold: collapsed by default, its panel in the DOM but hidden.+import { describe, expect, it } from "vitest";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { AdvancedFold } from "../src/features/settings/advanced-fold";++const render = (defaultOpen?: boolean) =>+ renderToStaticMarkup(+ createElement(AdvancedFold, {+ ...(defaultOpen === undefined ? {} : { defaultOpen }),+ children: createElement("p", null, "masked paths"),+ }),+ );++describe("the Advanced fold", () => {+ it.each([+ [undefined, "false", true],+ [true, "true", false],+ ] as const)("defaultOpen %s: aria-expanded=%s, panel hidden: %s", (open, expanded, hidden) => {+ const html = render(open);+ const id = new RegExp(`aria-expanded="${expanded}"[^>]*aria-controls="([^"]+)"`).exec(html)![1];+ const panel = new RegExp(`<div id="${id}"[^>]*>`).exec(html)![0];+ expect(panel.includes("hidden")).toBe(hidden);+ expect(html).toContain("masked paths");+ });+});diff --git a/packages/web/test/permission-level.test.ts b/packages/web/test/permission-level.test.tsindex 278fb463..8c517bda 100644--- a/packages/web/test/permission-level.test.ts+++ b/packages/web/test/permission-level.test.ts@@ -8,14 +8,21 @@* - Each level wears its own glyph, so the level never depends on colour alone.*/import { describe, expect, it } from "vitest";-import type { SessionSandbox } from "@lmliheng/penguin-server/api";+import type { ApprovalMode, SessionSandbox } from "@lmliheng/penguin-server/api";import {+ BUILTIN_PRESETS,PERMISSION_LEVEL_GLYPH,firstUnavailableBackend,fsModeBlock,+ matchPreset,+ menuPresets,networkBlock,permissionLevel,+ presetBlock,+ presetEffects,+ presetsOf,} from "../src/lib/permission-level";+import { APPROVAL_MODES, approvalModeChoices } from "../src/features/chat/approval-mode";const FULL: SessionSandbox = { mode: "danger-full-access", network: "open" };@@ -114,3 +121,122 @@ describe("permission level", () => {expect(new Set(glyphs).size).toBe(4);});});++describe("the composer's presets", () => {+ const byId = (id: string) => BUILTIN_PRESETS.find((p) => p.id === id)!;+ const MENU = ["full-access", "always-ask", "workspace-write", "read-only"];++ // A level set from the full settings is custom (null), never rounded to a row; disabled rows still name it.+ it.each([+ ["allow-all", {}, "full-access"],+ ["always-ask", {}, "always-ask"],+ ["allow-all", { mode: "read-only" }, "read-only"],+ ["deny-all", {}, "denied-all"],+ ["allow-all", { network: "none" }, undefined],+ ["read-only", {}, undefined],+ ] as const)("names %s over %o as %s", (approval, over, id) => {+ expect(matchPreset(BUILTIN_PRESETS, approval, { ...FULL, ...over })?.id).toBe(id);+ });++ it("names a level held by two rows by table order", () => {+ const twice = [+ { ...byId("always-ask"), id: "first" },+ { ...byId("always-ask"), id: "second", enabled: false },+ ];+ expect(matchPreset(twice, "always-ask", FULL)?.id).toBe("first");+ expect(matchPreset(twice.slice().reverse(), "always-ask", FULL)?.id).toBe("second");+ });++ it("offers the server's table when it reports one, else the built-in four", () => {+ const renamed = [{ ...byId("full-access"), name: "Anything goes" }];+ expect(presetsOf({ ...FULL, presets: renamed })).toBe(renamed);+ expect(presetsOf(FULL)).toBe(BUILTIN_PRESETS);+ expect(BUILTIN_PRESETS.filter((p) => p.enabled).map((p) => p.id)).toEqual(MENU);+ });++ // An organization's Session is never offered always-ask, unless it is the current preset;+ // a disabled row stays out even when current.+ const org = approvalModeChoices("org", "allow-all");+ it.each([+ [APPROVAL_MODES, "full-access", MENU],+ [org, "full-access", MENU.filter((id) => id !== "always-ask")],+ [org, null, MENU.filter((id) => id !== "always-ask")],+ [["allow-all"] as ApprovalMode[], "always-ask", MENU],+ [APPROVAL_MODES, "denied-all", MENU],+ ])("menu for modes %j, current %s", (modes, current, expected) => {+ const cur = current === null ? null : byId(current);+ expect(menuPresets(BUILTIN_PRESETS, modes, cur).map((p) => p.id)).toEqual(expected);+ });++ it("greys out a preset this server cannot enforce", () => {+ const blocks = (sandbox: SessionSandbox) =>+ Object.fromEntries(BUILTIN_PRESETS.map((p) => [p.id, presetBlock(sandbox, p)]));+ const none: SessionSandbox = {+ ...FULL,+ confinementSupported: false,+ noNetworkSupported: false,+ localNetworkSupported: false,+ unavailableBackends: [],+ };+ // No backend: every confining preset; filesystem-only: only the network cut.+ expect(blocks(none)).toMatchObject({ "full-access": null, "read-only": "no-backend" });+ expect(blocks(none)["workspace-write-ask"]).toBe("no-backend");+ const fsOnly: SessionSandbox = { ...none, confinementSupported: true };+ expect(Object.values(blocks(fsOnly)).every((b) => b === null)).toBe(true);+ expect(presetBlock(fsOnly, { mode: "read-only", network: "none" })).toBe("none-unsupported");+ const all = { ...fsOnly, noNetworkSupported: true, localNetworkSupported: true };+ expect(presetBlock(all, { mode: "workspace-write", network: "local" })).toBeNull();+ // An older server without the flags: nothing second-guessed but local.+ expect(Object.values(blocks(FULL)).every((b) => b === null)).toBe(true);+ expect(presetBlock(FULL, { mode: "read-only", network: "local" })).toBe("local-unsupported");+ });++ it("greys out a preset above the ceiling for a non-admin, never for an admin or the current one", () => {+ const presets = BUILTIN_PRESETS.map((p) =>+ p.mode === "danger-full-access" ? { ...p, aboveCeiling: true as const } : p,+ );+ const sandbox: SessionSandbox = {+ mode: "workspace-write",+ network: "open",+ confinementSupported: true,+ presets,+ };+ const blocked = (isAdmin: boolean, currentId: string | null) =>+ presets+ .filter((p) => presetBlock(sandbox, p, { isAdmin, current: byId(currentId ?? "") ?? null }))+ .map((p) => p.id);+ expect(presetBlock(sandbox, presets[0]!, { isAdmin: false, current: null })).toBe(+ "above-ceiling",+ );+ expect(blocked(false, "workspace-write")).toEqual(["full-access", "always-ask", "denied-all"]);+ expect(blocked(true, "workspace-write")).toEqual([]);+ expect(blocked(false, "always-ask")).toEqual(["full-access", "denied-all"]);+ // Unenforceable says that first, whoever picks it.+ const none = { ...sandbox, confinementSupported: false };+ expect(presetBlock(none, byId("read-only"), { isAdmin: true, current: null })).toBe(+ "no-backend",+ );+ });++ it.each([+ [byId("full-access"), [], ["files-everywhere", "network-open", "calls-unasked"]],+ [byId("always-ask"), ["unasked-calls"], ["files-everywhere", "network-open"]],+ [+ byId("workspace-write-ask"),+ ["write-outside-workspace", "unasked-calls"],+ ["files-in-workspace", "network-open"],+ ],+ [+ { mode: "read-only", network: "local", approvalMode: "read-only" } as const,+ ["write-anywhere", "network-beyond-localhost", "unasked-writes"],+ ["read-files", "localhost", "reads-unasked"],+ ],+ ])("says what %o blocks and allows", (preset, blocks, allows) => {+ expect(presetEffects(preset)).toEqual({ blocks, allows });+ });++ it("says denied-all blocks every call and a closed network blocks the network", () => {+ expect(presetEffects(byId("denied-all")).blocks).toEqual(["every-call"]);+ expect(presetEffects({ ...byId("full-access"), network: "none" }).blocks).toEqual(["network"]);+ });+});diff --git a/packages/web/test/permission-menu.test.ts b/packages/web/test/permission-menu.test.tsnew file mode 100644index 00000000..b6818840--- /dev/null+++ b/packages/web/test/permission-menu.test.ts@@ -0,0 +1,64 @@+/**+ * What the composer's permission menu lists by the server's Sandbox switch: approval modes alone+ * while it is off, presets while it is on or unreported. An approval-mode pick carries no policy.+ */+import { describe, expect, it } from "vitest";+import type { ApprovalMode, SessionSandbox } from "@lmliheng/penguin-server/api";+import {+ BUILTIN_PRESETS,+ approvalModePick,+ draftSandboxAfter,+ permissionMenu,+ presetPick,+} from "../src/lib/permission-level";+import { APPROVAL_MODES, approvalModeChoices } from "../src/features/chat/approval-mode";++const UNCONFINED: SessionSandbox = { mode: "danger-full-access", network: "open" };+const ids = (sandbox: SessionSandbox, modes: readonly ApprovalMode[] = APPROVAL_MODES) =>+ permissionMenu(sandbox, modes, null).map((r) => (r.kind === "preset" ? r.preset.id : r.mode));++describe("the permission menu by the Sandbox switch", () => {+ it("lists the approval modes alone while the switch is off, always-ask withheld from an org", () => {+ const off = { ...UNCONFINED, switchOn: false };+ expect(permissionMenu(off, APPROVAL_MODES, null)).toEqual(+ APPROVAL_MODES.map((mode) => ({ kind: "approval", mode })),+ );+ expect(ids(off, approvalModeChoices("org", "allow-all"))).toEqual([+ "read-only",+ "allow-all",+ "deny-all",+ ]);+ });++ it("lists the menu's presets in table order while the switch is on or unreported", () => {+ const inMenu = BUILTIN_PRESETS.filter((p) => p.enabled).map((p) => p.id);+ expect(ids({ ...UNCONFINED, switchOn: true })).toEqual(inMenu);+ expect(ids(UNCONFINED)).toEqual(inMenu);+ const preset = (id: string, enabled: boolean) => ({+ ...BUILTIN_PRESETS[0]!,+ id,+ name: id,+ enabled,+ });+ const presets = [preset("mine", true), preset("read-only", true), preset("denied-all", false)];+ expect(ids({ ...UNCONFINED, switchOn: true, presets })).toEqual(["mine", "read-only"]);+ });+});++describe("what a pick from the menu carries", () => {+ it("an approval-mode pick sends the mode alone and leaves a draft's sandbox as it was", () => {+ const pick = approvalModePick("always-ask");+ expect(pick).toEqual({ approvalMode: "always-ask" });+ expect("sandbox" in pick).toBe(false);+ expect(draftSandboxAfter({}, pick)).toEqual({});+ expect(draftSandboxAfter({ mode: "read-only" }, pick)).toEqual({ mode: "read-only" });+ });++ it("a preset pick sends its approval mode and its policy together", () => {+ const readOnly = BUILTIN_PRESETS.find((p) => p.id === "read-only")!;+ const { approvalMode, mode, network } = readOnly;+ const pick = presetPick(readOnly);+ expect(pick).toEqual({ approvalMode, sandbox: { mode, network } });+ expect(draftSandboxAfter({}, pick)).toEqual({ mode, network });+ });+});diff --git a/packages/web/test/plugin-config-card.test.ts b/packages/web/test/plugin-config-card.test.tsnew file mode 100644index 00000000..cf200a0f--- /dev/null+++ b/packages/web/test/plugin-config-card.test.ts@@ -0,0 +1,240 @@+/**+ * What the Sandbox card draws from its entry and draft: the switch alone while off, the table's+ * name boxes, "?"s, "(Default)" mark, row menus, pin toggles and locked cells.+ */+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import type { ReactElement } from "react";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import type { PluginConfigEntry, PluginConfigField } from "@lmliheng/penguin-server/api";+import { setActiveStrings, zh } from "../src/lib/strings";+import { en } from "../src/lib/strings-en";+import { drawnFields } from "../src/features/settings/plugin-config-draft";+import { rowHelp } from "../src/features/settings/plugin-config-field-cell";+import { ConfigHeading } from "../src/features/settings/plugin-config-heading";+import { rowActions } from "../src/features/settings/plugin-config-row-menu";+import { ConfigTable } from "../src/features/settings/plugin-config-table";+import { PinToggle } from "../src/features/settings/plugin-config-table-cells";++const ENTRY: PluginConfigEntry = {+ name: "sandbox",+ configuration: {+ title: "Sandbox",+ switch: "enabled",+ properties: {+ enabled: { type: "boolean", title: "Enable" },+ presets: { type: "table", title: "Presets", rowChoice: { field: "pick", title: "Default" } },+ pick: { type: "enum", title: "Default", options: [{ value: "a", title: "A" }] },+ masks: { type: "list", title: "Masked paths", advanced: true },+ },+ },+ values: {},+ notices: [+ { tone: "attention", text: "No usable backend" },+ { tone: "muted", text: "Backends: none" },+ ],+ actions: [{ id: "setup", title: "Set up" }],+};++const heading = (draft: Record<string, unknown>, entry = ENTRY) =>+ renderToStaticMarkup(+ createElement(ConfigHeading, {+ entry,+ draft,+ nested: false,+ disabled: false,+ onAction: () => {},+ locale: "en",+ }),+ );++describe("the settings card", () => {+ beforeAll(() => setActiveStrings(en));+ afterAll(() => setActiveStrings(zh));++ it("draws the switch alone while it is off, and everything else once it is on", () => {+ const names = (draft: Record<string, unknown>) => drawnFields(ENTRY, draft).map(([n]) => n);+ expect(names({})).toEqual(["enabled"]);+ // The row choice's field is drawn only as the table's marker.+ expect(names({ enabled: true })).toEqual(["enabled", "presets", "masks"]);+ for (const text of ["No usable backend", "Backends: none", "Set up"]) {+ expect(heading({ enabled: false })).not.toContain(text);+ expect(heading({ enabled: true })).toContain(text);+ }+ expect(heading({ enabled: false })).toContain("Sandbox");+ });++ it("holds the effective name in the name box, the declared one when not renamed", () => {+ const html = renderTable(PRESETS, { b: { name: "Look only", mode: "ro", enabled: false } });+ // A wrapping box: a <textarea>, whose value renders as its content.+ const box = (row: string) =>+ new RegExp(`<textarea[^>]*aria-label="${row} · Name"[^>]*>([^<]*)<`).exec(html) ?? [];+ expect(box("Full Access")[1]).toBe("Full Access");+ expect(box("Look only")[1]).toBe("Look only");+ expect(box("Look only")[0]).toContain('rows="1"');+ expect(box("Read Only")[0]).toBeUndefined();+ expect(html).not.toContain("placeholder=");+ });++ it('puts every description behind a "?" beside its title, never on screen', () => {+ const configuration = { ...ENTRY.configuration, description: "Card meaning" };+ const html = heading({}, { ...ENTRY, configuration }) + renderTable(PRESETS);+ for (const title of ["Sandbox", "Presets", "Name", "Files", "Pin"]) {+ expect(html).toContain(`aria-label="More info: ${title}"`);+ }+ expect(html).not.toMatch(/(Card|Table|Name|Files|Pin) meaning/);+ });++ it('marks the chosen row "(Default)" after its name, with no Default column or star', () => {+ const html = renderTable(PRESETS);+ expect(html.match(/\(Default\)/g)).toHaveLength(1);+ const at = html.indexOf('aria-label="Full Access · Name"');+ expect(html.indexOf("(Default)", at)).toBeLessThan(html.indexOf("Read Only", at));+ expect(html).not.toContain(">Default<");+ expect(html).not.toContain('data-tooltip="Already');+ // In Chinese, with the title's Chinese and full-width brackets.+ setActiveStrings(zh);+ try {+ const rowChoice = { field: "pick", title: "Default", titleZh: "默认" };+ expect(renderTable({ ...PRESETS, rowChoice }, {}, "zh")).toContain("(默认)");+ } finally {+ setActiveStrings(en);+ }+ });++ it('gives every row a "?" saying what the row is for', () => {+ expect(renderTable(PRESETS)).toContain('aria-label="More info: Read Only"');+ const cols = PRESETS.columns!;+ const row = (mode: string) => ({+ id: "b",+ declared: PRESETS.rows![1]!,+ cells: { name: "", mode, enabled: false },+ });+ const same = (text: string) => text;+ // A declared row keeping its choices: its own text; otherwise a line per choice.+ expect(rowHelp(cols, row("ro"), same)).toBe("For looking around");+ expect(rowHelp(cols, row("off"), same)).toEqual(["Files: Off. Writes anywhere."]);+ expect(rowHelp([cols[1]!], { id: "x", cells: { mode: "ro" } }, same)).toEqual([+ "Files: Read-only",+ ]);+ });++ it('gives every row a "…" menu button that announces a menu', () => {+ const html = renderTable(PRESETS);+ const button = /<button[^>]*aria-label="More actions: Read Only"[^>]*>/.exec(html)?.[0];+ expect(button).toContain('aria-haspopup="menu"');+ expect(button).toContain('type="button"');+ expect(button).not.toContain("tabindex");+ });++ it("offers Set as default on every row and Delete on an added row, both run", () => {+ const ran: string[] = [];+ const actions = (chosen: boolean, added: boolean, canChoose = true) =>+ rowActions({+ chosen,+ canChoose,+ added,+ onChoose: () => ran.push("choose"),+ onDelete: () => ran.push("delete"),+ });+ expect(actions(false, false).map((a) => a.id)).toEqual(["choose"]);+ expect(actions(false, false, false)).toEqual([]);+ const added = actions(false, true);+ expect(added.map((a) => [a.id, a.label, a.blocked])).toEqual([+ ["choose", "Set as default", undefined],+ ["delete", "Delete", undefined],+ ]);+ for (const a of added) a.run();+ expect(ran).toEqual(["choose", "delete"]);+ // The chosen row is already the default, and cannot be deleted until another row is.+ expect(actions(true, true).map((a) => a.blocked)).toEqual([+ "Already the default",+ "Set another row as default first",+ ]);+ });++ it("draws a pin column as a pressed or unpressed toggle, and reports the flip", () => {+ const html = renderTable(PRESETS);+ const pin = (row: string) =>+ new RegExp(`<button[^>]*aria-label="${row} · Pin"[^>]*>`).exec(html)?.[0];+ expect(pin("Full Access")).toContain('aria-pressed="true"');+ expect(pin("Read Only")).toContain('aria-pressed="false"');+ const flips: boolean[] = [];+ const toggle = PinToggle({+ label: "Read Only · Pin",+ pinned: false,+ tooltip: "Not in the menu",+ disabled: false,+ onChange: (on) => flips.push(on),+ }) as ReactElement<{ onPress: () => void }>;+ toggle.props.onPress();+ expect(flips).toEqual([true]);+ });++ it("draws a locked cell as its value alone, with no control and no mark", () => {+ const html = renderTable(PRESETS);+ const at = html.indexOf(`data-tooltip="${en.settings.pluginCellLocked}"`);+ const cell = html.slice(at, html.indexOf("</td>", at));+ // Announced as it reads, "locked" in visually hidden text after it.+ expect(cell).toContain(`>Off<span class="sr-only"> (${en.settings.pluginCellLocked})</span>`);+ expect(cell).not.toMatch(/aria-hidden|aria-label|<svg|<button/);+ });+});++/** A presets-like table: a name, a locked enum, a row choice before a pin column. */+const PRESETS: PluginConfigField = {+ type: "table",+ title: "Presets",+ description: "Table meaning",+ rowChoice: { field: "pick", title: "Default" },+ columns: [+ { name: "name", type: "string", title: "Name", description: "Name meaning" },+ {+ name: "mode",+ type: "enum",+ title: "Files",+ description: "Files meaning",+ options: [+ { value: "off", title: "Off", description: "Writes anywhere." },+ { value: "ro", title: "Read-only" },+ ],+ },+ { name: "enabled", type: "boolean", title: "Pin", description: "Pin meaning" },+ ],+ pin: { column: "enabled", on: "Pinned to the menu", off: "Not in the menu" },+ rows: [+ { id: "a", values: { name: "Full Access", mode: "off", enabled: true }, locked: ["mode"] },+ {+ id: "b",+ values: { name: "Read Only", mode: "ro", enabled: false },+ description: "For looking around",+ },+ ],+};++const renderTable = (+ field: PluginConfigField,+ rows: Record<string, Record<string, unknown>> = {},+ locale: "en" | "zh" = "en",+) =>+ renderToStaticMarkup(+ createElement(ConfigTable, {+ entry: ENTRY,+ name: "presets",+ field,+ table: {+ rows: {+ a: { name: "", mode: "off", enabled: true },+ b: { name: "", mode: "ro", enabled: false },+ ...rows,+ },+ added: {},+ order: ["a", "b"],+ },+ onChange: () => {},+ choice: "a",+ errors: [],+ disabled: false,+ locale,+ }),+ );diff --git a/packages/web/test/plugin-config-draft.test.ts b/packages/web/test/plugin-config-draft.test.tsnew file mode 100644index 00000000..ee33ca23--- /dev/null+++ b/packages/web/test/plugin-config-draft.test.ts@@ -0,0 +1,56 @@+// A settings table's draft reads its stored value the way the server's `resolveTable` does:+// locked or refused cells read as declared; malformed added rows are dropped.+import { describe, expect, it } from "vitest";+import type { PluginConfigField } from "@lmliheng/penguin-server/api";+import { tableDraftOf } from "../src/features/settings/plugin-config-draft";++const FIELD: PluginConfigField = {+ type: "table",+ title: "Rows",+ columns: [+ { name: "name", type: "string", title: "Name" },+ {+ name: "level",+ type: "enum",+ title: "Level",+ options: [+ { value: "low", title: "Low" },+ { value: "high", title: "High" },+ ],+ },+ ],+ rows: [+ { id: "a", values: { name: "A", level: "high" }, locked: ["level"] },+ { id: "b", values: { name: "B", level: "low" } },+ ],+ extensible: { add: "Add", values: { name: "New", level: "low" } },+};++describe("a table's draft", () => {+ it("reads a locked cell, or a value its column refuses, as declared", () => {+ const draft = tableDraftOf(FIELD, {+ a: { name: "Mine", level: "low" },+ b: { level: "max" },+ });+ expect(draft.rows).toEqual({+ a: { name: "Mine", level: "high" },+ b: { name: "", level: "low" },+ });+ });++ it("drops the malformed added rows the server's reading drops", () => {+ const draft = tableDraftOf(FIELD, {+ $added: {+ bad: { name: "Bad" },+ worse: { name: "W", level: "max" },+ Upper: { name: "U", level: "low" },+ a: { name: "Shadow", level: "low" },+ list: ["x"],+ ok: { name: "Ok", level: "low", extra: 1 },+ },+ $order: ["ok", "bad", "b"],+ });+ expect(draft.added).toEqual({ ok: { name: "Ok", level: "low" } });+ expect(draft.order).toEqual(["ok", "b", "a"]);+ });+});diff --git a/packages/web/test/sandbox-backend-prompt.test.ts b/packages/web/test/sandbox-backend-prompt.test.tsnew file mode 100644index 00000000..3a8cb0ed--- /dev/null+++ b/packages/web/test/sandbox-backend-prompt.test.ts@@ -0,0 +1,55 @@+/**+ * When the Sandbox card offers to install a backend: only where none for the OS is installed and+ * a default is named; "Don't ask again" holds per machine; broken storage never hides the prompt.+ */+import { describe, expect, it } from "vitest";+import {+ BACKEND_PROMPT_DISMISSED_KEY,+ backendPromptDismissed,+ backendToOffer,+ dismissBackendPrompt,+} from "../src/lib/sandbox-backend-prompt";+import type { PromptStorage } from "../src/lib/sandbox-backend-prompt";++function memoryStorage(): PromptStorage & { data: Map<string, string> } {+ const data = new Map<string, string>();+ return { data, getItem: (k) => data.get(k) ?? null, setItem: (k, v) => void data.set(k, v) };+}++const BWRAP = "@lmliheng/penguin-plugin-sandbox-bwrap";+const MISSING = { backend: { installed: false, recommended: BWRAP } };++describe("the default-backend prompt", () => {+ it.each([+ [MISSING, BWRAP],+ [{ backend: { installed: true, recommended: BWRAP } }, null],+ [{ backend: { installed: false } }, null],+ [{}, null],+ ])("offers %j: %s", (report, offer) => {+ expect(backendToOffer(report, "m1", memoryStorage())).toBe(offer);+ });++ it("remembers don't-ask-again per machine, in this browser's storage only", () => {+ const storage = memoryStorage();+ dismissBackendPrompt("m1", storage);+ dismissBackendPrompt("m1", storage);+ expect(backendToOffer(MISSING, "m1", storage)).toBeNull();+ expect(backendToOffer(MISSING, "m2", storage)).toBe(BWRAP);+ expect(JSON.parse(storage.data.get(BACKEND_PROMPT_DISMISSED_KEY)!)).toEqual(["m1"]);+ });++ it("asks again when storage is unavailable, throws or holds garbage", () => {+ const blocked = () => {+ throw new Error("blocked");+ };+ const throwing: PromptStorage = { getItem: blocked, setItem: blocked };+ expect(() => dismissBackendPrompt("m1", throwing)).not.toThrow();+ expect(backendToOffer(MISSING, "m1", throwing)).toBe(BWRAP);+ expect(backendToOffer(MISSING, "m1", null)).toBe(BWRAP);+ const garbage = memoryStorage();+ garbage.setItem(BACKEND_PROMPT_DISMISSED_KEY, "{not json");+ expect(backendPromptDismissed("m1", garbage)).toBe(false);+ dismissBackendPrompt("m1", garbage);+ expect(backendPromptDismissed("m1", garbage)).toBe(true);+ });+});