feat(cases): create a new case in a custom folder

POST /api/cases takes an optional path; Add Case > Create New gets a 'Create in a
custom folder' option with Browse. The folder is created (or an empty one filled),
scaffolded like a normal case and registered as a linked case. System, home,
credential and Codeman folders are refused; a folder with files is Link Existing's
job; a failure after the first write undoes what this call created. Admin only in
multi-user mode, like Link Existing.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Devvyn
2026-10-05 07:03:10 +08:00
co-authored by Claude Sonnet 5.5
parent ffaa5ee80c
commit 4150707a6b
13 changed files with 775 additions and 8 deletions
+137
View File
@@ -0,0 +1,137 @@
/**
* @fileoverview Validation for "create a new case in a custom folder" (`POST /api/cases` with a
* `path`). Creating a case writes a scaffold (`CLAUDE.md`, `src/`, `.claude/settings.local.json`)
* and registers the folder in the shared, ownerless linked-cases registry, so the target has to be
* judged before anything is created:
*
* - it must be an absolute path (a leading `~` is expanded) with no traversal and none of the shell
* metacharacters a session's working directory is later rejected for (`isValidWorkingDir`), so
* a case this accepts is one a session can actually start in;
* - it must not be a system directory, the home directory itself, Codeman's own data directory, or
* a credential/config tree (`~/.ssh`, `~/.aws`, `~/.claude`, ...). Judged on the path as typed AND on
* its symlink-resolved form, so a link into `/etc` is not a way around it;
* - its parent must already exist (one folder is created, never a whole chain), and the folder
* itself must not exist or must be an EMPTY directory (a folder with contents is Link Existing's
* job, and silently scaffolding into someone's project is the one thing this must never do);
* - it must not be a symlink.
*
* Pure except for the filesystem reads in `prepareNewCasePath`; the policy lives in `blockedReason`
* so it can be tested without a disk.
*
* @module web/case-path
*/
import { promises as fs } from 'node:fs';
import { basename, dirname, join, resolve, sep } from 'node:path';
import { isValidWorkingDir } from './schemas.js';
/** System trees nobody creates a project in; creating one here is a mistake or an attack. */
const BLOCKED_SYSTEM_ROOTS = [
'/bin',
'/boot',
'/dev',
'/etc',
'/lib',
'/lib32',
'/lib64',
'/proc',
'/run',
'/sbin',
'/sys',
'/usr',
];
/** Home-relative trees that hold credentials or other tools' own configuration. */
const BLOCKED_HOME_DIRS = ['.ssh', '.gnupg', '.aws', '.kube', '.docker', '.claude', '.codex', '.gemini'];
export interface NewCasePathContext {
home: string;
/** Codeman's own state directory (`getDataDir()`), which must never become a case. */
dataDir: string;
}
export type NewCasePathResult =
| { ok: true; path: string; existedEmpty: boolean }
| { ok: false; code: 'INVALID' | 'BLOCKED' | 'NOT_FOUND' | 'EXISTS'; reason: string };
const isWithin = (child: string, root: string): boolean =>
child === root || child.startsWith(root.endsWith(sep) ? root : root + sep);
/** `~` and `~/x` to the home directory; anything else is returned unchanged. */
export function expandHome(raw: string, home: string): string {
if (raw === '~') return home;
if (raw.startsWith('~/')) return join(home, raw.slice(2));
return raw;
}
/** Why a case may not live at this (already absolute and normalised) path, or null. */
export function blockedReason(absPath: string, ctx: NewCasePathContext): string | null {
if (absPath === sep) return 'The filesystem root cannot be a case';
for (const root of BLOCKED_SYSTEM_ROOTS) {
if (isWithin(absPath, root)) return `${root} is a system directory`;
}
if (absPath === ctx.home) return 'The home folder itself cannot be a case; pick a folder inside it';
for (const dir of BLOCKED_HOME_DIRS) {
if (isWithin(absPath, join(ctx.home, dir))) return `~/${dir} holds credentials or another tool's configuration`;
}
if (isWithin(absPath, ctx.dataDir)) return "Codeman's own data folder cannot be a case";
// Any Codeman instance's data dir under the home folder (~/.codeman, ~/.codeman-beta, ...), not only
// the one this process uses.
if (absPath.startsWith(ctx.home + sep)) {
const firstSegment = absPath.slice(ctx.home.length + 1).split(sep)[0];
if (/^\.codeman/.test(firstSegment)) return "Codeman's own data folder cannot be a case";
}
return null;
}
/**
* Judge `raw` as the folder for a new case and, if it is acceptable, say what to create.
* Never creates anything.
*/
export async function prepareNewCasePath(raw: string, ctx: NewCasePathContext): Promise<NewCasePathResult> {
const typed = raw.trim();
if (!typed) return { ok: false, code: 'INVALID', reason: 'Enter a folder path' };
const expanded = expandHome(typed, ctx.home);
if (!isValidWorkingDir(expanded)) {
return {
ok: false,
code: 'INVALID',
reason: 'Use an absolute path with letters, numbers, spaces, - _ . only (no .., no shell characters)',
};
}
const target = resolve(expanded);
const typedBlock = blockedReason(target, ctx);
if (typedBlock) return { ok: false, code: 'BLOCKED', reason: typedBlock };
// Resolve the parent's symlinks, then judge again: a link into a blocked tree must not pass.
let realParent: string;
try {
realParent = await fs.realpath(dirname(target));
if (!(await fs.stat(realParent)).isDirectory()) {
return { ok: false, code: 'INVALID', reason: `${dirname(target)} is not a folder` };
}
} catch {
return { ok: false, code: 'NOT_FOUND', reason: `The parent folder ${dirname(target)} does not exist` };
}
const real = join(realParent, basename(target));
const realBlock = blockedReason(real, ctx);
if (realBlock) return { ok: false, code: 'BLOCKED', reason: realBlock };
try {
const st = await fs.lstat(real);
if (st.isSymbolicLink()) return { ok: false, code: 'INVALID', reason: `${target} is a symbolic link` };
if (!st.isDirectory()) return { ok: false, code: 'INVALID', reason: `${target} exists and is not a folder` };
if ((await fs.readdir(real)).length > 0) {
return {
ok: false,
code: 'EXISTS',
reason: `${target} already has files in it. Use "Link Existing" for a project that already exists`,
};
}
return { ok: true, path: real, existedEmpty: true };
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { ok: true, path: real, existedEmpty: false };
return { ok: false, code: 'INVALID', reason: `Cannot read ${target}: ${(err as Error).message}` };
}
}
+14 -2
View File
@@ -2972,15 +2972,27 @@
<p class="set-section-blurb">A fresh workspace under ~/codeman-cases, scaffolded with its own CLAUDE.md.</p>
<div class="form-row">
<label>Case Name</label>
<input type="text" id="newCaseName" placeholder="my-project" pattern="[a-zA-Z0-9_-]+" autocomplete="off" autocapitalize="off" spellcheck="false">
<input type="text" id="newCaseName" placeholder="my-project" pattern="[a-zA-Z0-9_-]+" autocomplete="off" autocapitalize="off" spellcheck="false" oninput="app.updateNewCasePathPreview()">
<span class="form-hint">Letters, numbers, hyphens, underscores only. Created in ~/codeman-cases/</span>
</div>
<div class="form-row">
<label>Description (optional)</label>
<input type="text" id="newCaseDescription" placeholder="A brief description..." autocomplete="off">
</div>
<div class="form-row" id="newCaseCustomPathToggleRow">
<label class="checkbox-row"><input type="checkbox" id="newCaseCustomPathToggle" onchange="app.toggleNewCaseCustomPath()"> 📁 Create in a custom folder</label>
<span class="form-hint">By default a new case is created under ~/codeman-cases. Choose another folder and the case is created there instead; it is listed like any other case.</span>
</div>
<div class="form-row" id="newCaseCustomPathRow" style="display:none">
<label>Parent Folder</label>
<div class="path-input-group">
<input type="text" id="newCasePath" placeholder="~/projects" autocomplete="off" autocapitalize="off" autocorrect="off" spellcheck="false" oninput="app.updateNewCasePathPreview()">
<button type="button" class="btn path-input-browse" onclick="app.openNewCasePathPicker()">Browse&hellip;</button>
</div>
<span class="form-hint" id="newCasePathPreview">Pick the folder the new case folder should be created inside.</span>
</div>
<div class="form-row docker-quick-row">
<label class="checkbox-row"><input type="checkbox" id="newCaseDocker"> 🐳 Run in an isolated Docker container</label>
<label class="checkbox-row"><input type="checkbox" id="newCaseDocker" onchange="app.toggleNewCaseCustomPath()"> 🐳 Run in an isolated Docker container</label>
<span class="form-hint">Runs this case in a hardened, isolated container. The base image is built automatically on first use. Docker/Podman must be installed.</span>
<span class="form-hint">Already have a container running? <button type="button" class="btn-inline-check" id="dockerAdoptJumpBtn">Attach to it instead</button> Codeman only runs docker exec into it and never touches its lifecycle.</span>
</div>
+68 -2
View File
@@ -3098,6 +3098,16 @@ Object.assign(CodemanApp.prototype, {
showCreateCaseModal() {
document.getElementById('newCaseName').value = '';
document.getElementById('newCaseDescription').value = '';
// Custom folder starts off each time, and is not offered to a non-admin in multi-user mode: the
// server refuses it (it writes outside the cases directory and into the shared registry).
const customToggle = document.getElementById('newCaseCustomPathToggle');
if (customToggle) customToggle.checked = false;
const customPath = document.getElementById('newCasePath');
if (customPath) customPath.value = '';
const me = window.__codemanUser || {};
const customRow = document.getElementById('newCaseCustomPathToggleRow');
if (customRow) customRow.style.display = me.multiUser && me.role !== 'admin' ? 'none' : '';
this.toggleNewCaseCustomPath();
document.getElementById('linkCaseName').value = '';
document.getElementById('linkCasePath').value = '';
const remoteFields = [
@@ -3265,6 +3275,55 @@ Object.assign(CodemanApp.prototype, {
}
},
/**
* Custom-folder row for Create New: shows or hides the parent-folder field, and keeps it and the
* Docker option mutually exclusive (a Docker case has its own workspace flow, and the quick-create
* route has no `path`).
*/
toggleNewCaseCustomPath() {
const custom = document.getElementById('newCaseCustomPathToggle');
const docker = document.getElementById('newCaseDocker');
const row = document.getElementById('newCaseCustomPathRow');
if (!custom || !row) return;
row.style.display = custom.checked ? '' : 'none';
custom.disabled = !!docker?.checked;
custom.title = docker?.checked ? 'Not available for a Docker case' : '';
if (docker) {
docker.disabled = custom.checked;
docker.title = custom.checked ? 'Not available with a custom folder' : '';
}
this.updateNewCasePathPreview();
},
/** The folder the case would be created in: the parent field plus the case name. */
_newCaseTargetPath() {
const parent = (document.getElementById('newCasePath')?.value || '').trim().replace(/\/+$/, '');
const name = (document.getElementById('newCaseName')?.value || '').trim();
return parent && name ? `${parent}/${name}` : '';
},
updateNewCasePathPreview() {
const hint = document.getElementById('newCasePathPreview');
if (!hint) return;
const target = this._newCaseTargetPath();
hint.textContent = target ? `Will create: ${target}` : 'Pick the folder the new case folder should be created inside.';
},
openNewCasePathPicker() {
const input = document.getElementById('newCasePath');
PathPicker.open({
title: 'Choose the folder to create the case in',
initialPath: input.value.trim(),
directoriesOnly: true,
onSelect: (path) => {
input.value = path;
this.updateNewCasePathPreview();
input.focus();
input.setSelectionRange(path.length, path.length);
},
});
},
async createCase() {
const name = document.getElementById('newCaseName').value.trim();
const description = document.getElementById('newCaseDescription').value.trim();
@@ -3282,10 +3341,17 @@ Object.assign(CodemanApp.prototype, {
// One-click "Run in Docker": create the case folder AND a container, then start
// a session inside it. Optional expandable settings override the defaults.
const inDocker = document.getElementById('newCaseDocker')?.checked;
const customFolder = !inDocker && document.getElementById('newCaseCustomPathToggle')?.checked;
if (customFolder && !(document.getElementById('newCasePath')?.value || '').trim()) {
this.showToast('Choose the folder to create the case in', 'error');
return;
}
const endpoint = inDocker ? '/api/cases/docker-quickcreate' : '/api/cases';
const payload = inDocker
? { name, description, ...this._collectDockerQuickSettings() }
: { name, description };
: customFolder
? { name, description, path: this._newCaseTargetPath() }
: { name, description };
try {
const res = await fetch(endpoint, {
@@ -3307,7 +3373,7 @@ Object.assign(CodemanApp.prototype, {
// Start a session INSIDE the container (routes through quick-start).
await this.runClaude();
} else {
this.showToast(`Case "${name}" created`, 'success');
this.showToast(customFolder ? `Case "${name}" created in ${payload.path}` : `Case "${name}" created`, 'success');
}
} else {
this.showToast(data.error || 'Failed to create case', 'error');
+93 -2
View File
@@ -50,6 +50,7 @@ import {
} from '../../git-clone.js';
import type { GitRemoteProbe, GitUrlParse } from '../../git-clone.js';
import { generateClaudeMd } from '../../templates/claude-md.js';
import { prepareNewCasePath } from '../case-path.js';
import { readAgentCaseMarker, type AgentCaseMarker } from '../../agent-case-marker.js';
import { settingsWriteBlocker, writeHooksConfig } from '../../hooks-config.js';
import {
@@ -424,8 +425,98 @@ export function registerCaseRoutes(app: FastifyInstance, ctx: EventPort & Config
return { success: true, data: { cases: summaries } };
});
app.post('/api/cases', async (req): Promise<ApiResponse<{ case: { name: string; path: string } }>> => {
const { name, description } = parseBody(CreateCaseSchema, req.body);
/**
* `POST /api/cases` with a `path`: create the folder (or fill an EMPTY existing one), scaffold it
* exactly like a normal case, and register it in the linked-cases registry so it lists, resolves
* and deletes (unlinks, never removes files) like any linked case. Everything is judged before
* anything is written; a failure after the first write undoes what this call created.
*/
async function createCaseInCustomFolder(
name: string,
description: string | undefined,
customPath: string,
req: FastifyRequest,
reply: { code: (n: number) => unknown }
): Promise<ApiResponse<{ case: { name: string; path: string } }>> {
if (existsSync(join(resolveCasesDir(getAuthUser(req)), name))) {
reply.code(409);
return createErrorResponse(ApiErrorCode.ALREADY_EXISTS, 'A case with this name already exists in codeman-cases.');
}
const linkedCases = await readLinkedCases();
if (linkedCases[name]) {
reply.code(409);
return createErrorResponse(
ApiErrorCode.ALREADY_EXISTS,
`Case "${name}" is already linked to ${linkedCases[name]}`
);
}
const prepared = await prepareNewCasePath(customPath, { home: homedir(), dataDir: getDataDir() });
if (!prepared.ok) {
const status = prepared.code === 'NOT_FOUND' ? 404 : prepared.code === 'EXISTS' ? 409 : 400;
reply.code(status);
const code =
prepared.code === 'NOT_FOUND'
? ApiErrorCode.NOT_FOUND
: prepared.code === 'EXISTS'
? ApiErrorCode.ALREADY_EXISTS
: ApiErrorCode.INVALID_INPUT;
return createErrorResponse(code, prepared.reason);
}
const casePath = prepared.path;
const alreadyAs = Object.entries(linkedCases).find(([, p]) => p === casePath)?.[0];
if (alreadyAs) {
reply.code(409);
return createErrorResponse(ApiErrorCode.ALREADY_EXISTS, `That folder is already the case "${alreadyAs}"`);
}
const made: string[] = [];
try {
if (!prepared.existedEmpty) {
mkdirSync(casePath);
made.push(casePath);
}
mkdirSync(join(casePath, 'src'));
made.push(join(casePath, 'src'));
const templatePath = await ctx.getDefaultClaudeMdPath();
writeFileSync(join(casePath, 'CLAUDE.md'), generateClaudeMd(name, description || '', templatePath));
made.push(join(casePath, 'CLAUDE.md'));
made.push(join(casePath, '.claude')); // before the write, so a half-written one is undone too
await writeHooksConfig(casePath);
const codemanDir = getDataDir();
if (!existsSync(codemanDir)) mkdirSync(codemanDir, { recursive: true });
// Re-read right before writing: another request may have linked a case since the check above.
const fresh = await readLinkedCases();
if (fresh[name]) throw Object.assign(new Error(`Case "${name}" was just linked`), { conflict: true });
fresh[name] = casePath;
await fs.writeFile(LINKED_CASES_FILE, JSON.stringify(fresh, null, 2));
ctx.broadcast(SseEvent.CaseCreated, { name, path: casePath });
return { success: true, data: { case: { name, path: casePath } } };
} catch (err) {
// Undo only what this call made. The whole folder if we created it, otherwise the scaffold
// entries inside the empty folder the user picked; never anything else.
for (const p of made.reverse()) await fs.rm(p, { recursive: true, force: true }).catch(() => undefined);
if ((err as { conflict?: boolean }).conflict) {
reply.code(409);
return createErrorResponse(ApiErrorCode.ALREADY_EXISTS, getErrorMessage(err));
}
reply.code(500);
return createErrorResponse(ApiErrorCode.OPERATION_FAILED, getErrorMessage(err));
}
}
app.post('/api/cases', async (req, reply): Promise<ApiResponse<{ case: { name: string; path: string } }>> => {
const { name, description, path: customPath } = parseBody(CreateCaseSchema, req.body);
// A custom folder writes outside the cases directory and registers the path in the shared,
// ownerless linked-cases registry, so it carries the same bar as POST /api/cases/link.
if (customPath !== undefined) {
const denied = adminOnly(req, reply);
if (denied) return denied;
return createCaseInCustomFolder(name, description, customPath, req, reply);
}
const casePath = validatePathWithinBase(name, resolveCasesDir(getAuthUser(req)));
if (!casePath) {
+7
View File
@@ -668,6 +668,13 @@ export const CreateCaseSchema = z.object({
.string()
.regex(/^[a-zA-Z0-9_-]+$/, 'Invalid case name format. Use only letters, numbers, hyphens, underscores.'),
description: z.string().max(1000).optional(),
/**
* Create the case in this folder instead of under the cases directory. Absolute, or starting with
* `~`. Only length-bounded here: what makes it acceptable (shape, blocked trees, symlinks, an
* existing folder with contents) is judged by `prepareNewCasePath()` in web/case-path.ts, which
* also produces the user-facing reason.
*/
path: z.string().min(1).max(1000).optional(),
});
/**