A local-first multi-agent app development platform, built on PenguinHarness
feat(web,server,docs): raise attachment limits and make them admin-settable (#350)
Yaowei Zheng0cfc882f5399
diff --git a/changelog/unreleased/2026-08-19-larger-attachments.md b/changelog/unreleased/2026-08-19-larger-attachments.mdnew file mode 100644index 00000000..1599d519--- /dev/null+++ b/changelog/unreleased/2026-08-19-larger-attachments.md@@ -0,0 +1,36 @@+# Larger attachments, with the upload limits in the admin's hands++- **Date:** 2026-08-19+- **Type:** feature+- **Scope:** `server`, `web`, `docs`+- **Issue:** [#345](https://github.com/Prism-Shadow/penguin-harness/issues/345)++[中文版](2026-08-19-larger-attachments.zh.md)++The composer's file attachments were capped at 10MB per file and 12MB per message. The default is now **100MB per file and 120MB per message**, and an admin can change both from the user menu without touching a config file or restarting anything.++## The whole chain moves together, or not at all++The 10MB figure was written down in four independent places — the composer's pre-flight check, the server's per-file cap, and the text of both locales' rejection message — with nothing keeping them in step. Raising one of those numbers on its own is worse than leaving it alone: a client that allows more than the server does replaces a clear "too large" refusal with an upload that runs to completion and then dies on a generic error.++So the number now has one home. The server owns it, `GET /api/me` reports it under `uploadLimits`, and the composer validates against what it was told — which is also the number its message quotes, so the toast cannot claim a limit that is no longer in force.++The **request body cap** is derived rather than fixed, for the same reason. A draft chat has no Session to upload to, so attachments ride the task request itself as base64 `data:` URLs, which inflates them by 4/3; a cap left at 20MB would have rejected a 100MB attachment at the HTTP layer, with a body-shaped error rather than a size-shaped one. It is now `base64(per-message total) + headroom for one inline image and the JSON framing` — about 190MB at the default, and smaller again the moment an admin lowers the limit, so a server whose caps were left low does not keep accepting 300MB bodies.++## Upload limits (admin, user menu)++A new **Upload limits** dialog sits beside Proxy options, built the same way: a form, written by one `PUT /api/admin/settings`, admin-only, with the server as the validating authority.++- **Max attachment size** and **Max total per message**, both whole MB, both bounded to **1–200MB**. An admin typing 100GB — 102400 in a MB field — is refused with the reason under the input, not obeyed. The ceiling is where the transport actually stops working: the body is buffered and JSON-parsed as one string, and V8 caps a string near 512MB.+- The total may not sit below the per-file cap, checked against the **effective** post-write pair — so raising only the per-file cap, or lowering only the total, is refused too rather than quietly producing a configuration in which a legal single attachment cannot be sent.+- Validation precedes every write, so one bad field leaves the others untouched, and the change applies to the next request with no restart: the validators and the body cap both read the setting per request.++Two numbers are deliberately not exposed. The per-message file **count** stays at 20 — it bounds how usable the chip row is, not what the server can survive, which is what the byte budgets are for.++## Inline images keep their own, much lower ceiling++An attachment is not multimodal input: it is written to the Session scratchpad and handed to the model as an `[attached file: <path>]` line, opened with ordinary file tools. Nothing downstream scales with its size, which is what makes 100MB reasonable in the first place.++An inline image is the opposite. It enters the conversation, is written verbatim into the Trace JSONL, and that file is read back whole — into a single JS string — on every history page and every Session resume. A large inline image is not a slow request, it is a Session that never recovers. Images had also never been size-checked at all: the only reason a 50MB paste failed was that the body cap happened to be small, and it failed *after* the tab had base64'd the file and uploaded it.++Images are therefore capped explicitly at **20MB** (413 `image_too_large`), client-side as well as server-side, and that cap does not follow the attachment limit up. It is above what the old body cap effectively allowed, so no paste that worked before stops working. Note this is the transport ceiling, not a promise the model will take the image: providers commonly cap around 5MB, and the `read_image` tool at 5MB, so an image between those numbers and this one uploads fine and may still be refused by the model.diff --git a/changelog/unreleased/2026-08-19-larger-attachments.zh.md b/changelog/unreleased/2026-08-19-larger-attachments.zh.mdnew file mode 100644index 00000000..09ae8e8a--- /dev/null+++ b/changelog/unreleased/2026-08-19-larger-attachments.zh.md@@ -0,0 +1,36 @@+# 更大的附件,以及交到管理员手上的上传限制++- **Date:** 2026-08-19+- **Type:** feature+- **Scope:** `server`, `web`, `docs`+- **Issue:** [#345](https://github.com/Prism-Shadow/penguin-harness/issues/345)++[English](2026-08-19-larger-attachments.md)++输入框的文件附件此前限制为单个 10MB、单条消息合计 12MB。现在默认放宽为**单个 100MB、单条消息合计 120MB**,并且管理员可以直接在用户菜单里调整这两个数值,既不必改配置文件,也不必重启。++## 整条链路要么一起动,要么都不动++10MB 这个数字原本写在四个彼此独立的位置——输入框的预校验、服务端的单文件上限,以及两种语言各自的拒绝文案——之间没有任何东西保证它们同步。此时单独抬高其中一个,比原样不动更糟:客户端一旦比服务端更宽松,用户得到的就不再是一句清晰的「文件过大」,而是一次跑完整程、最后死在通用报错上的上传。++所以这个数字现在只有一个归属。它由服务端持有,经 `GET /api/me` 的 `uploadLimits` 下发,输入框据此校验——提示文案里引用的也是同一个数字,因此不会再出现提示中的上限早已失效的情况。++**请求体上限**同理,改为推导而非固定值。草稿会话尚无 Session 可供上传,附件因此以 base64 `data:` URL 随 Task 请求一起送达,体积膨胀 4/3;若上限仍停在 20MB,100MB 的附件会在 HTTP 层被拒,报出的还是「请求体」而非「文件大小」形态的错误。现在它等于 `base64(单条消息合计上限) + 一张内嵌图片与 JSON 外壳的余量`,默认约 190MB,并在管理员调低上限时随之回落——不会出现上限明明很低、服务器却仍然照单全收 300MB 请求体的情况。++## 上传限制(管理员,用户菜单)++新增的**上传限制**弹窗与「代理选项」并列,做法也完全一致:一个表单,由一次 `PUT /api/admin/settings` 写入,仅管理员可见,校验权在服务端。++- **单个附件上限**与**单条消息附件合计上限**,均以整数 MB 填写,取值范围 **1–200MB**。管理员若把「100GB」按 MB 填成 102400,会被拒绝并在输入框下方给出原因,而不是照单接受。这个天花板划在传输真正失效的位置:请求体被整体缓冲并作为单个字符串 JSON 解析,而 V8 对字符串长度的上限约为 512MB。+- 合计上限不得低于单个上限,且校验针对**生效后**的组合——因此只抬高单个上限、或只调低合计上限,同样会被拒绝,而不是悄悄产生一种「单个合法的附件反而发不出去」的配置。+- 校验一律先于写入,因此一个字段不合法不会影响其余字段;改动在下一次请求即生效,无需重启:校验逻辑与请求体上限都在每次请求时读取该设置。++有两个数值刻意不开放。单条消息的附件**数量**仍固定为 20——它约束的是小卡片一行还好不好用,而不是服务器扛不扛得住,后者是字节预算该管的事。++## 对话内嵌图片保留自己那条低得多的上限++附件并不是多模态输入:它被写入会话 scratchpad,以 `[attached file: <路径>]` 一行交给模型,由普通文件工具按路径打开。下游没有任何环节的开销随它的体积增长,这正是 100MB 得以成立的前提。++内嵌图片恰恰相反。它进入对话,被原样写进 Trace JSONL,而该文件在每次翻阅历史、每次恢复会话时都会被整体读回——读成一个 JS 字符串。一张过大的内嵌图片带来的不是一次慢请求,而是一个再也恢复不过来的会话。何况图片此前根本没有做过大小校验:50MB 的粘贴之所以会失败,只是因为请求体上限恰好卡在那里,而且失败发生在标签页已经把文件 base64 并上传完之后。++因此图片被明确限制在 **20MB**(超出返回 413 `image_too_large`),客户端与服务端同时把关,且不随附件上限一起放宽。这个数值高于旧请求体上限实际允许的体积,所以此前能粘贴成功的图片不会因此失效。需要说明的是,它只是传输层的上限,并不代表模型一定会接受:供应商通常在 5MB 左右,`read_image` 工具同为 5MB,介于两者之间的图片可以顺利上传,仍可能被模型拒绝。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex f5a28204..417c4b3b 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -10,7 +10,7 @@ The PenguinHarness server exposes a same-origin HTTP API used by the bundled Web- Stack: Hono + @hono/node-server, requires Node >= 24;- Storage: SQLite (built-in `node:sqlite`, WAL mode) holds only indexes and aggregates — users, auth sessions, Project authorization, Agent / Session indexes, usage, UI preferences, error records, and Schedule state; all Agent, Trace, and Workspace data stays as files under `~/.penguin/data`, shared with the CLI / SDK — see the [Configuration Reference](/configuration);- Binding: defaults to `127.0.0.1:7364`, adjustable via the `PORT` / `HOST` environment variables;-- Request bodies: writes accept JSON only (Content-Type check, one of the CSRF defenses), capped at 20MB — counted as the body is read, so a request that declares no length (chunked) is capped just the same;+- Request bodies: writes accept JSON only (Content-Type check, one of the CSRF defenses), capped at a size **derived from the attachment budget** rather than fixed — attachments ride the request as base64 `data:` URLs (4/3 inflation), so the cap is `base64(attachmentTotalMb) + headroom for one inline image and the JSON framing`, about 190MB at the default 120MB total and falling again if an admin lowers it. It is counted as the body is read, so a request that declares no length (chunked) is capped just the same;- Errors share a single shape:```text@@ -73,7 +73,7 @@ In desktop mode (the server spawned by the desktop app) the whole surface answer| Method | Path | Description || --- | --- | --- |-| GET | /api/admin/settings | Server-global settings: `{settings: {proxyForApp, proxyForAgent, proxyUrl}}` |+| GET | /api/admin/settings | Server-global settings: `{settings: {proxyForApp, proxyForAgent, proxyUrl, attachmentMaxMb, attachmentTotalMb}}` || PUT | /api/admin/settings | Update settings (fields optional; omitted fields keep their current value), returns the full updated settings |The proxy settings are two independent switches sharing one optional explicit address; changes take effect for newly initiated connections/spawns immediately — no restart:@@ -82,6 +82,13 @@ The proxy settings are two independent switches sharing one optional explicit ad- `proxyForAgent` ("agent environment uses the proxy", default on) governs agent command subprocess environments: on with `proxyUrl` set → `HTTP_PROXY` / `HTTPS_PROXY` (plus lowercase twins) are injected as that address together with the merged NO_PROXY, overriding inherited values (a `socks5://` address is injected verbatim — tools vary in accepting SOCKS URLs in these variables); on without an address → the host environment passes through unchanged; off → the proxy variables are stripped (NO_PROXY is kept).- `proxyUrl` (default null = follow the environment variables) is the shared explicit address. Validation on PUT: the value is trimmed; empty or null clears the address; accepted are the proxy URLs undici's dispatcher takes — `http://`, `https://` and (experimental in undici) `socks5://` / `socks://` addresses, credentials allowed — plus bare `host[:port]` (normalized to `http://host[:port]`); only normalized values are stored, and the response echoes the stored form. Anything else — unparseable, or a scheme undici refuses, such as `socks4://` — is `400` with code `invalid_proxy_url`, and the rejected PUT writes nothing.+The upload limits are two whole-MB integers governing composer file attachments; both apply to the next request with no restart (the validators and the body cap read them per request):++- `attachmentMaxMb` (default 100) is the per-file cap — a larger file is `413` `file_too_large`.+- `attachmentTotalMb` (default 120) is the per-message total of decoded bytes — `413` `payload_too_large` beyond it.+- Validation on PUT: each must be an integer between 1 and 200, and the **effective** total (the value in this PUT, or the stored one when this PUT does not change it) must not be below the effective per-file cap. Anything else is `400` with code `invalid_attachment_limit`, and the rejected PUT writes nothing.+- Not settable: the per-message file count (20) and the inline-image cap (20MB, `413` `image_too_large`). An inline image is written into the Trace and re-read on every history page and resume, so it deliberately does not follow the attachment cap up; `GET /api/me` reports all of these under `uploadLimits` so a client can pre-check a pick against the numbers actually in force.+In every on-state the effective NO_PROXY always includes `localhost,127.0.0.1,::1` (loopback is never proxied).### Version and Self-Update@@ -275,10 +282,11 @@ interface TaskCreateRequest {}type TaskInputPart =| { type: "text"; text: string }- | { type: "image_url"; imageUrl: string } // pasted images arrive as data URLs- // File attachment: base64 data: URL, ≤10MB each (413 file_too_large beyond that), at most 20- // per request and 12MB of decoded bytes in total (413 too_many_files / payload_too_large;- // all three are checked before anything is written). The server writes it into the Session+ | { type: "image_url"; imageUrl: string } // pasted images arrive as data URLs, ≤20MB (413 image_too_large)+ // File attachment: base64 data: URL, by default ≤100MB each (413 file_too_large beyond that),+ // at most 20 per request and 120MB of decoded bytes in total (413 too_many_files /+ // payload_too_large; all three are checked before anything is written). The two sizes are+ // admin-settable (PUT /api/admin/settings) and reported by GET /api/me. The server writes it into the Session// scratchpad and appends an `[attached file: <path>]` line to the message text — the model// opens the file by path. `fileName` carries no path separators; on disk it keeps its own// words (`报告 2026.pdf` → `报告-2026.pdf`: non-ASCII survives, shell-hostile ASCII becomesdiff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex be614fa2..d84333f2 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -10,7 +10,7 @@ PenguinHarness Server 提供一套同源 HTTP API,自带的 Web App 与其他- 技术栈:Hono + @hono/node-server,要求 Node >= 24;- 存储:SQLite(内置 `node:sqlite`,WAL 模式)仅存放索引与聚合数据——用户、登录会话、Project 授权、Agent / Session 索引、用量、UI 偏好、错误记录与 Schedule 状态;Agent、Trace 与 Workspace 数据全部以文件形式存放在 `~/.penguin/data` 下,与 CLI / SDK 共享,见[配置参考](/configuration);- 监听:默认 `127.0.0.1:7364`,可用环境变量 `PORT` / `HOST` 调整;-- 请求体:写请求仅接受 JSON(Content-Type 校验,CSRF 防线之一),上限 20MB —— 按读取到的字节数统计,未声明长度(分块传输)的请求同样受限;+- 请求体:写请求仅接受 JSON(Content-Type 校验,CSRF 防线之一),其上限**由附件预算推导**而非固定值——附件以 base64 `data:` URL 随请求送达(膨胀 4/3),故上限为 `base64(attachmentTotalMb) + 一张内嵌图片与 JSON 外壳的余量`,在默认 120MB 合计下约 190MB,管理员调低附件上限时随之回落。按读取到的字节数统计,未声明长度(分块传输)的请求同样受限;- 错误响应统一为:```text@@ -73,7 +73,7 @@ curl -c cookies.txt -H "Content-Type: application/json" \| 方法 | 路径 | 说明 || --- | --- | --- |-| GET | /api/admin/settings | 服务端全局设置:`{settings: {proxyForApp, proxyForAgent, proxyUrl}}` |+| GET | /api/admin/settings | 服务端全局设置:`{settings: {proxyForApp, proxyForAgent, proxyUrl, attachmentMaxMb, attachmentTotalMb}}` || PUT | /api/admin/settings | 更新设置(字段可省略,省略即保持现值),返回更新后的完整设置 |代理设置为两个独立开关共享一个可选的显式地址;修改即时生效(对新发起的连接与新派生的子进程),无需重启:@@ -84,6 +84,13 @@ curl -c cookies.txt -H "Content-Type: application/json" \任一开启状态下生效的 NO_PROXY 恒包含 `localhost,127.0.0.1,::1`(回环不代理)。+上传限制是两个整数 MB,约束输入框的文件附件;二者均在下一次请求即生效、无需重启(校验与请求体上限都按请求读取):++- `attachmentMaxMb`(默认 100)为单个附件上限,超出返回 `413` `file_too_large`。+- `attachmentTotalMb`(默认 120)为单条消息解码后的合计上限,超出返回 `413` `payload_too_large`。+- PUT 校验:两者都必须是 1 到 200 之间的整数,且**生效后**的合计值(本次 PUT 给出的值,或本次不修改时的存量值)不得低于生效后的单个上限。其余一律 `400`,错误码 `invalid_attachment_limit`,且被拒绝的 PUT 不写入任何字段。+- 不可配置项:单条消息的附件数量(20)与内嵌图片上限(20MB,超出返回 `413` `image_too_large`)。内嵌图片会写入轨迹,并在每次翻阅历史与恢复会话时被重新读取,因此刻意不随附件上限放宽;`GET /api/me` 会在 `uploadLimits` 下报告以上全部数值,客户端据此按当前生效的上限预先校验。+### 版本与在线更新| 方法 | 路径 | 说明 |@@ -273,9 +280,10 @@ interface TaskCreateRequest {}type TaskInputPart =| { type: "text"; text: string }- | { type: "image_url"; imageUrl: string } // 粘贴图片以 data URL 上送- // 文件附件:base64 data: URL,单个 ≤10MB(超出返回 413 file_too_large),单次请求最多 20 个、- // 解码后合计 ≤12MB(超出返回 413 too_many_files / payload_too_large;三项校验都在落盘前完成)。+ | { type: "image_url"; imageUrl: string } // 粘贴图片以 data URL 上送,≤20MB(超出返回 413 image_too_large)+ // 文件附件:base64 data: URL,默认单个 ≤100MB(超出返回 413 file_too_large),单次请求最多 20 个、+ // 解码后合计 ≤120MB(超出返回 413 too_many_files / payload_too_large;三项校验都在落盘前完成)。+ // 两个尺寸均可由管理员调整(PUT /api/admin/settings),并由 GET /api/me 下发。// 服务端将其写入该 Session 的 scratchpad,并在消息文本末尾追加一行// `[attached file: <path>]`——模型按路径读取该文件。`fileName` 不得含路径分隔符;落盘时保留// 原有词形(`报告 2026.pdf` → `报告-2026.pdf`:非 ASCII 字符原样保留,对 shell 不友好的diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.mdindex 404ca1e5..9693ef0a 100644--- a/packages/docs/content/web-app.en.md+++ b/packages/docs/content/web-app.en.md@@ -66,8 +66,8 @@ Copy buttons across the app confirm at the button itself: the copy icon flips to### Input and Shortcuts-- Enter sends, Shift+Enter inserts a newline, and images can be pasted;-- The "+" menu holds the input add-ons: **image upload**, **file attachment** and goal mode. An attachment can be any type (up to 20 at a time, ≤ 10MB each and 12MB in total; an oversize pick is refused before it is read, so nothing is uploaded to earn the rejection); selected files show as removable chips above the text body in the order they were picked, and a message with attachments and no text is sendable. On send the files are written into the Session's scratchpad — deleted with the Session — and the message gains an `[attached file: <path>]` line per file, which the conversation renders as an "Attached files" notice: the bytes never enter the conversation, the model opens each file by path with its ordinary file tools;+- Enter sends, Shift+Enter inserts a newline, and images can be pasted — an image placed inline in the conversation is capped at 20MB, separately from file attachments and not raised along with them: an inline image enters the conversation and the Trace, where its size is paid again on every history page and every session resume, whereas an attachment is only ever read from disk by path;+- The "+" menu holds the input add-ons: **image upload**, **file attachment** and goal mode. An attachment can be any type (up to 20 at a time, and by default ≤ 100MB each and 120MB in total — an admin can change both sizes under **Upload limits** in the user menu, see below; an oversize pick is refused before it is read, so nothing is uploaded to earn the rejection, and the message names the limit actually in force); selected files show as removable chips above the text body in the order they were picked, and a message with attachments and no text is sendable. On send the files are written into the Session's scratchpad — deleted with the Session — and the message gains an `[attached file: <path>]` line per file, which the conversation renders as an "Attached files" notice: the bytes never enter the conversation, the model opens each file by path with its ordinary file tools;- Files can also be **dragged onto the chat area** — the conversation and the composer, on the chat page and the draft page alike: while a file drag is over that region a "Drop files to attach" overlay covers it (it hides as soon as the drag moves off; dragging text or anything that isn't a file is ignored), and releasing attaches the whole batch to the composer — images join the pasted-image pipeline, everything else becomes file attachments, with the same type and size validation and the same errors as the "+" menu. Dropping works while a Task is running too (the attachments then send per the mid-run send mode below); goal mode takes dropped images but refuses files with a notice. Only the chat area reacts: dropping a file on the sidebar, the top bar, the docked panels or any page without a composer attaches nothing and shows nothing — it is simply ignored, instead of the browser navigating away to the dropped file;- Typing `/` opens the slash menu: trigger context compaction (`/compact`), hand the conversation over to another Agent (`/agent`), switch the model (`/model`) — both switch commands appear in an active session only, since a draft has nothing to switch and picks its Agent and model up front — or toggle installed Skills — chosen Skills are sent along with the message in a `[use_skills]` block;- While a Task is running the input stays live and the toolbar keeps a single action button: an empty composer shows **Stop**, and typing turns it into **Send**, whose behavior follows the **mid-run send mode** from the toolbar's More-settings popover (a compact extensible settings panel, also available in draft state; the choice is remembered): **Steer** (default) delivers the text **and any attached images** mid-run as a `[user_steering]` user message with the next turn (an image with no caption sends on its own, and the delivered message renders as a steering chip with its images inside it), **Queue** holds the whole message server-side as a follow-up and auto-sends it as an ordinary new message when the run finishes (an "N queued" hint shows near the input until then; the queue survives page reloads). A draft steering cannot carry — selected skills, file attachments, or a staged `/agent` or `/model` pick, with no text and no image — falls back to the queue for that one send, so the button never sits disabled with Stop displaced. Each queued hint line — an undelivered steering message or a queued follow-up — ends in a **recall** control (a curved-back arrow, "Recall") that withdraws the message back into the input box (attachments included) for editing and resending; a steering message that already reached the model can no longer be recalled;@@ -126,6 +126,14 @@ Read-only scoreboards per Benchmark: switch the metric (score / cost / duration)Admin only: list and create users, reset passwords, and delete users (the built-in admin cannot be deleted).+## Upload Limits++Admin only: **Upload limits** in the sidebar user menu opens a server-global form with two sizes — the **per-file attachment cap** and the **per-message total** — both whole MB, defaulting to 100MB and 120MB. Each may be set between 1 and 200MB, and the total may not sit below the per-file cap (that combination would make a legal single attachment unsendable). A value outside the range — "100GB" typed into a MB field as 102400, say — is refused with the reason shown under the input rather than accepted. Validation precedes every write: one bad field in a PUT leaves the other fields untouched too.++Saving takes effect immediately, with no restart: the attachment validators and the request body cap both read the setting per request. The body cap is not configured separately but derived from the total — attachments ride the request as base64 `data:` URLs, which inflates them by 4/3, so it has to rise with them or a request whose every attachment was individually legal would die at the HTTP layer instead.++Two numbers are deliberately not exposed. The per-message file **count** stays at 20: it bounds how usable the composer's chip row is, not what the server can survive — the byte budgets do that. And an inline **image** stays capped at 20MB rather than following the attachment limit up, because an image placed inline enters the conversation and the Trace, where its size is paid again on every history page and every session resume; the model side is lower still (providers commonly cap around 5MB, and the `read_image` tool at 5MB), so raising it to 100MB would only trade a clear refusal for a later, more confusing failure.+## Version and UpdatesThe sidebar user menu carries a manual "Check for updates" action directly below "Change password"; the running version sits muted on the right of that row, and its release date — stamped into the build by the release workflow, displayed without any network access — appears as the row's localized "Last updated Jul 26"-style tooltip (dev builds and releases that predate the stamping, v0.1.2 and earlier, have no date). The new-chat page shows the same identity as a version line under the brand. The app checks GitHub for a newer release once the menu has first been opened, and immediately — bypassing the cached result — when the manual action is clicked; the latter reports "You're on the latest version" when nothing newer exists. When a newer release is found, a dot appears on the user button, the version displays gain a small superscript "New version available" badge (the draft-page badge links to the release), and the menu gains a release-notes link, plus an "Update now" action for admins that runs `penguin update` on the server (the data directory is untouched). The service must be restarted afterwards for the update to take effect. Set `PENGUIN_UPDATE_CHECK=off` to disable the update check entirely — see the [Configuration Reference](/configuration).diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.mdindex 1ebc241f..b9cf5c99 100644--- a/packages/docs/content/web-app.zh.md+++ b/packages/docs/content/web-app.zh.md@@ -66,8 +66,8 @@ penguin web### 输入与快捷操作-- Enter 发送,Shift+Enter 换行,支持粘贴图片;-- 「+」菜单收纳输入附加项:**上传图片**、**上传文件**与目标模式。附件不限类型(一次最多 20 个,单个 ≤ 10MB、合计 ≤ 12MB;超限的文件在读取前即被拒绝,不会先上传再报错),已选文件按选择顺序以可移除的小卡片显示在文本框上方;只带附件、没有正文也可发送。发送时文件写入该 Session 的 scratchpad(随 Session 一并删除),消息里每个文件追加一行 `[attached file: <path>]`,对话中渲染为一条「附加文件」提示:文件内容不进入对话,模型用普通文件工具按路径读取;+- Enter 发送,Shift+Enter 换行,支持粘贴图片——嵌入对话的图片单独设有 20MB 上限,不随附件上限一起放宽:图片会进入对话与轨迹,此后每次翻阅历史、恢复会话都要重新付出它的体积,而附件只是按路径从磁盘读取;+- 「+」菜单收纳输入附加项:**上传图片**、**上传文件**与目标模式。附件不限类型(一次最多 20 个,默认单个 ≤ 100MB、合计 ≤ 120MB——两个尺寸均可由管理员在用户菜单的**上传限制**中调整,见下文;超限的文件在读取前即被拒绝,不会先上传再报错,提示中会写出当前生效的上限),已选文件按选择顺序以可移除的小卡片显示在文本框上方;只带附件、没有正文也可发送。发送时文件写入该 Session 的 scratchpad(随 Session 一并删除),消息里每个文件追加一行 `[attached file: <path>]`,对话中渲染为一条「附加文件」提示:文件内容不进入对话,模型用普通文件工具按路径读取;- 也可以把文件**拖拽到聊天区**上传(聊天区即对话与输入框所在区域,会话页与草稿页皆可):文件拖到该区域上方时显示覆盖该区域的「松开以添加附件」浮层(拖离即消失,拖动文本等非文件内容不触发),松开即把整批文件附加到输入框——图片走粘贴图片的同一管线,其余文件成为附件,类型与大小校验及报错与「+」菜单一致。任务运行中同样可以拖入(附件按下述运行中发送方式送出);目标模式下拖入的图片照常附加、文件会以提示拒绝。只有聊天区会响应:把文件放到侧边栏、顶栏、右侧停靠面板或任何没有输入框的页面上,既不显示浮层也不会添加附件,只是被直接忽略,同时不会让浏览器跳转打开该文件;- 输入 `/` 打开快捷菜单:触发上下文压缩(`/compact`)、把会话交接给其他 Agent(`/agent`)、切换模型(`/model`)——两个切换命令都只在进行中的会话里提供,草稿没有可切换的对话,Agent 与模型本就在草稿页选定——或勾选已安装的 Skill——所选 Skill 会以 `[use_skills]` 块随消息发送;- Task 运行期间输入框保持可用,工具条只保留一个操作按钮:输入框为空时是**停止**,一旦输入内容即变为**发送**,其行为遵循工具条「更多设置」弹出分组中的**运行中发送方式**(一个可扩展的设置面板,草稿态同样可设,选择会被记忆):**插话**(默认)把文字以 `[user_steering]` 用户消息随下一轮送达运行中的 Agent;**排队** 把整条消息暂存在服务端,本轮结束后自动作为普通新消息发出(期间在输入框附近显示「N 条已排队」提示;队列存放在服务端,刷新页面不丢失)。每条排队提示——未送达的插话或排队中的跟进消息——行尾都带一枚**撤回**按钮(一个向回弯的箭头图标),可把消息(含附件)撤回到输入框编辑后重新发送;插话一旦送达模型即不可撤回;@@ -125,6 +125,14 @@ Memory 标签页的开关拨动即写入,不参与标签页的保存按钮,仅管理员可见:列出与创建用户、重置密码、删除用户(内置 admin 不可删除)。+## 上传限制++仅管理员可见:侧边栏用户菜单的「上传限制」打开一个服务器全局的表单,可调整两个尺寸——**单个附件上限**与**单条消息附件合计上限**,均以整数 MB 填写,默认 100MB 与 120MB。两者的取值范围为 1–200MB,且合计不得低于单个上限(否则一个本身合法的附件将无法发送);超出范围的值——例如把「100GB」按 MB 填成 102400——会被服务端明确拒绝并在输入框下方给出原因,不会被接受。校验先于写入:一次 PUT 中只要有一个字段非法,其余字段也不会落库。++保存即刻生效,无需重启:附件校验与请求体上限都在每次请求时读取该设置。请求体上限本身不单独配置,而是由合计上限推导——附件以 base64 `data:` URL 随请求送达,体积膨胀 4/3,因此上限必须随之上浮,否则每个附件单独合法的请求会在 HTTP 层被拒。++有两个数值刻意不开放:单条消息的附件**数量**上限固定为 20(它约束的是输入框的可用性,而非服务器资源),对话内嵌**图片**上限固定为 20MB。图片不随附件上限放宽是有意为之——图片进入对话与轨迹,其体积在每次翻阅历史与恢复会话时被反复付出;而且模型侧另有更低的实际限制(供应商通常约 5MB,`read_image` 工具亦为 5MB),把它放宽到 100MB 只会把一个清晰的拒绝换成更靠后、更难懂的失败。+## 版本与更新侧边栏用户菜单在「修改密码」下方提供手动「检查更新」按钮,当前运行版本号以浅色显示在该行右侧;其发布日期(由发布流程在构建时打入、直接显示、无需联网)以「最近更新日期 7 月 26 日」样式的悬浮提示展示(开发构建以及打入机制之前的发布版,v0.1.2 及以前,没有日期)。新对话页在品牌下方以版本行显示同样的信息。菜单首次打开后会向 GitHub 查询是否有新版本;点击「检查更新」则立即查询(绕过缓存结果),已是最新时以提示告知。发现新版本时,用户按钮上会出现提示圆点,版本显示处会出现「有新版本可用」上标小徽标(新对话页的徽标可跳转 Release 页面),菜单内提供更新说明链接;管理员还可点击"立即更新",在服务器上执行 `penguin update`(数据目录不受影响)。更新完成后需要重启服务才会生效。设置 `PENGUIN_UPDATE_CHECK=off` 可完全关闭新版本检查——见[配置参考](/configuration)。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex d34465e2..ace2a4c2 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -91,6 +91,39 @@ export interface MeResponse {* token) may omit it.*/sessionVia: "password" | "desktop";+ /**+ * The upload limits currently in force, so the composer can refuse an oversize pick before+ * reading it and can name the real number in the message. They are admin-settable and ride+ * `/api/me` rather than `/api/admin/settings` because every user's composer needs them, not+ * just an admin's.+ */+ uploadLimits: UploadLimits;+}++/**+ * Upload limits as the web app sees them: whole MB, the same unit the admin form uses, so the+ * number in the error message is the number the admin typed.+ */+export interface UploadLimits {+ /** Per-file cap for composer file attachments. */+ attachmentMaxMb: number;+ /** Per-message total of decoded attachment bytes. */+ attachmentTotalMb: number;+ /** Per-message file count. Fixed server-side, not admin-settable. */+ attachmentMaxCount: number;+ /**+ * Per-image cap for images that ride the conversation inline. Fixed server-side and+ * deliberately far below the attachment cap — an inline image enters the conversation and the+ * Trace, where its size is paid again on every history page and every resume.+ */+ imageMaxMb: number;+ /**+ * The range the two admin-settable limits may be set to. Carried here so the admin form states+ * the real bounds without compiling its own copy of them — the server is the only place that+ * decides how large an upload it can survive.+ */+ attachmentLimitMinMb: number;+ attachmentLimitMaxMb: number;}export interface PasswordChangeRequest {@@ -153,6 +186,18 @@ export interface ServerSettings {* precedence over HTTP_PROXY / HTTPS_PROXY wherever the owning switch is on.*/proxyUrl: string | null;+ /**+ * Per-file cap for composer file attachments, in whole MB (default 100). Applies to the very+ * next upload — the validators read it per request, nothing is snapshotted at boot.+ */+ attachmentMaxMb: number;+ /**+ * Per-message total of decoded attachment bytes, in whole MB (default 120). Never below+ * `attachmentMaxMb`, so a message may always carry one full-size attachment. The global request+ * body cap is derived from this value (base64 inflates it by 4/3, plus headroom for one inline+ * image and the JSON framing), which is why raising it needs no separate setting.+ */+ attachmentTotalMb: number;}export interface ServerSettingsResponse {@@ -171,6 +216,19 @@ export interface ServerSettingsUpdateRequest {* (follow the environment variables); anything else is 400 `invalid_proxy_url`.*/proxyUrl?: string | null;+ /**+ * New per-file attachment cap in whole MB. Must be an integer between 1 and 200; anything else+ * — a fraction, a string, 102400 for "100GB" — is 400 `invalid_attachment_limit` and writes+ * nothing.+ */+ attachmentMaxMb?: number;+ /**+ * New per-message total attachment cap in whole MB. Same 1..200 integer range, and additionally+ * must not be below the *effective* per-file cap (the value in the same PUT, or the stored one+ * when this PUT does not change it) — a total below the per-file cap would make a legal single+ * attachment unsendable. Violations are 400 `invalid_attachment_limit`.+ */+ attachmentTotalMb?: number;}/** User UI preferences (SQLite ui_prefs, free-form JSON; known keys declared here). */@@ -1079,14 +1137,22 @@ export interface MessagesResponse {*/export type TaskInputPart =| { type: "text"; text: string }+ /**+ * An image that rides the conversation inline, as a base64 `data:` URL or an http(s) URL.+ * A data URL is capped at 20MB (413 `image_too_large`) — a fixed limit that does NOT follow+ * the admin-settable attachment cap, because an inline image is written into the Trace and+ * read back on every history page and every resume.+ */| { type: "image_url"; imageUrl: string }/*** File attachment (the composer's "+" menu): `dataUrl` is a base64 `data:` URL of the- * file's bytes, capped at 10MB each (413 `file_too_large` beyond that; the request as a- * whole still has to fit the global 20MB body limit). The server writes it into the- * Session scratchpad under a sanitized name and appends an `[attached file: <path>]` line- * to the message text — the bytes never enter the conversation, the model opens the file- * by path. `fileName` is the original name (no path separators, no `..`).+ * file's bytes, capped per file and per message by the admin-settable upload limits+ * (defaults 100MB / 120MB; 413 `file_too_large` / `payload_too_large` / `too_many_files`,+ * and the request as a whole still has to fit the body cap those limits derive). The+ * server writes it into the Session scratchpad under a sanitized name and appends an+ * `[attached file: <path>]` line to the message text — the bytes never enter the+ * conversation, the model opens the file by path. `fileName` is the original name (no path+ * separators, no `..`).*/| { type: "file"; fileName: string; dataUrl: string };diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex 6f39f1b9..a423fa99 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -10,7 +10,7 @@ import fs from "node:fs";import fsp from "node:fs/promises";import path from "node:path";import { Hono } from "hono";-import type { Context } from "hono";+import type { Context, MiddlewareHandler } from "hono";import { bodyLimit } from "hono/body-limit";import type { DatabaseSync } from "node:sqlite";import type { ProxyEnvPolicy } from "@prismshadow/penguin-core";@@ -94,9 +94,13 @@ import {} from "./services/preview-token.js";import type { PreviewTokenSigner } from "./services/preview-token.js";import { previewRoutes } from "./http/routes/preview.js";+import { bodyLimitBytes } from "./services/attachment-limits.js";-/** Request body size limit (tasks may carry data: images): 20MB. */-const MAX_BODY_BYTES = 20 * 1024 * 1024;+/**+ * The request body cap is no longer a constant: it is derived per request from the admin-settable+ * attachment budget (see services/attachment-limits.ts — tasks carry their attachments and images+ * inline as base64 `data:` URLs, which inflates them by 4/3).+ */export interface AppDeps {config: ServerConfig;@@ -417,24 +421,44 @@ export function createApp(deps: AppDeps): Hono<AppEnv> {});}- // API common defenses: request body size cap (20MB) and write-request Content-Type (one of the CSRF MVP defenses).+ // API common defenses: request body size cap and write-request Content-Type (one of the CSRF+ // MVP defenses).//// The cap has to be measured, not read: a chunked request carries no `content-length` at all,// so a header check alone passes a body of any size — the sinks behind it (task input images,// file attachments, Trace import) then decode whatever arrives. hono's bodyLimit keeps the// header fast path when the length is declared and otherwise counts bytes off the stream,// aborting the moment the total crosses the cap.- app.use(- "/api/*",- bodyLimit({- maxSize: MAX_BODY_BYTES,- // Its default is a bare text/plain 413; throw the App's own error instead so the response- // stays the documented `payload_too_large` body that every client already handles.- onError: () => {- throw new HttpError(413, "payload_too_large", "Request body exceeds the 20MB limit.");- },- }),- );+ //+ // The cap is DERIVED from the admin-settable attachment budget rather than fixed, because the+ // two must not disagree in either direction: a cap below the budget would reject a request whose+ // every attachment was individually legal (and with a body-shaped error, not a size-shaped one),+ // while a cap permanently sized for the largest budget an admin *could* set would keep accepting+ // 300MB bodies on a server whose limits were left at 10MB. It is re-derived per request, so an+ // admin's change takes effect immediately; the middleware itself is memoized on the resulting+ // size so the steady state allocates nothing.+ let capped: { size: number; mw: MiddlewareHandler } | null = null;+ app.use("/api/*", (c, next) => {+ const size = bodyLimitBytes(deps.serverSettingsRepo.getAttachmentLimitsMb());+ if (capped === null || capped.size !== size) {+ capped = {+ size,+ mw: bodyLimit({+ maxSize: size,+ // Its default is a bare text/plain 413; throw the App's own error instead so the+ // response stays the documented `payload_too_large` body that every client handles.+ onError: () => {+ throw new HttpError(+ 413,+ "payload_too_large",+ `Request body exceeds the ${Math.floor(size / (1024 * 1024))}MB limit.`,+ );+ },+ }),+ };+ }+ return capped.mw(c, next);+ });app.use("/api/*", jsonOnlyWrites);// Public routes (no login required).diff --git a/packages/server/src/db/repos/server-settings.ts b/packages/server/src/db/repos/server-settings.tsindex 30653154..497d85f0 100644--- a/packages/server/src/db/repos/server-settings.ts+++ b/packages/server/src/db/repos/server-settings.ts@@ -4,6 +4,11 @@* settings added after a web.db was formed need no migration.*/import type { DatabaseSync } from "node:sqlite";+import {+ clampAttachmentMb,+ DEFAULT_ATTACHMENT_MAX_MB,+ DEFAULT_ATTACHMENT_TOTAL_MB,+} from "../../services/attachment-limits.js";/** Key of the "application uses the proxy" switch (the server's own outbound dispatcher); default on. */const PROXY_FOR_APP_KEY = "proxy_for_app";@@ -22,6 +27,12 @@ const LEGACY_USE_SYSTEM_PROXY_KEY = "use_system_proxy";/** Key of the explicit proxy address; absent/null = follow the proxy environment variables. */const PROXY_URL_KEY = "proxy_url";+/** Key of the per-file composer attachment limit, in whole MB; default DEFAULT_ATTACHMENT_MAX_MB. */+const ATTACHMENT_MAX_MB_KEY = "attachment_max_mb";++/** Key of the per-message total attachment limit, in whole MB; default DEFAULT_ATTACHMENT_TOTAL_MB. */+const ATTACHMENT_TOTAL_MB_KEY = "attachment_total_mb";+export class ServerSettingsRepo {constructor(private readonly db: DatabaseSync) {}@@ -84,4 +95,52 @@ export class ServerSettingsRepo {setProxyUrl(value: string | null): void {this.set(PROXY_URL_KEY, JSON.stringify(value));}++ /**+ * Shared read for the two attachment limits: the stored whole-MB number, clamped back into the+ * legal range, or the built-in default when the row is absent or unreadable. Values only ever+ * enter through the validated PUT, so the clamp is for a database that predates a change to the+ * bounds (or was hand-edited) — using the nearest legal number is a better answer there than+ * refusing to serve uploads at all.+ */+ private getAttachmentMb(key: string, fallback: number): number {+ const raw = this.get(key);+ if (raw === null) return fallback;+ try {+ const value: unknown = JSON.parse(raw);+ return typeof value === "number" ? clampAttachmentMb(value, fallback) : fallback;+ } catch {+ return fallback;+ }+ }++ /** Per-file composer attachment cap, in whole MB. */+ getAttachmentMaxMb(): number {+ return this.getAttachmentMb(ATTACHMENT_MAX_MB_KEY, DEFAULT_ATTACHMENT_MAX_MB);+ }++ setAttachmentMaxMb(value: number): void {+ this.set(ATTACHMENT_MAX_MB_KEY, JSON.stringify(value));+ }++ /** Per-message total attachment cap (decoded bytes), in whole MB. */+ getAttachmentTotalMb(): number {+ return this.getAttachmentMb(ATTACHMENT_TOTAL_MB_KEY, DEFAULT_ATTACHMENT_TOTAL_MB);+ }++ setAttachmentTotalMb(value: number): void {+ this.set(ATTACHMENT_TOTAL_MB_KEY, JSON.stringify(value));+ }++ /**+ * The pair as one value — what the validators, the body cap and `/api/me` all read. Kept here+ * so no caller has to remember that the two numbers are only meaningful together (the total is+ * never below the per-file cap; the PUT enforces that against the effective post-write pair).+ */+ getAttachmentLimitsMb(): { attachmentMaxMb: number; attachmentTotalMb: number } {+ return {+ attachmentMaxMb: this.getAttachmentMaxMb(),+ attachmentTotalMb: this.getAttachmentTotalMb(),+ };+ }}diff --git a/packages/server/src/http/routes/admin-settings.ts b/packages/server/src/http/routes/admin-settings.tsindex 1a0916a6..36d24d6c 100644--- a/packages/server/src/http/routes/admin-settings.ts+++ b/packages/server/src/http/routes/admin-settings.ts@@ -1,13 +1,15 @@/*** Admin server-settings routes (admin only, 403 for non-admins):- * GET|PUT /api/admin/settings — the server-global settings stored in server_settings- * (currently the proxy settings: the "application uses the proxy" and "agent- * environment uses the proxy" switches and their shared explicit address).+ * GET|PUT /api/admin/settings — the server-global settings stored in server_settings:+ * the proxy settings (the "application uses the proxy" and "agent environment uses the+ * proxy" switches and their shared explicit address) and the upload limits (the+ * per-file and per-message attachment caps, in whole MB).* A PUT applies immediately: everything is validated first (a rejected request writes* nothing), then the persisted values are written, then the process dispatcher is* rebuilt so new outbound connections follow the change without a restart (the agent* switch needs no push — the command-subprocess policy getter re-reads the repo at- * every spawn).+ * every spawn). The upload limits need no push either, for the same reason: the+ * attachment validators and the request body cap both read the repo per request.*/import { Hono } from "hono";import type { ServerSettingsResponse } from "../../api/types.js";@@ -16,6 +18,7 @@ import type { AppEnv } from "../../auth/middleware.js";import { optionalBoolean, readJson } from "../validate.js";import type { AppDeps } from "../../app.js";import { applyProxySettings, normalizeProxyUrl } from "../../net/proxy.js";+import { MAX_ATTACHMENT_MB, MIN_ATTACHMENT_MB } from "../../services/attachment-limits.js";/*** proxyUrl update value -> stored value: null and empty/whitespace-only clear the@@ -36,6 +39,23 @@ function parseProxyUrl(value: unknown): string | null {);}+/**+ * An attachment limit update value -> stored whole-MB integer. Everything outside the supported+ * range is refused with one dedicated code the Web App renders under the field — the range is the+ * point of the setting (an admin typing 100GB must be told no, not obeyed), so the failure has to+ * be legible rather than a generic `bad_request`.+ */+function parseAttachmentMb(value: unknown, field: string): number {+ if (typeof value === "number" && Number.isInteger(value)) {+ if (value >= MIN_ATTACHMENT_MB && value <= MAX_ATTACHMENT_MB) return value;+ }+ throw new HttpError(+ 400,+ "invalid_attachment_limit",+ `${field} must be a whole number of MB between ${MIN_ATTACHMENT_MB} and ${MAX_ATTACHMENT_MB}.`,+ );+}+export function adminSettingsRoutes(deps: AppDeps): Hono<AppEnv> {const app = new Hono<AppEnv>();@@ -51,6 +71,7 @@ export function adminSettingsRoutes(deps: AppDeps): Hono<AppEnv> {proxyForApp: deps.serverSettingsRepo.getProxyForApp(),proxyForAgent: deps.serverSettingsRepo.getProxyForAgent(),proxyUrl: deps.serverSettingsRepo.getProxyUrl(),+ ...deps.serverSettingsRepo.getAttachmentLimitsMb(),},});@@ -64,9 +85,35 @@ export function adminSettingsRoutes(deps: AppDeps): Hono<AppEnv> {const proxyForAgent = optionalBoolean(body, "proxyForAgent");const proxyUrlProvided = body.proxyUrl !== undefined;const proxyUrl = proxyUrlProvided ? parseProxyUrl(body.proxyUrl) : null;+ const attachmentMaxMb =+ body.attachmentMaxMb === undefined+ ? undefined+ : parseAttachmentMb(body.attachmentMaxMb, "attachmentMaxMb");+ const attachmentTotalMb =+ body.attachmentTotalMb === undefined+ ? undefined+ : parseAttachmentMb(body.attachmentTotalMb, "attachmentTotalMb");+ // The pair is only meaningful together, so the relation is checked against the EFFECTIVE+ // post-write values: a PUT that raises only the per-file cap must be refused when the stored+ // total would leave a legal single attachment unsendable, and one that lowers only the total+ // must be refused for the same reason. Checked before any write, like every other field.+ const stored = deps.serverSettingsRepo.getAttachmentLimitsMb();+ const effectiveMax = attachmentMaxMb ?? stored.attachmentMaxMb;+ const effectiveTotal = attachmentTotalMb ?? stored.attachmentTotalMb;+ if (effectiveTotal < effectiveMax) {+ throw new HttpError(+ 400,+ "invalid_attachment_limit",+ `attachmentTotalMb (${effectiveTotal}) must not be below attachmentMaxMb (${effectiveMax}).`,+ );+ }if (proxyForApp !== undefined) deps.serverSettingsRepo.setProxyForApp(proxyForApp);if (proxyForAgent !== undefined) deps.serverSettingsRepo.setProxyForAgent(proxyForAgent);if (proxyUrlProvided) deps.serverSettingsRepo.setProxyUrl(proxyUrl);+ if (attachmentMaxMb !== undefined) deps.serverSettingsRepo.setAttachmentMaxMb(attachmentMaxMb);+ if (attachmentTotalMb !== undefined) {+ deps.serverSettingsRepo.setAttachmentTotalMb(attachmentTotalMb);+ }// Mirror the app switch + address into the process: rebuilds the global fetch// dispatcher (live change, no restart; a no-op when nothing effectively changed).applyProxySettings({diff --git a/packages/server/src/http/routes/me.ts b/packages/server/src/http/routes/me.tsindex f4c9e390..4abe6f9b 100644--- a/packages/server/src/http/routes/me.ts+++ b/packages/server/src/http/routes/me.ts@@ -11,6 +11,12 @@ import type { AppEnv } from "../../auth/middleware.js";import { readJson, requireString } from "../validate.js";import type { AppDeps } from "../../app.js";import { resolvePreviewTarget } from "../../services/preview-token.js";+import {+ INLINE_IMAGE_MAX_MB,+ MAX_ATTACHMENT_COUNT,+ MAX_ATTACHMENT_MB,+ MIN_ATTACHMENT_MB,+} from "../../services/attachment-limits.js";export function meRoutes(deps: AppDeps): Hono<AppEnv> {const app = new Hono<AppEnv>();@@ -25,11 +31,22 @@ export function meRoutes(deps: AppDeps): Hono<AppEnv> {deps.config.previewOrigin,deps.config,);+ // Read per request, not captured once: an admin's change to the limits reaches an already+ // open tab on its next /api/me (a reload, or the settings dialog's own refresh) without a+ // server restart, and a tab that never refetches simply keeps proposing the older number —+ // the server re-validates every upload against the current one regardless.return c.json({user: toUserInfo(c.var.user),previewIsolated: target !== null,desktopMode: deps.desktop !== null,sessionVia: c.var.sessionVia,+ uploadLimits: {+ ...deps.serverSettingsRepo.getAttachmentLimitsMb(),+ attachmentMaxCount: MAX_ATTACHMENT_COUNT,+ imageMaxMb: INLINE_IMAGE_MAX_MB,+ attachmentLimitMinMb: MIN_ATTACHMENT_MB,+ attachmentLimitMaxMb: MAX_ATTACHMENT_MB,+ },} satisfies MeResponse);});diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.tsindex ae786ecb..243a3015 100644--- a/packages/server/src/http/routes/sessions.ts+++ b/packages/server/src/http/routes/sessions.ts@@ -60,6 +60,12 @@ import {removeAttachments,} from "../../services/task-attachments.js";import type { TaskAttachment } from "../../services/task-attachments.js";+import {+ INLINE_IMAGE_MAX_BYTES,+ INLINE_IMAGE_MAX_MB,+ toAttachmentLimits,+} from "../../services/attachment-limits.js";+import type { AttachmentLimits } from "../../services/attachment-limits.js";import type { RecallStore } from "../../runtime/session-manager.js";/** Max title length for manual renames: looser than the auto-generated 30-char limit, to accommodate users' own organizing conventions. */@@ -182,13 +188,40 @@ const IMAGE_DATA_URL = /^data:[^;,]+;base64,[A-Za-z0-9+/=\s]+$/;function requireImageUrl(url: unknown, field: string): string {if (typeof url === "string") {if (url.startsWith("http://") || url.startsWith("https://")) return url;- if (IMAGE_DATA_URL.test(url)) return url;+ if (IMAGE_DATA_URL.test(url)) {+ // An inline image is not an attachment: it enters the conversation and is written verbatim+ // into the Trace, which is read back whole — into one JS string — on every history page and+ // every resume. So it gets its own fixed ceiling instead of following the (much larger,+ // admin-settable) attachment cap up. Measured on the decoded length rather than the data+ // URL's, so the number in the error is the number a person sees in a file manager.+ const bytes = dataUrlByteLength(url);+ if (bytes > INLINE_IMAGE_MAX_BYTES) {+ throw new HttpError(+ 413,+ "image_too_large",+ `${field} exceeds the ${INLINE_IMAGE_MAX_MB}MB inline image limit.`,+ );+ }+ return url;+ }}throw badRequest(`${field} must be an http(s) URL or a base64 data: URL (data:<mime>;base64,<bytes>).`,);}+/**+ * Decoded byte length of a base64 data URL, computed from the payload's length rather than by+ * decoding it: the point is to reject an oversize image *before* materializing it as a Buffer.+ * Whitespace and padding are discounted, so the result is the file's real size.+ */+function dataUrlByteLength(dataUrl: string): number {+ // Padding and whitespace carry no bytes; every 4 remaining characters carry 3. Same arithmetic+ // the composer uses to size a recalled attachment's chip (chat-input.tsx dataUrlBytes).+ const payload = dataUrl.slice(dataUrl.indexOf(",") + 1).replace(/[=\s]+/g, "");+ return Math.floor((payload.length * 3) / 4);+}+/*** Resolve a scratchpad file name to an absolute path inside `dir`, or null when it could point* anywhere else (the caller turns that into the same 404 a missing file gets, so a probe learns@@ -227,7 +260,7 @@ interface ParsedTaskInput {}/** Validate Prompt input parts: text, image (data: / http(s) URL), or an uploaded file. */-function parseTaskInput(body: Record<string, unknown>): ParsedTaskInput {+function parseTaskInput(body: Record<string, unknown>, limits: AttachmentLimits): ParsedTaskInput {const input = body.input;if (!Array.isArray(input) || input.length === 0) {throw badRequest("input must be an array with at least one item.");@@ -258,10 +291,10 @@ function parseTaskInput(body: Record<string, unknown>): ParsedTaskInput {if (part.type === "file") {// Not an OmniMessage of its own: the file becomes an `[attached file: …]` line on the// text message once written to the scratchpad, so it carries no payload into the run.- attachments.push(parseAttachmentPart(part, i));+ attachments.push(parseAttachmentPart(part, i, limits));// Per-request count / total-bytes caps, re-checked on every part so a hostile `input`// is cut off at the item that crosses the line (see assertAttachmentBudget).- assertAttachmentBudget(attachments);+ assertAttachmentBudget(attachments, limits);return;}throw badRequest(`input[${i}].type must be one of text / image_url / file.`);@@ -326,7 +359,10 @@ function parseSteerImages(body: Record<string, unknown>): string[] {* input's `{type:"file"}` parts (parseAttachmentPart, budget re-checked per item), absent or* empty = no attachments.*/-function parseSteerFiles(body: Record<string, unknown>): TaskAttachment[] {+function parseSteerFiles(+ body: Record<string, unknown>,+ limits: AttachmentLimits,+): TaskAttachment[] {const files = body.files;if (files === undefined) return [];if (!Array.isArray(files)) throw badRequest("files must be an array.");@@ -335,8 +371,8 @@ function parseSteerFiles(body: Record<string, unknown>): TaskAttachment[] {if (item === null || typeof item !== "object" || Array.isArray(item)) {throw badRequest(`files[${i}] must be an object.`);}- attachments.push(parseAttachmentPart(item as Record<string, unknown>, i, "files"));- assertAttachmentBudget(attachments);+ attachments.push(parseAttachmentPart(item as Record<string, unknown>, i, limits, "files"));+ assertAttachmentBudget(attachments, limits);});return attachments;}@@ -813,6 +849,9 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {// the session's default. In goal mode it rides every round of the goal; a queued// follow-up keeps its level for its auto-start.const thinkingLevel = optionalEnum(body, "thinkingLevel", THINKING_LEVELS);+ // Resolved per request from the admin settings, so a limit change applies to the very next+ // upload rather than at the next restart.+ const limits = toAttachmentLimits(deps.serverSettingsRepo.getAttachmentLimitsMb());if (goal) {// Goal mode: the input needs non-empty text, since its marker-stripped text becomes the// objective that every round re-injects and an image on its own doesn't say what the@@ -820,7 +859,7 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {// inside the objective (whatever the model's vision) so they survive the rounds. File// attachments cannot: nothing folds them into the objective, so they are turned away// here, before any upload is written to disk.- const { messages, attachments } = parseTaskInput(body);+ const { messages, attachments } = parseTaskInput(body, limits);const text = messages.filter((m) => (m.payload as { type?: string }).type === "text").map((m) => (m.payload as { text: string }).text)@@ -839,7 +878,7 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {});return c.json({ sessionId } satisfies TaskCreateResponse, 202);}- const parsed = parseTaskInput(body);+ const parsed = parseTaskInput(body, limits);// Follow-up queue: with queueIfBusy, a busy session enqueues the input instead of 409// (auto-starts as an ordinary next task once idle; the response says which happened).const queueIfBusy = body.queueIfBusy === true;@@ -889,7 +928,10 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {const body = await readJson(c);const text = typeof body.text === "string" ? body.text.trim() : "";const images = parseSteerImages(body);- const files = parseSteerFiles(body);+ const files = parseSteerFiles(+ body,+ toAttachmentLimits(deps.serverSettingsRepo.getAttachmentLimitsMb()),+ );// Any part can carry the message on its own: an image or a file with no caption is a// complete steering message, and so is plain text.if (!text && images.length === 0 && files.length === 0) {diff --git a/packages/server/src/services/attachment-limits.ts b/packages/server/src/services/attachment-limits.tsnew file mode 100644index 00000000..349f817d--- /dev/null+++ b/packages/server/src/services/attachment-limits.ts@@ -0,0 +1,159 @@+/**+ * The one place every attachment size number is defined.+ *+ * Four layers used to carry their own copy of "10MB" — the composer's pre-flight check, the+ * server's per-file cap, the per-request budget and the global body cap — and nothing kept them+ * in step. They are derived from one another here instead, because the failure mode of a+ * disagreement is bad in a specific way: a client that allows more than the server does turns a+ * clear "too large" refusal into an upload that runs to completion and then dies on a generic+ * error.+ *+ * ## Why the numbers are what they are+ *+ * A file attachment is not multimodal input. It is written to the Session scratchpad and handed+ * to the model as an `[attached file: <path>]` line, which the model opens with its ordinary file+ * tools — the bytes never enter the conversation (see task-attachments.ts). Nothing downstream+ * therefore scales with the file's size, which is what makes a 100MB ceiling reasonable at all.+ *+ * An **inline image** is the opposite: it rides the conversation as a data URL, is written+ * verbatim into the Trace JSONL, and that file is read back whole — into a single JS string — on+ * every history page and every Session resume. A large inline image is not a slow request, it is+ * a Session that never recovers. So images keep their own much smaller ceiling+ * (INLINE_IMAGE_MAX_MB) and deliberately do NOT follow the attachment limit up.+ *+ * ## The transport tax+ *+ * A draft chat has no Session yet, so there is nowhere to upload to before the message exists:+ * attachments ride the task request itself as base64 `data:` URLs. Base64 inflates by 4/3, so the+ * body cap has to be derived from the byte budget rather than fixed, or the request dies at the+ * HTTP layer with `payload_too_large` while every attachment was individually legal.+ */++/** Bytes per MB. The admin-facing settings are whole MB; everything internal is bytes. */+const MB = 1024 * 1024;++/**+ * Per-file default. The issue asked for 100MB and nothing on the file path scales with it —+ * the bytes go to disk and are read back through the model's bounded file tools, never into+ * the conversation.+ */+export const DEFAULT_ATTACHMENT_MAX_MB = 100;++/**+ * Per-request default, kept at 1.2x the per-file default exactly as the old 10/12 pair was: one+ * full-size attachment stays sendable next to a couple of ordinary ones, without letting a single+ * message carry twenty full-size ones.+ */+export const DEFAULT_ATTACHMENT_TOTAL_MB = 120;++/** Floor for both admin-settable limits: below 1MB the feature stops being useful at all. */+export const MIN_ATTACHMENT_MB = 1;++/**+ * Ceiling for both admin-settable limits — the reason an admin typing 100GB is refused rather+ * than obeyed.+ *+ * This is not a taste judgement, it is where the transport actually stops working. The whole+ * request body is buffered and JSON-parsed as one string, and V8 caps a string near 512MB. At+ * 200MB of decoded attachments the body is ~267MB of base64 plus headroom — comfortably inside+ * that wall, with the peak memory of one such request (raw body + parsed string + decoded+ * buffers) still on the order of a gigabyte. Anything materially larger stops failing with a 413+ * and starts failing with a RangeError, which is exactly the "worse than a clear refusal" outcome+ * this module exists to prevent.+ */+export const MAX_ATTACHMENT_MB = 200;++/**+ * Per-request file count. Deliberately NOT admin-settable: it bounds how many files one message+ * can name, which is a composer-usability question, not a server-resource one — the byte budgets+ * above are what actually bound memory and disk. 20 is far past any plausible composer use (the+ * chip row stops being usable long before that) while still allowing "drop a folder of small+ * files in".+ */+export const MAX_ATTACHMENT_COUNT = 20;++/**+ * Per-image ceiling for images that ride the conversation inline.+ *+ * Before this existed, images were bounded by nothing but the global body cap — the only reason a+ * 50MB paste failed was that the body cap happened to be 20MB. Raising that cap for attachments+ * would have silently handed images the new ceiling too, letting one paste write a 100MB+ record+ * into the Trace. 20MB is above what the old body cap effectively allowed (~15MB decoded), so no+ * paste that works today stops working; it is a bound where there was none, not a new restriction.+ *+ * Note this is the *transport* ceiling, not a promise the model will accept the image: providers+ * impose their own per-image limits (commonly ~5MB), and core's `read_image` tool caps at 5MB.+ * An image between those numbers and this one uploads fine and may still be refused by the model.+ */+export const INLINE_IMAGE_MAX_MB = 20;++/** Byte length of the base64 encoding of `bytes` bytes (4 characters per 3-byte group, padded). */+export function base64Length(bytes: number): number {+ return Math.ceil(bytes / 3) * 4;+}++/**+ * Slack added on top of the base64'd attachment budget when deriving the body cap: one full-size+ * inline image (images are capped individually but not in aggregate, so the body cap is what+ * bounds a request carrying several), plus 4MB for the message text and the JSON framing around+ * all of it. Derived rather than hardcoded so that changing the image ceiling cannot leave the+ * body cap too small to carry one.+ *+ * A request that fills the whole attachment budget *and* carries a full-size image is over the cap+ * and is refused — correctly, since that is genuinely more than the budget allows.+ */+const BODY_HEADROOM_BYTES = base64Length(INLINE_IMAGE_MAX_MB * MB) + 4 * MB;++/**+ * The resolved, in-force limits for one request, in bytes. Read fresh per request from the+ * settings repo rather than snapshotted at boot, so an admin's change applies to the very next+ * upload without a restart.+ */+export interface AttachmentLimits {+ /** Per-file cap. */+ maxBytes: number;+ /** Per-request total of decoded attachment bytes. */+ totalBytes: number;+ /** Per-request file count. */+ maxCount: number;+}++/** Admin-settable limits as they travel over the API: whole MB, which is the unit the form uses. */+export interface AttachmentLimitsMb {+ attachmentMaxMb: number;+ attachmentTotalMb: number;+}++/** Resolve the MB-denominated settings into the byte limits the validators enforce. */+export function toAttachmentLimits(mb: AttachmentLimitsMb): AttachmentLimits {+ return {+ maxBytes: mb.attachmentMaxMb * MB,+ totalBytes: mb.attachmentTotalMb * MB,+ maxCount: MAX_ATTACHMENT_COUNT,+ };+}++/** The inline-image ceiling in bytes (a constant, but expressed through the same MB unit). */+export const INLINE_IMAGE_MAX_BYTES = INLINE_IMAGE_MAX_MB * MB;++/**+ * The global request body cap implied by the attachment budget.+ *+ * Derived rather than fixed so the two can never disagree: the cap is always large enough for a+ * full attachment budget once base64 has inflated it, and no larger than that plus one image's+ * worth of headroom. An admin who lowers the attachment limit gets a smaller body cap back — the+ * server does not keep accepting 300MB bodies because it once could.+ */+export function bodyLimitBytes(mb: AttachmentLimitsMb): number {+ return base64Length(mb.attachmentTotalMb * MB) + BODY_HEADROOM_BYTES;+}++/**+ * Clamp a stored setting back into range. Rows are written only through the validated PUT, so+ * this matters for a value that predates a change to the bounds, or a hand-edited database —+ * cases where refusing to start would be a worse answer than using the nearest legal number.+ */+export function clampAttachmentMb(value: number, fallback: number): number {+ if (!Number.isFinite(value) || !Number.isInteger(value)) return fallback;+ return Math.min(MAX_ATTACHMENT_MB, Math.max(MIN_ATTACHMENT_MB, value));+}diff --git a/packages/server/src/services/task-attachments.ts b/packages/server/src/services/task-attachments.tsindex 805aad87..1ffced05 100644--- a/packages/server/src/services/task-attachments.ts+++ b/packages/server/src/services/task-attachments.ts@@ -24,30 +24,17 @@ import {import type { OmniMessage } from "@prismshadow/penguin-core";import { HttpError } from "../http/errors.js";import { badRequest } from "../http/validate.js";+import type { AttachmentLimits } from "./attachment-limits.js";/**- * Per-file cap. Deliberately below the workspace upload's 14MB: several attachments can ride- * one task request, and the whole body still has to fit the global 20MB limit (base64 inflates- * by 4/3), so a smaller per-file ceiling keeps "one big file" working while leaving room for- * "a handful of ordinary ones". Oversize is a 413, matching the workspace upload route.+ * The size limits are no longer constants here: they are admin-settable (see attachment-limits.ts+ * for the numbers and the reasoning) and are resolved per request, so a change applies to the very+ * next upload without a restart. The caps are still enforced in THIS module rather than delegated+ * to the global body cap — that cap is derived from these limits, and a validator that depends on+ * the middleware upstream of it would be silently unbounded by a caller that never passes through+ * it. Without the per-request caps a legal body fits ~350k minimal `file` parts, which is 350k+ * sequential writes into one directory and 350k marker lines on one message.*/-export const MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024;--/**- * Per-request caps, checked while the parts are validated — before a single byte reaches the- * disk. They are deliberately NOT delegated to the global body cap: this module has to hold on- * its own, so that a change to that middleware (or a caller that never goes through it) cannot- * silently unbound it. Without them a legal 20MB body fits ~350k minimal `file` parts, which is- * 350k sequential writes into one directory and 350k marker lines on one message.- *- * 20 files is far past any plausible composer use — the chip row stops being usable long before- * that — while still allowing "drop a folder of small files in". 12MB of decoded bytes keeps one- * full-size 10MB attachment usable next to a couple of ordinary ones; base64 inflates by 4/3, so- * 12MB decoded is ~16MB of body and this cap, not the 20MB body cap, is the one a caller- * actually reaches.- */-export const MAX_ATTACHMENT_COUNT = 20;-export const MAX_TOTAL_ATTACHMENT_BYTES = 12 * 1024 * 1024;/*** Longest stem kept on disk, measured in **UTF-8 bytes**: filesystems cap a name near 255@@ -118,6 +105,7 @@ export interface TaskAttachment {export function parseAttachmentPart(part: Record<string, unknown>,index: number,+ limits: AttachmentLimits,field = "input",): TaskAttachment {const fileName = part.fileName;@@ -150,11 +138,11 @@ export function parseAttachmentPart(if (bytes.length === 0) {throw badRequest(`${field}[${index}].dataUrl decodes to an empty file.`);}- if (bytes.length > MAX_ATTACHMENT_BYTES) {+ if (bytes.length > limits.maxBytes) {throw new HttpError(413,"file_too_large",- `Attached file exceeds the ${MAX_ATTACHMENT_BYTES / (1024 * 1024)}MB limit.`,+ `Attached file exceeds the ${limits.maxBytes / (1024 * 1024)}MB limit.`,);}return { fileName, bytes, mime: match[1]! };@@ -202,21 +190,24 @@ export async function readRecalledFiles(* dedicated `too_many_files` code, the aggregate the `payload_too_large` the body cap already* uses — from the caller's side it is the same "this request is too big" outcome.*/-export function assertAttachmentBudget(attachments: TaskAttachment[]): void {- if (attachments.length > MAX_ATTACHMENT_COUNT) {+export function assertAttachmentBudget(+ attachments: TaskAttachment[],+ limits: AttachmentLimits,+): void {+ if (attachments.length > limits.maxCount) {throw new HttpError(413,"too_many_files",- `A message may carry at most ${MAX_ATTACHMENT_COUNT} attached files.`,+ `A message may carry at most ${limits.maxCount} attached files.`,);}let total = 0;for (const a of attachments) total += a.bytes.length;- if (total > MAX_TOTAL_ATTACHMENT_BYTES) {+ if (total > limits.totalBytes) {throw new HttpError(413,"payload_too_large",- `Attached files exceed the ${MAX_TOTAL_ATTACHMENT_BYTES / (1024 * 1024)}MB total limit for one message.`,+ `Attached files exceed the ${limits.totalBytes / (1024 * 1024)}MB total limit for one message.`,);}}diff --git a/packages/server/test/admin-settings.test.ts b/packages/server/test/admin-settings.test.tsindex 51b65ab0..f1978d81 100644--- a/packages/server/test/admin-settings.test.ts+++ b/packages/server/test/admin-settings.test.ts@@ -4,9 +4,21 @@* legacy single-switch key, PUT persistence and validation (proxy-address normalization* and rejection), and merge semantics (an omitted field keeps its current value; a* rejected PUT writes nothing).+ *+ * The upload limits ride the same route and are covered here too: their defaults, the bounded+ * range (the reason "100GB" is a clear refusal rather than an accepted number), the relation+ * between the two — the total may not sit below the per-file cap, checked against the EFFECTIVE+ * post-write pair so a one-field PUT cannot create an unsendable configuration — and the same+ * atomicity guarantee the proxy fields have.*/import { afterEach, beforeEach, describe, expect, it } from "vitest";import type { ServerSettingsResponse } from "../src/api/types.js";+import {+ DEFAULT_ATTACHMENT_MAX_MB,+ DEFAULT_ATTACHMENT_TOTAL_MB,+ MAX_ATTACHMENT_MB,+ MIN_ATTACHMENT_MB,+} from "../src/services/attachment-limits.js";import { apiClient, createTestApp, loginAdmin, provisionUser } from "./helpers.js";import type { TestApp } from "./helpers.js";@@ -170,4 +182,100 @@ describe("admin server settings", () => {expect(settings.proxyForAgent).toBe(true);expect(settings.proxyUrl).toBe("http://proxy.corp.example:8080");});++ it("upload limits: defaults with no rows, and a 403 for a non-admin on both verbs", async () => {+ const { settings } = await getSettings();+ expect(settings.attachmentMaxMb).toBe(DEFAULT_ATTACHMENT_MAX_MB);+ expect(settings.attachmentTotalMb).toBe(DEFAULT_ATTACHMENT_TOTAL_MB);+ const { cookie } = await provisionUser(t.app, "limitless");+ const api = apiClient(t.app, cookie);+ expect((await api.get("/api/admin/settings")).status).toBe(403);+ expect((await api.put("/api/admin/settings", { attachmentMaxMb: 1 })).status).toBe(403);+ // The refused PUT wrote nothing.+ expect(t.deps.serverSettingsRepo.getAttachmentMaxMb()).toBe(DEFAULT_ATTACHMENT_MAX_MB);+ });++ it("upload limits: a valid PUT persists, echoes, and needs no restart to take effect", async () => {+ const res = await admin.put("/api/admin/settings", {+ attachmentMaxMb: 25,+ attachmentTotalMb: 40,+ });+ expect(res.status).toBe(200);+ const echoed = ((await res.json()) as ServerSettingsResponse).settings;+ expect(echoed.attachmentMaxMb).toBe(25);+ expect(echoed.attachmentTotalMb).toBe(40);+ // Round-trip through the repo, which is what the validators and the body cap read per+ // request — the response echoing the right number would not prove the server uses it.+ expect(t.deps.serverSettingsRepo.getAttachmentLimitsMb()).toEqual({+ attachmentMaxMb: 25,+ attachmentTotalMb: 40,+ });+ });++ it("upload limits: out-of-range values are refused with invalid_attachment_limit", async () => {+ // 102400 is "100GB" typed into a MB field — the case the bounds exist for. Zero, a negative,+ // a fraction and a string are the other ways a form can produce nonsense.+ for (const bad of [102400, MAX_ATTACHMENT_MB + 1, 0, -5, 1.5, "100", null]) {+ const res = await admin.put("/api/admin/settings", { attachmentMaxMb: bad });+ expect(res.status, JSON.stringify(bad)).toBe(400);+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe(+ "invalid_attachment_limit",+ );+ }+ // Nothing was written by any of them.+ expect(t.deps.serverSettingsRepo.getAttachmentMaxMb()).toBe(DEFAULT_ATTACHMENT_MAX_MB);+ });++ it("upload limits: the extremes of the allowed range are accepted", async () => {+ const res = await admin.put("/api/admin/settings", {+ attachmentMaxMb: MIN_ATTACHMENT_MB,+ attachmentTotalMb: MIN_ATTACHMENT_MB,+ });+ expect(res.status).toBe(200);+ const max = await admin.put("/api/admin/settings", {+ attachmentMaxMb: MAX_ATTACHMENT_MB,+ attachmentTotalMb: MAX_ATTACHMENT_MB,+ });+ expect(max.status).toBe(200);+ expect(t.deps.serverSettingsRepo.getAttachmentMaxMb()).toBe(MAX_ATTACHMENT_MB);+ });++ it("upload limits: the total may not sit below the per-file cap", async () => {+ const both = await admin.put("/api/admin/settings", {+ attachmentMaxMb: 50,+ attachmentTotalMb: 20,+ });+ expect(both.status).toBe(400);+ expect(((await both.json()) as { error: { code: string } }).error.code).toBe(+ "invalid_attachment_limit",+ );+ expect(t.deps.serverSettingsRepo.getAttachmentMaxMb()).toBe(DEFAULT_ATTACHMENT_MAX_MB);+ });++ it("upload limits: the relation is checked against the effective pair, not just the body", async () => {+ await admin.put("/api/admin/settings", { attachmentMaxMb: 10, attachmentTotalMb: 12 });+ // Raising ONLY the per-file cap past the stored total would leave a legal single attachment+ // unsendable, so it is refused even though the body carries no total at all.+ const raise = await admin.put("/api/admin/settings", { attachmentMaxMb: 100 });+ expect(raise.status).toBe(400);+ // Lowering ONLY the total below the stored per-file cap is the same fault from the other side.+ const lower = await admin.put("/api/admin/settings", { attachmentTotalMb: 5 });+ expect(lower.status).toBe(400);+ // Neither attempt changed anything.+ expect(t.deps.serverSettingsRepo.getAttachmentLimitsMb()).toEqual({+ attachmentMaxMb: 10,+ attachmentTotalMb: 12,+ });+ });++ it("upload limits: a PUT mixing a good proxy field with a bad limit writes neither", async () => {+ const res = await admin.put("/api/admin/settings", {+ proxyForApp: false,+ attachmentMaxMb: 999999,+ });+ expect(res.status).toBe(400);+ const { settings } = await getSettings();+ expect(settings.proxyForApp).toBe(true);+ expect(settings.attachmentMaxMb).toBe(DEFAULT_ATTACHMENT_MAX_MB);+ });});diff --git a/packages/server/test/body-limit.test.ts b/packages/server/test/body-limit.test.tsindex 9f2a25d1..a8bd42db 100644--- a/packages/server/test/body-limit.test.ts+++ b/packages/server/test/body-limit.test.ts@@ -1,17 +1,24 @@/**- * Global request body cap (`/api/*`, 20MB).+ * Global request body cap (`/api/*`).** The cap used to read `content-length` only, which a chunked request simply does not carry —* `Number(undefined ?? 0)` is 0, so a body of any size passed straight through to the sinks* behind it (task input images, file attachments, Trace import). These tests post a body with* **no declared length** and require the same 413 `payload_too_large` a declared one gets, plus* an under-cap streamed body still arriving intact (the cap has to re-feed what it counted).+ *+ * The cap is no longer a constant: it is derived from the admin-settable attachment budget+ * (bodyLimitBytes). So these tests turn that budget down to its floor and compute the expected+ * cap with the same helper the server uses — which makes them a test of the derivation too, not+ * just of the middleware. A hardcoded byte count here would silently stop testing the cap the+ * moment the defaults moved.*/import { afterEach, beforeEach, describe, expect, it } from "vitest";import { assistantText } from "@prismshadow/penguin-core";import type { OmniMessage } from "@prismshadow/penguin-core";import type { SessionRow } from "../src/db/repos/sessions.js";import type { RuntimeSession } from "../src/runtime/session-manager.js";+import { bodyLimitBytes, MIN_ATTACHMENT_MB } from "../src/services/attachment-limits.js";import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";import type { TestApp } from "./helpers.js";@@ -57,6 +64,8 @@ describe("request body cap", () => {let api: ReturnType<typeof apiClient>;let cookie: string;let runs: OmniMessage[][];+ /** The body cap implied by the budget set in beforeEach. */+ let cap: number;const postStream = (fill: number) =>t.app.request(`/api/sessions/${SID}/tasks`, {@@ -100,13 +109,21 @@ describe("request body cap", () => {async *compact() {},};t.deps.manager.adopt(row, session);+ // Smallest budget an admin can set, so the derived cap is as low as it goes and the+ // over-cap body these tests have to stream stays cheap to produce.+ t.deps.serverSettingsRepo.setAttachmentMaxMb(MIN_ATTACHMENT_MB);+ t.deps.serverSettingsRepo.setAttachmentTotalMb(MIN_ATTACHMENT_MB);+ cap = bodyLimitBytes({+ attachmentMaxMb: MIN_ATTACHMENT_MB,+ attachmentTotalMb: MIN_ATTACHMENT_MB,+ });});afterEach(async () => {await t.cleanup();});it("a body with no declared length is still capped", async () => {- const res = await postStream(24 * MB);+ const res = await postStream(cap + 2 * MB);expect(res.status).toBe(413);expect(((await res.json()) as { error: { code: string } }).error.code).toBe("payload_too_large",@@ -122,7 +139,7 @@ describe("request body cap", () => {headers: {cookie,"content-type": "application/json",- "content-length": String(21 * MB),+ "content-length": String(cap + MB),},body: JSON.stringify({ input: [{ type: "text", text: "small" }] }),});diff --git a/packages/server/test/task-attachments.test.ts b/packages/server/test/task-attachments.test.tsindex 789b0fc6..5997df0a 100644--- a/packages/server/test/task-attachments.test.ts+++ b/packages/server/test/task-attachments.test.ts@@ -25,17 +25,24 @@ import {import type { OmniMessage } from "@prismshadow/penguin-core";import type { SessionRow } from "../src/db/repos/sessions.js";import type { RuntimeSession } from "../src/runtime/session-manager.js";-import {- MAX_ATTACHMENT_BYTES,- MAX_ATTACHMENT_COUNT,- MAX_TOTAL_ATTACHMENT_BYTES,-} from "../src/services/task-attachments.js";+import { MAX_ATTACHMENT_COUNT } from "../src/services/attachment-limits.js";import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";import type { TestApp } from "./helpers.js";const SID = "session-2026-07-29-10-00-00-aabb0001";const PROJECT_ID = "attacher-default_project";+/**+ * Deliberately tiny limits for the cap tests (see beforeEach), in whole MB and in bytes. The+ * total is kept below twice the per-file cap so that "two individually legal files that together+ * cross the aggregate" is expressible — with total >= 2x per-file, each half would trip the+ * per-file check first and the aggregate cap would never be the thing under test.+ */+const TEST_MAX_MB = 2;+const TEST_TOTAL_MB = 3;+const TEST_MAX_BYTES = TEST_MAX_MB * 1024 * 1024;+const TEST_TOTAL_BYTES = TEST_TOTAL_MB * 1024 * 1024;+/** Fake Session that records each run's input and finishes immediately (no LLM, no approvals). */function recordingFakeSession(sessionId: string, runs: OmniMessage[][]): RuntimeSession {return {@@ -104,6 +111,12 @@ describe("task input file attachments", () => {runs = [];t.deps.manager.adopt(row, recordingFakeSession(SID, runs));dir = path.join(scratchpadDir(t.root, PROJECT_ID, "default_agent"), SID);+ // The shipped defaults are 100MB/120MB — allocating buffers that size to prove a cap works+ // would cost hundreds of megabytes per assertion. The caps are read from the settings repo+ // per request, so the tests turn them down instead: that also makes these the tests of the+ // *configured* limit rather than of a compiled-in constant.+ t.deps.serverSettingsRepo.setAttachmentMaxMb(TEST_MAX_MB);+ t.deps.serverSettingsRepo.setAttachmentTotalMb(TEST_TOTAL_MB);});afterEach(async () => {await t.cleanup();@@ -250,7 +263,7 @@ describe("task input file attachments", () => {type: "file",fileName: "big.bin",dataUrl: `data:application/octet-stream;base64,${Buffer.alloc(- MAX_ATTACHMENT_BYTES + 1,+ TEST_MAX_BYTES + 1,).toString("base64")}`,},],@@ -260,6 +273,63 @@ describe("task input file attachments", () => {await expect(fs.access(dir)).rejects.toThrow();});+ it("what /api/me advertises is exactly what the upload path enforces", async () => {+ // The composer refuses an oversize pick using the number this endpoint hands it, so the two+ // must agree on the boundary itself, not merely be "about the same". A file of exactly the+ // advertised limit has to be accepted and one byte more has to be refused — if the server+ // were stricter by a byte, the composer would upload a file the server then rejects, which is+ // precisely the failure the client-side check exists to prevent.+ const me = (await api.get("/api/me")).clone();+ const { uploadLimits } = (await me.json()) as {+ uploadLimits: { attachmentMaxMb: number; attachmentTotalMb: number; imageMaxMb: number };+ };+ expect(uploadLimits.attachmentMaxMb).toBe(TEST_MAX_MB);+ expect(uploadLimits.attachmentTotalMb).toBe(TEST_TOTAL_MB);++ const atLimit = await api.post(`/api/sessions/${SID}/tasks`, {+ input: [+ {+ type: "file",+ fileName: "exact.bin",+ dataUrl: `data:application/octet-stream;base64,${Buffer.alloc(+ uploadLimits.attachmentMaxMb * 1024 * 1024,+ ).toString("base64")}`,+ },+ ],+ });+ expect(atLimit.status).toBe(202);+ await waitFor(() => runs.length === 1);++ const overLimit = await api.post(`/api/sessions/${SID}/tasks`, {+ input: [+ {+ type: "file",+ fileName: "over.bin",+ dataUrl: `data:application/octet-stream;base64,${Buffer.alloc(+ uploadLimits.attachmentMaxMb * 1024 * 1024 + 1,+ ).toString("base64")}`,+ },+ ],+ });+ expect(overLimit.status).toBe(413);+ });++ it("an inline image over its own cap is a 413, and the cap does not follow the attachment limit", async () => {+ // Images are bounded separately and far lower: they enter the conversation and the Trace,+ // where the bytes are paid again on every history page and every resume. Raising the+ // attachment ceiling must not raise this one — so the image here is well under the+ // attachment cap that the surrounding suite configured, and still refused.+ const me = (await api.get("/api/me")).clone();+ const { uploadLimits } = (await me.json()) as { uploadLimits: { imageMaxMb: number } };+ const oversize = Buffer.alloc(uploadLimits.imageMaxMb * 1024 * 1024 + 1).toString("base64");+ const res = await api.post(`/api/sessions/${SID}/tasks`, {+ input: [{ type: "image_url", imageUrl: `data:image/png;base64,${oversize}` }],+ });+ expect(res.status).toBe(413);+ expect(((await res.json()) as { error: { code: string } }).error.code).toBe("image_too_large");+ expect(runs).toHaveLength(0);+ });+it("goal mode rejects attachments before anything is written", async () => {const res = await api.post(`/api/sessions/${SID}/tasks`, {input: [@@ -310,7 +380,7 @@ describe("task input file attachments", () => {it("more than the per-request total size is a 413 and writes nothing", async () => {// Two files, each individually legal, that together cross the aggregate cap: the per-file// check alone would let this through and land both on disk.- const half = Buffer.alloc(Math.floor(MAX_TOTAL_ATTACHMENT_BYTES / 2) + 1).toString("base64");+ const half = Buffer.alloc(Math.floor(TEST_TOTAL_BYTES / 2) + 1).toString("base64");const res = await api.post(`/api/sessions/${SID}/tasks`, {input: [{diff --git a/packages/web/src/components/account/upload-limits-dialog.tsx b/packages/web/src/components/account/upload-limits-dialog.tsxnew file mode 100644index 00000000..2fdad1a8--- /dev/null+++ b/packages/web/src/components/account/upload-limits-dialog.tsx@@ -0,0 +1,160 @@+/**+ * Admin upload-limits dialog (server-global), opened from the sidebar user menu next to the+ * proxy options it is modelled on. Two whole-MB numbers — the per-file attachment cap and the+ * per-message total — written together by a single PUT to /api/admin/settings, so a rejected+ * value writes nothing.+ *+ * The bounds and the fixed limits quoted in the hint come from the server (`/api/me`+ * uploadLimits) rather than from constants here: the range is a statement about what the server+ * can survive, and a second copy of it in the browser would be a copy that goes stale. A value+ * outside it is refused by the server with `invalid_attachment_limit` and rendered inline under+ * the field, the same way the proxy dialog handles a bad address.+ *+ * Saving takes effect immediately — the attachment validators and the request body cap both read+ * the setting per request — so there is nothing to restart and nothing to warn about.+ */+import { useEffect, useState } from "react";+import type { ServerSettings } from "@prismshadow/penguin-server/api";+import * as api from "../../api/endpoints";+import { ApiError } from "../../api/client";+import { S } from "../../lib/strings";+import { apiErrorText } from "../../lib/api-error";+import { useAuth } from "../../state/auth";+import { Button } from "../ui/button";+import { Input } from "../ui/input";+import { Modal } from "../ui/modal";+import { toastError, toastInfo, toastSuccess } from "../ui/toast";++export function UploadLimitsDialog({ open, onClose }: { open: boolean; onClose: () => void }) {+ const { uploadLimits, refresh } = useAuth();+ /** Stored settings as hydrated on open (null until then) — the no-change baseline. */+ const [settings, setSettings] = useState<ServerSettings | null>(null);+ // Kept as strings: a number input that clears to NaN cannot be typed into (backspacing the+ // last digit would snap the field back to a value the user is in the middle of replacing).+ const [maxMb, setMaxMb] = useState("");+ const [totalMb, setTotalMb] = useState("");+ /** Inline error under whichever field the server rejected. */+ const [limitError, setLimitError] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);++ useEffect(() => {+ if (!open) return;+ let cancelled = false;+ setSettings(null);+ setLimitError(null);+ setBusy(false);+ void api+ .adminGetSettings()+ .then((res) => {+ if (cancelled) return;+ setSettings(res.settings);+ setMaxMb(String(res.settings.attachmentMaxMb));+ setTotalMb(String(res.settings.attachmentTotalMb));+ })+ .catch((e: unknown) => {+ // Controls stay disabled; closing and reopening retries the fetch.+ if (!cancelled) toastError(apiErrorText(e));+ });+ return () => {+ cancelled = true;+ };+ }, [open]);++ const save = async () => {+ if (settings === null || busy) return;+ const parsedMax = Number(maxMb.trim());+ const parsedTotal = Number(totalMb.trim());+ // Shape-check locally so an empty or non-numeric field never becomes a NaN in the request+ // body; the RANGE is left to the server, which owns it (this dialog only reports its verdict).+ if (+ maxMb.trim() === "" ||+ totalMb.trim() === "" ||+ !Number.isInteger(parsedMax) ||+ !Number.isInteger(parsedTotal)+ ) {+ setLimitError(S.errors.byCode.invalid_attachment_limit);+ return;+ }+ if (parsedMax === settings.attachmentMaxMb && parsedTotal === settings.attachmentTotalMb) {+ toastInfo(S.common.noChangesToSave);+ return;+ }+ setBusy(true);+ setLimitError(null);+ try {+ await api.adminPutSettings({ attachmentMaxMb: parsedMax, attachmentTotalMb: parsedTotal });+ // The composer reads the limits from /api/me, so re-pull them: without this the tab that+ // just raised the cap would keep refusing files at the old number until the next reload.+ await refresh().catch(() => {});+ toastSuccess(S.common.saved);+ onClose();+ } catch (e) {+ if (e instanceof ApiError && e.code === "invalid_attachment_limit") {+ setLimitError(apiErrorText(e));+ } else {+ toastError(apiErrorText(e));+ }+ } finally {+ setBusy(false);+ }+ };++ const hydrated = settings !== null;+ return (+ <Modal+ open={open}+ title={S.settings.uploadLimitsDialogTitle}+ onClose={onClose}+ footer={+ <>+ <Button onClick={onClose} disabled={busy}>+ {S.common.cancel}+ </Button>+ <Button variant="primary" disabled={!hydrated || busy} onClick={() => void save()}>+ {S.common.save}+ </Button>+ </>+ }+ >+ <div className="space-y-4">+ <Input+ label={S.settings.attachmentMaxMb}+ size="sm"+ type="number"+ inputMode="numeric"+ min={uploadLimits.attachmentLimitMinMb}+ max={uploadLimits.attachmentLimitMaxMb}+ value={maxMb}+ disabled={!hydrated}+ onChange={(e) => {+ setMaxMb(e.target.value);+ if (limitError !== null) setLimitError(null);+ }}+ />+ <Input+ label={S.settings.attachmentTotalMb}+ size="sm"+ type="number"+ inputMode="numeric"+ min={uploadLimits.attachmentLimitMinMb}+ max={uploadLimits.attachmentLimitMaxMb}+ value={totalMb}+ disabled={!hydrated}+ {...(limitError !== null ? { error: limitError } : {})}+ onChange={(e) => {+ setTotalMb(e.target.value);+ if (limitError !== null) setLimitError(null);+ }}+ />+ <p className="text-xs text-gray-500 dark:text-gray-400">+ {S.settings.uploadLimitsHint(+ uploadLimits.attachmentLimitMinMb,+ uploadLimits.attachmentLimitMaxMb,+ uploadLimits.attachmentMaxCount,+ uploadLimits.imageMaxMb,+ )}+ </p>+ </div>+ </Modal>+ );+}diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex 23e039d2..2350501e 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -145,6 +145,7 @@ import type { DraftSessionEntry } from "../../features/chat/draft-sessions";import { CreateProjectDialog, ProjectSettingsDialog } from "./project-dialogs";import { ChangePasswordDialog } from "../account/change-password-dialog";import { ProxySettingsDialog } from "../account/proxy-settings-dialog";+import { UploadLimitsDialog } from "../account/upload-limits-dialog";import { UpdateDialog } from "../account/update-dialog";import { forceUpdateCheck, updateCheckOutcome, useVersionInfo } from "../../lib/use-version-info";@@ -367,6 +368,11 @@ export function Sidebar({* ProxySettingsDialog.*/const [proxySettingsOpen, setProxySettingsOpen] = useState(false);+ /**+ * Admin-only server-global upload limits, alongside the proxy row and built the same way:+ * the menu carries the opener, the form and its hydration live in UploadLimitsDialog.+ */+ const [uploadLimitsOpen, setUploadLimitsOpen] = useState(false);const currentProjectId = currentProject?.projectId ?? null;/** This Project's read markers; re-renders the rows whenever one is stamped. */const sessionSeen = useSessionSeen(currentProjectId);@@ -1791,6 +1797,20 @@ export function Sidebar({{S.settings.proxyMenu}</button>)}+ {/* Admin-only, server-global upload limits: same one-row idiom as the proxy+ opener above. */}+ {user?.isAdmin && (+ <button+ type="button"+ className={menuItemClass}+ onClick={() => {+ setUserOpen(false);+ setUploadLimitsOpen(true);+ }}+ >+ {S.settings.uploadLimitsMenu}+ </button>+ )}{/* THE update row — one button, two jobs, directly below Change password (ownerlayout: the menu used to stack a release-notes link, an admin "Update now" rowand this check row on top of each other). It reads "Check for updates" and runs@@ -1889,6 +1909,7 @@ export function Sidebar({onClose={() => setChangePasswordOpen(false)}/><ProxySettingsDialog open={proxySettingsOpen} onClose={() => setProxySettingsOpen(false)} />+ <UploadLimitsDialog open={uploadLimitsOpen} onClose={() => setUploadLimitsOpen(false)} /><UpdateDialogopen={updateDialogOpen}onClose={() => setUpdateDialogOpen(false)}diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsxindex 8a6807e8..cd3bdc86 100644--- a/packages/web/src/features/chat/chat-input.tsx+++ b/packages/web/src/features/chat/chat-input.tsx@@ -82,6 +82,7 @@ import { S } from "../../lib/strings";import { formatBytes, humanizeTokens } from "../../lib/format";import { resolveContextWindow } from "../../lib/context";import { useLocale } from "../../state/locale";+import { useAuth } from "../../state/auth";import { agentDisplayName } from "../../state/project";import { AgentAvatar } from "../../components/ui/agent-avatar";import { Dropdown } from "../../components/ui/dropdown";@@ -116,6 +117,7 @@ import { isStopAction, midRunAction } from "./composer-send";import { PAPERCLIP_ICON } from "./attached-files-banner";import { FileDropZone } from "./drop-zone";import { splitDroppedFiles } from "../../lib/file-drop";+import { splitBySize } from "../../lib/upload-limits";const APPROVAL_MODES: ApprovalMode[] = ["always-ask", "read-only", "allow-all", "deny-all"];@@ -809,8 +811,14 @@ interface Attachment {dataUrl: string;}-/** Mirrors the server's per-file attachment cap (services/task-attachments.ts), so an oversize pick is refused here instead of costing an upload and a 413. */-const MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024;+/**+ * The upload caps are no longer compiled in here: they are admin-settable and arrive on+ * `/api/me` (see state/auth uploadLimits), so this check and the server's cannot drift apart and+ * the toast can name the number actually in force. Enforcing it client-side at all is still+ * worth it — an oversize pick is refused before the file is read, instead of costing the user a+ * base64 encode, an upload 33% larger than the file, and a 413 to learn the same thing. The+ * partition itself lives in lib/upload-limits (splitBySize), shared with the image intake.+ *//** Reads one file as a base64 data URL; resolves to null on a read error rather than rejecting, so one unreadable file cannot drop the rest of the batch. */function readDataUrl(file: File): Promise<string | null> {@@ -1144,6 +1152,9 @@ export function ChatInput({onNewSession?: () => void;}) {const { locale } = useLocale();+ // Admin-settable, delivered on /api/me: the pre-flight checks below and the numbers in their+ // messages both come from here, so what the composer refuses is exactly what the server would.+ const { uploadLimits } = useAuth();const [text, setText] = useState(initialText ?? "");/** Live text mirror for slash-command run() closures (the commands memo deliberately doesn't depend on text). */const textRef = useRef(text);@@ -1995,8 +2006,17 @@ export function ChatInput({};const addFiles = (files: Iterable<File>) => {- for (const file of files) {- if (!file.type.startsWith("image/")) continue;+ // Images had no size check at all: an oversize paste was read into a data URL, JSON'd and+ // uploaded, freezing the tab on the way to a generic body-cap 413. They are capped well+ // below file attachments on purpose — an inline image rides the conversation and the Trace,+ // where its size is paid again on every history page and every resume.+ const imageFiles: File[] = [];+ for (const file of files) if (file.type.startsWith("image/")) imageFiles.push(file);+ const { accepted, rejected } = splitBySize(imageFiles, uploadLimits.imageMaxMb);+ for (const file of rejected) {+ toastError(S.chat.attachmentTooLarge(file.name, uploadLimits.imageMaxMb));+ }+ for (const file of accepted) {const reader = new FileReader();reader.onload = () => {if (typeof reader.result === "string") {@@ -2041,13 +2061,9 @@ export function ChatInput({*/const addAttachments = (files: Iterable<File>) => {if (goalOn) return; // goal input is text-only, same rule as images- const picked: File[] = [];- for (const file of files) {- if (file.size > MAX_ATTACHMENT_BYTES) {- toastError(S.chat.attachmentTooLarge(file.name));- continue;- }- picked.push(file);+ const { accepted: picked, rejected } = splitBySize(files, uploadLimits.attachmentMaxMb);+ for (const file of rejected) {+ toastError(S.chat.attachmentTooLarge(file.name, uploadLimits.attachmentMaxMb));}if (picked.length === 0) return;void Promise.all(picked.map(readDataUrl)).then((urls) => {@@ -2066,7 +2082,8 @@ export function ChatInput({/*** Files dropped onto the chat area (see FileDropZone): one batch, routed into the SAME two* intakes the "+" menu and paste use — images join the pasted-image pipeline, everything- * else joins the file-attachment pipeline (10MB cap, same rejection toast). Goal mode takes+ * else joins the file-attachment pipeline (each with its own cap and the same rejection toast,+ * see uploadLimits). Goal mode takes* images but not files (nothing folds a file into the re-injected objective — the "+" menu* grays its file entry out for the same reason); a drop has no disabled affordance to gray,* so the refusal is said out loud instead of silently swallowing the files.diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 479ef6b6..8eefae79 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -42,6 +42,18 @@ export const en: Strings = {/** The shared explicit proxy address (empty = follow the proxy environment variables). */proxyAddress: "Proxy address",proxyAddressPlaceholder: "Empty = follow system proxy",+ /** Admin-only user-menu row opening the upload-limits dialog. */+ uploadLimitsMenu: "Upload limits…",+ uploadLimitsDialogTitle: "Upload limits",+ /** The dialog's two number fields, both in whole MB. */+ attachmentMaxMb: "Max attachment size (MB)",+ attachmentTotalMb: "Max total per message (MB)",+ /** Explains what the numbers govern and what stays fixed, so the form needs no separate docs trip. */+ uploadLimitsHint: (min: number, max: number, count: number, imageMb: number): string =>+ `${min}–${max} MB; the total may not be below the per-file limit. A message may carry at ` ++ `most ${count} attachments. Images placed inline in the 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.`,theme: "Theme",themeLight: "Light",themeDark: "Dark",@@ -1342,8 +1354,8 @@ Scenarios:uploadFile: "Upload file",uploadFileDesc: "Saved to the session scratchpad; the model reads them by path",removeFile: "Remove file",- attachmentTooLarge: (name: string): string =>- `${name} exceeds the 10MB limit and was not attached.`,+ attachmentTooLarge: (name: string, limitMb: number): string =>+ `${name} exceeds the ${limitMb}MB limit and was not attached.`,/** Overlay covering the chat area while files are dragged over it (drag-and-drop upload). */dropFilesTitle: "Drop files to attach",dropFilesDesc: "Images and files are added to the message draft",@@ -1554,6 +1566,7 @@ Scenarios:file_too_large: "The file is too large.",too_many_files: "Too many files attached to one message.",payload_too_large: "The request is too large.",+ image_too_large: "The image is too large to send inline.",dir_not_absolute: "The directory must be an absolute path.",dir_not_found: "That directory does not exist or is inaccessible.",not_a_dir: "That path is not a directory.",@@ -1582,6 +1595,8 @@ Scenarios:invalid_title: "The title is invalid.",invalid_proxy_url:"Invalid proxy address — use an http(s):// or socks5:// proxy URL, or host[:port].",+ invalid_attachment_limit:+ "Invalid upload limit — use a whole number of MB inside the allowed range, with the total no lower than the per-file limit.",invalid_trace: "This file is not a valid Trace file.",trace_not_found: "This Trace file no longer exists.",trace_session_exists:diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 30745ccd..5c5e37e2 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -44,6 +44,16 @@ export const zh = {/** The shared explicit proxy address (empty = follow the proxy environment variables). */proxyAddress: "代理地址",proxyAddressPlaceholder: "留空 = 跟随系统代理",+ /** Admin-only user-menu row opening the upload-limits dialog. */+ uploadLimitsMenu: "上传限制",+ uploadLimitsDialogTitle: "上传限制",+ /** The dialog's two number fields, both in whole MB. */+ attachmentMaxMb: "单个附件上限(MB)",+ attachmentTotalMb: "单条消息附件合计上限(MB)",+ /** Explains what the numbers govern and what stays fixed, so the form needs no separate docs trip. */+ uploadLimitsHint: (min: number, max: number, count: number, imageMb: number): string =>+ `取值 ${min}–${max} MB,合计不得低于单个上限。一条消息最多 ${count} 个附件;` ++ `对话内嵌图片另有 ${imageMb}MB 上限,不随此设置变化——图片会进入对话与轨迹,每次翻阅历史与恢复会话都要重新付出它的体积。`,theme: "主题",themeLight: "浅色",themeDark: "深色",@@ -1298,8 +1308,12 @@ Benchmark:uploadFile: "上传文件",uploadFileDesc: "文件存入会话临时目录,模型按路径读取",removeFile: "移除文件",- /** Toast for a picked file rejected before reading (the server's per-file cap is 10MB). */- attachmentTooLarge: (name: string): string => `${name} 超过 10MB 上限,未添加。`,+ /**+ * Toast for a picked file rejected before reading. The limit is admin-settable and differs+ * between file attachments and inline images, so it is passed in rather than written here.+ */+ attachmentTooLarge: (name: string, limitMb: number): string =>+ `${name} 超过 ${limitMb}MB 上限,未添加。`,/** Overlay covering the chat area while files are dragged over it (drag-and-drop upload). */dropFilesTitle: "松开以添加附件",dropFilesDesc: "图片与文件将添加到输入框",@@ -1512,6 +1526,7 @@ Benchmark:file_too_large: "文件过大。",too_many_files: "一条消息附加的文件过多。",payload_too_large: "请求体过大。",+ image_too_large: "图片过大,无法随对话发送。",dir_not_absolute: "目录必须是绝对路径。",dir_not_found: "该目录不存在或不可访问。",not_a_dir: "该路径不是目录。",@@ -1537,6 +1552,7 @@ Benchmark:version_conflict: "快照版本不高于当前版本。",invalid_title: "标题无效。",invalid_proxy_url: "代理地址无效:应为 http(s):// 或 socks5:// 代理 URL,或 主机[:端口]。",+ invalid_attachment_limit: "上传限制无效:请填写允许范围内的整数 MB,且合计不低于单个上限。",invalid_trace: "该文件不是有效的 Trace 文件。",trace_not_found: "该 Trace 文件已不存在。",trace_session_exists: "该 Agent 已存在同名 Session,无法导入重复的 Trace。",diff --git a/packages/web/src/lib/upload-limits.ts b/packages/web/src/lib/upload-limits.tsnew file mode 100644index 00000000..e2cb533e--- /dev/null+++ b/packages/web/src/lib/upload-limits.ts@@ -0,0 +1,55 @@+/**+ * The composer's pre-flight size check, kept DOM-free so it can be tested directly.+ *+ * Both composer intakes need it and they need it with *different* ceilings: a file attachment is+ * written to the Session scratchpad and read back by path, so it can be large, while an inline+ * image rides the conversation and the Trace and cannot. Sharing the partition function rather+ * than the number is what lets the two stay different without the check itself being written+ * twice.+ *+ * The ceilings themselves are not defined here. They are admin-settable and arrive from the+ * server on `/api/me` (see state/auth `uploadLimits`), because a limit the browser invented would+ * be a limit the server does not enforce — and the failure mode of that disagreement is the one+ * worth avoiding: a client that allows more than the server does turns a clear refusal into a+ * full upload that dies on a generic error.+ */++/** Bytes in one MB. Limits travel over the API in whole MB — the unit the admin form uses. */+export const MB_BYTES = 1024 * 1024;++/** The part of a `File` this check needs; keeps callers free to pass a test double. */+export interface SizedFile {+ name: string;+ size: number;+}++export interface SizeSplit<T> {+ /** Files within the ceiling, in the order they were picked. */+ accepted: T[];+ /** Files over it — refused before being read, so nothing is uploaded to earn the rejection. */+ rejected: T[];+}++/**+ * Split a picked batch against a per-file ceiling given in whole MB.+ *+ * The comparison is `>`, not `>=`: a file of exactly the limit is legal, matching the server's+ * own check (`bytes.length > limits.maxBytes`). An off-by-one in this direction would be+ * invisible in normal use and would reject exactly the file a user resized to fit.+ *+ * Order is preserved on both sides, because the accepted order decides the order of the chips+ * and therefore of the `[attached file: …]` lines the message ends up carrying.+ */+export function splitBySize<T extends SizedFile>(+ files: Iterable<T>,+ limitMb: number,+): SizeSplit<T> {+ const limitBytes = limitMb * MB_BYTES;+ const accepted: T[] = [];+ const rejected: T[] = [];+ for (const file of files) {+ if (file.size > limitBytes) rejected.push(file);+ else accepted.push(file);+ }+ return { accepted, rejected };+}diff --git a/packages/web/src/state/auth.tsx b/packages/web/src/state/auth.tsxindex 82218394..79921d77 100644--- a/packages/web/src/state/auth.tsx+++ b/packages/web/src/state/auth.tsx@@ -6,10 +6,25 @@*/import { createContext, useCallback, useContext, useEffect, useState } from "react";import type { ReactNode } from "react";-import type { UserInfo } from "@prismshadow/penguin-server/api";+import type { UploadLimits, UserInfo } from "@prismshadow/penguin-server/api";import * as api from "../api/endpoints";import { ApiError, setUnauthorizedHandler } from "../api/client";+/**+ * Stand-in until GET /api/me answers, matching the server's shipped defaults. The window is the+ * mount-time fetch, before a composer can be used at all; the server re-validates every upload+ * against the real limits regardless, so a stale value here can only make the composer's+ * pre-flight check slightly wrong, never let an oversize file through.+ */+const DEFAULT_UPLOAD_LIMITS: UploadLimits = {+ attachmentMaxMb: 100,+ attachmentTotalMb: 120,+ attachmentMaxCount: 20,+ imageMaxMb: 20,+ attachmentLimitMinMb: 1,+ attachmentLimitMaxMb: 200,+};+interface AuthContextValue {/** undefined = initializing; null = not logged in. */user: UserInfo | null | undefined;@@ -32,6 +47,12 @@ interface AuthContextValue {* password without the old one.*/sessionVia: "password" | "desktop";+ /**+ * Upload limits in force on this server (admin-settable). The composer reads them to refuse an+ * oversize pick before reading it and to name the real number in the message, so the client+ * check and the server check can never disagree about what "too large" means.+ */+ uploadLimits: UploadLimits;login: (userId: string, password: string) => Promise<void>;logout: () => Promise<void>;/** Refetch /api/me (e.g. to refresh the passwordIsInitial flag after a password change). */@@ -47,6 +68,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {const [previewIsolated, setPreviewIsolated] = useState(true);const [desktopMode, setDesktopMode] = useState(false);const [sessionVia, setSessionVia] = useState<"password" | "desktop">("password");+ const [uploadLimits, setUploadLimits] = useState<UploadLimits>(DEFAULT_UPLOAD_LIMITS);// Any API returning 401 (session expired / database rebuilt) clears the current user, and// RequireAuth redirects back to the login page.@@ -67,6 +89,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {setPreviewIsolated(res.previewIsolated);setDesktopMode(res.desktopMode);setSessionVia(res.sessionVia);+ setUploadLimits(res.uploadLimits);}).catch((err: unknown) => {if (cancelled) return;@@ -94,6 +117,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {setPreviewIsolated(me.previewIsolated);setDesktopMode(me.desktopMode);setSessionVia(me.sessionVia);+ setUploadLimits(me.uploadLimits);} catch {// Login itself succeeded; keep the optimistic default.}@@ -113,11 +137,21 @@ export function AuthProvider({ children }: { children: ReactNode }) {setPreviewIsolated(res.previewIsolated);setDesktopMode(res.desktopMode);setSessionVia(res.sessionVia);+ setUploadLimits(res.uploadLimits);}, []);return (<AuthContext.Provider- value={{ user, previewIsolated, desktopMode, sessionVia, login, logout, refresh }}+ value={{+ user,+ previewIsolated,+ desktopMode,+ sessionVia,+ uploadLimits,+ login,+ logout,+ refresh,+ }}>{children}</AuthContext.Provider>diff --git a/packages/web/test/upload-limits.test.ts b/packages/web/test/upload-limits.test.tsnew file mode 100644index 00000000..0f65132c--- /dev/null+++ b/packages/web/test/upload-limits.test.ts@@ -0,0 +1,52 @@+/**+ * The composer's pre-flight size check (lib/upload-limits).+ *+ * What matters here is agreement with the server rather than the function's own arithmetic: the+ * client refuses a pick only to save the user a pointless upload, so it must draw the line in+ * exactly the same place the server does — `>` the limit, not `>=` — and must draw it from the+ * limit it was handed rather than one of its own. A client stricter than the server silently+ * blocks legal files; a client looser than the server replaces a clear "too large" message with a+ * completed upload that dies on a generic error.+ */+import { describe, expect, it } from "vitest";+import { MB_BYTES, splitBySize } from "../src/lib/upload-limits";++const file = (name: string, size: number) => ({ name, size });++describe("composer upload size check", () => {+ it("accepts a file of exactly the limit and rejects one byte more", () => {+ // The server's check is `bytes.length > limit`, so the boundary file is legal. Pinning both+ // sides of it is the point: an off-by-one here rejects precisely the file a user just+ // resized to fit, and nothing else would reveal it.+ const limitMb = 10;+ const exact = file("exact.bin", limitMb * MB_BYTES);+ const over = file("over.bin", limitMb * MB_BYTES + 1);+ const { accepted, rejected } = splitBySize([exact, over], limitMb);+ expect(accepted).toEqual([exact]);+ expect(rejected).toEqual([over]);+ });++ it("follows the limit it is given, so a raised server limit raises the client check", () => {+ // The same 50MB file is refused under a 10MB limit and accepted under 100MB. This is the+ // behavior that makes the limit admin-settable at all: nothing in the client decides it.+ const big = file("big.zip", 50 * MB_BYTES);+ expect(splitBySize([big], 10).rejected).toEqual([big]);+ expect(splitBySize([big], 100).accepted).toEqual([big]);+ });++ it("keeps the picked order on both sides", () => {+ // Accepted order decides the chip order and therefore the order of the `[attached file: …]`+ // lines on the message, so the batch must not be reordered by the filtering.+ const a = file("a.txt", 1);+ const big = file("big.bin", 99 * MB_BYTES);+ const b = file("b.txt", 2);+ const big2 = file("big2.bin", 99 * MB_BYTES);+ const { accepted, rejected } = splitBySize([a, big, b, big2], 1);+ expect(accepted.map((f) => f.name)).toEqual(["a.txt", "b.txt"]);+ expect(rejected.map((f) => f.name)).toEqual(["big.bin", "big2.bin"]);+ });++ it("an empty batch splits into two empty sides", () => {+ expect(splitBySize([], 10)).toEqual({ accepted: [], rejected: [] });+ });+});