Files
oh-my-pi/packages/coding-agent/test/session-manager/continue-relocation.test.ts
T
bling cfa9a2d53e fix(coding-agent): resume sessions after a worktree move/rename
When a session's working directory is moved or renamed (e.g. `git worktree
move`), the session file stays under the old cwd-encoded bucket while the new
directory is empty. Resuming was lossy:

- `--continue` rejected the terminal breadcrumb purely on cwd mismatch and then
  found nothing in the new bucket, silently starting a fresh empty session.
- cross-project `--resume <id>` only offered to *fork* (duplicate) the session
  into the new directory, forcing manual id selection and leaving a stale copy.

Detect relocation via the strong, low-false-positive signal "recorded cwd no
longer exists on disk" and re-root in place with the existing `moveTo()`:

- `continueRecent` re-roots the terminal's last session into the current
  directory when its recorded cwd is gone and the new location has no sessions
  of its own (otherwise behavior is unchanged). `readTerminalBreadcrumb` is
  refactored into `readTerminalBreadcrumbEntry` returning the raw cwd +
  session file so callers can interpret a cwd mismatch.
- cross-project `--resume <id>` offers "Move (re-root)" instead of fork when the
  source directory is gone; a still-existing different project still forks.

Tests: continue-relocation (re-root on move, no-hijack on plain cd, prefer
local recent) and cross-project move-vs-fork routing.
2026-06-07 18:34:51 -04:00

234 lines
9.1 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it } from "bun:test";
import * as fs from "node:fs";
import * as fsp from "node:fs/promises";
import * as os from "node:os";
import * as path from "node:path";
import {
loadEntriesFromFile,
type SessionHeader,
SessionManager,
} from "@oh-my-pi/pi-coding-agent/session/session-manager";
import { getTerminalId } from "@oh-my-pi/pi-tui";
import { getConfigRootDir, getTerminalSessionsDir, setAgentDir } from "@oh-my-pi/pi-utils";
import { makeAssistantMessage } from "./helpers";
function getHeader(entries: unknown[]): SessionHeader | undefined {
return entries.find(
(e): e is SessionHeader =>
typeof e === "object" && e !== null && "type" in e && (e as { type: unknown }).type === "session",
);
}
function writeBreadcrumb(cwd: string, sessionFile: string): string {
const terminalId = getTerminalId();
if (!terminalId) throw new Error("Expected a terminal id for breadcrumb test");
const dir = getTerminalSessionsDir();
fs.mkdirSync(dir, { recursive: true });
const file = path.join(dir, terminalId);
fs.writeFileSync(file, `${cwd}\n${sessionFile}\n`);
return file;
}
describe("SessionManager.continueRecent relocation", () => {
let testAgentDir: string;
let cwdA: string;
let cwdB: string;
const originalAgentDir = process.env.PI_CODING_AGENT_DIR;
const originalTmuxPane = process.env.TMUX_PANE;
const fallbackAgentDir = path.join(getConfigRootDir(), "agent");
beforeEach(async () => {
// Force a deterministic, non-TTY terminal id so breadcrumb read/write is stable.
process.env.TMUX_PANE = "%relocation-test";
testAgentDir = await fsp.mkdtemp(path.join(os.tmpdir(), "omp-reloc-test-"));
setAgentDir(testAgentDir);
cwdA = path.join(testAgentDir, "worktree-old");
cwdB = path.join(testAgentDir, "worktree-new");
fs.mkdirSync(cwdA, { recursive: true });
fs.mkdirSync(cwdB, { recursive: true });
});
afterEach(async () => {
if (originalTmuxPane === undefined) delete process.env.TMUX_PANE;
else process.env.TMUX_PANE = originalTmuxPane;
if (originalAgentDir) {
setAgentDir(originalAgentDir);
} else {
setAgentDir(fallbackAgentDir);
delete process.env.PI_CODING_AGENT_DIR;
}
await fsp.rm(testAgentDir, { recursive: true, force: true });
});
it("re-roots the terminal's session when its directory was moved/renamed", async () => {
const session = SessionManager.create(cwdA);
session.appendMessage({ role: "user", content: "before move", timestamp: 1 });
session.appendMessage(makeAssistantMessage());
await session.flush();
const oldFile = session.getSessionFile();
if (!oldFile) throw new Error("Expected persisted session file");
await session.close();
// Breadcrumb points at the old session, recorded under the old cwd.
writeBreadcrumb(cwdA, oldFile);
// Simulate `git worktree move`: the old directory no longer exists.
await fsp.rm(cwdA, { recursive: true, force: true });
const resumed = await SessionManager.continueRecent(cwdB);
try {
// The relocated session is adopted, not discarded for a fresh one.
expect(resumed.getCwd()).toBe(path.resolve(cwdB));
const newFile = resumed.getSessionFile();
if (!newFile) throw new Error("Expected re-rooted session file");
expect(newFile).not.toBe(oldFile);
expect(fs.existsSync(oldFile)).toBe(false);
const entries = await loadEntriesFromFile(newFile);
expect(getHeader(entries)?.cwd).toBe(path.resolve(cwdB));
const userMessages = entries.filter(e => e.type === "message" && e.message.role === "user");
expect(userMessages).toHaveLength(1);
} finally {
await resumed.close();
}
});
it("does not hijack the session when the recorded directory still exists (plain cd)", async () => {
const session = SessionManager.create(cwdA);
session.appendMessage({ role: "user", content: "other project", timestamp: 1 });
session.appendMessage(makeAssistantMessage());
await session.flush();
const oldFile = session.getSessionFile();
if (!oldFile) throw new Error("Expected persisted session file");
await session.close();
// Breadcrumb from a still-existing different project; user just cd'd elsewhere.
writeBreadcrumb(cwdA, oldFile);
const resumed = await SessionManager.continueRecent(cwdB);
try {
// Old project's session is left untouched; a fresh session starts in cwdB.
expect(fs.existsSync(oldFile)).toBe(true);
expect(resumed.getSessionFile()).not.toBe(oldFile);
expect(resumed.getEntries()).toHaveLength(0);
} finally {
await resumed.close();
}
});
it("does not re-root when the new directory already has its own sessions", async () => {
const moved = SessionManager.create(cwdA);
moved.appendMessage({ role: "user", content: "moved", timestamp: 1 });
moved.appendMessage(makeAssistantMessage());
await moved.flush();
const movedFile = moved.getSessionFile();
if (!movedFile) throw new Error("Expected persisted session file");
await moved.close();
// cwdB already owns a local session.
const local = SessionManager.create(cwdB);
local.appendMessage({ role: "user", content: "local", timestamp: 2 });
local.appendMessage(makeAssistantMessage());
await local.flush();
const localFile = local.getSessionFile();
if (!localFile) throw new Error("Expected persisted local session file");
await local.close();
writeBreadcrumb(cwdA, movedFile);
await fsp.rm(cwdA, { recursive: true, force: true });
const resumed = await SessionManager.continueRecent(cwdB);
try {
// Prefer cwdB's own recent session over re-rooting the moved one.
expect(resumed.getSessionFile()).toBe(localFile);
expect(fs.existsSync(movedFile)).toBe(true);
} finally {
await resumed.close();
}
});
it("moves a relocated breadcrumb session into an explicit sessionDir", async () => {
const session = SessionManager.create(cwdA);
session.appendMessage({ role: "user", content: "explicit dir", timestamp: 1 });
session.appendMessage(makeAssistantMessage());
await session.flush();
const oldFile = session.getSessionFile();
if (!oldFile) throw new Error("Expected persisted session file");
await session.close();
const explicitSessionDir = path.join(testAgentDir, "custom-sessions");
writeBreadcrumb(cwdA, oldFile);
await fsp.rm(cwdA, { recursive: true, force: true });
const resumed = await SessionManager.continueRecent(cwdB, explicitSessionDir);
try {
const newFile = resumed.getSessionFile();
if (!newFile) throw new Error("Expected re-rooted session file");
expect(path.dirname(newFile)).toBe(path.resolve(explicitSessionDir));
expect(fs.existsSync(oldFile)).toBe(false);
expect(getHeader(await loadEntriesFromFile(newFile))?.cwd).toBe(path.resolve(cwdB));
} finally {
await resumed.close();
}
});
it("re-roots when the stale breadcrumb file is already in the explicit sessionDir", async () => {
const explicitSessionDir = path.join(testAgentDir, "shared-custom-sessions");
const session = SessionManager.create(cwdA, explicitSessionDir);
session.appendMessage({ role: "user", content: "same explicit dir", timestamp: 1 });
session.appendMessage(makeAssistantMessage());
await session.flush();
const oldFile = session.getSessionFile();
if (!oldFile) throw new Error("Expected persisted session file");
expect(path.dirname(oldFile)).toBe(path.resolve(explicitSessionDir));
await session.close();
writeBreadcrumb(cwdA, oldFile);
await fsp.rm(cwdA, { recursive: true, force: true });
const resumed = await SessionManager.continueRecent(cwdB, explicitSessionDir);
try {
const newFile = resumed.getSessionFile();
if (!newFile) throw new Error("Expected re-rooted session file");
expect(newFile).toBe(oldFile);
expect(resumed.getCwd()).toBe(path.resolve(cwdB));
expect(getHeader(await loadEntriesFromFile(newFile))?.cwd).toBe(path.resolve(cwdB));
} finally {
await resumed.close();
}
});
it("prefers an existing current-cwd session in a shared explicit sessionDir", async () => {
const explicitSessionDir = path.join(testAgentDir, "shared-current-sessions");
const local = SessionManager.create(cwdB, explicitSessionDir);
local.appendMessage({ role: "user", content: "local current cwd", timestamp: 1 });
local.appendMessage(makeAssistantMessage());
await local.flush();
const localFile = local.getSessionFile();
if (!localFile) throw new Error("Expected persisted local session file");
await local.close();
// Ensure the stale moved session is newer than the local current-cwd session.
await new Promise(resolve => setTimeout(resolve, 20));
const moved = SessionManager.create(cwdA, explicitSessionDir);
moved.appendMessage({ role: "user", content: "newer stale moved cwd", timestamp: 2 });
moved.appendMessage(makeAssistantMessage());
await moved.flush();
const movedFile = moved.getSessionFile();
if (!movedFile) throw new Error("Expected persisted moved session file");
await moved.close();
writeBreadcrumb(cwdA, movedFile);
await fsp.rm(cwdA, { recursive: true, force: true });
const resumed = await SessionManager.continueRecent(cwdB, explicitSessionDir);
try {
expect(resumed.getSessionFile()).toBe(localFile);
expect(resumed.getCwd()).toBe(path.resolve(cwdB));
expect(fs.existsSync(movedFile)).toBe(true);
} finally {
await resumed.close();
}
});
});