diff --git a/.changeset/rename-cases.md b/.changeset/rename-cases.md index 031b69cb..08e0022e 100644 --- a/.changeset/rename-cases.md +++ b/.changeset/rename-cases.md @@ -2,4 +2,4 @@ "aicodeman": minor --- -Rename a case and its folder from the case manager. A case under `~/codeman-cases` is renamed as a name and folder; a linked case can rename only its name or its real folder too. Live sessions that have the folder open are listed and only stopped if you agree, the folder is locked while it moves so nothing starts in it half-moved, a folder another program holds open is reported instead of forced, and Claude Code's conversation history, the case order and the last used case follow the new name. +Rename a case and its folder from the case manager. A case under `~/codeman-cases` is renamed as a name and folder; a linked case can rename only its name or its real folder too. Live sessions that have the folder open are listed and only stopped if you agree, the folder is locked while it moves so nothing starts in it half-moved, a folder another program holds open is reported instead of forced, and Claude Code's conversation history (including the Resume list), the case order, the last used case and the default session group follow the new name. diff --git a/CLAUDE.md b/CLAUDE.md index 973b8783..ecc6b1d2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -181,7 +181,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph **DeepSeek web UI** (`POST`/`GET`/`DELETE /api/deepseek/web`, `deepseek-web-server.ts`): the Run menu's "DeepSeek web UI..." entry supervises ONE background `dsh web` child process, deliberately **NOT a shell session**. ⚠️ Every piece is load-bearing: exactly one server (a second click REUSES it), restarted when the browser authority changes (`--trusted-host`, last asker wins), killed on shutdown via `stopDeepSeekWeb()` (the detached child would otherwise outlive Codeman and hold its port), and failures returned to the caller. ⚠️ Never hardcode the port: search from 3080 across 40, detect free ports by BINDING, then wait for the server to really answer. ⚠️ Both `POST` and `DELETE` must stay behind `canUsernameRunPrivilegedCommands` (booting a profile runs its plugin code; the server is shared). → [architecture-invariants#deepseek-web-ui](docs/architecture-invariants.md#deepseek-web-ui) -**Case rename** (`POST /api/cases/:name/rename`, `src/case-rename.ts`; `docs/wiki/Core-Concepts.md#case`): a case under the cases dir is its folder name and always moves; a linked case renames its alias and moves its real folder only with `renameFolder`; remote and Docker cases are refused. ⚠️ A folder that sessions have open is the hazard: live sessions at or under it make the route answer `409 requiresStop` with their names, and only `stopSessions: true` ends them (via `ctx.cleanupSession`, nothing is restarted). `withCaseLock` holds the old and new paths for the whole operation (`isCasePathLocked`; the `Session` constructor throws for a working directory inside a held path, so nothing starts mid-move), `moveCaseFolder` refuses an existing target itself (POSIX `rename` would silently replace an EMPTY directory) and retries `EBUSY`/`EPERM`/`EACCES` before answering `423 LOCKED`. If the registries (`linked-cases.json`, `caseOrder`, `lastUsedCase`) fail after the move, the folder is moved back. Claude Code keys history by path (`claudeProjectDirName`: every non-alphanumeric becomes `-`), so `/projects/` is renamed too; other CLIs' history, Docker bind mounts and `git worktree` links are NOT migrated. +**Case rename** (`POST /api/cases/:name/rename`, `src/case-rename.ts`; `docs/wiki/Core-Concepts.md#case`): a case under the cases dir is its folder name and always moves; a linked case renames its alias and moves its real folder only with `renameFolder`; remote and Docker cases are refused. ⚠️ A folder that sessions have open is the hazard: live sessions at or under it make the route answer `409 requiresStop` with their names, and only `stopSessions: true` ends them (via `ctx.cleanupSession`, nothing is restarted). `withCaseLock` holds the old and new paths for the whole operation (`isCasePathLocked`; the `Session` constructor throws for a working directory inside a held path, so nothing starts mid-move), `moveCaseFolder` refuses an existing target itself (POSIX `rename` would silently replace an EMPTY directory) and retries `EBUSY`/`EPERM`/`EACCES` before answering `423 LOCKED`. If the registries (`linked-cases.json`, `caseOrder`, `lastUsedCase`) fail after the move, the folder is moved back. Claude Code keys history by path (`claudeProjectDirName`: every non-alphanumeric becomes `-`), so `/projects/` is renamed too; other CLIs' history, Docker bind mounts, `git worktree` links, cron jobs' `workingDir` and Claude history of subfolder sessions are NOT migrated. The history scanner prefers the decoded project key over a transcript's `cwd` that no longer exists, so Resume follows a rename. Only an admin's rename touches the server-wide `settings.json` (`caseOrder`, `lastUsedCase`); the owner's default session group is carried across with `TabLayoutService`. `settings.json` is written before `linked-cases.json`, and the registry is restored if its write fails. **Custom Model Endpoint Profiles** (opt-in, `customModelEndpointsEnabled`, SYNCED, default OFF; `docs/custom-model-endpoints.md`): points a session at a user-configured OpenAI-compatible endpoint (store `custom-model-hosts.ts`, `~/.codeman/custom-model-hosts.json`, 0600). `authStyle` is `bearer` or `api-key`, never both headers (hangs the server). The per-CLI redirect is registry data, `capabilities.customModelInjection` (`env` / `configContentEnv` / `configDir` / `unsupported`), computed by the pure `custom-model-injection.ts`; ⚠️ `configDir` writes an isolated per-session config, NEVER the user's real `~/.codex`/`~/.pi`/`~/.omp`/grok config. ⚠️ Claude applies via `Session.restartCli()` (a relaunch in the existing pane, so the conversation is pinned as `resumeSessionId`), the rest one-shot at launch; retired env keys must also be `setenv -u`'d (`_pendingEnvUnsets`), since tmux env survives `respawn-pane`. ⚠️ Remote/Docker sessions are refused (400). ⚠️ Persist only KEYS (`__customModel`), never values (they carry the API key). ⚠️ Every redirectable var must be in that CLI's `privilegedEnvKeys`, and `ANTHROPIC_*` stays out of claude's `allowedPrefixes`. ⚠️ The Run-menu picker builds entries from `window.__codemanCustomModelClis` (escaped via `escapeScriptJson()`), never a hardcoded CLI id list, and launches through `run()` via a temporary `_runMode` swap, never `setRunMode()`. → [architecture-invariants#custom-model-endpoint-profiles](docs/architecture-invariants.md#custom-model-endpoint-profiles) diff --git a/docs/wiki/Core-Concepts.md b/docs/wiki/Core-Concepts.md index ab3d50b3..b2197382 100644 --- a/docs/wiki/Core-Concepts.md +++ b/docs/wiki/Core-Concepts.md @@ -14,25 +14,25 @@ Codeman-side configuration: - Which CLI the Run button should default to. - Per-case toggles (Agent Teams, 1M Opus context). - A **Default session group** (Case settings…): new sessions of the case land in that tab group of the - vertical rail unless you start them from a group's own *New session* or they follow the session that - spawned them. *Ungrouped* turns it off. It follows you across devices, never moves existing tabs, and a + vertical rail unless you start them from a group's own _New session_ or they follow the session that + spawned them. _Ungrouped_ turns it off. It follows you across devices, never moves existing tabs, and a deleted group simply falls back to Ungrouped. - Where it runs, if it is not the local filesystem: see [Location overlays](#location-overlays). Three ways to get one, all under **New or link a case…** at the bottom of the case picker (the case dropdown in the bottom toolbar; on a phone, the case sheet's **Create New Case**): -| How | Result | -| ----------------- | ------------------------------------------------------------------------------------------------------ | +| How | Result | +| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Create New** | A fresh `~/codeman-cases/` with a scaffolded `CLAUDE.md`, or with **Create in a custom folder**, a new folder inside a parent you choose, scaffolded the same way and registered in place like a linked case. | -| **Clone Repo** | A repo cloned into `~/codeman-cases/` and registered as a case. Private repos need this machine's own git credentials (see below). | -| **Link Existing** | An existing folder anywhere on disk, registered in place. Nothing is copied or moved. | +| **Clone Repo** | A repo cloned into `~/codeman-cases/` and registered as a case. Private repos need this machine's own git credentials (see below). | +| **Link Existing** | An existing folder anywhere on disk, registered in place. Nothing is copied or moved. | Linked cases keep living where they are. Deleting a case in Codeman removes the registration, and for a linked case that is all it removes. **Renaming a case.** In the case manager (Settings, or the case picker's manage view) the pencil -button renames a case and its folder. A case under `~/codeman-cases` *is* its folder name, so it +button renames a case and its folder. A case under `~/codeman-cases` _is_ its folder name, so it always moves. A linked case renames its name in the list only; Codeman then asks whether to rename the real folder as well, next to where it is (Cancel leaves the folder alone). Remote and Docker cases cannot be renamed. Renaming does the following for you: @@ -45,7 +45,12 @@ cases cannot be renamed. Renaming does the following for you: is in use and to close whatever has it (a terminal, an editor, a file browser, a sync client). - **Claude Code's history follows.** It keys conversations by the folder's path, so the rename moves `/projects/` to the new path and `--resume` still finds them. Other CLIs' - history, Docker mounts and `git worktree` links that point at the old path are not updated. + history, Docker mounts and `git worktree` links that point at the old path are not updated. The + Resume list uses the renamed folder too, and the case's default session group follows the new name. +- **Not migrated.** Scheduled (cron) jobs keep the old `workingDir` and fail at their next run until you + edit them; Claude history of sessions started in a subfolder (including `.claude/worktrees/`) + stays under the old path. In multi-user mode only an admin's rename updates the shared case order and + last used case. - **The case order, the last used case and this browser's per-case options follow the new name.** **Clone Repo never asks for credentials.** It uses whatever the server's own git already has: @@ -92,10 +97,10 @@ Claude-only where it appears, and [Agent CLIs](Agent-CLIs) lists them in one pla Where a case runs is **separate from** which CLI it runs. There are three locations: -| Location | What happens | -| -------------- | ------------------------------------------------------------------------------------------------------------ | -| **Local** | The default. tmux and the CLI run on the Codeman host. | -| **Docker** | One long-lived container per case; sessions `docker exec` into it. See [Docker Cases](Docker-Cases). | +| Location | What happens | +| -------------- | -------------------------------------------------------------------------------------------------------------------------------- | +| **Local** | The default. tmux and the CLI run on the Codeman host. | +| **Docker** | One long-lived container per case; sessions `docker exec` into it. See [Docker Cases](Docker-Cases). | | **Remote SSH** | A durable tmux server on the remote host, fronted by a local pane running `ssh`. See [Remote SSH Sessions](Remote-SSH-Sessions). | This matters because it is a common source of confusion: Docker is **not** an eleventh run @@ -130,14 +135,14 @@ sessions never appear in a bare `tmux ls`. ## What persists -| Survives | Does not survive | -| -------------------------------------------- | --------------------------------------------------- | -| Closing the browser | `tmux -L codeman kill-server` | -| Losing the network | A machine reboot (tmux dies with it) | -| Restarting the Codeman server | Killing the session from the UI | -| `codeman web --stop` | | -| A dropped SSH link, for remote cases | | -| A container restart, for docker cases | | +| Survives | Does not survive | +| ------------------------------------- | ------------------------------------ | +| Closing the browser | `tmux -L codeman kill-server` | +| Losing the network | A machine reboot (tmux dies with it) | +| Restarting the Codeman server | Killing the session from the UI | +| `codeman web --stop` | | +| A dropped SSH link, for remote cases | | +| A container restart, for docker cases | | Conversation history is a separate question: Claude transcripts live in `~/.claude/`, so a conversation can be resumed even after the tmux session is gone. That is what the welcome @@ -147,18 +152,18 @@ screen's **Resume Conversation** list offers. Everything Codeman knows lives under `~/.codeman/`: -| File | Holds | -| ---------------------------------------- | -------------------------------------------------------------------- | -| `state.json` | Sessions, settings, respawn config, orchestrator state, cron jobs. | -| `settings.json` | User preferences that sync across your devices. | -| `mux-sessions.json` | tmux recovery data. | -| `session-lifecycle.jsonl` | Append-only audit log of session starts, exits, and kills. | -| `linked-cases.json` | Registered cases. | -| `remote-hosts.json`, `docker-hosts.json` | Location overlay configuration. | -| `webviews.json` | Saved dashboard URLs. | -| `users.json` | Multi-user accounts, mode 0600. | -| `push-*.json` | Web push keys and subscriptions. | -| `certs/` | Self-signed TLS for `--https`. | +| File | Holds | +| ---------------------------------------- | --------------------------------------------------------------------------------------------- | +| `state.json` | Sessions, settings, respawn config, orchestrator state, cron jobs. | +| `settings.json` | User preferences that sync across your devices. | +| `mux-sessions.json` | tmux recovery data. | +| `session-lifecycle.jsonl` | Append-only audit log of session starts, exits, and kills. | +| `linked-cases.json` | Registered cases. | +| `remote-hosts.json`, `docker-hosts.json` | Location overlay configuration. | +| `webviews.json` | Saved dashboard URLs. | +| `users.json` | Multi-user accounts, mode 0600. | +| `push-*.json` | Web push keys and subscriptions. | +| `certs/` | Self-signed TLS for `--https`. | | `backups/config/` | Timestamped copies of the files above that you customized ([Config Backups](Config-Backups)). | None of it needs root, none of it leaves the machine, and deleting `~/.codeman/` resets @@ -201,17 +206,17 @@ See [Hooks And Integrations](Hooks-And-Integrations). ## Vocabulary -| Term | Means | -| --------------- | ---------------------------------------------------------------------------- | -| **Case** | Named working directory. | -| **Session** | One CLI in one tmux session. | -| **Run mode** | Which CLI: claude, opencode, codex, gemini, antigravity, pi, grok, deepseek, omp, copilot, shell. | -| **Respawn** | Restarting the CLI on idle to keep an unattended run going. | -| **Ralph loop** | An autonomous single-session task loop. | -| **Orchestrator**| A phased plan driven across multiple agents. | -| **Subagent** | An agent the CLI spawned itself, shown live in its own window. | -| **Web tab** | A saved dashboard URL rendered as a tab. Not a session. | -| **Instance** | One Codeman server with its own data directory and tmux socket. | +| Term | Means | +| ---------------- | ------------------------------------------------------------------------------------------------- | +| **Case** | Named working directory. | +| **Session** | One CLI in one tmux session. | +| **Run mode** | Which CLI: claude, opencode, codex, gemini, antigravity, pi, grok, deepseek, omp, copilot, shell. | +| **Respawn** | Restarting the CLI on idle to keep an unattended run going. | +| **Ralph loop** | An autonomous single-session task loop. | +| **Orchestrator** | A phased plan driven across multiple agents. | +| **Subagent** | An agent the CLI spawned itself, shown live in its own window. | +| **Web tab** | A saved dashboard URL rendered as a tab. Not a session. | +| **Instance** | One Codeman server with its own data directory and tmux socket. | ## Read next diff --git a/src/case-rename.ts b/src/case-rename.ts index 6c0ece4f..70b9399c 100644 --- a/src/case-rename.ts +++ b/src/case-rename.ts @@ -113,7 +113,7 @@ export async function moveCaseFolder(from: string, to: string, attempts = 4, del throw new CaseRenameError( 'LOCKED', `The folder is in use by another program (${code}), so it could not be renamed. Close anything that has it open ` + - '(a terminal, an editor, a file browser or a sync client), or stop the sessions using it, and try again.' + '(an editor, a file browser or a sync client) and try again.' ); } if (code === 'ENOTEMPTY' || code === 'EEXIST') { diff --git a/src/web/public/i18n.js b/src/web/public/i18n.js index 2d0bbda9..7b16e451 100644 --- a/src/web/public/i18n.js +++ b/src/web/public/i18n.js @@ -86,6 +86,17 @@ 'Web tab settings': '网页标签设置', 'New group': '新建分组', 'Rename group': '重命名分组', + 'Rename case': '重命名案例', + Rename: '重命名', + 'New name': '新名称', + 'letters, numbers, - and _': '字母、数字、- 和 _', + 'Also rename the folder on disk': '同时重命名磁盘上的文件夹', + 'A case under the cases folder is renamed together with its folder.': + '案例文件夹下的案例会连同其文件夹一起重命名。', + 'Stop sessions and rename': '停止会话并重命名', + 'Enter a different name.': '请输入不同的名称。', + 'Use only letters, numbers, hyphens and underscores.': '只能使用字母、数字、连字符和下划线。', + 'Failed to rename the case.': '重命名案例失败。', 'Move group up': '上移分组', 'Move group down': '下移分组', 'Delete group': '删除分组', @@ -1332,6 +1343,12 @@ (_m, version, shown, more) => `Codeman 已更新到 v${version}:${shown}${more ? `(另有 ${more} 项)` : ''}`, ], [/^Selected: (.+)$/, (_m, value) => `已选择:${value}`], + [/^Case renamed to "(.+)"$/, (_m, name) => `案例已重命名为“${name}”`], + [/^New name for "(.+)"$/, (_m, name) => `“${name}”的新名称`], + [ + /^These sessions have the folder open: (.+)\. They will be stopped \(nothing is restarted\) before the folder is renamed\.$/, + (_m, list) => `这些会话正在使用该文件夹:${list}。重命名前将停止它们(不会重新启动)。`, + ], [/^Failed to (.+)$/, (_m, action) => `操作失败:${action}`], [/^Will create: (.+)$/, (_m, path) => `将创建:${path}`], // The spreadsheet preview: an HTTP status, and the notice bar's counts. diff --git a/src/web/routes/case-routes.ts b/src/web/routes/case-routes.ts index 6934634c..b0f05cc4 100644 --- a/src/web/routes/case-routes.ts +++ b/src/web/routes/case-routes.ts @@ -10,7 +10,7 @@ import { FastifyInstance } from 'fastify'; import { existsSync, lstatSync, mkdirSync, writeFileSync, readdirSync, readFileSync, createReadStream } from 'node:fs'; import { exec } from 'node:child_process'; import fs from 'node:fs/promises'; -import { join, resolve, basename } from 'node:path'; +import { join, resolve, basename, sep } from 'node:path'; import { fileURLToPath } from 'node:url'; import { homedir } from 'node:os'; import type { @@ -1799,7 +1799,6 @@ export function registerCaseRoutes( const casesBase = resolveCasesDir(user); const linkedCases = await readLinkedCases(); const isLinked = Boolean(linkedCases[name]) && (!isMultiUserMode() || isAdmin(req)); - if (isLinked && !isAdmin(req)) return fail(403, ApiErrorCode.FORBIDDEN, 'Admin only in multi-user mode'); const oldPath = isLinked ? linkedCases[name] : join(casesBase, name); // The new name must be free in every namespace the list merges. @@ -1813,7 +1812,8 @@ export function registerCaseRoutes( const state = await probePath(oldPath); if (state === 'absent') return fail(404, ApiErrorCode.NOT_FOUND, `Case "${name}" not found`); - if (state === 'unknown') { + // An alias-only rename never touches the folder, so an unreachable one does not block it. + if (state === 'unknown' && (!isLinked || body.renameFolder === true)) { return fail(503, ApiErrorCode.OPERATION_FAILED, describeUnknownPath('Case folder', oldPath, { pastCap: true })); } @@ -1824,10 +1824,14 @@ export function registerCaseRoutes( } // Sessions with the folder open. Only a move disturbs them; an alias-only rename leaves them running. + // Remote sessions carry the remote path as their workingDir, so they are not this folder's. + const heldRoot = resolve(oldPath); const open = moveFolder - ? Array.from(ctx.sessions.values()).filter( - (s) => s.workingDir === oldPath || s.workingDir.startsWith(oldPath + '/') - ) + ? Array.from(ctx.sessions.values()).filter((s) => { + if (s.remote) return false; + const dir = resolve(s.workingDir); + return dir === heldRoot || dir.startsWith(heldRoot + sep); + }) : []; if (open.some((s) => !canAccessOwned(user, s.owner))) { return fail(403, ApiErrorCode.FORBIDDEN, "Another user's session has this case open"); @@ -1845,25 +1849,36 @@ export function registerCaseRoutes( await withCaseLock(oldPath, newPath, async () => { for (const s of open) await ctx.cleanupSession(s.id, true, 'case_rename'); if (moveFolder) await moveCaseFolder(oldPath, newPath); + const originalLinks = isLinked ? await readLinkedCases() : undefined; try { - if (isLinked) { - const links = await readLinkedCases(); + // settings.json is server-wide and caseOrder/lastUsedCase name the admin's cases, so only the + // admin's rename touches it (a non-admin's own rename must not rewrite someone else's list). + // Written before linked-cases.json so a failure here leaves the registry untouched. + if (isAdmin(req)) { + const existing = await readJsonConfig>(SETTINGS_PATH, 'settings.json', {}); + const order = renameInOrder(existing.caseOrder, name, newName); + const last = existing.lastUsedCase === name ? newName : undefined; + if (order || last) { + await fs.writeFile( + SETTINGS_PATH, + JSON.stringify( + { ...existing, ...(order ? { caseOrder: order } : {}), ...(last ? { lastUsedCase: last } : {}) }, + null, + 2 + ) + ); + } + } + if (originalLinks) { + const links = { ...originalLinks }; delete links[name]; links[newName] = newPath; - await fs.writeFile(LINKED_CASES_FILE, JSON.stringify(links, null, 2)); - } - const existing = await readJsonConfig>(SETTINGS_PATH, 'settings.json', {}); - const order = renameInOrder(existing.caseOrder, name, newName); - const last = existing.lastUsedCase === name ? newName : undefined; - if (order || last) { - await fs.writeFile( - SETTINGS_PATH, - JSON.stringify( - { ...existing, ...(order ? { caseOrder: order } : {}), ...(last ? { lastUsedCase: last } : {}) }, - null, - 2 - ) - ); + try { + await fs.writeFile(LINKED_CASES_FILE, JSON.stringify(links, null, 2)); + } catch (err) { + await fs.writeFile(LINKED_CASES_FILE, JSON.stringify(originalLinks, null, 2)).catch(() => {}); + throw err; + } } } catch (err) { // The folder moved but the registries did not follow: put it back rather than leave a case @@ -1872,6 +1887,15 @@ export function registerCaseRoutes( throw err; } if (moveFolder) await moveClaudeHistory(oldPath, newPath); + // The owner's default session group is keyed by case name: carry it over, best effort. + const layoutOwner = ownerLayoutKey(ownerFor(req)); + try { + const { groupId } = await ctx.tabLayouts.caseDefaultGroup(layoutOwner, name); + if (groupId) await ctx.tabLayouts.setCaseDefaultGroup(layoutOwner, newName, groupId); + } catch { + /* the group is a convenience; the rename already happened */ + } + await ctx.tabLayouts.forgetCaseDefaultGroup(layoutOwner, name).catch(() => undefined); }); ctx.broadcast(SseEvent.CaseRenamed, { oldName: name, newName, oldPath, newPath, folderMoved: moveFolder }); return { @@ -1881,7 +1905,13 @@ export function registerCaseRoutes( } catch (err) { if (err instanceof CaseRenameError) { const status = err.code === 'BUSY' ? 409 : err.code === 'EXISTS' ? 409 : err.code === 'LOCKED' ? 423 : 400; - return fail(status, ApiErrorCode.OPERATION_FAILED, err.message, { renameCode: err.code }); + const code = + err.code === 'EXISTS' + ? ApiErrorCode.ALREADY_EXISTS + : err.code === 'BUSY' + ? ApiErrorCode.CONFLICT + : ApiErrorCode.OPERATION_FAILED; + return fail(status, code, err.message, { renameCode: err.code }); } return fail(500, ApiErrorCode.OPERATION_FAILED, getErrorMessage(err)); } diff --git a/src/web/routes/session-routes.ts b/src/web/routes/session-routes.ts index 3982f4ea..bab07989 100644 --- a/src/web/routes/session-routes.ts +++ b/src/web/routes/session-routes.ts @@ -4,6 +4,7 @@ * auto-clear, auto-compact, image watcher, flicker filter, and logout. */ +import { claudeProjectDirName } from '../../case-rename.js'; import { FastifyInstance, type FastifyReply, type FastifyRequest } from 'fastify'; import { z } from 'zod'; import { join, dirname, extname, basename, resolve as resolvePath } from 'node:path'; @@ -5118,6 +5119,7 @@ export function registerSessionRoutes( if (!stat?.isDirectory()) return out; const workingDir = await decodeProjectKey(projDir); + const staleCwd = new Map(); const entries = await fs.readdir(projPath).catch(() => [] as string[]); for (const entry of entries) { @@ -5222,13 +5224,35 @@ export function registerSessionRoutes( worktreeRepo: headGit.worktreeRepo ?? tailGit.worktreeRepo, }; + // A case rename moves the project directory but leaves the old path in each transcript's + // cwd. When that cwd is gone and the decoded key is a real folder that encodes back to this + // very key (not the $HOME collapse of #265), the key is the truer answer. + let cwd = git.cwd; + if (cwd !== undefined && cwd !== workingDir) { + let stale = staleCwd.get(cwd); + if (stale === undefined) { + stale = + claudeProjectDirName(workingDir) === projDir && + (await fs.stat(cwd).then( + () => false, + () => true + )) && + (await fs.stat(workingDir).then( + (s) => s.isDirectory(), + () => false + )); + staleCwd.set(cwd, stale); + } + if (stale) cwd = undefined; + } + out.push({ sessionId, // The transcript's literal cwd beats decodeProjectKey's stat-walked guess, // which silently collapses to $HOME once the directory is gone (#265). // Absent cwd falls back to the old behaviour rather than inventing a path. - workingDir: git.cwd ?? workingDir, - workingDirExact: git.cwd !== undefined, + workingDir: cwd ?? workingDir, + workingDirExact: cwd !== undefined, projectKey: projDir, sizeBytes: fileStat.size, lastModified: fileStat.mtime.toISOString(), diff --git a/test/routes/case-rename-routes.test.ts b/test/routes/case-rename-routes.test.ts index 609c967b..cb1a2a10 100644 --- a/test/routes/case-rename-routes.test.ts +++ b/test/routes/case-rename-routes.test.ts @@ -4,14 +4,14 @@ * registries (caseOrder, lastUsedCase, linked-cases.json) and Claude's history follow. Real filesystem under * test/setup.ts's temp HOME; every folder is removed through safeRmHomeTree. Port: N/A (app.inject()). */ -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'; import { homedir } from 'node:os'; -import { basename, join } from 'node:path'; +import { basename, dirname, join } from 'node:path'; import { createRouteTestHarness } from './_route-test-utils.js'; import { registerCaseRoutes } from '../../src/web/routes/case-routes.js'; import { dataPath } from '../../src/config/instance.js'; -import { SETTINGS_PATH } from '../../src/web/route-helpers.js'; +import { SETTINGS_PATH, resolveCasesDir } from '../../src/web/route-helpers.js'; import { claudeProjectDirName } from '../../src/case-rename.js'; import { safeRmHomeTree } from '../mocks/index.js'; @@ -109,6 +109,36 @@ describe('POST /api/cases/:name/rename (a case under the cases directory)', () = expect(existsSync(join(CASES_DIR(), 'beta'))).toBe(true); }); + it('does not stop a remote session whose remote path equals the local folder', async () => { + const { app, ctx } = await createRouteTestHarness(registerCaseRoutes); + const dir = localCase('alpha'); + (ctx.sessions as Map).set('s-remote', { id: 's-remote', name: 'r', workingDir: dir, remote: {} }); + const res = await rename(app, 'alpha', { newName: 'beta' }); + made.push(join(CASES_DIR(), 'beta')); + expect(res.statusCode).toBe(200); + expect(ctx.cleanupSession).not.toHaveBeenCalled(); + }); + + it("carries the owner's default session group to the new name", async () => { + const { app, ctx } = await createRouteTestHarness(registerCaseRoutes); + localCase('alpha'); + vi.mocked(ctx.tabLayouts.caseDefaultGroup).mockResolvedValueOnce({ groupId: 'g1', groups: [] }); + const res = await rename(app, 'alpha', { newName: 'beta' }); + made.push(join(CASES_DIR(), 'beta')); + expect(res.statusCode).toBe(200); + expect(ctx.tabLayouts.setCaseDefaultGroup).toHaveBeenCalledWith(expect.any(String), 'beta', 'g1'); + expect(ctx.tabLayouts.forgetCaseDefaultGroup).toHaveBeenCalledWith(expect.any(String), 'alpha'); + }); + + it('answers a folder that appears at the target with ALREADY_EXISTS and keeps renameCode', async () => { + const { app } = await createRouteTestHarness(registerCaseRoutes); + localCase('alpha'); + localCase('beta'); + const res = await rename(app, 'alpha', { newName: 'beta' }); + expect(res.statusCode).toBe(409); + expect(res.json().errorCode).toBe('ALREADY_EXISTS'); + }); + it('does not touch a case whose name merely starts with the same letters', async () => { const { app, ctx } = await createRouteTestHarness(registerCaseRoutes); localCase('alpha'); @@ -166,14 +196,41 @@ describe('POST /api/cases/:name/rename (a linked case)', () => { expect(existsSync(join(work, 'renamed'))).toBe(false); }); - it('is admin only in multi-user mode', async () => { + it('puts the folder and the registry back when settings.json cannot be written', async () => { + const { app } = await createRouteTestHarness(registerCaseRoutes); + const real = join(work, 'my-project'); + mkdirSync(real); + writeFileSync(LINKED(), JSON.stringify({ proj: real, other: join(work, 'x') })); + writeFileSync(SETTINGS_PATH, JSON.stringify({ caseOrder: ['proj'] })); + chmodSync(SETTINGS_PATH, 0o444); + const res = await rename(app, 'proj', { newName: 'renamed', renameFolder: true }); + chmodSync(SETTINGS_PATH, 0o644); + expect(res.statusCode).toBe(500); + expect(existsSync(real)).toBe(true); + expect(linked()).toEqual({ proj: real, other: join(work, 'x') }); + }); + + it('answers 404 for a linked case a non-admin cannot see in multi-user mode', async () => { process.env.CODEMAN_MULTIUSER = '1'; const { app } = await createRouteTestHarness(registerCaseRoutes, { authUser: { username: 'bob', role: 'user' } }); const real = join(work, 'p'); mkdirSync(real); writeFileSync(LINKED(), JSON.stringify({ proj: real })); const res = await rename(app, 'proj', { newName: 'renamed' }); - expect(res.statusCode).not.toBe(200); + expect(res.statusCode).toBe(404); expect(linked()).toEqual({ proj: real }); }); + + it('leaves the server-wide settings.json alone when a non-admin renames their own case', async () => { + process.env.CODEMAN_MULTIUSER = '1'; + const { app } = await createRouteTestHarness(registerCaseRoutes, { authUser: { username: 'bob', role: 'user' } }); + const bobsDir = join(resolveCasesDir({ username: 'bob', role: 'user' } as never), 'alpha'); + mkdirSync(bobsDir, { recursive: true }); + made.push(dirname(bobsDir)); + const before = readFileSync(SETTINGS_PATH, 'utf8'); + const res = await rename(app, 'alpha', { newName: 'bobs' }); + expect(res.statusCode).toBe(200); + expect(existsSync(join(dirname(bobsDir), 'bobs'))).toBe(true); + expect(readFileSync(SETTINGS_PATH, 'utf8')).toBe(before); + }); }); diff --git a/test/routes/session-routes.test.ts b/test/routes/session-routes.test.ts index 1d6eaf8b..aa03f208 100644 --- a/test/routes/session-routes.test.ts +++ b/test/routes/session-routes.test.ts @@ -2613,6 +2613,26 @@ describe('session-routes', () => { expect(row.workingDir).not.toBe(home); }); + it("resumes a renamed case's conversation in the new folder, not the stale cwd in the transcript", async () => { + const home = process.env.HOME as string; + const realDir = join(home, 'renamed-case'); + await mkdir(realDir, { recursive: true }); + + const projectKey = realDir.replace(/[^a-zA-Z0-9]/g, '-'); + const projDir = join(home, '.claude', 'projects', projectKey); + await mkdir(projDir, { recursive: true }); + + const sessionId = '33333333-3333-3333-3333-333333333333'; + const line = + JSON.stringify({ type: 'user', cwd: join(home, 'old-case-name'), message: { role: 'user', content: 'hi' } }) + + '\n'; + await writeFile(join(projDir, `${sessionId}.jsonl`), line + '#'.repeat(4200 - line.length)); + + const res = await harness.app.inject({ method: 'GET', url: `/api/history/sessions?projectKey=${projectKey}` }); + const row = JSON.parse(res.body).data.sessions.find((s: { sessionId: string }) => s.sessionId === sessionId); + expect(row.workingDir).toBe(realDir); + }); + it('prefers the dotdir over a same-named non-dot sibling, and never emits a "//" path', async () => { // A doubled dash also lets the decoder read the empty split segment as a // directory NAME. `isDir(current + '/' + '')` stats `current + '/'`, which