From 11dcc04ac4d0ababe878d151ae9909df1ebc792a Mon Sep 17 00:00:00 2001 From: nntrivi2001 Date: Mon, 7 Sep 2026 16:29:11 +0700 Subject: [PATCH] fix(cc-config): one account is one profile, and rename it in place MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Four defects, all from one design mistake: a profile's display name and its filename were the same string. - Saving the logged-in account made a SECOND profile of an account another profile already held. Both then reported themselves active, so there was nothing to switch between. `POST /profiles` now refuses `EDUPLICATE` and names the profile that already holds the account. Re-saving into the account's own profile stays allowed - that is the token-refresh path. - Worse, an accidental duplicate could not be cleaned up: two profiles of one account are both active, and the delete guard refused any active profile, so neither was ever deletable. The guard now blocks only the LAST saved copy of the live account, which is the actual credential-loss condition it exists for. The trash button had to follow, or the server would allow what the UI hid. - A name could not contain spaces or diacritics, because it had to be filename-safe. A profile now carries `name` (internal identifier, still the filename, still what every route takes) and `label` (what the user reads and edits: 1-60 free-form characters, control characters rejected, stored trimmed, unique case-insensitively). A label never touches a path, which is what makes "Tài khoản chính" a legal name. - Naming happened up front in a "save current account as" field. That field is gone. The server derives the identifier, the save button lives on the live account's card and appears only while it is unsaved, and the label is edited by clicking it (Enter saves, Escape cancels). Renaming rewrites the label in place and deliberately does NOT move `name`, so it cannot half-fail and leave a profile unreachable. Profiles written before labels existed report `label` equal to their `name`, so nothing needs migrating. Adds `PATCH /api/cc-config/profiles`; `POST` now takes an optional `name`. Verified: server 1431/1431 (11 new), client 459/459, tsc clean. Also exercised end to end against a COPY of the real profile store on this machine: the duplicate deleted, the last copy still refused, a Vietnamese label accepted, and the stored access/refresh tokens and 0600 mode intact after a rename. --- ARCHITECTURE.md | 6 +- client/src/i18n/locales/en/ccConfig.json | 15 +-- client/src/i18n/locales/vi/ccConfig.json | 15 +-- client/src/lib/api.ts | 25 +++- client/src/pages/CcConfig.tsx | 105 ++++++++++------ docs/API.md | 11 +- openapi.yaml | 95 +++++++++++++-- server/README.md | 5 +- server/__tests__/cc-profiles.test.js | 119 ++++++++++++++++++ server/lib/cc-profiles.js | 149 ++++++++++++++++++++--- server/openapi-extra/cc-config.js | 102 ++++++++++++++-- server/routes/cc-config.js | 15 +++ 12 files changed, 560 insertions(+), 102 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index c1b99ebb..eeaffb23 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -348,8 +348,8 @@ graph TD | `server/lib/scoped-stats.js` | Source-scoped variants of the stats/analytics aggregates, used **only** when a `?sources=` scope filter is active — the unscoped fast paths in `routes/stats.js` / `routes/analytics.js` are untouched when no scope is set | | `lib/cc-discovery.js` | Read-only discovery of every Claude Code config surface for the Config Explorer page. Pure file reads; never writes. Surfaces: skills (`/skills//SKILL.md`), subagents (`/agents/*.md`), slash commands (`/commands/*.md`), output styles (`/output-styles/*.md`), plugins (`/plugins/installed_plugins.json` joined with `enabledPlugins` in settings + per-plugin `contributes` counts **and** `contributes.items`, which names every skill / subagent / command / output style the plugin ships — each surface read from the conventional install subdirectory *and* from whatever path `plugin.json` declares for that key, with declared paths outside the plugin's own install dir dropped by `isUnder()`, so a plugin that lists its commands explicitly and keeps `commands/` empty no longer reports zero + `plugin.json` metadata), marketplaces (`known_marketplaces.json` enriched with each `marketplace.json`), MCP servers (top-level + per-project from `~/.claude.json`), hooks (across user / project / project-local settings.json), keybindings (`/keybindings.json`), statusline config + `statusline.py` / `statusline-command.sh` content, hook scripts dir (`/hooks/`), settings (with secret-key redaction matching `/token\|secret\|password\|api[_-]?key\|auth/i`), memory (`CLAUDE.md` at user + project **plus** the per-project file-based auto-memory store — every `*.md` under `~/.claude/projects//memory/`, returned as `scope:"auto-memory"` items carrying `project`, `name`, `isIndex`, and parsed `frontmatter`, so a `MEMORY.md` index and one file per remembered fact, often 100+, all surface). Path containment via `isUnder()` — every read must resolve under CLAUDE_HOME, project `.claude/`, or be a project CLAUDE.md. 256 KB read cap. Minimal YAML frontmatter parser handles `key: value` + quoted strings + indented continuation lines | | `lib/cc-mutate.js` | Create / overwrite / delete for the **low-risk text-file surfaces only** (skills, subagents, slash commands, output styles, memory — including the per-project file-based auto-memory store, mutated via `scope: "auto-memory"`, `type: "auto-memory"`, `project`, `name`, with its backups landing in `/.cc-config-backups/auto-memory/`), plus `writeKeybindings()` for the structured `keybindings.json` editor (read-modify-write that preserves top-level metadata, rejects duplicate contexts/keys, and backs up to `/cc-config-backups/keybindings/`). Plugins, MCP, hooks-in-settings, and `settings.json` files are NEVER written from here — they have concurrent-write races with the live Claude Code CLI. Every mutation creates a timestamped backup at `/cc-config-backups//..bak[.dir]` BEFORE the change — backups land outside the directories Claude Code scans, so a deleted skill cannot resurface as a backup-named one. Writes are atomic: temp file in same dir → fsync → `renameSync`. Tmp removed on every failure path. Skill dirs are backed up whole (preserving bundled assets) before recursive removal. Strict `name` regex (`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`), 256 KB content cap, double-checked path containment via `isUnder()` | -| `routes/cc-config.js` | HTTP surface for the Claude Config Explorer. Read endpoints for every surface (skills, agents, commands, output-styles, plugins, marketplaces, mcp, hooks, hook-scripts, keybindings, statusline, settings, memory, file, overview), plus mutation endpoints (`PUT /file`, `DELETE /file`, and a structured `PUT /keybindings`) that delegate to `cc-mutate.js`, plus a `GET /backups` listing for the recovery modal, plus the auth-profile routes (`GET/POST/DELETE /profiles`, `POST /profiles/activate`) that delegate to `cc-profiles.js`. After every successful PUT/DELETE the route broadcasts `cc_config_changed` over the WebSocket so any open `/cc-config` tab refetches without polling. All errors return structured `{error: {code, message}}` shapes mapped to 400/404/413/500 statuses | -| `lib/cc-profiles.js` | Named Claude Code **auth profiles** — swap which Anthropic account (and therefore which quota) the local `claude` CLI runs as. A profile is exactly two identity artifacts: `claudeAiOauth` out of `/.credentials.json`, and `oauthAccount` + `userID` out of the `.claude.json` config file(s) (`.json` and `/.claude.json`, each key-merged in place and only when it already exists, so `projects`/`numStartups`/everything else survives). Skills, subagents, commands, memory, plugins, marketplaces, MCP servers and settings are never read or written here — that is what makes a switch keep the whole workspace and change only the account; `mcpOAuth` stays put too (machine MCP tokens, not account identity). Stored one JSON file per profile under `/agenthub-profiles/` (dir `0700`, files `0600`), holding live OAuth tokens, so **no route ever returns token material** — `listProfiles()` answers identity metadata only. Cannot mint credentials (only `claude auth login` can): a new profile is captured by logging in, then snapshotting. `activateProfile()` re-snapshots the outgoing account first so refreshed tokens are not lost, and refuses (`EUNSAVED`) to switch away from an account that was never saved — that would discard the only copy of its credentials. Atomic temp + rename at `0600` | +| `routes/cc-config.js` | HTTP surface for the Claude Config Explorer. Read endpoints for every surface (skills, agents, commands, output-styles, plugins, marketplaces, mcp, hooks, hook-scripts, keybindings, statusline, settings, memory, file, overview), plus mutation endpoints (`PUT /file`, `DELETE /file`, and a structured `PUT /keybindings`) that delegate to `cc-mutate.js`, plus a `GET /backups` listing for the recovery modal, plus the auth-profile routes (`GET/POST/PATCH/DELETE /profiles`, `POST /profiles/activate`) that delegate to `cc-profiles.js`. After every successful PUT/DELETE the route broadcasts `cc_config_changed` over the WebSocket so any open `/cc-config` tab refetches without polling. All errors return structured `{error: {code, message}}` shapes mapped to 400/404/413/500 statuses | +| `lib/cc-profiles.js` | Named Claude Code **auth profiles** — swap which Anthropic account (and therefore which quota) the local `claude` CLI runs as. A profile is exactly two identity artifacts: `claudeAiOauth` out of `/.credentials.json`, and `oauthAccount` + `userID` out of the `.claude.json` config file(s) (`.json` and `/.claude.json`, each key-merged in place and only when it already exists, so `projects`/`numStartups`/everything else survives). Skills, subagents, commands, memory, plugins, marketplaces, MCP servers and settings are never read or written here — that is what makes a switch keep the whole workspace and change only the account; `mcpOAuth` stays put too (machine MCP tokens, not account identity). Stored one JSON file per profile under `/agenthub-profiles/` (dir `0700`, files `0600`), holding live OAuth tokens, so **no route ever returns token material** — `listProfiles()` answers identity metadata only. A profile carries two names: `name`, the filename and the id every route takes, and `label`, the free-form display name (spaces and diacritics fine, since it never touches a path) that `renameProfile()` edits in place without moving the file. One account is one profile — `saveProfile()` refuses `EDUPLICATE` rather than making a second copy, because duplicates both report themselves active, and `deleteProfile()` blocks only the LAST copy of the live account so a duplicate stays cleanable. Cannot mint credentials (only `claude auth login` can): a new profile is captured by logging in, then snapshotting. `activateProfile()` re-snapshots the outgoing account first so refreshed tokens are not lost, and refuses (`EUNSAVED`) to switch away from an account that was never saved — that would discard the only copy of its credentials. Atomic temp + rename at `0600` | | `lib/cc-watcher.js` | Best-effort `fs.watch` over `~/.claude/` (recursive where the platform / Node version honors it — macOS / Windows always; Linux from Node 20) plus `~/.claude.json`. Coalesces bursts at 500 ms and broadcasts `cc_config_changed` with `{ source: "fs", paths: [...] }` so the Config Explorer picks up changes from external tools (CLI installs a plugin, manual `settings.json` edits, dropping a new skill) without a manual refresh. Started from `server/index.js` after the HTTP server boots; failures are caught and logged so a flaky watcher can't take the server down | | `lib/tmux.js` | Wrapper around tmux CLI for session management. `createSession(sessionName, cwd)` creates a new tmux session in the specified working directory. `sendCommand(sessionName, command)` sends a command into the session. `killSession(sessionName)` terminates the session. `listSessions()` returns all active sessions. Session management is the foundation for the PTY transport layer | | `lib/pty-run.js` | PTY lifecycle for tmux-backed runs. Manages one tmux session per lane, named `agenthub-lane-`. Exports `startRun()` to create/attach a session and return a `runId` opaque handle; internally uses tmux to manage the pseudoterminal. Spawned `claude` processes run inside the session and fire the dashboard's hooks like any other CLI session, so they show up in `/api/sessions`, the analytics, the Kanban board, and the Workflows page automatically. The PTY frames (terminal input/output deltas) are streamed to the client over `/ws-pty/:runId` (see `server/websocket.js`) at binary frame granularity rather than as JSON envelopes; the client's xterm.js terminal widget renders these raw PTY updates live | @@ -614,7 +614,7 @@ graph LR | `/sessions/:id` | SessionDetail | `GET /api/sessions/:id` (agents + events), `GET /api/sessions/:id/stats` (overview tiles, top tools, subagent breakdown, token totals — debounced live-refresh on `new_event`/`agent_*`/`session_updated`), `GET /api/sessions/:id/transcripts` (Conversation tab transcript list), `GET /api/sessions/:id/transcript` (cursor-paginated message stream, including inline `session_event` rename markers; optional `run_id` resolves a workflow inner agent's nested transcript). Probes `/api/run` (and listens for `run_status`) to surface a green "Open in Run page" banner when this session is currently being driven by an in-flight Run handle. When the session sits in the Waiting overlay, renders a yellow waiting-for-input banner naming the `awaiting_reason` (Needs input / Turn done / At prompt / Interrupted) and how long it has waited; every Waiting `StatusBadge` across the app carries the same reason as a hover tooltip, with an inline nested chip on the wider surfaces (Sessions table, session-detail header) — compact card badges (Dashboard) stay tooltip-only | | `/activity` | ActivityFeed | `GET /api/events?limit=100` — click row to expand inline payload; "Session →" button navigates to `/sessions/:id` | | `/workflows` | Workflows | `GET /api/workflows?status=active\|completed`, `GET /api/workflows/session/:id` + WebSocket auto-refresh (3s debounce) | -| `/cc-config` | CcConfig | 12-tab Claude Code configuration explorer. Reads via `GET /api/cc-config/{overview,skills,agents,commands,output-styles,plugins,marketplaces,mcp,hooks,hook-scripts,keybindings,statusline,settings,memory}`. Mutations for skills/agents/commands/output-styles/memory — including the per-project file-based auto-memory store (`*.md` under `~/.claude/projects//memory/`, grouped by project and searchable in the Memory tab, with clickable `MEMORY.md` index links that scroll to + highlight the matching fact file) — via `PUT /api/cc-config/file` + `DELETE /api/cc-config/file` (timestamped backups, atomic writes). The Keybindings tab additionally offers a structured inline editor that persists via `PUT /api/cc-config/keybindings` (same backup-first, atomic-write guarantees). `GET /api/cc-config/file?path=…` for single-file viewer. `GET /api/cc-config/backups` for the recovery modal. A **Switch profile** button left of Backups opens the auth-profile modal (`/api/cc-config/profiles*`): save the logged-in Anthropic account under a name, then switch between accounts — only the login is swapped, so skills / subagents / memory / plugins / marketplaces / settings stay put. It cannot log in for you (`claude auth login` does that) and a switch applies to new sessions only. Subscribes to `cc_config_changed` WS messages for live refresh on both dashboard mutations and external file edits picked up by `cc-watcher`. The Settings tab leads with a client-side **Current configuration** summary that resolves the `/config` options (model, verbose, theme, output style, effort, auto-compact, notifications, …) across user / project / project-local scopes, showing defaults when unset. Live / Offline indicator next to the title | +| `/cc-config` | CcConfig | 12-tab Claude Code configuration explorer. Reads via `GET /api/cc-config/{overview,skills,agents,commands,output-styles,plugins,marketplaces,mcp,hooks,hook-scripts,keybindings,statusline,settings,memory}`. Mutations for skills/agents/commands/output-styles/memory — including the per-project file-based auto-memory store (`*.md` under `~/.claude/projects//memory/`, grouped by project and searchable in the Memory tab, with clickable `MEMORY.md` index links that scroll to + highlight the matching fact file) — via `PUT /api/cc-config/file` + `DELETE /api/cc-config/file` (timestamped backups, atomic writes). The Keybindings tab additionally offers a structured inline editor that persists via `PUT /api/cc-config/keybindings` (same backup-first, atomic-write guarantees). `GET /api/cc-config/file?path=…` for single-file viewer. `GET /api/cc-config/backups` for the recovery modal. A **Switch profile** button left of Backups opens the auth-profile modal (`/api/cc-config/profiles*`): save the logged-in Anthropic account, rename it by clicking its name, then switch between accounts — only the login is swapped, so skills / subagents / memory / plugins / marketplaces / settings stay put. There is no name field (the server derives the identifier) and the save button shows only while the live account is unsaved, since one account is one profile. It cannot log in for you (`claude auth login` does that) and a switch applies to new sessions only. Subscribes to `cc_config_changed` WS messages for live refresh on both dashboard mutations and external file edits picked up by `cc-watcher`. The Settings tab leads with a client-side **Current configuration** summary that resolves the `/config` options (model, verbose, theme, output style, effort, auto-compact, notifications, …) across user / project / project-local scopes, showing defaults when unset. Live / Offline indicator next to the title | | `/run` | Workspace | Merged workspace page combining lanes and runs. Attaches to a tmux-backed pseudoterminal tied to a lane: the UI selects a lane, calls `POST /api/run` with that lane's `id`, and receives a `runId` + tmux session name. The Workspace displays a horizontal lane strip at the top, the selected lane's pipeline map, and a real interactive terminal (xterm.js) fed by `/ws-pty/:runId` binary frames below. `TerminalView` re-attaches 1.5 s after any unexpected socket close (server restart included) and stops only on the server's `exit` frame — a dead socket used to leave the pane frozen on its last frame, looking live while swallowing every keystroke and mouse report. It also calls `preventDefault()` on Shift+Tab (keeping xterm's own handling): xterm emits `ESC[Z` for that combo but, unlike plain Tab, never marks the event cancelled, so the browser's default moved focus out of the terminal and the pane saw only the first press — `shift+tab to cycle` (claude's permission mode) looked dead in the browser while working in a real terminal. It also installs a custom wheel handler that returns `false`: without it, xterm falls back on an alt-screen buffer to translating each wheel notch into a cursor-key press (`ESC[A`/`ESC[B`), which a `claude` pane reads as arrow up/down and uses to walk the prompt history instead of scrolling. That handler suppresses only the emulation branch — real mouse reports are emitted by a separate listener xterm registers when the pane's program enables mouse tracking. Its xterm viewport scrollbar is hidden by design (`.xterm-viewport` rule in `client/src/index.css`): tmux repaints the whole pane, so xterm's scrollback is always empty and scrolling happens via mouse reports forwarded to the pane's program, not the DOM. Pre-flight: `GET /api/run/{tmux,binary,cwds,files}` for tmux availability + `claude` binary check + `@`-file autocomplete. Start/resume: `POST /api/run` (requires `laneId`; optionally accepts `prompt` to send immediately); `GET /api/run/:id` (returns handle); `DELETE /api/run/:id` (stops). History: `GET /api/run/history?laneId=` lists only that lane's runs. PTY streaming: `/ws-pty/:runId` delivers raw PTY frames as binary WebSocket frames — no JSON envelope overhead, direct to xterm.js for live rendering; the same tmux session can have multiple simultaneous clients (browser Workspace, `agenthub lanes shell` CLI, other tools), all synced live. Lane self-heal: `GET /api/lanes/:id` auto-corrects `run_id`/`status` if the tmux session has been killed externally. Tier 1 TUI parity: tmux session is a real shell, not headless — supports editors, pagers, interactive subcommands. **The console never writes a lane's stage** — stage moves only through `agenthub stage` commands. Live / Offline indicator next to the title | | `/settings` | Settings | `GET /api/settings/info`, `GET /api/pricing`, `GET /api/pricing/cost` + `localStorage` for notification prefs. Hosts the **Remote Data Sources** panel (`components/RemoteSources.tsx`) — CRUD + test + sync over `/api/remote-sources`, live status from `remote_source.status` WS messages | | `/*` | NotFound | None (static 404 page) | diff --git a/client/src/i18n/locales/en/ccConfig.json b/client/src/i18n/locales/en/ccConfig.json index 212928e5..d2e4145e 100644 --- a/client/src/i18n/locales/en/ccConfig.json +++ b/client/src/i18n/locales/en/ccConfig.json @@ -222,12 +222,9 @@ "warning": "Close your running Claude Code sessions before switching - a live session rewrites the config on exit and would put the old account back.", "activeLabel": "Logged in now", "noActive": "No Claude account is logged in on this machine.", - "unsavedActive": "This account is not saved as a profile yet - save it below, otherwise you cannot switch away without losing its credentials.", - "saveLabel": "Save the current account as a profile", - "namePlaceholder": "profile name (e.g. work)", - "saveButton": "Save", - "saveHint": "The dashboard cannot log in for you. To add another account: run `claude auth login` in a terminal, sign in, then come back and save it under a new name.", - "saveSuccess": "Saved the current account as profile \"{{name}}\".", + "unsavedActive": "This account is not saved as a profile yet - save it, otherwise you cannot switch away without losing its credentials.", + "saveButton": "Save this account as a profile", + "saveSuccess": "Saved the account you are logged in as. Click its name to rename it.", "empty": "No profiles saved yet - save the account you are logged in as to get started.", "activeBadge": "active", "switchButton": "Switch to", @@ -236,7 +233,11 @@ "deleteButton": "Delete profile", "deleteSuccess": "Deleted profile \"{{name}}\".", "savedAt": "Saved {{time}}", - "loginHint": "Add another account by logging in from a terminal first:" + "loginHint": "Add another account by logging in from a terminal first:", + "saving": "Saving…", + "renameLabel": "Profile name", + "renameHint": "Click to rename", + "renameSuccess": "Renamed to \"{{name}}\"." }, "explain": { "hooks": { diff --git a/client/src/i18n/locales/vi/ccConfig.json b/client/src/i18n/locales/vi/ccConfig.json index f7ca9d71..daac00a5 100644 --- a/client/src/i18n/locales/vi/ccConfig.json +++ b/client/src/i18n/locales/vi/ccConfig.json @@ -217,12 +217,9 @@ "warning": "Hãy đóng các phiên Claude Code đang chạy trước khi đổi - phiên đang chạy sẽ ghi lại config khi thoát và đưa tài khoản cũ quay về.", "activeLabel": "Đang đăng nhập", "noActive": "Chưa có tài khoản Claude nào đăng nhập trên máy này.", - "unsavedActive": "Tài khoản này chưa được lưu thành profile - hãy lưu bên dưới, nếu không sẽ không thể đổi sang profile khác mà không mất credentials của nó.", - "saveLabel": "Lưu tài khoản hiện tại thành profile", - "namePlaceholder": "tên profile (vd: work)", - "saveButton": "Lưu", - "saveHint": "Dashboard không thể đăng nhập thay bạn. Để thêm tài khoản khác: chạy `claude auth login` trong terminal, đăng nhập, rồi quay lại đây lưu với tên mới.", - "saveSuccess": "Đã lưu tài khoản hiện tại thành profile \"{{name}}\".", + "unsavedActive": "Tài khoản này chưa được lưu thành profile - hãy lưu lại, nếu không sẽ không thể đổi sang profile khác mà không mất credentials của nó.", + "saveButton": "Lưu tài khoản này thành profile", + "saveSuccess": "Đã lưu tài khoản đang đăng nhập. Bấm vào tên của nó để đổi tên.", "empty": "Chưa có profile nào - hãy lưu tài khoản đang đăng nhập để bắt đầu.", "activeBadge": "đang dùng", "switchButton": "Chuyển sang", @@ -231,7 +228,11 @@ "deleteButton": "Xoá profile", "deleteSuccess": "Đã xoá profile \"{{name}}\".", "savedAt": "Lưu lúc {{time}}", - "loginHint": "Thêm tài khoản khác bằng cách đăng nhập từ terminal trước:" + "loginHint": "Thêm tài khoản khác bằng cách đăng nhập từ terminal trước:", + "saving": "Đang lưu…", + "renameLabel": "Tên profile", + "renameHint": "Bấm để đổi tên", + "renameSuccess": "Đã đổi tên thành \"{{name}}\"." }, "explain": { "hooks": { diff --git a/client/src/lib/api.ts b/client/src/lib/api.ts index deacdeb3..7af60b1c 100644 --- a/client/src/lib/api.ts +++ b/client/src/lib/api.ts @@ -1517,13 +1517,23 @@ export const api = { profiles: () => request<{ items: CcProfile[]; active: CcAccountIdentity | null }>("/cc-config/profiles"), /** - * POST /api/cc-config/profiles - snapshot the logged-in account under - * `name`, overwriting a profile of that name. + * POST /api/cc-config/profiles - snapshot the logged-in account as a + * profile. The identifier and initial label are derived from the account; + * saving an account another profile already holds fails `EDUPLICATE`. */ - saveProfile: (name: string) => - request<{ ok: true; name: string } & CcAccountIdentity>("/cc-config/profiles", { - method: "POST", - body: JSON.stringify({ name }), + saveProfile: () => + request<{ ok: true; name: string; label: string } & CcAccountIdentity>( + "/cc-config/profiles", + { method: "POST", body: JSON.stringify({}) } + ), + /** + * PATCH /api/cc-config/profiles - change a profile's display label. The + * `name` identifier does not move; spaces and diacritics are allowed. + */ + renameProfile: (name: string, label: string) => + request<{ ok: true; name: string; label: string }>("/cc-config/profiles", { + method: "PATCH", + body: JSON.stringify({ name, label }), }), /** * POST /api/cc-config/profiles/activate - make a saved profile the account @@ -2310,7 +2320,10 @@ export interface CcAccountIdentity { /** One saved auth profile from GET /api/cc-config/profiles. */ export interface CcProfile extends CcAccountIdentity { + /** Internal identifier (also its filename) — what the mutation routes take. */ name: string; + /** Display name the user edits; falls back to `name` for older profiles. */ + label: string; /** When the profile was last snapshotted, epoch ms. */ savedAt: number | null; /** True when this profile's account is the one logged in right now. */ diff --git a/client/src/pages/CcConfig.tsx b/client/src/pages/CcConfig.tsx index bd032ad6..07cacf92 100644 --- a/client/src/pages/CcConfig.tsx +++ b/client/src/pages/CcConfig.tsx @@ -4521,7 +4521,12 @@ function CommandSnippet({ command, label }: { command: string; label?: string }) // // The dashboard cannot log a new account in (only `claude auth login` can mint // tokens), so adding a profile is always "log in, then snapshot what the CLI -// wrote". Hence the save-current field rather than an add-account flow. +// wrote" — hence a save button on the live account rather than an add-account +// flow. There is no name field: the server derives the identifier, and the user +// edits the display label in place by clicking it. That keeps the one string +// the user types free of filename rules, so spaces and diacritics are fine. +// The save button only appears while the live account is unsaved, because one +// account is one profile — a second copy would just report itself active too. function ProfilesModal({ onClose, onToast }: { onClose: () => void; onToast: (t: Toast) => void }) { const { t } = useTranslation("ccConfig"); @@ -4529,7 +4534,9 @@ function ProfilesModal({ onClose, onToast }: { onClose: () => void; onToast: (t: const [active, setActive] = useState(null); const [error, setError] = useState(null); const [busy, setBusy] = useState(null); - const [newName, setNewName] = useState(""); + /** `name` of the profile whose label is being edited inline, plus its draft. */ + const [renaming, setRenaming] = useState(null); + const [draft, setDraft] = useState(""); const load = useCallback(async () => { try { @@ -4576,6 +4583,10 @@ function ProfilesModal({ onClose, onToast }: { onClose: () => void; onToast: (t: const activeSaved = items?.some((p) => p.active) ?? false; + /** How many saved profiles hold the same account as `p`. */ + const copies = (p: CcProfile) => + items?.filter((q) => q.accountUuid && q.accountUuid === p.accountUuid).length ?? 1; + return (
void; onToast: (t:
{t("profiles.noActive")}
)} {active && !activeSaved && ( -
- {t("profiles.unsavedActive")} +
+
{t("profiles.unsavedActive")}
+
)}
-
-
- {t("profiles.saveLabel")} -
-
- setNewName(e.target.value)} - placeholder={t("profiles.namePlaceholder")} - className="h-7 flex-1 min-w-0 rounded-md border border-border bg-surface-1 px-2 text-xs text-fg-primary placeholder:text-fg-muted focus:outline-none focus:ring-1 focus:ring-accent/40" - /> - -
-

