mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-16 03:09:33 +01:00
fix(cases): address review of the rename route
Only an admin's rename touches the server-wide settings.json, which is now written before linked-cases.json with the registry restored on failure. The Resume list follows a renamed folder, the owner's default session group is carried over, remote sessions are never listed or stopped, errorCode maps EXISTS and BUSY, and the unmigrated items are documented.
This commit is contained in:
1 parent
201603e57b
commit
1cad4dd848
9 files changed
+229
-76
No files matched your search
+1
-1
@@ -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') {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<Record<string, unknown>>(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<Record<string, unknown>>(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));
|
||||
}
|
||||
|
||||
@@ -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<string, boolean>();
|
||||
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(),
|
||||
|
||||
Reference in new issue
Block a user