Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/coding-agent/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@
- **Git and worktrees:** Fixed selective commit and cross-worktree edit reporting, including handling of stale or conflicting remote changes ([#20801](https://github.com/can1357/oh-my-pi/pull/20801) by [@Quantum-Quasar](https://github.com/Quantum-Quasar), [#20823](https://github.com/can1357/oh-my-pi/pull/20823) by [@Quantum-Quasar](https://github.com/Quantum-Quasar), [#17446](https://github.com/can1357/oh-my-pi/issues/17446), [#20252](https://github.com/can1357/oh-my-pi/issues/20252)).
- **Dictation:** Fixed live transcription, GPU fallback messages, and completion notifications ([#11040](https://github.com/can1357/oh-my-pi/issues/11040), [#16121](https://github.com/can1357/oh-my-pi/issues/16121)).
- **Settings reference:** Documented 14 `tui.*` settings, including boxed-prompt IME layout, Kitty text sizing, inline image budget placeholders, and Mermaid diagrams ([#20863](https://github.com/can1357/oh-my-pi/issues/20863), [#20956](https://github.com/can1357/oh-my-pi/pull/20956) by [@koeria](https://github.com/koeria)).
- `/restart` and OSC 7577 terminal session restore now forward the active working directory instead of replaying a stale or relative startup `--cwd` flag ([#N](https://github.com/can1357/oh-my-pi/pull/N) by [@eggpeat](https://github.com/eggpeat))

### Removed

Expand Down
2 changes: 1 addition & 1 deletion packages/coding-agent/src/modes/interactive-mode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5934,7 +5934,7 @@ export class InteractiveMode implements InteractiveModeContext {
}

const sessionFile = this.sessionManager.isSessionOnDisk() ? this.sessionManager.getSessionFile() : undefined;
const cmd = buildResumeArgv(sessionFile);
const cmd = buildResumeArgv(sessionFile, this.sessionManager.getCwd());
const resumeToken = getProgramResumeToken();
await postmortem.cleanup();
await postmortem.drainStdout();
Expand Down
39 changes: 30 additions & 9 deletions packages/coding-agent/src/utils/program-resume.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import * as crypto from "node:crypto";
import * as path from "node:path";
import { writeTerminalSequence } from "@oh-my-pi/pi-tui/driver/session";
import { getActiveProfile, isTerminalHeadless } from "@oh-my-pi/pi-utils";
import { restartArgv } from "../cli/flag-tables";
import { flagConsumesValue, restartArgv } from "../cli/flag-tables";
import { resolveRestartCmd } from "../subprocess/worker-client";

import {
Expand Down Expand Up @@ -75,24 +75,45 @@ const runtime: {
disposed: false,
};

function hasLaunchCwd(argv: readonly string[]): boolean {
let hasCwd = false;
for (let i = 0; i < argv.length; i++) {
const arg = argv[i]!;
if (arg === "--") break;
if (!arg.startsWith("-")) continue;
if (arg === "--cwd") {
hasCwd = Boolean(argv[++i]);
continue;
}
if (arg.startsWith("--cwd=")) {
hasCwd = arg.length > "--cwd=".length;
continue;
}
if (flagConsumesValue(arg, argv[i + 1])) i++;
}
return hasCwd;
}

/**
* Build the argv to relaunch/resume omp with its current flags, active profile,
* and optional on-disk `sessionFile` (`--restore`). Shared by `/restart` and
* OSC 7577 reporting.
* current working directory (when `--cwd` was supplied at launch), and optional
* on-disk `sessionFile` (`--restore`). Shared by `/restart` and OSC 7577 reporting.
*/
export function buildResumeArgv(
sessionFile: string | undefined,
cwd: string,
options?: { launchArgs?: string[]; baseCmd?: string[] },
): string[] {
const launchArgs = options?.launchArgs ?? process.argv.slice(2);
const activeProfile = getActiveProfile();
const cmd = [
...(options?.baseCmd ?? resolveRestartCmd()),
...restartArgv(
options?.launchArgs ?? process.argv.slice(2),
sessionFile ? path.resolve(sessionFile) : undefined,
activeProfile ? { "--profile": true } : undefined,
),
...restartArgv(launchArgs, sessionFile ? path.resolve(sessionFile) : undefined, {
"--cwd": true,
...(activeProfile ? { "--profile": true } : undefined),
}),
];
if (hasLaunchCwd(launchArgs)) cmd.push("--cwd", path.resolve(cwd));
if (activeProfile) cmd.push("--profile", activeProfile);
return cmd;
}
Expand Down Expand Up @@ -179,7 +200,7 @@ export function reportProgramResume(): void {
if (!process.stdout.isTTY || isTerminalHeadless()) return;
const sessionFile = runtime.source.sessionFile();
const cwd = path.resolve(runtime.source.cwd());
const argv = buildResumeArgv(sessionFile, {
const argv = buildResumeArgv(sessionFile, cwd, {
launchArgs: runtime.source.launchArgs?.(),
baseCmd: runtime.source.baseCmd?.(),
});
Expand Down
73 changes: 71 additions & 2 deletions packages/coding-agent/test/interactive-mode-restart.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "bun:test";
import * as fs from "node:fs/promises";
import * as os from "node:os";
import * as path from "node:path";
import { Agent, type AgentMessage } from "@oh-my-pi/pi-agent-core";
import { type Args, parseArgs } from "@oh-my-pi/pi-coding-agent/cli/args";
import { applyStartupCwd } from "@oh-my-pi/pi-coding-agent/cli/startup-cwd";
import { ModelRegistry } from "@oh-my-pi/pi-coding-agent/config/model-registry";
import { resetSettingsForTest, Settings } from "@oh-my-pi/pi-coding-agent/config/settings";
import { createSessionManager } from "@oh-my-pi/pi-coding-agent/main";
Expand All @@ -10,7 +13,7 @@ import { AgentSession } from "@oh-my-pi/pi-coding-agent/session/agent-session";
import { AuthStorage } from "@oh-my-pi/pi-coding-agent/session/auth-storage";
import { SessionManager } from "@oh-my-pi/pi-coding-agent/session/session-manager";
import * as natives from "@oh-my-pi/pi-natives";
import { postmortem, TempDir } from "@oh-my-pi/pi-utils";
import { getProjectDir, postmortem, setProjectDir, TempDir } from "@oh-my-pi/pi-utils";
import { initTheme } from "../src/ui/theme/service";
import { createModeTerminal } from "./helpers/mode-terminal";

Expand All @@ -20,13 +23,16 @@ describe("InteractiveMode restart", () => {
let sessionManager: SessionManager;
let session: AgentSession | undefined;
const originalArgv = process.argv;
let originalProjectDir: string;
let relaunch: string[] = [];

beforeEach(async () => {
initTheme();
resetSettingsForTest();
tempDir = TempDir.createSync("@omp-restart-");
await Settings.init({ inMemory: true, cwd: tempDir.path() });
authStorage = await AuthStorage.create(path.join(tempDir.path(), "auth.db"));
originalProjectDir = getProjectDir();
sessionManager = SessionManager.create(tempDir.path(), path.join(tempDir.path(), "persona sessions"));
});

Expand All @@ -37,6 +43,7 @@ describe("InteractiveMode restart", () => {
session = undefined;
await sessionManager.close();
authStorage.close();
setProjectDir(originalProjectDir);
tempDir.removeSync();
resetSettingsForTest();
});
Expand All @@ -50,7 +57,7 @@ describe("InteractiveMode restart", () => {
}

/** Restart with `argv` and parse the replacement command's arguments from `--model` on. */
async function restart(argv: string[]) {
async function restart(argv: string[], beforeRestart?: (mode: InteractiveMode) => Promise<void>) {
const modelRegistry = new ModelRegistry(authStorage);
const model = modelRegistry.find("anthropic", "claude-sonnet-4-5");
if (!model) throw new Error("expected bundled model");
Expand All @@ -70,6 +77,7 @@ describe("InteractiveMode restart", () => {
createModeTerminal().frame,
);
process.argv = [originalArgv[0], originalArgv[1], ...argv];
await beforeRestart?.(mode);
// Stop only at the process replacement boundary; teardown and argv production run for real.
const exec = vi.spyOn(natives, "execReplace").mockImplementation(() => undefined as never);
const spawn = vi.spyOn(Bun, "spawn").mockReturnValue({ exited: Promise.resolve(0) } as never);
Expand All @@ -79,6 +87,7 @@ describe("InteractiveMode restart", () => {
await mode.restart();
const command = process.platform === "win32" ? spawn.mock.calls[0]?.[0] : exec.mock.calls[0]?.[1];
if (!Array.isArray(command)) throw new Error("expected replacement command");
relaunch = command;
return parseArgs(command.slice(command.indexOf("--model")));
}

Expand Down Expand Up @@ -157,4 +166,64 @@ describe("InteractiveMode restart", () => {
if (!file) throw new Error("expected allocated journal path");
expect(await Bun.file(file).exists()).toBe(false);
});

it("replaces a relative --cwd with the resolved directory and preserves home launches across restart", async () => {
const homeDir = path.join(tempDir.path(), "home");
await fs.mkdir(path.join(homeDir, "tmp"), { recursive: true });
vi.spyOn(os, "homedir").mockReturnValue(homeDir);

setProjectDir(tempDir.path());
const launchArgv = ["--cwd", "home", "--model", "anthropic/claude-sonnet-4-5"];
await applyStartupCwd(parseArgs(launchArgv));
await sessionManager.close();
sessionManager = SessionManager.create(getProjectDir(), path.join(tempDir.path(), "home-sessions"));

const parsed = await restart(launchArgv);
expect(relaunch.filter(arg => arg === "--cwd" || arg.startsWith("--cwd="))).toEqual(["--cwd"]);
expect(relaunch[relaunch.indexOf("--cwd") + 1]).toBe(homeDir);
await applyStartupCwd(parsed);
expect(parsed.cwd).toBe(homeDir);
expect(getProjectDir()).toBe(homeDir);
});

it.skipIf(process.platform === "win32")(
"updates --cwd after /move so restart neither fails on a removed startup directory nor jumps back",
async () => {
const dirA = path.join(tempDir.path(), "dir-a");
const dirB = path.join(tempDir.path(), "dir-b");
const agentDir = path.join(tempDir.path(), "agent");
await fs.mkdir(dirA, { recursive: true });
await fs.mkdir(dirB, { recursive: true });

setProjectDir(tempDir.path());
const launchArgv = [`--cwd=${dirA}`, "--model", "anthropic/claude-sonnet-4-5"];
await applyStartupCwd(parseArgs(launchArgv));
await sessionManager.close();
sessionManager = SessionManager.create(dirA, SessionManager.getDefaultSessionDir(dirA, agentDir));
sessionManager.appendMessage({ role: "user", content: "moved session", timestamp: 1 });
await sessionManager.ensureOnDisk();

const parsed = await restart(launchArgv, async mode => {
await fs.rm(dirA, { recursive: true });
await mode.handleMoveCommand(dirB);
});

expect(relaunch).not.toContain(`--cwd=${dirA}`);
expect(relaunch).not.toContain(dirA);
expect(relaunch[relaunch.indexOf("--cwd") + 1]).toBe(dirB);
await applyStartupCwd(parsed);
expect(parsed.cwd).toBe(dirB);
expect(getProjectDir()).toBe(dirB);
const resumed = await createSessionManager(parsed, getProjectDir(), Settings.isolated());
if (!resumed) throw new Error("expected resumed journal");
try {
expect(resumed.getCwd()).toBe(dirB);
expect(resumed.buildSessionContext().messages).toEqual([
{ role: "user", content: "moved session", timestamp: 1 },
]);
} finally {
await resumed.close();
}
},
);
});
51 changes: 51 additions & 0 deletions packages/coding-agent/test/program-resume.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,4 +175,55 @@ describe("OSC 7577 program resume reporting", () => {
expect(process.env[OSC_7577_TOKEN_ENV]).toBeUndefined();
expect(writes).toHaveLength(0);
});

it("replaces a startup --cwd flag with the current session directory without touching non-cwd tokens", () => {
process.env[OSC_7577_TOKEN_ENV] = SPEC_TOKEN;
const state = {
sessionFile: "/tmp/sessions/moved.jsonl" as string | undefined,
cwd: "/tmp/orig/subdir",
launchArgs: ["--cwd", "subdir", "--model", "opus"],
};

initProgramResume({
sessionFile: () => state.sessionFile,
cwd: () => state.cwd,
baseCmd: () => ["/usr/local/bin/omp"],
launchArgs: () => state.launchArgs,
nowSeconds: () => SPEC_TIME,
});
expect(writes).toHaveLength(1);
expect(decodeArgv(parseOsc7577(writes[0], SPEC_TOKEN).argv)).toEqual([
"/usr/local/bin/omp",
"--model",
"opus",
"--restore",
"/tmp/sessions/moved.jsonl",
"--cwd",
"/tmp/orig/subdir",
]);

state.cwd = "/tmp/relocated";
reportProgramResume();
expect(writes).toHaveLength(2);
expect(decodeArgv(parseOsc7577(writes[1], SPEC_TOKEN).argv)).toEqual([
"/usr/local/bin/omp",
"--model",
"opus",
"--restore",
"/tmp/sessions/moved.jsonl",
"--cwd",
"/tmp/relocated",
]);

state.launchArgs = ["--system-prompt", "--cwd", "--", "--cwd", "subdir"];
reportProgramResume();
expect(writes).toHaveLength(3);
expect(decodeArgv(parseOsc7577(writes[2], SPEC_TOKEN).argv)).toEqual([
"/usr/local/bin/omp",
"--system-prompt",
"--cwd",
"--restore",
"/tmp/sessions/moved.jsonl",
]);
});
});