Skip to content

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

feat(server,web): a profile page sets the user's avatar and nickname (#714)

Yaowei Zheng5a2d3c99f9b1
diff --git a/changelog/unreleased/2026-09-12-user-profile.md b/changelog/unreleased/2026-09-12-user-profile.md
new file mode 100644
index 00000000..8e0f7341
--- /dev/null
+++ b/changelog/unreleased/2026-09-12-user-profile.md
@@ -0,0 +1,52 @@
+# A profile page sets the user's avatar and nickname
+
+- **Date:** 2026-09-12
+- **Type:** feature
+- **Scope:** `server`, `web`, `docs`
+- **PR:** [#714](https://github.com/Prism-Shadow/penguin-harness/pull/714)
+
+[中文版](2026-09-12-user-profile.zh.md)
+
+An account was its user id everywhere it appeared: the sidebar's bottom user row, the collapsed
+rail's trigger, the admin user list. A new **Profile** page, heading the personal group of the
+System settings dialog, gives every account an avatar and a nickname, and the surfaces that used
+to draw the id and its letter tile draw those instead.
+
+## Details
+
+- The page holds two rows and no footer: every control writes when it is used, and the button
+ that writes a value stands beside that value. **Change avatar** opens a picture picker and the
+ picked image applies at once — centre-cropped to a square and re-encoded at 128×128 as PNG, or
+ as JPEG at quality 0.85 when the PNG would pass 100 KB; an image still over 128 KiB is refused
+ inline instead of being sent for the server to reject. **Restore default** beside it puts the
+ letter tile back. The **nickname** is typed text, so it keeps an explicit **Save** next to the
+ field and a **Restore default** of its own, whose default is the user id; both write on click,
+ so the two buttons beside one field never disagree about when they act. It is 1–32 characters,
+ counted as characters so a Chinese name may be 32 of them, and saving it blank clears it. On
+ both rows the buttons hold their width and the field is what gives, so a narrow dialog never
+ breaks a label across two lines — flex will not shrink a control below its min-content width,
+ and for a CJK label that is one character, so a squeezed button stacks 恢复默认 two high where
+ an English one is held open by its longest word.
+- A button that would write what is already stored is disabled, and nothing is applied
+ optimistically: every surface, the page's own preview included, draws what is stored, so a
+ write that fails leaves the screen agreeing with the server and reports the failure inline
+ rather than showing an avatar that disappears on the next load.
+- The page is visible in every session, the desktop shell's own token window included — unlike
+ the Account page beside it, which needs a password to change. `PUT /api/me/profile` follows the
+ same rule and takes any authenticated session.
+- The route is a patch: an absent field keeps its stored value, `null` clears it, and a body
+ naming neither field is a 400. It validates the nickname's length and rejects control
+ characters in it, and requires the avatar to be a `data:image/(png|jpeg|webp);base64,…` URL of
+ at most 131072 characters whose payload decodes — the same number, in the same unit, that the
+ browser measures its re-encode against.
+- `GET /api/me` carries `displayName` and `avatar`, omitted when unset. The admin user list
+ carries the nickname only — it is unpaged, and an avatar per account would answer a table
+ that shows the nickname alone with megabytes. The avatar and nickname render through one
+ shared `UserAvatar` component, so the nav row, the collapsed rail, the new account-menu
+ header and the page's own 64px preview cannot drift apart; the admin list shows the nickname
+ in small grey text under the user id.
+- Schema migration 5, `user-profile`: two nullable columns, `users.display_name` and
+ `users.avatar`. Additive and swap-safe — a platform rolled back to a predecessor that does not
+ know them never reads or writes them — and reversible, though its `down` drops the columns and
+ takes every stored nickname and avatar with them. Nothing to do for an existing install: every
+ account simply starts with no profile and keeps showing its user id until it sets one.
diff --git a/changelog/unreleased/2026-09-12-user-profile.zh.md b/changelog/unreleased/2026-09-12-user-profile.zh.md
new file mode 100644
index 00000000..a6962b53
--- /dev/null
+++ b/changelog/unreleased/2026-09-12-user-profile.zh.md
@@ -0,0 +1,19 @@
+# 个人资料页可设置用户的头像与昵称
+
+- **Date:** 2026-09-12
+- **Type:** feature
+- **Scope:** `server`, `web`, `docs`
+- **PR:** [#714](https://github.com/Prism-Shadow/penguin-harness/pull/714)
+
+[English](2026-09-12-user-profile.md)
+
+账号在界面上出现的每一处都只是它的用户名:侧边栏底部的用户行、收起态侧栏的触发点、用户管理列表。新增的**个人资料**页位于系统设置「个人」组之首,为每个账号提供头像与昵称,原本绘制用户名与首字母头像的位置改为显示它们。
+
+## 细节
+
+- 该页有两行设置且没有页脚:每个控件被使用时即写入,写入某个值的按钮就挨着那个值。**更换头像**打开图片选择器,选中的图片立即生效——按中心裁成正方形,并以 128×128 重新编码为 PNG,若 PNG 超过 100 KB 则改用质量 0.85 的 JPEG;仍超过 128 KiB 的图片在页面内直接报错,不再发出服务端同样会拒绝的请求。旁边的**恢复默认**把首字母头像换回来。**昵称**是输入的文本,因此保留挨着输入框的显式**保存**,并配一个自己的**恢复默认**——其默认值为用户名;两者都在点击时写入,因此同一字段旁的两个按钮不会在「何时生效」上各说各话。昵称为 1–32 个字符,按字符计,因此中文昵称可以有 32 个;保存空值即清除昵称。两行的按钮都保持自身宽度,让位的是输入框,因此对话框变窄也不会把某个按钮的文字折成两行——flex 不会把控件压到小于其 min-content 宽度,而中文文案的 min-content 是一个字,于是被压窄的按钮会把「恢复默认」摞成两行,英文按钮则由其最长的单词撑着。
+- 当按钮要写入的正是已存储的值时,它处于禁用态;本页也不做乐观更新:包括本页预览在内的所有位置都展示已存储的值,因此写入失败时界面仍与服务端一致,并就地给出失败提示,而不会先显示一张在下次加载时消失的头像。
+- 该页在任何会话中都可见,包括桌面 shell 自己的 token 窗口——与旁边需要密码的「账户」页不同。`PUT /api/me/profile` 遵循同一规则,接受任何已认证会话。
+- 该路由为补丁语义:字段缺省表示保持原值,`null` 表示清除,两个字段都未出现则返回 400。它校验昵称长度并拒绝其中的控制字符,并要求头像是 `data:image/(png|jpeg|webp);base64,…` 形式的 data URL、长度不超过 131072 个字符且载荷可解码——与浏览器衡量重新编码结果所用的数值和单位完全一致。
+- `GET /api/me` 开始下发 `displayName` 与 `avatar`,未设置时字段整个省略。用户管理列表只下发昵称——该列表不分页,而每个账号都带一份头像会让一张只显示昵称的表格返回数 MB 数据。头像与昵称统一经由共享的 `UserAvatar` 组件渲染,因此导航行、收起态侧栏、新增的账户菜单头部与本页 64px 的预览不会各自走偏;用户管理列表以浅灰小字把昵称显示在用户名下方。
+- 数据库迁移 5,`user-profile`:新增两个可空列 `users.display_name` 与 `users.avatar`。它是纯增量且 swap-safe 的——回滚到不认识这两列的旧平台既不会读也不会写它们——并且可回退,只是其 `down` 会删除这两列,已保存的昵称与头像随之丢失。既有部署无需任何操作:所有账号只是尚未设置个人资料,在设置之前继续显示用户名。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 5710a947..ec0cbc47 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -72,6 +72,7 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
| GET | /api/install | Public: `{installId}` — an opaque id identifying the data root being served (`<root>/install-id`), minted the first time the root is used. The Web App compares it against the one it stored and clears the browser-side UI state that references server entities when it differs, so replacing the data root no longer leaves the old Workspace, drafts and pins in place. `null` means the server could not establish one; clients must then change nothing. |
| GET | /api/me | Current user info |
| PUT | /api/me/password | Change password: `{oldPassword, newPassword}`; a desktop or first-login session may omit `oldPassword` — its current password is random and was never shown |
+| PUT | /api/me/profile | Set the avatar and nickname: `{displayName?, avatar?}` → `{user}`. A patch — an absent field keeps its stored value, `null` clears it, and a body naming neither is a `400`. `displayName` must be 1–32 characters once trimmed (counted as characters, so a CJK name may be 32 of them) and carry no control characters; `avatar` must be a `data:image/(png|jpeg|webp);base64,…` URL of at most 131072 characters whose payload decodes. Open to every authenticated session, the desktop shell's token session included — unlike the password route above, a profile has no old credential to check |
| GET | /api/me/prefs | Read UI preferences |
| PUT | /api/me/prefs | Write UI preferences (shallow merge) |
@@ -79,7 +80,7 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
| Method | Path | Description |
| --- | --- | --- |
-| GET | /api/admin/users | List users |
+| GET | /api/admin/users | List users. Each row carries the account's nickname when it has one; avatars are deliberately left out, since the list is unpaged and one data URL per account would dwarf the rest of the response |
| POST | /api/admin/users | Create a user: `{userId, password}` |
| POST | /api/admin/users/:userId/password | Reset a password (invalidates all of that user's login sessions) |
| DELETE | /api/admin/users/:userId | Delete a user |
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 0bf1836b..7fb650b9 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -72,6 +72,7 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
| GET | /api/install | 公开:`{installId}`——标识当前所服务数据根的不透明 id(`<root>/install-id`),在该根首次被使用时铸造。Web App 将其与自己存下的值比较,不一致时清除浏览器侧那些引用服务端实体的 UI 状态,因此更换数据根后不会再留下旧的 Workspace、草稿与置顶。`null` 表示服务端无法确定该 id,此时客户端不应改动任何内容。 |
| GET | /api/me | 当前用户信息 |
| PUT | /api/me/password | 修改密码:`{oldPassword, newPassword}`;桌面会话与首次登录会话可省略 `oldPassword`——其当前密码是随机生成且从未展示过的 |
+| PUT | /api/me/profile | 设置头像与昵称:`{displayName?, avatar?}` → `{user}`。为补丁语义——字段缺省表示保持原值,`null` 表示清除,两个字段都未出现则返回 `400`。`displayName` 去除首尾空白后须为 1–32 个字符(按字符计,因此中文昵称可以有 32 个)且不含控制字符;`avatar` 须是 `data:image/(png|jpeg|webp);base64,…` 形式的 data URL,长度不超过 131072 个字符且载荷可解码。任何已认证会话均可调用,含桌面 shell 的 token 会话——与上面的密码路由不同,个人资料没有需要校验的旧凭据 |
| GET | /api/me/prefs | 读取 UI 偏好 |
| PUT | /api/me/prefs | 写入 UI 偏好(浅合并) |
@@ -79,7 +80,7 @@ curl -H "Authorization: Bearer $(cat ~/.penguin/data/api-token)" \
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | /api/admin/users | 用户列表 |
+| GET | /api/admin/users | 用户列表。每行在账号设置了昵称时带上昵称;头像刻意不下发——该列表不分页,每个账号一份 data URL 会让响应体积远超这张表实际用到的内容 |
| POST | /api/admin/users | 创建用户:`{userId, password}` |
| POST | /api/admin/users/:userId/password | 重置密码(该用户全部登录会话失效) |
| DELETE | /api/admin/users/:userId | 删除用户 |
diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.md
index 9855f26b..2a4a6bfd 100644
--- a/packages/docs/content/web-app.en.md
+++ b/packages/docs/content/web-app.en.md
@@ -151,7 +151,11 @@ Read-only scoreboards per Benchmark: switch the metric (score / cost / duration)
One dialog for the settings that belong to neither a Project nor an Agent, opened from the sidebar user menu's **System settings** row: a left rail of pages, each page a list of rows — title and a one-line explanation on the left, the control on the right.
-The rail is grouped. **Personal** holds preferences that belong to the signed-in account and apply the moment they are touched — no Save button, nothing to lose by closing the dialog. **Server** holds the server-global surfaces: the settings written through `GET|PUT /api/admin/settings` and user management are admin-only — a non-admin gets neither those entries nor any hint they exist, and the APIs answer a non-admin with 403 whatever the browser rendered. A non-admin is therefore left with the Personal pages alone, and the rail draws no group headings at all. In the desktop app the user-management page is absent (the server runs single-user), and the shell's own window also has no Account page — it signs in through the shell's token and holds no password to change, while a browser signed into the same server with a password keeps it. Checking for updates is not a page here — see [Version and Updates](#version-and-updates).
+The rail is grouped. **Personal** holds preferences that belong to the signed-in account and apply the moment they are touched — no Save button, nothing to lose by closing the dialog; the Profile page's nickname is the one exception, since typed text needs a commit, and its Save sits beside the field rather than under the page. **Server** holds the server-global surfaces: the settings written through `GET|PUT /api/admin/settings` and user management are admin-only — a non-admin gets neither those entries nor any hint they exist, and the APIs answer a non-admin with 403 whatever the browser rendered. A non-admin is therefore left with the Personal pages alone, and the rail draws no group headings at all. In the desktop app the user-management page is absent (the server runs single-user), and the shell's own window also has no Account page — it signs in through the shell's token and holds no password to change, while a browser signed into the same server with a password keeps it. Checking for updates is not a page here — see [Version and Updates](#version-and-updates).
+
+### Profile
+
+Personal, and present in **every** session — the desktop shell's own window included, since neither field needs a password to change. An **avatar** and a **nickname**, and the page has no footer: every control writes when it is used, and the button that writes a value stands next to that value. Choosing an image applies it at once — centre-cropped to a square and re-encoded at 128×128, as PNG or, when the PNG would pass 100 KB, as JPEG; anything still over 128 KiB is refused in the browser rather than sent for the server to reject — and **Restore default** beside it puts the letter tile back. The nickname is typed text, so it keeps an explicit **Save**, with a **Restore default** of its own next to it; both of those write on click, so the two buttons beside the field never disagree about when they act. It is 1–32 characters (counted as characters, so a Chinese name may be 32 of them), its default is the user id, and saving it blank clears it. Each button is dead when it would write what is already stored. Nothing is applied optimistically: the preview shows the stored avatar, so a write that fails leaves every surface agreeing with the server and says so inline. Both start unset, so an account that predates this page shows its user id and the letter tile until it sets them. Once set they replace that pair on the sidebar's bottom user row, on the collapsed rail's avatar and at the head of the account menu those two open — where the user id stays visible under the nickname — and the nickname also shows under the id in the **Users** list.
### General
diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.md
index df485a22..8bb19b4f 100644
--- a/packages/docs/content/web-app.zh.md
+++ b/packages/docs/content/web-app.zh.md
@@ -150,7 +150,11 @@ Memory 标签页的开关拨动即写入,不参与标签页的保存按钮,
把既不属于 Project 也不属于 Agent 的设置收进一个弹窗,入口是侧边栏用户菜单的「系统设置」:左侧一列页面导航,右侧每页是一列设置行——左边标题加一行说明,右边控件。
-导航按组划分。**个人**组存放属于当前账号的偏好,改动即刻生效,没有保存按钮,关闭弹窗也不会丢失什么;**服务器**组存放服务器全局的界面:经 `GET|PUT /api/admin/settings` 写入的设置与用户管理仅管理员可见——非管理员既看不到这些条目、也不会得知它们存在,无论前端渲染成什么,接口对非管理员一律返回 403。因此非管理员只会看到「个人」组的几页,此时导航不再绘制分组标题。桌面应用中没有用户管理页(服务端是单用户模式);桌面 shell 自己的窗口还没有「账户」页——它通过 shell 的一次性 token 登录,没有可修改的密码,而用密码登录同一服务器的浏览器会话仍保留该页。检查更新不是这里的一页,见[版本与更新](#版本与更新)。
+导航按组划分。**个人**组存放属于当前账号的偏好,改动即刻生效,没有保存按钮,关闭弹窗也不会丢失什么——唯一的例外是「个人资料」页的昵称,输入的文本需要一次显式提交,其「保存」按钮就挨着输入框,而不在页面底部;**服务器**组存放服务器全局的界面:经 `GET|PUT /api/admin/settings` 写入的设置与用户管理仅管理员可见——非管理员既看不到这些条目、也不会得知它们存在,无论前端渲染成什么,接口对非管理员一律返回 403。因此非管理员只会看到「个人」组的几页,此时导航不再绘制分组标题。桌面应用中没有用户管理页(服务端是单用户模式);桌面 shell 自己的窗口还没有「账户」页——它通过 shell 的一次性 token 登录,没有可修改的密码,而用密码登录同一服务器的浏览器会话仍保留该页。检查更新不是这里的一页,见[版本与更新](#版本与更新)。
+
+### 个人资料
+
+个人设置,且在**任何**会话中都存在——包括桌面 shell 自己的窗口,因为这两项都不需要密码即可修改。**头像**与**昵称**;本页没有页脚,每个控件被使用时即写入,写入某个值的按钮就挨着那个值。选中图片即刻生效——按中心裁成正方形并以 128×128 重新编码:默认 PNG,PNG 超过 100 KB 时改用 JPEG;仍超过 128 KiB 的在浏览器内即被拒绝,不会发出服务端同样会拒绝的请求——旁边的**恢复默认**把首字母头像换回来。昵称是输入的文本,因此保留显式的**保存**,并在其旁配一个自己的**恢复默认**;两者都在点击时写入,因此同一字段旁的两个按钮不会在「何时生效」上各说各话。昵称为 1–32 个字符(按字符计,因此中文昵称可以有 32 个),其默认值是用户名,保存空值即清除。当按钮要写入的正是已存储的值时,它处于禁用态。本页不做乐观更新:预览展示的是已存储的头像,因此写入失败时各处显示仍与服务端一致,并就地给出提示。两项默认都未设置,因此本页之前就存在的账号在设置之前一直显示用户名与首字母头像。设置之后,侧边栏底部用户行、收起态侧栏头像,以及由这两处打开的账户菜单顶部都换成新的头像与昵称——菜单里用户名仍显示在昵称下方——昵称同时出现在**用户管理**列表中用户名的下方。
### 通用
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 6d3bbf53..e46a54ed 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -55,9 +55,34 @@ export interface UserInfo {
isAdmin: boolean;
/** Still using the initial password (seeded/set by admin): frontend prompts the user to change it soon. */
passwordIsInitial: boolean;
+ /**
+ * Nickname the account chose (1-32 characters), shown wherever the id would otherwise be.
+ * Omitted when unset — every account that predates the Profile page starts without one, and
+ * a surface with no value falls back to `userId`.
+ */
+ displayName?: string;
+ /**
+ * Avatar as a `data:image/...;base64,` URL, at most 131072 characters. Omitted when unset,
+ * and a surface with no value draws the letter placeholder instead.
+ */
+ avatar?: string;
createdAt: string;
}
+/**
+ * PUT /api/me/profile — a patch, not a replacement: an absent field keeps what is stored,
+ * `null` clears it, a string sets it. A body naming neither field is a 400, since it can only
+ * be a mistake.
+ */
+export interface UpdateProfileRequest {
+ displayName?: string | null;
+ avatar?: string | null;
+}
+
+export interface UpdateProfileResponse {
+ user: UserInfo;
+}
+
export interface AuthLoginRequest {
userId: string;
password: string;
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index e28027b1..f633db87 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -172,6 +172,8 @@ export interface AppDeps {
config: ServerConfig;
db: DatabaseSync;
sessionsRepo: SessionsRepo;
+ /** The `users` table itself, for the one route that writes a column no service owns (PUT /api/me/profile). */
+ usersRepo: UsersRepo;
prefsRepo: UiPrefsRepo;
/** Admin-level server-global settings (currently the proxy switches and address). */
serverSettingsRepo: ServerSettingsRepo;
@@ -1116,6 +1118,7 @@ export function buildAppDeps(
config,
db,
sessionsRepo,
+ usersRepo,
prefsRepo,
serverSettingsRepo,
authService,
diff --git a/packages/server/src/auth/service.ts b/packages/server/src/auth/service.ts
index 977020ce..3b30c22f 100644
--- a/packages/server/src/auth/service.ts
+++ b/packages/server/src/auth/service.ts
@@ -52,11 +52,14 @@ export function generateInitialAdminPassword(): string {
*/
export type SessionVia = "password" | "desktop" | "setup" | "token";
+/** Row -> DTO. The two profile columns are omitted rather than sent as null when unset. */
export function toUserInfo(row: UserRow): UserInfo {
return {
userId: row.userId,
isAdmin: row.isAdmin,
passwordIsInitial: row.passwordIsInitial,
+ ...(row.displayName !== null ? { displayName: row.displayName } : {}),
+ ...(row.avatar !== null ? { avatar: row.avatar } : {}),
createdAt: row.createdAt,
};
}
@@ -141,6 +144,8 @@ export class AuthService {
passwordHash: await hashPassword(password, this.hashCost),
isAdmin: true,
passwordIsInitial: true,
+ displayName: null,
+ avatar: null,
createdAt: this.now().toISOString(),
};
this.deps.users.insert(user);
diff --git a/packages/server/src/db/migrations.ts b/packages/server/src/db/migrations.ts
index 3d4ced3d..0b0c25a2 100644
--- a/packages/server/src/db/migrations.ts
+++ b/packages/server/src/db/migrations.ts
@@ -219,6 +219,31 @@ export const MIGRATIONS: readonly Migration[] = [
`);
},
},
+ {
+ version: 5,
+ name: "user-profile",
+ // Two nullable columns on `users`, no default and nothing existing rewritten: a platform
+ // rolled back to a predecessor that does not know them never selects or writes them, and
+ // every existing account simply reads NULL — no profile yet.
+ swapSafe: true,
+ up(db) {
+ // Frozen copy of the DDL as of the user-profile feature; do not re-derive from schema.ts.
+ // SQLite has no ADD COLUMN IF NOT EXISTS, and the declarative track may already have
+ // added both (ADOPTION), so each one goes through the same table_info guard the
+ // declarative track uses.
+ ensureColumn(db, "users", "display_name", "TEXT");
+ ensureColumn(db, "users", "avatar", "TEXT");
+ },
+ // LOSES every stored nickname and avatar: both live entirely in the two columns this
+ // drops, and nothing else on disk holds a copy. Dropped in reverse order for symmetry
+ // with `up`; neither column is indexed, which is what lets SQLite drop them at all.
+ down(db) {
+ const cols = db.prepare("PRAGMA table_info(users)").all() as { name: string }[];
+ const has = (name: string): boolean => cols.some((c) => c.name === name);
+ if (has("avatar")) db.exec("ALTER TABLE users DROP COLUMN avatar");
+ if (has("display_name")) db.exec("ALTER TABLE users DROP COLUMN display_name");
+ },
+ },
];
/** The highest version this build knows how to reach. */
diff --git a/packages/server/src/db/repos/users.ts b/packages/server/src/db/repos/users.ts
index 33263030..e34e5125 100644
--- a/packages/server/src/db/repos/users.ts
+++ b/packages/server/src/db/repos/users.ts
@@ -10,6 +10,10 @@ export interface UserRow {
isAdmin: boolean;
/** Still using the initial password (seeded / set by an admin); cleared to 0 once the user changes it. */
passwordIsInitial: boolean;
+ /** Nickname shown in place of the id; null = never set. */
+ displayName: string | null;
+ /** Avatar as a data URL; null = never set. */
+ avatar: string | null;
createdAt: string;
}
@@ -19,6 +23,8 @@ function mapRow(r: Record<string, unknown>): UserRow {
passwordHash: r.password_hash as string,
isAdmin: (r.is_admin as number) === 1,
passwordIsInitial: (r.password_is_initial as number) === 1,
+ displayName: (r.display_name as string | null) ?? null,
+ avatar: (r.avatar as string | null) ?? null,
createdAt: r.created_at as string,
};
}
@@ -29,13 +35,16 @@ export class UsersRepo {
insert(row: UserRow): void {
this.db
.prepare(
- "INSERT INTO users (user_id, password_hash, is_admin, password_is_initial, created_at) VALUES (?, ?, ?, ?, ?)",
+ "INSERT INTO users (user_id, password_hash, is_admin, password_is_initial, display_name, avatar, created_at)" +
+ " VALUES (?, ?, ?, ?, ?, ?, ?)",
)
.run(
row.userId,
row.passwordHash,
row.isAdmin ? 1 : 0,
row.passwordIsInitial ? 1 : 0,
+ row.displayName,
+ row.avatar,
row.createdAt,
);
}
@@ -63,6 +72,29 @@ export class UsersRepo {
.run(passwordHash, isInitial ? 1 : 0, userId);
}
+ /**
+ * Writes the profile fields the patch names, leaving the rest as they are: an absent key
+ * keeps the stored value, `null` clears it, a string replaces it. A patch naming neither
+ * field writes nothing rather than issuing an UPDATE with an empty SET list.
+ */
+ updateProfile(
+ userId: string,
+ patch: { displayName?: string | null; avatar?: string | null },
+ ): void {
+ const sets: string[] = [];
+ const values: (string | null)[] = [];
+ if (patch.displayName !== undefined) {
+ sets.push("display_name = ?");
+ values.push(patch.displayName);
+ }
+ if (patch.avatar !== undefined) {
+ sets.push("avatar = ?");
+ values.push(patch.avatar);
+ }
+ if (sets.length === 0) return;
+ this.db.prepare(`UPDATE users SET ${sets.join(", ")} WHERE user_id = ?`).run(...values, userId);
+ }
+
/** Used by admin user deletion and account-creation compensation paths (owned Projects must be cleaned up first). */
delete(userId: string): void {
this.db.prepare("DELETE FROM users WHERE user_id = ?").run(userId);
diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.ts
index ec6c56fc..4d4e9b84 100644
--- a/packages/server/src/db/schema.ts
+++ b/packages/server/src/db/schema.ts
@@ -18,6 +18,8 @@ CREATE TABLE IF NOT EXISTS users (
password_hash TEXT NOT NULL, -- scrypt$N$r$p$salt$hash(base64)
is_admin INTEGER NOT NULL DEFAULT 0, -- 1 for the built-in admin (seeded at startup)
password_is_initial INTEGER NOT NULL DEFAULT 0, -- 1=initial password (seeded/admin-set); cleared once the user changes it
+ display_name TEXT, -- nickname shown in place of user_id (1-32 characters); NULL = never set, surfaces show the id
+ avatar TEXT, -- avatar as a data URL (image/png|jpeg|webp, <= 131072 characters); NULL = never set, surfaces draw the letter placeholder
created_at TEXT NOT NULL
);
-- Server-side sessions backing the HttpOnly cookie: the cookie carries a 32-byte random
diff --git a/packages/server/src/http/routes/me.ts b/packages/server/src/http/routes/me.ts
index 68245e61..eb9404e0 100644
--- a/packages/server/src/http/routes/me.ts
+++ b/packages/server/src/http/routes/me.ts
@@ -1,17 +1,30 @@
/**
- * Current-user routes: GET /api/me, PUT /api/me/password, GET|PUT /api/me/prefs.
+ * Current-user routes: GET /api/me, PUT /api/me/password, PUT /api/me/profile,
+ * GET|PUT /api/me/prefs.
* ui_prefs is free-form JSON (theme / lastProjectId / credentialGuideSeen, etc.): GET reads
* it whole, PUT shallow-merges (PATCH semantics) — several independent writers each write
* their own fields without clobbering each other. Free-form does not mean unbounded: a key
* carrying user-authored text is validated and capped on the way in (draftShortcuts).
+ *
+ * The profile (nickname + avatar) is a column pair on `users` rather than a prefs key: it is
+ * read back by surfaces other than the browser that wrote it (the admin user list names the
+ * nickname), and a blob capped at 128 KiB does not belong in a free-form JSON document that
+ * every unrelated writer re-serializes whole.
*/
import { Hono } from "hono";
import { setCookie } from "hono/cookie";
-import type { MeResponse, PrefsResponse, UiPrefs } from "../../api/types.js";
+import type {
+ MeResponse,
+ PrefsResponse,
+ UiPrefs,
+ UpdateProfileRequest,
+ UpdateProfileResponse,
+} from "../../api/types.js";
import { toUserInfo } from "../../auth/service.js";
import { SESSION_COOKIE, cookieOptions } from "../../auth/middleware.js";
import type { AppEnv } from "../../auth/middleware.js";
-import { readJson, requireString } from "../validate.js";
+import { badRequest, readJson, requireString } from "../validate.js";
+import { HttpError } from "../errors.js";
import type { AppDeps } from "../../app.js";
import { resolvePreviewTarget } from "../../services/preview-token.js";
import { validateDraftShortcuts } from "../../services/draft-shortcuts.js";
@@ -22,6 +35,70 @@ import {
MIN_ATTACHMENT_MB,
} from "../../services/attachment-limits.js";
+/** Nickname bounds, counted in user-perceived code points so a CJK name is 32 characters, not 96. */
+const DISPLAY_NAME_MIN = 1;
+const DISPLAY_NAME_MAX = 32;
+
+/**
+ * Avatar cap, in characters of the data URL as it arrives — the same number the browser
+ * measures its re-encode against, so the client and this check can never disagree about what
+ * "too large" means. 131072 characters of base64 hold roughly 96 KiB of image.
+ */
+const AVATAR_MAX_CHARS = 131072;
+
+/** The three formats the picker offers, all of which every target browser can re-encode. */
+const AVATAR_DATA_URL = /^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/=]+$/;
+
+/**
+ * The stored form of a nickname: trimmed, since leading and trailing spaces are invisible in
+ * every surface that renders it and would make two names look identical. Length is measured in
+ * code points (Array.from) rather than UTF-16 units, so a 32-character Chinese name fits and a
+ * 32-emoji one does not sneak past a byte count.
+ */
+function parseDisplayName(raw: unknown): string | null {
+ if (raw === null) return null;
+ if (typeof raw !== "string") throw badRequest("displayName must be a string or null.");
+ const trimmed = raw.trim();
+ const length = Array.from(trimmed).length;
+ if (length < DISPLAY_NAME_MIN || length > DISPLAY_NAME_MAX) {
+ throw badRequest(
+ `displayName must be ${DISPLAY_NAME_MIN} to ${DISPLAY_NAME_MAX} characters once trimmed.`,
+ );
+ }
+ // Control characters carry no glyph: they would let a name imitate another one, or break the
+ // line it is rendered on.
+ if (/\p{Cc}/u.test(trimmed)) {
+ throw badRequest("displayName must not contain control characters.");
+ }
+ return trimmed;
+}
+
+/** The stored form of an avatar: the data URL itself, validated shape-first, then decoded. */
+function parseAvatar(raw: unknown): string | null {
+ if (raw === null) return null;
+ if (typeof raw !== "string") throw badRequest("avatar must be a string or null.");
+ // Length first: the pattern below is linear in the input, and a caller may send megabytes.
+ if (raw.length > AVATAR_MAX_CHARS) {
+ throw badRequest(`avatar must be at most ${AVATAR_MAX_CHARS} characters.`);
+ }
+ if (!AVATAR_DATA_URL.test(raw)) {
+ throw badRequest(
+ "avatar must be a base64 data URL of type image/png, image/jpeg or image/webp.",
+ );
+ }
+ const payload = raw.slice(raw.indexOf(",") + 1);
+ // The pattern admits the alphabet but not the arithmetic: a length that is 1 mod 4, or padding
+ // in the middle, is not decodable base64 and would be stored as an <img src> that never loads.
+ let decodedLength: number;
+ try {
+ decodedLength = atob(payload).length;
+ } catch {
+ throw badRequest("avatar is not valid base64.");
+ }
+ if (decodedLength === 0) throw badRequest("avatar is not valid base64.");
+ return raw;
+}
+
export function meRoutes(deps: AppDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
@@ -84,6 +161,35 @@ export function meRoutes(deps: AppDeps): Hono<AppEnv> {
return c.body(null, 204);
});
+ /**
+ * Nickname and avatar, as a patch: an absent field keeps what is stored, `null` clears it.
+ *
+ * Open to EVERY authenticated session, the desktop shell's own token session included —
+ * deliberately not the password route's gate above. That gate exists because a password
+ * change needs a password to check against, which a token session has never seen; a profile
+ * is just the account's own display data, and the shell's window is a signed-in account like
+ * any other.
+ */
+ app.put("/profile", async (c) => {
+ const body = await readJson(c);
+ const patch: UpdateProfileRequest = {};
+ if (body.displayName !== undefined) patch.displayName = parseDisplayName(body.displayName);
+ if (body.avatar !== undefined) patch.avatar = parseAvatar(body.avatar);
+ // A body naming neither field cannot mean anything: answering 200 with the row unchanged
+ // would let a client's typo read as a successful save.
+ if (patch.displayName === undefined && patch.avatar === undefined) {
+ throw badRequest("Request body must name displayName or avatar.");
+ }
+ deps.usersRepo.updateProfile(c.var.user.userId, patch);
+ const updated = deps.usersRepo.findById(c.var.user.userId);
+ if (updated === null) {
+ // The session resolved to this user one middleware ago, so the row can only be gone if
+ // an admin deleted the account mid-request.
+ throw new HttpError(404, "not_found", "Account no longer exists.");
+ }
+ return c.json({ user: toUserInfo(updated) } satisfies UpdateProfileResponse);
+ });
+
app.get("/prefs", (c) => {
const raw = deps.prefsRepo.get(c.var.user.userId);
let prefs: UiPrefs = {};
diff --git a/packages/server/src/services/admin-service.ts b/packages/server/src/services/admin-service.ts
index 66e2416b..889d28cf 100644
--- a/packages/server/src/services/admin-service.ts
+++ b/packages/server/src/services/admin-service.ts
@@ -42,8 +42,16 @@ export class AdminService {
this.hashCost = deps.passwordHashCost ?? SCRYPT_COST;
}
+ /**
+ * Every account, for the admin user backend. The avatar is dropped on the way out: a stored
+ * avatar is a data URL of up to 128 KiB and this list is unpaged, so carrying one per account
+ * would answer a table that only shows the nickname with megabytes.
+ */
listUsers(): UserInfo[] {
- return this.deps.users.list().map(toUserInfo);
+ return this.deps.users.list().map((row) => {
+ const { avatar: _avatar, ...info } = toUserInfo(row);
+ return info;
+ });
}
async createUser(userId: string, password: string): Promise<UserInfo> {
@@ -65,6 +73,8 @@ export class AdminService {
passwordHash: await hashPassword(password, this.hashCost),
isAdmin: false,
passwordIsInitial: true,
+ displayName: null,
+ avatar: null,
createdAt: this.now().toISOString(),
};
this.deps.users.insert(user);
diff --git a/packages/server/test/db-migrations.test.ts b/packages/server/test/db-migrations.test.ts
index 30db4485..dfd96e2e 100644
--- a/packages/server/test/db-migrations.test.ts
+++ b/packages/server/test/db-migrations.test.ts
@@ -1,6 +1,7 @@
/**
- * The ordered-migration mechanism, the 0.2.4 → 0.2.7 migration that is its first entry, and
- * the 0.2.9 → 0.2.10 drop that is its first restart-only one.
+ * The ordered-migration mechanism, the 0.2.4 → 0.2.7 migration that is its first entry, the
+ * 0.2.9 → 0.2.10 drop that is its first restart-only one, and the additive column pair that
+ * the user profile added to `users`.
*
* Two properties carry everything else: a real 0.2.4 database reaches exactly the shape a
* fresh one is created with (so a runtime older than the platform pushed onto it becomes
@@ -54,6 +55,10 @@ function open024(): DatabaseSync {
db.exec("DROP TABLE messaging_bindings");
db.exec("DROP INDEX IF EXISTS idx_auth_sessions_expires");
db.exec("DROP INDEX IF EXISTS idx_auth_sessions_user");
+ // No account had a profile before migration 5: the current declaration's two columns
+ // must come off, or a round trip through migration 5's down would land on a narrower
+ // `users` than this fixture and read as a rollback that lost something.
+ dropProfileColumns(db);
db.exec(GOAL_STATE_DDL);
return db;
}
@@ -64,12 +69,39 @@ function open029(): DatabaseSync {
db.exec(SCHEMA_SQL);
db.exec(GOAL_STATE_DDL);
// SCHEMA_SQL declares the CURRENT shape, and a 0.2.9 database has no machines tables —
- // migration 4 is what adds them. Without this the fixture is a database no release made.
+ // migration 4 is what adds them — and no profile columns, which migration 5 adds. Without
+ // both the fixture is a database no release made.
db.exec("DROP TABLE machine_project; DROP TABLE machines; DROP TABLE machine;");
+ dropProfileColumns(db);
db.exec("PRAGMA user_version = 2");
return db;
}
+/**
+ * A database from before the user profile: today's declaration minus exactly the two columns
+ * migration 5 adds, stamped at the version before it. Derived from SCHEMA_SQL for the reason
+ * open024 is — a hand-copied `users` table would fork from reality.
+ */
+function openPreProfile(): DatabaseSync {
+ const db = new sqlite.DatabaseSync(":memory:");
+ db.exec(SCHEMA_SQL);
+ dropProfileColumns(db);
+ db.exec("PRAGMA user_version = 4");
+ return db;
+}
+
+/** Takes migration 5's two columns off a database built from the current declaration. */
+function dropProfileColumns(db: DatabaseSync): void {
+ db.exec("ALTER TABLE users DROP COLUMN avatar");
+ db.exec("ALTER TABLE users DROP COLUMN display_name");
+}
+
+/** Column names of `users`, for the two cases that are about columns rather than whole shapes. */
+function userColumns(db: DatabaseSync): string[] {
+ const rows = db.prepare("PRAGMA table_info(users)").all() as { name: string }[];
+ return rows.map((r) => r.name);
+}
+
/** Runs `fn` with the restart-only migration taken off the list, so a swap-path case can see swap-safe ones apply. */
function withoutRestartOnly<T>(fn: () => T): T {
const list = MIGRATIONS as unknown as (typeof MIGRATIONS)[number][];
@@ -146,6 +178,7 @@ describe("migration mechanism", () => {
"messaging-delivery-flags",
"drop-goal-state",
"machines",
+ "user-profile",
]);
expect(schemaVersion(db)).toBe(LATEST_VERSION);
} finally {
@@ -205,6 +238,7 @@ describe("the swap path refuses what a rollback could not survive", () => {
"messaging-bindings",
"messaging-delivery-flags",
"machines",
+ "user-profile",
]);
} finally {
db.close();
@@ -225,6 +259,7 @@ describe("the swap path refuses what a rollback could not survive", () => {
"messaging-delivery-flags",
"drop-goal-state",
"machines",
+ "user-profile",
]);
} finally {
db.close();
@@ -248,12 +283,12 @@ describe("0.2.9 → current: drop-goal-state", () => {
const fresh = new sqlite.DatabaseSync(":memory:");
try {
fresh.exec(SCHEMA_SQL);
- expect(migrate(db).applied).toEqual(["drop-goal-state", "machines"]);
+ expect(migrate(db).applied).toEqual(["drop-goal-state", "machines", "user-profile"]);
expect(shape(db)).toBe(shape(fresh));
// IF EXISTS: a database this build created, stamped 2 by an older mechanism, has no
// goal_state to drop and must not fail on it.
fresh.exec("PRAGMA user_version = 2");
- expect(migrate(fresh).applied).toEqual(["drop-goal-state", "machines"]);
+ expect(migrate(fresh).applied).toEqual(["drop-goal-state", "machines", "user-profile"]);
} finally {
db.close();
fresh.close();
@@ -278,6 +313,51 @@ describe("0.2.9 → current: drop-goal-state", () => {
});
});
+describe("pre-profile → current: user-profile", () => {
+ it("adds both columns, and a database that already has them migrates the same", () => {
+ const db = openPreProfile();
+ const fresh = new sqlite.DatabaseSync(":memory:");
+ try {
+ fresh.exec(SCHEMA_SQL);
+ expect(userColumns(db)).not.toContain("display_name");
+ expect(migrate(db).applied).toEqual(["user-profile"]);
+ expect(userColumns(db)).toContain("display_name");
+ expect(userColumns(db)).toContain("avatar");
+ expect(shape(db)).toBe(shape(fresh));
+
+ // ADOPTION: on a database this build created, the declarative track already added both,
+ // so the migration must find its work done, add nothing twice, and stamp anyway.
+ fresh.exec("PRAGMA user_version = 4");
+ expect(migrate(fresh).applied).toEqual(["user-profile"]);
+ expect(userColumns(fresh).filter((c) => c === "avatar")).toEqual(["avatar"]);
+ } finally {
+ db.close();
+ fresh.close();
+ }
+ });
+
+ it("down removes both columns, taking every nickname and avatar with them", () => {
+ const db = openPreProfile();
+ try {
+ db.exec(
+ "INSERT INTO users (user_id, password_hash, is_admin, created_at) VALUES ('bob', 'h', 0, '2026-01-01T00:00:00Z')",
+ );
+ const before = shape(db);
+ migrate(db);
+ db.exec("UPDATE users SET display_name = 'Bob', avatar = 'data:image/png;base64,AAAA'");
+
+ rollbackTo(db, 4);
+ expect(shape(db)).toBe(before);
+ expect(userColumns(db)).not.toContain("display_name");
+ expect(userColumns(db)).not.toContain("avatar");
+ // The account itself survives; only what the two columns held is gone.
+ expect(db.prepare("SELECT user_id FROM users").all()).toEqual([{ user_id: "bob" }]);
+ } finally {
+ db.close();
+ }
+ });
+});
+
describe("0.2.4 → current", () => {
/** The whole point: an older runtime's database becomes what a current build creates. */
it("brings a 0.2.4 database to the shape a fresh one is created with", () => {
@@ -339,11 +419,11 @@ describe("rollbackTo", () => {
migrate(db);
expect(schemaVersion(db)).toBe(LATEST_VERSION);
- const r = rollbackTo(db, LATEST_VERSION - 2);
+ const r = rollbackTo(db, 2);
expect(r.from).toBe(LATEST_VERSION);
- expect(r.to).toBe(LATEST_VERSION - 2);
- // Newest first: the machines tables go, then goal_state comes back.
- expect(r.reverted).toEqual(["machines", "drop-goal-state"]);
+ expect(r.to).toBe(2);
+ // Newest first: the profile columns go, then the machines tables, then goal_state returns.
+ expect(r.reverted).toEqual(["user-profile", "machines", "drop-goal-state"]);
const tables = (
db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all() as {
name: string;
@@ -382,6 +462,7 @@ describe("rollbackTo", () => {
migrate(db);
const r = rollbackTo(db, 0);
expect(r.reverted).toEqual([
+ "user-profile",
"machines",
"drop-goal-state",
"messaging-delivery-flags",
diff --git a/packages/server/test/me-profile.test.ts b/packages/server/test/me-profile.test.ts
new file mode 100644
index 00000000..64c39d63
--- /dev/null
+++ b/packages/server/test/me-profile.test.ts
@@ -0,0 +1,193 @@
+/**
+ * PUT /api/me/profile: the nickname and avatar an account sets for itself.
+ *
+ * Two properties carry the rest. The route is a PATCH — an absent field keeps what is
+ * stored and `null` clears it — so every case asserts what it did NOT touch as well as what
+ * it did. And the validation is what keeps a display column safe to render: the cases below
+ * are one per rule, because each one has its own message and a shared "400 for bad input"
+ * assertion would pass with the wrong check firing.
+ */
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import type { MeResponse, UpdateProfileResponse } from "../src/api/types.js";
+import {
+ apiClient,
+ createDesktopApp,
+ createTestApp,
+ desktopLoginCookie,
+ loginAdmin,
+ provisionUser,
+} from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+/** A real 1x1 RGBA PNG: the route decodes the payload, so a placeholder string would not do. */
+const PNG_1X1 =
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg==";
+
+/** The route's own cap, in characters of the data URL. */
+const AVATAR_MAX_CHARS = 131072;
+
+async function errorOf(res: Response): Promise<{ code: string; message: string }> {
+ const body = (await res.json()) as { error: { code: string; message: string } };
+ return body.error;
+}
+
+describe("PUT /api/me/profile", () => {
+ let t: TestApp;
+
+ beforeEach(async () => {
+ t = await createTestApp();
+ });
+ afterEach(async () => {
+ await t.cleanup();
+ });
+
+ it("sets both fields, and GET /api/me reads them back", async () => {
+ const bob = await provisionUser(t.app, "bob");
+ // Neither field is sent at all before one is set, rather than sent as null.
+ expect(bob.user.displayName).toBeUndefined();
+ expect(bob.user.avatar).toBeUndefined();
+
+ const api = apiClient(t.app, bob.cookie);
+ const res = await api.put("/api/me/profile", { displayName: "Bob Loblaw", avatar: PNG_1X1 });
+ expect(res.status).toBe(200);
+ const saved = (await res.json()) as UpdateProfileResponse;
+ expect(saved.user.displayName).toBe("Bob Loblaw");
+ expect(saved.user.avatar).toBe(PNG_1X1);
+ // The response is the row, not an echo of the request: the menu updates from it without
+ // a second call, so a divergence here would show stale data until the next reload.
+ const me = (await (await api.get("/api/me")).json()) as MeResponse;
+ expect(me.user.displayName).toBe("Bob Loblaw");
+ expect(me.user.avatar).toBe(PNG_1X1);
+ });
+
+ it("is a patch: an absent field keeps its value, null clears it", async () => {
+ const bob = await provisionUser(t.app, "bob");
+ const api = apiClient(t.app, bob.cookie);
+ await api.put("/api/me/profile", { displayName: "Bob", avatar: PNG_1X1 });
+
+ // Avatar alone: the nickname is untouched.
+ const avatarOnly = (await (
+ await api.put("/api/me/profile", { avatar: null })
+ ).json()) as UpdateProfileResponse;
+ expect(avatarOnly.user.displayName).toBe("Bob");
+ expect(avatarOnly.user.avatar).toBeUndefined();
+
+ const nameCleared = (await (
+ await api.put("/api/me/profile", { displayName: null })
+ ).json()) as UpdateProfileResponse;
+ expect(nameCleared.user.displayName).toBeUndefined();
+ });
+
+ it("stores the nickname trimmed, and counts its length in characters", async () => {
+ const bob = await provisionUser(t.app, "bob");
+ const api = apiClient(t.app, bob.cookie);
+ const padded = (await (
+ await api.put("/api/me/profile", { displayName: " Bob " })
+ ).json()) as UpdateProfileResponse;
+ expect(padded.user.displayName).toBe("Bob");
+
+ // 32 Chinese characters: 96 bytes in UTF-8, and accepted — the bound is on characters.
+ const cjk = "名".repeat(32);
+ const res = await api.put("/api/me/profile", { displayName: cjk });
+ expect(res.status).toBe(200);
+ expect(((await res.json()) as UpdateProfileResponse).user.displayName).toBe(cjk);
+ });
+
+ it("rejects a nickname that is empty, too long, or carries a control character", async () => {
+ const bob = await provisionUser(t.app, "bob");
+ const api = apiClient(t.app, bob.cookie);
+
+ // Blank is not "clear" — null is. A field the user emptied is caught by the client, which
+ // sends null; a blank string reaching here is a caller that did not.
+ const blank = await api.put("/api/me/profile", { displayName: " " });
+ expect(blank.status).toBe(400);
+ expect((await errorOf(blank)).message).toMatch(/displayName must be 1 to 32 characters/);
+
+ const long = await api.put("/api/me/profile", { displayName: "x".repeat(33) });
+ expect(long.status).toBe(400);
+ expect((await errorOf(long)).message).toMatch(/displayName must be 1 to 32 characters/);
+
+ // A pasted two-line value: the newline survives trim(), which only takes the ends.
+ const control = await api.put("/api/me/profile", { displayName: "Bob\nLoblaw" });
+ expect(control.status).toBe(400);
+ expect((await errorOf(control)).message).toMatch(/control characters/);
+
+ // Nothing was stored by any of the three.
+ const me = (await (await api.get("/api/me")).json()) as MeResponse;
+ expect(me.user.displayName).toBeUndefined();
+ });
+
+ it("rejects an avatar that is not an image data URL, and one over the cap", async () => {
+ const bob = await provisionUser(t.app, "bob");
+ const api = apiClient(t.app, bob.cookie);
+
+ const svg = await api.put("/api/me/profile", {
+ avatar: "data:image/svg+xml;base64,PHN2Zy8+",
+ });
+ expect(svg.status).toBe(400);
+ expect((await errorOf(svg)).message).toMatch(/image\/png, image\/jpeg or image\/webp/);
+
+ // Well-formed prefix, undecodable payload: a length of 1 mod 4 is not base64.
+ const truncated = await api.put("/api/me/profile", { avatar: "data:image/png;base64,A" });
+ expect(truncated.status).toBe(400);
+ expect((await errorOf(truncated)).message).toMatch(/valid base64/);
+
+ const oversize = await api.put("/api/me/profile", {
+ avatar: `data:image/png;base64,${"A".repeat(AVATAR_MAX_CHARS)}`,
+ });
+ expect(oversize.status).toBe(400);
+ expect((await errorOf(oversize)).message).toMatch(/at most 131072 characters/);
+
+ const me = (await (await api.get("/api/me")).json()) as MeResponse;
+ expect(me.user.avatar).toBeUndefined();
+ });
+
+ it("rejects a body naming neither field", async () => {
+ const bob = await provisionUser(t.app, "bob");
+ const res = await apiClient(t.app, bob.cookie).put("/api/me/profile", { nickname: "Bob" });
+ expect(res.status).toBe(400);
+ expect((await errorOf(res)).message).toMatch(/must name displayName or avatar/);
+ });
+
+ it("shows an admin the nicknames of the accounts they manage, but not their avatars", async () => {
+ const bob = await provisionUser(t.app, "bob");
+ await apiClient(t.app, bob.cookie).put("/api/me/profile", {
+ displayName: "Bob Loblaw",
+ avatar: PNG_1X1,
+ });
+ const admin = await loginAdmin(t.app);
+ const list = (await (await apiClient(t.app, admin.cookie).get("/api/admin/users")).json()) as {
+ users: { userId: string; displayName?: string; avatar?: string }[];
+ };
+ const row = list.users.find((u) => u.userId === "bob");
+ expect(row?.displayName).toBe("Bob Loblaw");
+ // The list is unpaged and its table shows only the nickname, so an avatar per account
+ // would be up to 128 KiB of payload that nothing renders.
+ expect(row?.avatar).toBeUndefined();
+ expect(list.users.find((u) => u.userId === "admin")?.displayName).toBeUndefined();
+ });
+});
+
+describe("PUT /api/me/profile in desktop mode", () => {
+ let t: TestApp;
+
+ beforeEach(async () => {
+ t = await createDesktopApp();
+ });
+ afterEach(async () => {
+ await t.cleanup();
+ });
+
+ /**
+ * Deliberately NOT the password route's gate, which the shell's window fails: a profile is
+ * the account's own display data and needs no old password to check against. The shell's
+ * window is the only session some desktop installs ever have, so gating it out would put the
+ * Profile page behind a login that install does not have.
+ */
+ it("accepts the desktop shell's own token session", async () => {
+ const cookie = await desktopLoginCookie(t.app);
+ const res = await apiClient(t.app, cookie).put("/api/me/profile", { displayName: "Penguin" });
+ expect(res.status).toBe(200);
+ expect(((await res.json()) as UpdateProfileResponse).user.displayName).toBe("Penguin");
+ });
+});
diff --git a/packages/server/test/reset-admin-password.test.ts b/packages/server/test/reset-admin-password.test.ts
index 832b52bd..8f4fe7d4 100644
--- a/packages/server/test/reset-admin-password.test.ts
+++ b/packages/server/test/reset-admin-password.test.ts
@@ -43,6 +43,8 @@ describe("resetAdminPassword", () => {
passwordHash: await hashPassword("old-password-1"),
isAdmin: true,
passwordIsInitial: false,
+ displayName: null,
+ avatar: null,
createdAt,
});
users.insert({
@@ -50,6 +52,8 @@ describe("resetAdminPassword", () => {
passwordHash: await hashPassword("alice-password-1"),
isAdmin: false,
passwordIsInitial: false,
+ displayName: null,
+ avatar: null,
createdAt,
});
const sessions = new AuthSessionsRepo(db);
diff --git a/packages/server/test/scheduler.test.ts b/packages/server/test/scheduler.test.ts
index 66ee0e57..1ca69604 100644
--- a/packages/server/test/scheduler.test.ts
+++ b/packages/server/test/scheduler.test.ts
@@ -68,6 +68,8 @@ describe("scheduler", () => {
passwordHash: "x",
isAdmin: false,
passwordIsInitial: false,
+ displayName: null,
+ avatar: null,
createdAt: "2026-07-16T00:00:00Z",
});
const projects = new ProjectsRepo(db);
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 77f799f4..9f3d9862 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -134,6 +134,8 @@ import type {
UiPrefs,
UpdateCheckResponse,
UpdateJobStatus,
+ UpdateProfileRequest,
+ UpdateProfileResponse,
RestartResponse,
DesktopTrayPatch,
DesktopTrayStatusResponse,
@@ -173,6 +175,14 @@ export const getMe = () => apiFetch<MeResponse>("/api/me");
export const changePassword = (body: PasswordChangeRequest) =>
apiFetch<void>("/api/me/password", { method: "PUT", body });
+/**
+ * Nickname and avatar, as a patch: an absent field keeps what is stored, `null` clears it.
+ * The response carries the updated user, which the caller feeds straight back into the auth
+ * state so the sidebar's avatar and name change without a second round trip.
+ */
+export const updateProfile = (body: UpdateProfileRequest) =>
+ apiFetch<UpdateProfileResponse>("/api/me/profile", { method: "PUT", body });
+
export const getPrefs = () => apiFetch<PrefsResponse>("/api/me/prefs");
export const putPrefs = (prefs: UiPrefs) =>
diff --git a/packages/web/src/components/layout/app-layout.tsx b/packages/web/src/components/layout/app-layout.tsx
index d9472911..ebfd9f4a 100644
--- a/packages/web/src/components/layout/app-layout.tsx
+++ b/packages/web/src/components/layout/app-layout.tsx
@@ -19,6 +19,7 @@ import { Drawer } from "../ui/drawer";
import { GlyphIcon } from "../ui/glyph-icon";
import { Tooltip } from "../ui/tooltip";
import { UpdateDot } from "../ui/update-dot";
+import { UserAvatar } from "../ui/user-avatar";
import { CloseIcon, NAV_ICONS } from "../ui/icons";
import { NEW_CHAT_ICON, Sidebar } from "./sidebar";
import { UserMenu } from "./user-menu";
@@ -123,16 +124,18 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {
};
/**
- * The avatar's accessible name keeps the signed-in id: the menu behind it shows no id of its
- * own, so while the sidebar is collapsed this is the only place one appears. The visible
- * tooltip names what the control does instead — an initial in a circle is not a name a reader
- * needs read back. Both carry what the update trail is waiting on, which from this rail is the
- * only route left to the update row.
+ * The avatar's accessible name names the signed-in account — its nickname once there is one,
+ * since that is the name the account chose to be called. The trigger itself is nothing but an
+ * avatar, so without this the collapsed rail offers a control with no name at all; the visible
+ * tooltip says what the control does instead, because neither an initial in a circle nor a
+ * photograph is a name a reader needs read back. Both carry what the update trail is waiting
+ * on, which from this rail is the only route left to the update row.
*/
+ const accountName = user?.displayName ?? user?.userId;
const avatarName =
badges.softwareNote !== null
- ? `${user?.userId ?? ""} · ${badges.softwareNote}`
- : (user?.userId ?? S.auth.admin);
+ ? `${accountName ?? ""} · ${badges.softwareNote}`
+ : (accountName ?? S.auth.admin);
const avatarTooltip =
badges.softwareNote !== null
? `${S.nav.userSettings} · ${badges.softwareNote}`
@@ -239,12 +242,15 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {
between them would pop on every collapse while the box beside it animates
smoothly. The button keeps the rail's 32px square, which is every other
entry's target. */}
- <span className="relative flex h-7 w-7 items-center justify-center rounded-full bg-gray-900 text-xs font-bold text-white dark:bg-gray-200 dark:text-gray-900">
- {(user?.userId ?? "?").slice(0, 1).toUpperCase()}
+ <UserAvatar
+ userId={user?.userId ?? "?"}
+ {...(user?.displayName !== undefined ? { displayName: user.displayName } : {})}
+ {...(user?.avatar !== undefined ? { avatar: user.avatar } : {})}
+ >
{/* Update reminder, mirroring the pinned sidebar's avatar: the update row sits in
the menu this opens, and the label above names what is waiting. */}
{badges.software !== null && <UpdateDot />}
- </span>
+ </UserAvatar>
</button>
</Tooltip>
)}
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index 288691fe..7cb0bef8 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -122,6 +122,7 @@ import {
} from "../ui/session-row-menu";
import type { SessionRowAction } from "../ui/session-row-menu";
import { AgentAvatar } from "../ui/agent-avatar";
+import { UserAvatar } from "../ui/user-avatar";
import { CheckIcon, ChevronDown, GEAR_ICON, MESSAGING_RELAY_ICON, NAV_ICONS } from "../ui/icons";
import {
FOLDER_ICON,
@@ -2249,18 +2250,23 @@ export function Sidebar({
// The dot alone is mysterious: name what is waiting on the trigger (hover
// tooltip + accessible name), in the update row's own wording.
title: badges.softwareNote,
- "aria-label": `${user?.userId ?? ""} · ${badges.softwareNote}`,
+ "aria-label": `${user?.displayName ?? user?.userId ?? ""} · ${badges.softwareNote}`,
}
: {})}
className="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors duration-150 hover:bg-gray-200/70 dark:hover:bg-gray-800"
>
- <span className="relative flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-gray-900 text-xs font-bold text-white dark:bg-gray-200 dark:text-gray-900">
- {(user?.userId ?? "?").slice(0, 1).toUpperCase()}
+ <UserAvatar
+ userId={user?.userId ?? "?"}
+ {...(user?.displayName !== undefined ? { displayName: user.displayName } : {})}
+ {...(user?.avatar !== undefined ? { avatar: user.avatar } : {})}
+ >
{/* Update reminder: the menu behind this trigger holds the row that acts on
it, and the trigger's tooltip/label above say what it is. */}
{badges.software !== null && <UpdateDot />}
+ </UserAvatar>
+ <span className="min-w-0 flex-1 truncate text-sm font-medium">
+ {user?.displayName ?? user?.userId}
</span>
- <span className="min-w-0 flex-1 truncate text-sm font-medium">{user?.userId}</span>
{user?.isAdmin && (
<span className="text-xs text-gray-400 dark:text-gray-500">{S.auth.admin}</span>
)}
diff --git a/packages/web/src/components/layout/user-menu.tsx b/packages/web/src/components/layout/user-menu.tsx
index ae1745a3..dd7b1043 100644
--- a/packages/web/src/components/layout/user-menu.tsx
+++ b/packages/web/src/components/layout/user-menu.tsx
@@ -9,13 +9,19 @@
*
* The settings dialog is mounted OUTSIDE the panel: the panel's children unmount the moment
* the menu closes, and the settings row closes the menu as it opens the dialog.
+ *
+ * The panel heads itself with the account it belongs to — avatar, nickname, and the id under
+ * it once a nickname stands in for it. Both anchors are avatars, and the rail's is nothing but
+ * an avatar, so without the header the menu never says whose account its rows act on.
*/
import { useState } from "react";
import type { ReactNode } from "react";
import { useNavigate } from "react-router";
import { S } from "../../lib/strings";
+import { ICON_GAP } from "../../lib/icon-scale";
import { useAuth } from "../../state/auth";
import { Dropdown, menuItemClass } from "../ui/dropdown";
+import { UserAvatar } from "../ui/user-avatar";
import type { DropdownPortal } from "../ui/dropdown";
import { UpdateRow } from "../account/update-row";
import { openUpdateModal } from "../../lib/use-update-flow";
@@ -43,7 +49,7 @@ export function UserMenu({
className?: string;
}) {
const navigate = useNavigate();
- const { logout, desktopMode } = useAuth();
+ const { user, logout, desktopMode } = useAuth();
const [open, setOpen] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
@@ -60,6 +66,27 @@ export function UserMenu({
{...(anchorOwner !== undefined ? { anchorOwner } : {})}
>
<div className="py-1">
+ {/* Whose account this is. Not a row: nothing here is actionable, and the avatar plus
+ the name is what makes the rows below unambiguous on the collapsed rail, where the
+ anchor carries no text at all. The id shows under the nickname only when one is
+ set — otherwise the two lines would repeat each other. */}
+ {user && (
+ <div
+ className={`mb-1 flex items-center ${ICON_GAP.menu} border-b border-gray-100 px-3.5 pb-2.5 dark:border-gray-800`}
+ >
+ <UserAvatar
+ userId={user.userId}
+ {...(user.displayName !== undefined ? { displayName: user.displayName } : {})}
+ {...(user.avatar !== undefined ? { avatar: user.avatar } : {})}
+ />
+ <div className="min-w-0">
+ <p className="truncate text-sm font-medium">{user.displayName ?? user.userId}</p>
+ {user.displayName !== undefined && (
+ <p className="truncate text-xs text-gray-500 dark:text-gray-400">{user.userId}</p>
+ )}
+ </div>
+ </div>
+ )}
{/* System settings dialog: everyone gets the row — the dialog always has the
personal pages, and the server-global ones inside it stay gated by the
section registry rather than by this row. The preference rows that used to
diff --git a/packages/web/src/components/ui/user-avatar.tsx b/packages/web/src/components/ui/user-avatar.tsx
new file mode 100644
index 00000000..14b4640a
--- /dev/null
+++ b/packages/web/src/components/ui/user-avatar.tsx
@@ -0,0 +1,78 @@
+/**
+ * The signed-in account's avatar, wherever it is drawn: the sidebar's bottom user row, the
+ * collapsed rail's trigger, the account menu's header, and the Profile page's preview.
+ *
+ * Two states, one component. With an avatar stored it is that image, cropped to the circle;
+ * without one it is the letter tile the app has always drawn — a solid dark disc with the
+ * initial in white, which is deliberately NOT the tinted hashed tile `AgentAvatar` uses: an
+ * account is the one identity the viewer already knows, so it does not need a colour to be
+ * told apart from its neighbours, and there is only ever one of it on screen. The initial
+ * follows the nickname once there is one, falling back to the id, so the tile changes with
+ * the name rather than contradicting it.
+ *
+ * `size` is in pixels and the letter's size is derived from it, rather than both coming from
+ * the type scale: the disc is a fixed box, so a letter that grew with the user's font-size
+ * setting would outgrow it at the largest tier. The two rungs in use are named below.
+ */
+import type { CSSProperties, ReactNode } from "react";
+
+import { avatarInitial } from "../../lib/avatar";
+
+/**
+ * The sizes a user avatar is drawn at, named by the slot rather than by the number (the
+ * `icon-scale.ts` convention). `tile` is what the nav row, the rail and the menu header share
+ * — the three must stay identical, because collapsing the sidebar swaps one for another and a
+ * changed size would pop. `preview` is the Profile page, where the avatar is the subject.
+ */
+export const USER_AVATAR_SIZE = { tile: 28, preview: 64 } as const;
+
+/** The letter's share of the disc: large enough to read at 28px, still inside the circle at 64. */
+const INITIAL_RATIO = 0.45;
+
+export function UserAvatar({
+ userId,
+ displayName,
+ avatar,
+ size = USER_AVATAR_SIZE.tile,
+ className,
+ children,
+}: {
+ /** The account's id — the fallback initial, and what the accessible name names. */
+ userId: string;
+ /** Nickname, when set: it supplies the initial and the accessible name. */
+ displayName?: string;
+ /** Stored avatar as a data URL; absent, the letter tile is drawn. */
+ avatar?: string;
+ /** Edge length in pixels — pass a `USER_AVATAR_SIZE` rung. */
+ size?: number;
+ className?: string;
+ /** Overlay slot, positioned against this disc: the nav and rail triggers hang UpdateDot here. */
+ children?: ReactNode;
+}) {
+ const who = displayName ?? userId;
+ const box: CSSProperties = { width: size, height: size };
+ if (avatar !== undefined) {
+ return (
+ <span className={`relative block shrink-0 ${className ?? ""}`} style={box}>
+ {/* object-cover, though a stored avatar is already square: one written by an API client
+ rather than by the Profile page's crop must still fill the circle, not stretch into
+ it. alt="" for the reason the letter tile is aria-hidden — see below. */}
+ <img src={avatar} alt="" className="h-full w-full rounded-full object-cover" style={box} />
+ {children}
+ </span>
+ );
+ }
+ return (
+ <span
+ // Decorative, like the image above: the mark is never the account's name. Every anchor
+ // this sits in already names the account, in its own accessible name or in the text
+ // beside it, so announcing a bare initial as well would only repeat the first letter.
+ aria-hidden
+ className={`relative flex shrink-0 items-center justify-center rounded-full bg-gray-900 font-bold text-white dark:bg-gray-200 dark:text-gray-900 ${className ?? ""}`}
+ style={{ ...box, fontSize: Math.round(size * INITIAL_RATIO) }}
+ >
+ {avatarInitial(who, userId)}
+ {children}
+ </span>
+ );
+}
diff --git a/packages/web/src/features/admin/admin-users-page.tsx b/packages/web/src/features/admin/admin-users-page.tsx
index 51687f0f..8b597e34 100644
--- a/packages/web/src/features/admin/admin-users-page.tsx
+++ b/packages/web/src/features/admin/admin-users-page.tsx
@@ -79,6 +79,14 @@ export function AdminUsersSection() {
<Badge tone="gray">{S.admin.initialPasswordFlag}</Badge>
</span>
)}
+ {/* The nickname under the id, not instead of it: every other control on the
+ row acts on the id, and a list that showed only the chosen name would
+ leave an admin guessing which account they are resetting. */}
+ {u.displayName !== undefined && (
+ <p className="text-xs font-normal text-gray-500 dark:text-gray-400">
+ {u.displayName}
+ </p>
+ )}
</td>
<td className="whitespace-nowrap px-3 py-2">
<Badge tone="gray">{u.isAdmin ? S.admin.roleAdmin : S.admin.roleUser}</Badge>
diff --git a/packages/web/src/features/settings/profile-section.tsx b/packages/web/src/features/settings/profile-section.tsx
new file mode 100644
index 00000000..8a05db0d
--- /dev/null
+++ b/packages/web/src/features/settings/profile-section.tsx
@@ -0,0 +1,211 @@
+/**
+ * Profile page of System settings: the avatar and nickname the account shows itself by.
+ *
+ * Unlike the Account page beside it, this one exists in every session — the desktop shell's
+ * own token window included, which for a desktop install is the only session there is. A
+ * profile is display data, so there is no old password for the server to check.
+ *
+ * The page has no footer: every control writes when it is used, and the button that writes a
+ * value stands next to that value. Choosing an image applies it at once, because a picture is
+ * direct manipulation with nothing to review before committing, and one staged behind a button
+ * is the kind of edit people set and then lose by closing the dialog. Typed text is the one
+ * thing here that still needs an explicit commit, so the nickname keeps a Save — beside the
+ * field, not under the page. Restore default is a write like any other on both rows, so the
+ * two buttons next to one control never disagree about when they act.
+ *
+ * Both control rows are rigid and the field is what gives: the buttons carry `shrink-0` and the
+ * nickname field `min-w-0`, so a narrow dialog takes width from the field rather than from the
+ * buttons. Without it the row collapses in Chinese and not in English, which is the surprising
+ * half: flex will not shrink an item below its min-content width, and min-content for a CJK label
+ * is one character — the browser breaks between any two of them — while an English label is held
+ * open by its longest word. A squeezed button then wraps "恢复默认" onto two lines and stands twice
+ * as tall as the row beside it.
+ *
+ * Nothing is applied optimistically: the preview and every other surface show what is STORED.
+ * A write that fails therefore leaves the screen agreeing with the server and says so inline,
+ * rather than showing a picture that silently disappears on the next load.
+ */
+import { useState } from "react";
+import type { ChangeEvent } from "react";
+import type { UpdateProfileRequest } from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { avatarDataUrlFromFile } from "../../lib/avatar-image";
+import { profileControls } from "../../lib/profile-form";
+import { useAuth } from "../../state/auth";
+import { Button, labelButtonClass } from "../../components/ui/button";
+import { HiddenFileInput } from "../../components/ui/hidden-file-input";
+import { Input } from "../../components/ui/input";
+import { UserAvatar, USER_AVATAR_SIZE } from "../../components/ui/user-avatar";
+import { toastSuccess } from "../../components/ui/toast";
+import { PrefRow } from "./setting-row";
+
+/** What the picker offers — the three formats the server stores, spelled the way `accept` wants. */
+const AVATAR_ACCEPT = "image/png,image/jpeg,image/webp";
+
+const CHANGE_AVATAR_CLASS = labelButtonClass("secondary", "sm");
+
+/**
+ * The same control while a write is running. `Button`'s `disabled:` rules cannot help here — a
+ * `<label>` takes no disabled state — and a `cursor-not-allowed` beside `labelButtonClass`'s
+ * `cursor-pointer` would be decided by the order the stylesheet was generated in rather than by
+ * this string. `pointer-events-none` has no counterpart to lose to, and it removes the hover
+ * colour and the pointer cursor together; the input inside is `disabled`, so Tab skips it too.
+ */
+const CHANGE_AVATAR_BUSY_CLASS = `${CHANGE_AVATAR_CLASS} pointer-events-none opacity-60`;
+
+/** Which row is mid-write. One at a time, so the busy mark always names the row being used. */
+type PendingWrite = "avatar" | "nickname";
+
+export function ProfileSection() {
+ const { user, setUserInfo } = useAuth();
+ /** The typed nickname; `undefined` means "not edited here", so the field shows what is stored. */
+ const [draftName, setDraftName] = useState<string | undefined>(undefined);
+ const [error, setError] = useState<string | null>(null);
+ const [pending, setPending] = useState<PendingWrite | null>(null);
+
+ /**
+ * One patch out, and the row that comes back becomes the auth state: the sidebar's user row,
+ * the collapsed rail's trigger and the account menu's header all read it, so they change with
+ * this call rather than on the next page load.
+ */
+ const send = async (patch: UpdateProfileRequest): Promise<boolean> => {
+ try {
+ const res = await api.updateProfile(patch);
+ setUserInfo(res.user);
+ toastSuccess(S.common.saved);
+ return true;
+ } catch (e) {
+ setError(apiErrorText(e));
+ return false;
+ }
+ };
+
+ /**
+ * Every control goes through here, so two writes can never be in flight together and the last
+ * failure is never left standing beside a control the user has since used again.
+ */
+ const run = async (what: PendingWrite, body: () => Promise<unknown>): Promise<void> => {
+ if (pending !== null) return;
+ setPending(what);
+ setError(null);
+ try {
+ await body();
+ } finally {
+ setPending(null);
+ }
+ };
+
+ const onPickFile = (e: ChangeEvent<HTMLInputElement>): void => {
+ const file = e.target.files?.[0];
+ // Reset before reading so re-picking the same file fires change again.
+ e.target.value = "";
+ if (file === undefined) return;
+ // The encode runs inside the busy window as well as the request: it decodes the picked file
+ // and redraws it, which for a phone photograph is long enough to click twice through.
+ void run("avatar", async () => {
+ const dataUrl = await avatarDataUrlFromFile(file).catch(() => undefined);
+ if (dataUrl === undefined) {
+ setError(S.profile.avatarUnreadable);
+ return;
+ }
+ if (dataUrl === null) {
+ setError(S.profile.avatarTooLarge);
+ return;
+ }
+ await send({ avatar: dataUrl });
+ });
+ };
+
+ if (!user) return null;
+ const controls = profileControls(user, draftName ?? user.displayName ?? "");
+ const busy = pending !== null;
+
+ return (
+ <section>
+ <div className="divide-y divide-gray-100 dark:divide-gray-800/60">
+ <PrefRow label={S.profile.avatar} info={S.profile.avatarInfo}>
+ <div className="flex items-center gap-3">
+ <UserAvatar
+ userId={user.userId}
+ {...(user.displayName !== undefined ? { displayName: user.displayName } : {})}
+ {...(user.avatar !== undefined ? { avatar: user.avatar } : {})}
+ size={USER_AVATAR_SIZE.preview}
+ />
+ {/* A label rather than a Button: the hidden file input has to be labelled for a
+ click to open the native picker. Same two records Button reads, at the form rung
+ its neighbours sit on. */}
+ <label className={`shrink-0 ${busy ? CHANGE_AVATAR_BUSY_CLASS : CHANGE_AVATAR_CLASS}`}>
+ <HiddenFileInput accept={AVATAR_ACCEPT} disabled={busy} onChange={onPickFile} />
+ {S.profile.changeAvatar}
+ </label>
+ <Button
+ size="sm"
+ variant="secondary"
+ className="shrink-0"
+ aria-label={S.profile.restoreDefaultOf(S.profile.avatar)}
+ disabled={busy || !controls.canRestoreAvatar}
+ onClick={() => void run("avatar", () => send({ avatar: null }))}
+ >
+ {S.profile.restoreDefault}
+ </Button>
+ </div>
+ </PrefRow>
+ <PrefRow label={S.profile.displayName} hint={S.profile.displayNameHint}>
+ <div className="flex items-center gap-2">
+ <Input
+ size="sm"
+ className="w-48 min-w-0"
+ maxLength={32}
+ value={draftName ?? user.displayName ?? ""}
+ placeholder={S.profile.displayNamePlaceholder}
+ disabled={busy}
+ aria-label={S.profile.displayName}
+ onChange={(e) => {
+ setDraftName(e.target.value);
+ setError(null);
+ }}
+ />
+ <Button
+ size="sm"
+ variant="primary"
+ className="shrink-0"
+ disabled={busy || !controls.canSaveNickname}
+ onClick={() =>
+ void run("nickname", async () => {
+ // Back to "not edited" only once it landed, so a failed save keeps the text
+ // the user typed instead of snapping the field back to the stored value.
+ if (await send({ displayName: controls.nicknameToStore })) {
+ setDraftName(undefined);
+ }
+ })
+ }
+ >
+ {S.common.save}
+ </Button>
+ <Button
+ size="sm"
+ variant="secondary"
+ className="shrink-0"
+ aria-label={S.profile.restoreDefaultOf(S.profile.displayName)}
+ disabled={busy || !controls.canRestoreNickname}
+ onClick={() =>
+ void run("nickname", async () => {
+ if (await send({ displayName: null })) setDraftName(undefined);
+ })
+ }
+ >
+ {S.profile.restoreDefault}
+ </Button>
+ </div>
+ </PrefRow>
+ </div>
+ {/* Busy and failed, in the one place both rows can say it: a write here changes the
+ sidebar as well as this page, so "it did not happen" has to be stated rather than
+ left to the preview looking unchanged. */}
+ {busy && <p className="mt-2 text-xs text-gray-500 dark:text-gray-400">{S.common.saving}</p>}
+ {error !== null && <p className="mt-2 text-xs text-red-600 dark:text-red-400">{error}</p>}
+ </section>
+ );
+}
diff --git a/packages/web/src/features/settings/settings-dialog.tsx b/packages/web/src/features/settings/settings-dialog.tsx
index a766c73c..23ff2d54 100644
--- a/packages/web/src/features/settings/settings-dialog.tsx
+++ b/packages/web/src/features/settings/settings-dialog.tsx
@@ -20,6 +20,7 @@ import { PagedDialog } from "../../components/ui/paged-dialog";
import type { PagedDialogGroup } from "../../components/ui/paged-dialog";
import { Icon } from "../../components/ui/group-list";
import { GEAR_ICON } from "../../components/ui/icons";
+import { ProfileSection } from "./profile-section";
import { GeneralSection } from "./general-section";
import { AppearanceSection } from "./appearance-section";
import { AccountSection } from "./account-section";
@@ -29,6 +30,9 @@ import { AdminUsersSection } from "../admin/admin-users-page";
/** Rail glyphs, on the shared 24x24 stroke grid (see NAV_ICONS' conventions). */
const SECTION_ICONS: Record<SettingsSectionKey, string> = {
+ /** Person in a circle: the account's own identity, distinct from the bust used for credentials. */
+ profile:
+ "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zM12 11.5a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM6.2 18.4a6 6 0 0 1 11.6 0",
general: GEAR_ICON,
/** Sun: appearance. */
appearance:
@@ -67,6 +71,7 @@ export function SettingsDialog({ open, onClose }: { open: boolean; onClose: () =
// Read inside the component: after a language switch remount, these pick up the current dictionary.
const sectionLabel: Record<SettingsSectionKey, string> = {
+ profile: S.settings.profile,
general: S.settings.generalTitle,
appearance: S.settings.appearanceTitle,
account: S.settings.accountTitle,
@@ -109,6 +114,7 @@ export function SettingsDialog({ open, onClose }: { open: boolean; onClose: () =
active={current}
onSelect={setActive}
>
+ {current === "profile" && <ProfileSection />}
{current === "general" && <GeneralSection />}
{current === "appearance" && <AppearanceSection />}
{current === "account" && <AccountSection />}
diff --git a/packages/web/src/lib/avatar-image.ts b/packages/web/src/lib/avatar-image.ts
new file mode 100644
index 00000000..de558b5f
--- /dev/null
+++ b/packages/web/src/lib/avatar-image.ts
@@ -0,0 +1,100 @@
+/**
+ * Turning a picked image file into the data URL the profile route stores.
+ *
+ * Three decisions live here, and only the last of them needs a browser:
+ *
+ * 1. **The crop.** An avatar is drawn in a circle, so the square the centre crop keeps is the
+ * only part a viewer ever sees; cropping before scaling is what keeps a wide photo from
+ * being squeezed into it.
+ * 2. **The size.** 128x128 is the largest rung any surface draws (the Profile page's preview
+ * is 64px, the nav tile 28px), doubled for a 2x screen. A bigger source buys nothing and is
+ * paid for on every page load, since the data URL travels inside `GET /api/me`.
+ * 3. **The format.** PNG first, because a flat or generated image stays small and stays sharp;
+ * a photograph does not, so a PNG over its budget is re-exported as JPEG.
+ *
+ * Everything but `avatarDataUrlFromFile` is pure, and the format decision takes its encoder as
+ * an argument rather than reaching for a canvas: this package's vitest runs in Node with no
+ * DOM, so a size/format rule that could only be exercised through a real canvas could not be
+ * exercised at all.
+ *
+ * Both budgets are measured in CHARACTERS OF THE DATA URL, which is also the unit the server's
+ * cap is written in — so "fits" means the same thing on both sides of the request, with no
+ * base64-expansion arithmetic in between to get wrong.
+ */
+
+/** Edge of the stored square, in pixels. */
+export const AVATAR_EDGE = 128;
+
+/**
+ * Where PNG stops being worth it. Under this, the sharper lossless encoding is kept; over it,
+ * the image is photographic enough that JPEG is both smaller and indistinguishable at 128px.
+ */
+export const AVATAR_PNG_BUDGET = 100 * 1024;
+
+/** The hard cap, in data-URL characters — the same number `PUT /api/me/profile` enforces. */
+export const AVATAR_MAX_CHARS = 128 * 1024;
+
+/** JPEG quality for the re-export: visually clean at 128px, and roughly a third of q=1. */
+export const AVATAR_JPEG_QUALITY = 0.85;
+
+export type AvatarMimeType = "image/png" | "image/jpeg";
+
+/** Encodes the already-drawn 128x128 surface as a data URL. `canvas.toDataURL`, injected. */
+export type AvatarEncoder = (type: AvatarMimeType, quality?: number) => string;
+
+/** The source rectangle a centre crop keeps: the largest square centred on the image. */
+export function centreCropRect(
+ width: number,
+ height: number,
+): { x: number; y: number; size: number } {
+ const size = Math.min(width, height);
+ return { x: Math.round((width - size) / 2), y: Math.round((height - size) / 2), size };
+}
+
+/**
+ * The data URL to store, or null when even the JPEG re-export is over the cap.
+ *
+ * Null is a real outcome rather than an error: a 128x128 JPEG past 128 KiB means the encoder
+ * produced something the server will not take, which the page reports inline instead of
+ * sending a request that is certain to 400.
+ */
+export function fitAvatarDataUrl(encode: AvatarEncoder): string | null {
+ const png = encode("image/png");
+ if (png.length <= AVATAR_PNG_BUDGET) return png;
+ const jpeg = encode("image/jpeg", AVATAR_JPEG_QUALITY);
+ return jpeg.length <= AVATAR_MAX_CHARS ? jpeg : null;
+}
+
+/** Decodes a picked file into an element `drawImage` accepts. Rejects if it is not an image. */
+function loadImage(file: File): Promise<HTMLImageElement> {
+ return new Promise((resolve, reject) => {
+ const url = URL.createObjectURL(file);
+ const img = new Image();
+ img.onload = () => {
+ // The bitmap is already decoded into the element, so the blob URL has done its job.
+ URL.revokeObjectURL(url);
+ resolve(img);
+ };
+ img.onerror = () => {
+ URL.revokeObjectURL(url);
+ reject(new Error("The picked file could not be decoded as an image."));
+ };
+ img.src = url;
+ });
+}
+
+/**
+ * A picked file as a stored avatar: centre-cropped, drawn at AVATAR_EDGE, encoded by the rule
+ * above. Null means it did not fit; it throws only when the file is not a readable image.
+ */
+export async function avatarDataUrlFromFile(file: File): Promise<string | null> {
+ const image = await loadImage(file);
+ const canvas = document.createElement("canvas");
+ canvas.width = AVATAR_EDGE;
+ canvas.height = AVATAR_EDGE;
+ const ctx = canvas.getContext("2d");
+ if (ctx === null) throw new Error("This browser did not provide a 2D canvas context.");
+ const crop = centreCropRect(image.naturalWidth, image.naturalHeight);
+ ctx.drawImage(image, crop.x, crop.y, crop.size, crop.size, 0, 0, AVATAR_EDGE, AVATAR_EDGE);
+ return fitAvatarDataUrl((type, quality) => canvas.toDataURL(type, quality));
+}
diff --git a/packages/web/src/lib/profile-form.ts b/packages/web/src/lib/profile-form.ts
new file mode 100644
index 00000000..191d3aaf
--- /dev/null
+++ b/packages/web/src/lib/profile-form.ts
@@ -0,0 +1,40 @@
+/**
+ * The Profile page's write rules, kept out of the component so a test can reach them.
+ *
+ * Every control on that page performs a write when it is used — choosing an image applies it,
+ * and the nickname's Save and Restore default each send a patch of their own — so what has to
+ * be checkable is WHICH value each one would store and WHEN it is live. This package's vitest
+ * runs in Node with no DOM (the same reason `settings-sections.ts` holds the dialog's
+ * visibility rules rather than the dialog), so the rules live here rather than inside the JSX.
+ */
+import type { UserInfo } from "@prismshadow/penguin-server/api";
+
+/** What the nickname row's two buttons would do, given the stored profile and the typed text. */
+export interface ProfileControls {
+ /**
+ * What Save writes: the trimmed text, or `null` for a blank box — the route spells "no
+ * nickname" as `null`, and trimming here is what makes the comparison below see the value
+ * that would actually be stored.
+ */
+ nicknameToStore: string | null;
+ /** Live only when that differs from what is stored: re-saving the stored value is not a save. */
+ canSaveNickname: boolean;
+ /**
+ * Live only when a nickname is stored. With none stored the default is already in force —
+ * every surface falls back to the user id — so the button would write `null` over `null`.
+ */
+ canRestoreNickname: boolean;
+ /** The same rule for the avatar: with none stored, the letter tile is already what is drawn. */
+ canRestoreAvatar: boolean;
+}
+
+export function profileControls(user: UserInfo, typedNickname: string): ProfileControls {
+ const trimmed = typedNickname.trim();
+ const nicknameToStore = trimmed === "" ? null : trimmed;
+ return {
+ nicknameToStore,
+ canSaveNickname: (nicknameToStore ?? "") !== (user.displayName ?? ""),
+ canRestoreNickname: user.displayName !== undefined,
+ canRestoreAvatar: user.avatar !== undefined,
+ };
+}
diff --git a/packages/web/src/lib/settings-sections.ts b/packages/web/src/lib/settings-sections.ts
index 5b9d785c..7ffbbc0b 100644
--- a/packages/web/src/lib/settings-sections.ts
+++ b/packages/web/src/lib/settings-sections.ts
@@ -5,12 +5,13 @@
* belong to admins alone; the personal pages are per-user preferences every signed-in user
* owns. Two pages additionally depend on how this session runs: the account page only
* exists where a password can be changed (see offersChangePassword), and user management
- * disappears in desktop mode, where the app is single-user. Updating is not a page here at
- * all — both the server check and the desktop client's live in the sidebar user menu, under
- * the entry that opens this dialog. The rules live here rather than inside the dialog
- * because this package's vitest runs in Node with no DOM — a pure function is the only
- * thing a test can pin directly — and because rail and content have to apply the same rule
- * to avoid a visible-but-forbidden entry.
+ * disappears in desktop mode, where the app is single-user. The profile page is neither — an
+ * avatar and a nickname are display data, so every signed-in session may set them. Updating
+ * is not a page here at all — both the server check and the desktop client's live in the
+ * sidebar user menu, under the entry that opens this dialog. The rules live here rather than
+ * inside the dialog because this package's vitest runs in Node with no DOM — a pure function
+ * is the only thing a test can pin directly — and because rail and content have to apply the
+ * same rule to avoid a visible-but-forbidden entry.
*
* A page the viewer may not open is dropped from the list entirely rather than rendered
* disabled: a greyed-out "Proxy" row still tells a non-admin the setting exists and that
@@ -24,7 +25,7 @@ import type { AccountMenuSession } from "./account-menu";
/** A page of the System settings dialog. */
export type SettingsSectionKey =
- "general" | "appearance" | "account" | "proxy" | "uploads" | "users";
+ "profile" | "general" | "appearance" | "account" | "proxy" | "uploads" | "users";
/** Rail heading a page sits under: the viewer's own preferences vs. the whole server's. */
export type SettingsGroupKey = "personal" | "server";
@@ -45,6 +46,10 @@ export interface SettingsViewer extends AccountMenuSession {
*/
const SECTION_RULES: ReadonlyArray<SettingsSection & { visible(viewer: SettingsViewer): boolean }> =
[
+ // Heads the personal group, and unlike the account page below it is visible in every
+ // session: a nickname and an avatar need no password to change, so the desktop shell's
+ // own window — which for some installs is the only session there is — keeps it.
+ { key: "profile", group: "personal", visible: () => true },
{ key: "general", group: "personal", visible: () => true },
{ key: "appearance", group: "personal", visible: () => true },
// The desktop shell's own window has no password to change; a password-established
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 3a6d7cb4..d297d542 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -127,6 +127,7 @@ export const en: Strings = {
groupPersonal: "Personal",
groupServer: "Server",
/** Personal pages of the settings dialog. */
+ profile: "Profile",
generalTitle: "General",
appearanceTitle: "Appearance",
accountTitle: "Account",
@@ -443,6 +444,35 @@ export const en: Strings = {
"The first-login link stops working once the server has a password, and a restart replaces it with a new one. Sign in with your username and password below, or ask your administrator for a new sign-in link.",
},
+ /**
+ * The Profile page of System settings, and the avatar/nickname it writes. Visible in every
+ * session, the desktop shell's own window included: a profile needs no password to change.
+ */
+ profile: {
+ /** Avatar row: its label, and the two actions beside the preview. */
+ avatar: "Avatar",
+ /** Disclosed by the "?" beside that label: when a picked image takes effect. */
+ avatarInfo:
+ "A picture takes effect as soon as you choose it — there is no separate Save for it. The nickname beside it is typed text, so it keeps a Save of its own.",
+ changeAvatar: "Change avatar",
+ /**
+ * Shared label of the two buttons that put a field back to what an account with nothing set
+ * shows: the letter tile for the avatar, the username for the nickname. Neither deletes
+ * anything the app cannot draw again, which is why it does not say "remove".
+ */
+ restoreDefault: "Restore default",
+ /** The same, named for what it restores: two of these sit on one page. */
+ restoreDefaultOf: (subject: string) => `Restore default: ${subject}`,
+ /** The picked image could not be brought under the size limit even as JPEG. */
+ avatarTooLarge: "That image is too large. Please pick a smaller one.",
+ /** The picked file could not be decoded as an image at all. */
+ avatarUnreadable: "That image could not be read. Please pick another file.",
+ /** Nickname row: the field, and the shape rule that stays on screen while typing. */
+ displayName: "Nickname",
+ displayNameHint: "1–32 characters; leave blank to clear",
+ displayNamePlaceholder: "Blank shows the username",
+ },
+
account: {
changePassword: "Change password",
oldPassword: "Current password",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 3af6b5f3..bef48c03 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -147,6 +147,7 @@ export const zh = {
groupPersonal: "个人",
groupServer: "服务器",
/** Personal pages of the settings dialog. */
+ profile: "个人资料",
generalTitle: "通用",
appearanceTitle: "外观",
accountTitle: "账户",
@@ -448,6 +449,35 @@ export const zh = {
"首次登录链接在服务端设置密码后即失效,重启服务端也会换发新的链接。请在下方用账号密码登录,或向管理员索取新的登录链接。",
},
+ /**
+ * The Profile page of System settings, and the avatar/nickname it writes. Visible in every
+ * session, the desktop shell's own window included: a profile needs no password to change.
+ */
+ profile: {
+ /** Avatar row: its label, and the two actions beside the preview. */
+ avatar: "头像",
+ /** Disclosed by the "?" beside that label: when a picked image takes effect. */
+ avatarInfo:
+ "选择图片后立即生效,无需另行保存;旁边的昵称是输入的文本,因此保留了自己的保存按钮。",
+ changeAvatar: "更换头像",
+ /**
+ * Shared label of the two buttons that put a field back to what an account with nothing set
+ * shows: the letter tile for the avatar, the username for the nickname. Neither deletes
+ * anything the app cannot draw again, which is why it does not say "remove".
+ */
+ restoreDefault: "恢复默认",
+ /** The same, named for what it restores: two of these sit on one page. */
+ restoreDefaultOf: (subject: string) => `恢复默认:${subject}`,
+ /** The picked image could not be brought under the size limit even as JPEG. */
+ avatarTooLarge: "图片过大,请换一张尺寸更小的图片。",
+ /** The picked file could not be decoded as an image at all. */
+ avatarUnreadable: "无法读取这张图片,请换一个文件。",
+ /** Nickname row: the field, and the shape rule that stays on screen while typing. */
+ displayName: "昵称",
+ displayNameHint: "1–32 个字符,留空即清除",
+ displayNamePlaceholder: "留空则显示用户名",
+ },
+
account: {
changePassword: "修改密码",
oldPassword: "当前密码",
diff --git a/packages/web/src/state/auth.tsx b/packages/web/src/state/auth.tsx
index 9809a6b1..66c2abaf 100644
--- a/packages/web/src/state/auth.tsx
+++ b/packages/web/src/state/auth.tsx
@@ -59,6 +59,13 @@ interface AuthContextValue {
logout: () => Promise<void>;
/** Refetch /api/me (e.g. to refresh the passwordIsInitial flag after a password change). */
refresh: () => Promise<void>;
+ /**
+ * Adopt a user the server has just returned — the Profile page's save. `refresh()` would
+ * reach the same state through a second request, and the fields it would bring back with it
+ * (previewIsolated, the upload limits) did not change, so the response is the cheaper and
+ * more direct source: the sidebar's avatar and name move in the same commit as the save.
+ */
+ setUserInfo: (user: UserInfo) => void;
}
const AuthContext = createContext<AuthContextValue | null>(null);
@@ -133,6 +140,8 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}
}, []);
+ const setUserInfo = useCallback((next: UserInfo) => setUser(next), []);
+
const refresh = useCallback(async () => {
const res = await api.getMe();
setUser(res.user);
@@ -153,6 +162,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
login,
logout,
refresh,
+ setUserInfo,
}}
>
{children}
diff --git a/packages/web/test/avatar-image.test.ts b/packages/web/test/avatar-image.test.ts
new file mode 100644
index 00000000..d5537adb
--- /dev/null
+++ b/packages/web/test/avatar-image.test.ts
@@ -0,0 +1,93 @@
+/**
+ * avatar-image.ts: the crop rectangle and the format decision behind a picked avatar.
+ *
+ * vitest runs node-only here (`environment: "node"`, no jsdom), which is why the encoder is a
+ * parameter rather than a canvas call: the rule that decides PNG-or-JPEG-or-refuse is the part
+ * a user hits, and it is exercised here with a fake encoder instead of being unreachable.
+ */
+import { describe, expect, it } from "vitest";
+import {
+ AVATAR_JPEG_QUALITY,
+ AVATAR_MAX_CHARS,
+ AVATAR_PNG_BUDGET,
+ centreCropRect,
+ fitAvatarDataUrl,
+} from "../src/lib/avatar-image";
+import type { AvatarMimeType } from "../src/lib/avatar-image";
+
+/** A data URL of exactly `length` characters in the given format. */
+function fakeDataUrl(type: AvatarMimeType, length: number): string {
+ const prefix = `data:${type};base64,`;
+ return prefix + "A".repeat(Math.max(0, length - prefix.length));
+}
+
+/**
+ * An encoder that answers with a fixed size per format, recording what it was asked for — the
+ * two things a call site can get wrong are asking for the wrong quality and asking twice.
+ */
+function encoderOf(sizes: { png: number; jpeg: number }) {
+ const calls: { type: AvatarMimeType; quality?: number }[] = [];
+ const encode = (type: AvatarMimeType, quality?: number): string => {
+ calls.push(quality === undefined ? { type } : { type, quality });
+ return fakeDataUrl(type, type === "image/png" ? sizes.png : sizes.jpeg);
+ };
+ return { encode, calls };
+}
+
+describe("centreCropRect", () => {
+ it("keeps the whole image when it is already square", () => {
+ expect(centreCropRect(200, 200)).toEqual({ x: 0, y: 0, size: 200 });
+ });
+
+ it("takes the middle square of a wide image, and of a tall one", () => {
+ // 400x200: a 200px square with 100px trimmed from each side.
+ expect(centreCropRect(400, 200)).toEqual({ x: 100, y: 0, size: 200 });
+ expect(centreCropRect(200, 400)).toEqual({ x: 0, y: 100, size: 200 });
+ });
+
+ it("rounds an odd offset rather than leaving a fractional source rectangle", () => {
+ expect(centreCropRect(101, 100)).toEqual({ x: 1, y: 0, size: 100 });
+ });
+});
+
+describe("fitAvatarDataUrl", () => {
+ it("keeps the PNG when it is inside the budget, and asks for nothing else", () => {
+ const { encode, calls } = encoderOf({ png: 1000, jpeg: 500 });
+ const result = fitAvatarDataUrl(encode);
+ expect(result?.startsWith("data:image/png;base64,")).toBe(true);
+ // The JPEG is smaller here and is still not asked for: a small PNG is the sharper of the
+ // two at 128px, so the budget decides, not the byte count.
+ expect(calls).toEqual([{ type: "image/png" }]);
+ });
+
+ it("re-exports as JPEG at the fixed quality once the PNG is over budget", () => {
+ const { encode, calls } = encoderOf({ png: AVATAR_PNG_BUDGET + 1, jpeg: 40000 });
+ expect(fitAvatarDataUrl(encode)?.startsWith("data:image/jpeg;base64,")).toBe(true);
+ expect(calls).toEqual([
+ { type: "image/png" },
+ { type: "image/jpeg", quality: AVATAR_JPEG_QUALITY },
+ ]);
+ });
+
+ it("accepts a JPEG between the budget and the cap", () => {
+ // The budget is where PNG stops being worth it; the cap is what the server takes. A JPEG in
+ // between is stored, so the two numbers are not the same check.
+ const { encode } = encoderOf({ png: AVATAR_MAX_CHARS, jpeg: AVATAR_MAX_CHARS });
+ expect(fitAvatarDataUrl(encode)?.length).toBe(AVATAR_MAX_CHARS);
+ });
+
+ it("returns null when even the JPEG is over the cap, rather than a request certain to 400", () => {
+ const { encode } = encoderOf({ png: 400000, jpeg: AVATAR_MAX_CHARS + 1 });
+ expect(fitAvatarDataUrl(encode)).toBe(null);
+ });
+});
+
+describe("the cap", () => {
+ it("is the same number the server enforces, in the same unit", () => {
+ // server/src/http/routes/me.ts rejects an avatar over 131072 CHARACTERS of data URL. Both
+ // sides measuring the string rather than the decoded bytes is what keeps a picture this
+ // module just accepted from being refused by the request that carries it.
+ expect(AVATAR_MAX_CHARS).toBe(131072);
+ expect(AVATAR_PNG_BUDGET).toBeLessThan(AVATAR_MAX_CHARS);
+ });
+});
diff --git a/packages/web/test/control-size.test.ts b/packages/web/test/control-size.test.ts
index 452ab843..86ade8a6 100644
--- a/packages/web/test/control-size.test.ts
+++ b/packages/web/test/control-size.test.ts
@@ -134,6 +134,7 @@ function findLooseFooterButtons(): string[] {
*/
const DIALOG_BODY_MODULES = new Set([
"features/settings/account-section.tsx",
+ "features/settings/profile-section.tsx",
"features/settings/appearance-section.tsx",
"features/settings/general-section.tsx",
"features/settings/proxy-section.tsx",
diff --git a/packages/web/test/profile-form.test.ts b/packages/web/test/profile-form.test.ts
new file mode 100644
index 00000000..5c3278b5
--- /dev/null
+++ b/packages/web/test/profile-form.test.ts
@@ -0,0 +1,57 @@
+/**
+ * profile-form.ts: what the Profile page's nickname buttons write, and when they are live.
+ *
+ * The page's other half — a picked image applying without a Save — is a React effect of the
+ * pick handler and this package's vitest is node-only (`environment: "node"`, no jsdom), so it
+ * is not reachable from here; what IS reachable is the rule that decides the two nickname
+ * writes, which is the half a regression would land on silently.
+ */
+import { describe, expect, it } from "vitest";
+import type { UserInfo } from "@prismshadow/penguin-server/api";
+import { profileControls } from "../src/lib/profile-form";
+
+/** An account with nothing set: the state every account predating the Profile page is in. */
+const bare: UserInfo = {
+ userId: "bob",
+ isAdmin: false,
+ passwordIsInitial: false,
+ createdAt: "2026-01-01T00:00:00Z",
+};
+
+const named: UserInfo = { ...bare, displayName: "Bob Loblaw" };
+
+describe("profileControls", () => {
+ it("stores the trimmed text, and spells a blank box as null rather than an empty name", () => {
+ // null is the route's "clear it": a blank string would be refused as a 1-32 character name,
+ // so a field the user emptied has to leave as null or the save 400s.
+ expect(profileControls(named, " Bob ").nicknameToStore).toBe("Bob");
+ expect(profileControls(named, " ").nicknameToStore).toBe(null);
+ });
+
+ it("keeps Save dead until the box would store something else", () => {
+ expect(profileControls(named, "Bob Loblaw").canSaveNickname).toBe(false);
+ // Whitespace either side is not an edit: the server trims too, so saving it would write
+ // the value that is already there.
+ expect(profileControls(named, " Bob Loblaw ").canSaveNickname).toBe(false);
+ expect(profileControls(named, "Bob").canSaveNickname).toBe(true);
+ // Emptying the field is a change — it stores null — while an already-blank one is not.
+ expect(profileControls(named, "").canSaveNickname).toBe(true);
+ expect(profileControls(bare, "").canSaveNickname).toBe(false);
+ expect(profileControls(bare, "Bob").canSaveNickname).toBe(true);
+ });
+
+ it("restores the default by writing null, and only when there is something stored", () => {
+ // Restore default is a write like Save, not a clear of the input box: with a nickname
+ // stored it must reach the server, and with none stored the button has nothing to do
+ // because every surface already falls back to the user id.
+ expect(profileControls(named, "anything typed").canRestoreNickname).toBe(true);
+ expect(profileControls(bare, "anything typed").canRestoreNickname).toBe(false);
+ });
+
+ it("reads the avatar's Restore default off what is stored, not off the typed nickname", () => {
+ expect(profileControls(bare, "Bob").canRestoreAvatar).toBe(false);
+ expect(
+ profileControls({ ...bare, avatar: "data:image/png;base64,AAAA" }, "").canRestoreAvatar,
+ ).toBe(true);
+ });
+});
diff --git a/packages/web/test/settings-sections.test.ts b/packages/web/test/settings-sections.test.ts
index 03f89b5d..8339e7c0 100644
--- a/packages/web/test/settings-sections.test.ts
+++ b/packages/web/test/settings-sections.test.ts
@@ -52,6 +52,7 @@ const desktopBrowser = visibleSettingsSections({
describe("visibleSettingsSections", () => {
it("gives a web admin every page, in rail order", () => {
expect(admin.map((s) => s.key)).toEqual([
+ "profile",
"general",
"appearance",
"account",
@@ -66,19 +67,27 @@ describe("visibleSettingsSections", () => {
// admin surfaces, and the whole point of dropping them is that a non-admin is never
// told they exist. Updating is not among them either way: it lives in the sidebar user
// menu, outside this dialog, for every account.
- expect(plain.map((s) => s.key)).toEqual(["general", "appearance", "account"]);
+ expect(plain.map((s) => s.key)).toEqual(["profile", "general", "appearance", "account"]);
});
it("strips the desktop shell's window down to what a token session can use", () => {
// No account page (no password to change — see offersChangePassword), no user
- // management (single-user server).
- expect(shell.map((s) => s.key)).toEqual(["general", "appearance", "proxy", "uploads"]);
+ // management (single-user server). The profile page stays: an avatar and a nickname need
+ // no password, and this window is the only session a desktop install has.
+ expect(shell.map((s) => s.key)).toEqual([
+ "profile",
+ "general",
+ "appearance",
+ "proxy",
+ "uploads",
+ ]);
});
it("keeps the account page for a password session against a desktop-mode server", () => {
// Mirrors the old menu row's two-field rule: that session typed a real password and
// can still change it, while user management stays desktop-hidden.
expect(desktopBrowser.map((s) => s.key)).toEqual([
+ "profile",
"general",
"appearance",
"account",
@@ -104,19 +113,20 @@ describe("resolveSettingsSection", () => {
it("passes through a page the viewer may open", () => {
expect(resolveSettingsSection("proxy", admin)).toBe("proxy");
expect(resolveSettingsSection("appearance", plain)).toBe("appearance");
+ expect(resolveSettingsSection("profile", plain)).toBe("profile");
});
it("sends a non-admin asking for an admin page to their own first page", () => {
// Answering identically to an unknown request is the point: a requested key cannot be
// used to find out that "users" is a real page.
- expect(resolveSettingsSection("users", plain)).toBe("general");
- expect(resolveSettingsSection("proxy", plain)).toBe("general");
- expect(resolveSettingsSection("no-such-section", plain)).toBe("general");
+ expect(resolveSettingsSection("users", plain)).toBe("profile");
+ expect(resolveSettingsSection("proxy", plain)).toBe("profile");
+ expect(resolveSettingsSection("no-such-section", plain)).toBe("profile");
});
it("falls back to the first visible page for a missing request", () => {
- expect(resolveSettingsSection(null, admin)).toBe("general");
- expect(resolveSettingsSection(undefined, admin)).toBe("general");
+ expect(resolveSettingsSection(null, admin)).toBe("profile");
+ expect(resolveSettingsSection(undefined, admin)).toBe("profile");
});
it("returns null when nothing is visible, rather than inventing a page", () => {