Files
oh-my-pi/packages/coding-agent/src/cli/startup-cwd.ts
T
can1357 6d7dab0c68 fix(coding-agent): prevented crash when resuming session in deleted directory
- Export `directoryExists` in `utils` to safely validate working directories before traversal.
- Update `SessionManager` and startup logic to fallback to the launch directory if a session's recorded working directory no longer exists.
- Add regression tests to ensure sessions now correctly adopt the launch directory instead of crashing on missing paths.
2026-06-19 16:06:01 +02:00

59 lines
1.5 KiB
TypeScript

import * as os from "node:os";
import * as path from "node:path";
import { directoryExists, getProjectDir, normalizePathForComparison, setProjectDir } from "@oh-my-pi/pi-utils";
import type { Args } from "./args";
async function maybeAutoChdir(parsed: Args): Promise<void> {
if (parsed.allowHome || parsed.cwd) {
return;
}
const home = os.homedir();
if (!home) {
return;
}
const normalizePath = normalizePathForComparison;
const cwd = normalizePath(getProjectDir());
const normalizedHome = normalizePath(home);
if (cwd !== normalizedHome) {
return;
}
const candidates = [path.join(home, "tmp"), "/tmp", "/var/tmp"];
for (const candidate of candidates) {
try {
if (!(await directoryExists(candidate))) {
continue;
}
setProjectDir(candidate);
return;
} catch {
// Try next candidate.
}
}
try {
const fallback = os.tmpdir();
if (fallback && normalizePath(fallback) !== cwd && (await directoryExists(fallback))) {
setProjectDir(fallback);
}
} catch {
// Ignore fallback errors.
}
}
export async function applyStartupCwd(parsed: Args): Promise<void> {
if (parsed.cwd) {
setProjectDir(parsed.cwd);
// setProjectDir resolves the (possibly relative) target against the launch
// cwd and chdirs into it. Re-sync parsed.cwd to the resolved absolute path
// so downstream consumers (buildSessionOptions, settings/discovery, session
// persistence) don't re-resolve a relative string against the new cwd.
parsed.cwd = getProjectDir();
return;
}
await maybeAutoChdir(parsed);
}