Repository navigation
Conversation
|
Opened upstream as can1357#21257 (commit 0cca3a8) Tests
Review of 0cca3a8: 1 finding (1 fixed).
Grade: Ready to merge (P0). The Windows skip now covers the test that deletes its current folder, resolving the earlier finding. The new diff changes only that test and adds no problem. Local tests could not run because this read-only checkout cannot install dependencies; the reported merged suite passed. Risk flags: this touches credentials (tokens, keys, logins or .env files). What happens next: I close this fork pull request and its linked issue when that upstream pull request merges or closes there. History
|
Keep the current folder on /restart and terminal restore after the latest upstream changes, and drop the old startup --cwd flag.
fdf3d39 to
69e4a03
Compare
Windows cannot delete the folder the process is still in, so that check now skips there the same way the existing deleted-folder restart check does.
|
This pull request is ready for Title and commit subject: Suggested sentence: I fixed /restart and terminal session restore for anyone who launches with --cwd, so they now use the session's current folder instead of a stale or relative startup path that could fail or put them back in the wrong folder. Description (the ## What
{{SENTENCE}}
`buildResumeArgv` now drops the original `--cwd` and, if that flag was used at launch, appends the session's current absolute directory. `/restart` supplies `SessionManager.getCwd()`, and OSC 7577 reporting supplies its current session directory. This keeps both relaunch paths aligned after `/move` or `/wt`.
## Why
Users who launched with a relative `--cwd` could hit a second resolution from the directory it had already selected, making `/restart` fail. A stale absolute path could pull the new process back to the original directory or abort startup after that directory was deleted. Terminal session restore inherited the same problem through the shared argv builder.
## Testing
```sh
bun install --frozen-lockfile && bun test packages/coding-agent/test/interactive-mode-restart.test.ts packages/coding-agent/test/program-resume.test.ts
```
The new tests fail on `main` without the change and pass with it. They cover relative and home-directory launches, moving away from a deleted launch directory, restoring the moved session, and OSC 7577 updates that leave non-cwd tokens intact. The full test suite passed with the change merged into `main`, including package type checks and the CLI smoke test.
Launches without `--cwd` retain the existing startup directory selection. Other flags, active-profile forwarding, and `--restore` behavior are unchanged.
---
- [ ] `bun check` passes
- [x] Tested locally
- [x] CHANGELOG updated with the required attribution (if user-facing; internal issue fixes use issue links, external contributions add the PR link and contributor credit after creation)Changelog ( - `/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))What robo-egg checked:
Already on
29 more found, none like this change
Try it yourself in the folder robo-egg made for you (its path is in your private message): bun install --frozen-lockfile && bun test packages/coding-agent/test/interactive-mode-restart.test.ts packages/coding-agent/test/program-resume.test.tsThe diff (5 files)diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index beb65d610b..e6fa51cc59 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -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
diff --git a/packages/coding-agent/src/modes/interactive-mode.ts b/packages/coding-agent/src/modes/interactive-mode.ts
index ab84ef998d..6066c42918 100644
--- a/packages/coding-agent/src/modes/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive-mode.ts
@@ -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();
diff --git a/packages/coding-agent/src/utils/program-resume.ts b/packages/coding-agent/src/utils/program-resume.ts
index f89a34c9d9..45bf5830fb 100644
--- a/packages/coding-agent/src/utils/program-resume.ts
+++ b/packages/coding-agent/src/utils/program-resume.ts
@@ -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 {
@@ -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;
}
@@ -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?.(),
});
diff --git a/packages/coding-agent/test/interactive-mode-restart.test.ts b/packages/coding-agent/test/interactive-mode-restart.test.ts
index 6d8824ceee..6245b1fb3b 100644
--- a/packages/coding-agent/test/interactive-mode-restart.test.ts
+++ b/packages/coding-agent/test/interactive-mode-restart.test.ts
@@ -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";
@@ -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";
@@ -20,6 +23,8 @@ describe("InteractiveMode restart", () => {
let sessionManager: SessionManager;
let session: AgentSession | undefined;
const originalArgv = process.argv;
+ let originalProjectDir: string;
+ let relaunch: string[] = [];
beforeEach(async () => {
initTheme();
@@ -27,6 +32,7 @@ describe("InteractiveMode restart", () => {
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"));
});
@@ -37,6 +43,7 @@ describe("InteractiveMode restart", () => {
session = undefined;
await sessionManager.close();
authStorage.close();
+ setProjectDir(originalProjectDir);
tempDir.removeSync();
resetSettingsForTest();
});
@@ -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");
@@ -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);
@@ -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")));
}
@@ -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();
+ }
+ },
+ );
});
diff --git a/packages/coding-agent/test/program-resume.test.ts b/packages/coding-agent/test/program-resume.test.ts
index 4611ecb9d6..8a9506c221 100644
--- a/packages/coding-agent/test/program-resume.test.ts
+++ b/packages/coding-agent/test/program-resume.test.ts
@@ -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",
+ ]);
+ });
});Sending: robo-egg opens it on |
|
Opened upstream as can1357#21257. It is built on can1357/oh-my-pi's main at b6cb669, where its test and the full suite passed: robo-egg cannot build main's newer commits (up to eb5f79e). |
Fixes #255
What
Updated the shared session relaunch command builder and /restart to drop the old --cwd argument and, when --cwd was used at launch, pass the session's current folder path instead. Added tests for relative --cwd launches, home folder launches, /move after deleting the original folder, and terminal session restore reporting.
packages/coding-agent/CHANGELOG.mdpackages/coding-agent/src/modes/interactive-mode.tspackages/coding-agent/src/utils/program-resume.tspackages/coding-agent/test/interactive-mode-restart.test.tspackages/coding-agent/test/program-resume.test.tsWhy
Starting omp with the --cwd folder option broke restarting the app. A relative folder path crashed on /restart, and moving to a new folder with /move or /wt either jumped back to the old folder or failed to start if the old folder had been deleted. Terminal session auto-restore had the same bug because it shared the same command builder.
When omp built the command to restart or auto-restore a session, it copied the original --cwd argument from launch instead of replacing it with the folder the session is currently in.
Testing
packages/coding-agent/test/interactive-mode-restart.test.ts packages/coding-agent/test/program-resume.test.ts) itself: it fails on upstream-main without this change and passes with it.Review
Auditor model: google-antigravity/gemini-4-neon (issue #255)
Worker model: google-antigravity/gemini-4-carbon (high thinking), lane carbon
Follow-up worker models: xai-oauth/grok-4.7 (xhigh thinking), lane grok-2; xai-oauth/grok-4.7 (xhigh thinking), lane grok
Reviewer model: kimi-code/k3.1-pro (max thinking), lane kimi-grade; reviewed commit 0cca3a8 on 2026-12-01 08:10 UTC
Autoreview: Ready to merge (P0). The Windows skip now covers the test that deletes its current folder, resolving the earlier finding. The new diff changes only that test and adds no problem. Local tests could not run because this read-only checkout cannot install dependencies; the reported merged suite passed.
Risk flags: this touches credentials (tokens, keys, logins or .env files).
Review of 0cca3a8: 1 finding (1 fixed).
This review looked only at the commits since 69e4a03, and at whether each earlier finding is fixed: 1 of 1 now fixed.
Technical details
packages/coding-agent/test/interactive-mode-restart.test.ts packages/coding-agent/test/program-resume.test.ts