- {t("profiles.saveHint")} -

-
- {items === null && !error && } {items !== null && items.length === 0 && (
@@ -4674,7 +4664,41 @@ function ProfilesModal({ onClose, onToast }: { onClose: () => void; onToast: (t: {items?.map((p) => (
- {p.name} + {renaming === p.name ? ( + setDraft(e.target.value)} + onBlur={() => setRenaming(null)} + onKeyDown={(e) => { + if (e.key === "Escape") setRenaming(null); + if (e.key !== "Enter") return; + const next = draft.trim(); + setRenaming(null); + if (!next || next === p.label) return; + void run( + `rename:${p.name}`, + () => api.ccConfig.renameProfile(p.name, next), + t("profiles.renameSuccess", { name: next }) + ); + }} + maxLength={60} + aria-label={t("profiles.renameLabel")} + className="h-7 w-48 rounded-md border border-accent/40 bg-surface-1 px-2 text-xs text-fg-primary focus:outline-none focus:ring-1 focus:ring-accent/40" + /> + ) : ( + + )} {p.active && ( {t("profiles.activeBadge")} @@ -4690,7 +4714,7 @@ function ProfilesModal({ onClose, onToast }: { onClose: () => void; onToast: (t: void run( `switch:${p.name}`, () => api.ccConfig.activateProfile(p.name), - t("profiles.switchSuccess", { name: p.name }) + t("profiles.switchSuccess", { name: p.label }) ) } className="h-7 text-[11px] font-medium px-2.5 rounded-md border border-accent/30 bg-accent/10 hover:bg-accent/20 text-accent disabled:opacity-50" @@ -4700,14 +4724,17 @@ function ProfilesModal({ onClose, onToast }: { onClose: () => void; onToast: (t: : t("profiles.switchButton")} )} - {!p.active && ( + {/* Deletable unless it is the ONLY saved copy of the live + account — a redundant copy has to be removable, or an + accidental duplicate could never be cleaned up. */} + {(!p.active || copies(p) > 1) && (