feat: confirm creating missing session cwd

This commit is contained in:
shiyue
2026-03-30 04:46:13 +08:00
parent a3df0cc6f0
commit 86d044f8a9
3 changed files with 160 additions and 7 deletions

View File

@@ -937,6 +937,58 @@ function getDefaultSessionCwd() {
|| path.resolve(process.cwd());
}
function resolveSessionCwd(candidate, options = {}) {
if (!candidate || !String(candidate).trim()) {
return { ok: true, path: getDefaultSessionCwd(), created: false };
}
const resolvedPath = path.resolve(String(candidate).trim());
try {
if (fs.existsSync(resolvedPath)) {
const realPath = fs.realpathSync(resolvedPath);
const stat = fs.statSync(realPath);
if (!stat.isDirectory()) {
return {
ok: false,
code: 'new_session_cwd_invalid',
resolvedPath,
message: '工作目录不是目录,请重新选择。',
};
}
return { ok: true, path: realPath, created: false };
}
if (!options.createMissing) {
return {
ok: false,
code: 'new_session_cwd_missing',
resolvedPath,
message: '工作目录不存在',
};
}
fs.mkdirSync(resolvedPath, { recursive: true });
const createdPath = normalizeExistingDirPath(resolvedPath);
if (!createdPath) {
return {
ok: false,
code: 'new_session_cwd_create_failed',
resolvedPath,
message: '目录已创建,但当前进程无法访问,请检查权限。',
};
}
return { ok: true, path: createdPath, created: true };
} catch (err) {
return {
ok: false,
code: options.createMissing ? 'new_session_cwd_create_failed' : 'new_session_cwd_invalid',
resolvedPath,
message: `${options.createMissing ? '创建工作目录失败' : '解析工作目录失败'}: ${err.message}`,
};
}
}
function collectRecentSessionCwds(limit = 12) {
const results = [];
const seen = new Set();
@@ -2564,10 +2616,16 @@ function handleNewSession(ws, msg) {
const cwd = (msg && msg.cwd) ? String(msg.cwd) : null;
const agent = normalizeAgent(msg?.agent);
const requestedMode = ['default', 'plan', 'yolo'].includes(msg?.mode) ? msg.mode : 'yolo';
if (cwd && !normalizeExistingDirPath(cwd)) {
return wsSend(ws, { type: 'error', message: '工作目录不存在或不可访问,请重新选择。' });
const cwdResult = resolveSessionCwd(cwd, { createMissing: !!msg?.createCwd });
if (!cwdResult.ok) {
return wsSend(ws, {
type: 'error',
code: cwdResult.code,
cwd: cwdResult.resolvedPath || cwd || null,
message: cwdResult.message,
});
}
const resolvedCwd = normalizeExistingDirPath(cwd) || getDefaultSessionCwd();
const resolvedCwd = cwdResult.path || getDefaultSessionCwd();
const id = crypto.randomUUID();
const session = {
id,