Skip to content

fix(coding-agent): forward active working directory on /restart - #270

Open
robo-egg wants to merge 2 commits into
upstream-mainfrom
robo-egg/255-fix-coding-agent-drop-stale-cwd-flag-on
Open

robo-egg wants to merge 2 commits into
upstream-mainfrom
robo-egg/255-fix-coding-agent-drop-stale-cwd-flag-on

Conversation

@robo-egg

@robo-egg robo-egg commented Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator

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.md
  • packages/coding-agent/src/modes/interactive-mode.ts
  • packages/coding-agent/src/utils/program-resume.ts
  • packages/coding-agent/test/interactive-mode-restart.test.ts
  • packages/coding-agent/test/program-resume.test.ts

Why

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

  • robo-egg ran the new test (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.
  • The full test suite passed in 69s with this change merged into upstream-main at 3607a23.
  • The fixer's own checks: Verified the new tests fail before the fix and pass after it, ran type checks across all packages, ran the coding-agent restart/move/fork/resume tests, and ran the full workspace test suite and CLI smoke test.

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.

  • Fixed: E1: packages/coding-agent/test/interactive-mode-restart.test.ts:205: This deletes dirA while it is the process's working directory. Windows forbids that, so the test fails there despite a correct fix; skip this case on Windows, as the existing deleted-directory restart test does.
Technical details
  • Test arguments: packages/coding-agent/test/interactive-mode-restart.test.ts packages/coding-agent/test/program-resume.test.ts
  • Commits:
    • fdf3d39 fix(coding-agent): forward active working directory on /restart

  • New test fails without the fix and passes with it
  • Full test suite passes merged with upstream-main
  • Reviewed by robo-egg's grader at this commit
  • No open findings

@robo-egg

robo-egg commented Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator Author

Opened upstream as can1357#21257 (commit 0cca3a8)

Tests

  • Full test suite, merged with upstream-main: passed in 2 min (upstream-main at b6cb669).
  • Proof: a fix; the test packages/coding-agent/test/interactive-mode-restart.test.ts packages/coding-agent/test/program-resume.test.ts fails without the change and passes with it.
  • Checks on GitHub: none.

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.

  • Fixed: E1: packages/coding-agent/test/interactive-mode-restart.test.ts:205: This deletes dirA while it is the process's working directory. Windows forbids that, so the test fails there despite a correct fix; skip this case on Windows, as the existing deleted-directory restart test does.

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
  • Fix rounds done: 2.
  • 2026-11-29 15:26 UTC: Pushed 69e4a03 to pull request fix(coding-agent): forward active working directory on /restart #270 for 1 input(s). What changed: Restart now keeps the folder you are in, even after the latest project updates. A relative folder, a deleted startup folder, and moving with /move no longer send the restarted app back to the old place. Terminal session restore uses the same fix.
    • On "Merge the latest upstream-main into this branch and resolve the conflicts.": Merged the latest main line and kept the restart fix. The only clash was in the restart test, which now matches the newer test helper and still checks that the old folder flag is replaced with the current folder.
  • 2026-12-01 07:24 UTC: Graded P1: The code fixes the reported restart and terminal-restore problem, and the new tests cover those cases. One added test deletes the directory it is still running in, which Windows does not allow, so the test suite would fail on Windows. This needs a small test correction before merging.
  • 2026-12-01 07:56 UTC: Pushed 0cca3a8 to pull request fix(coding-agent): forward active working directory on /restart #270 for 1 input(s). What changed: The restart check that deletes the folder it is still running in now skips on Windows, same as the other deleted-folder restart check. It still runs everywhere else, and the restart fix is unchanged.
    • On "packages/coding-agent/test/interactive-mode-restart.test.ts:205: This deletes dirA while it is the process's working directory. Windows forbids that, so the test fails there despite a correct fix; sk…": You were right. That check deleted the folder the app was still running in, which Windows does not allow. It now skips on Windows, the same way the other deleted-folder restart check does. The restart fix itself is unchanged.
  • 2026-12-01 08:11 UTC: Graded 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.
  • 2026-12-01 08:33 UTC: Posted the review packet for can1357/oh-my-pi: fix(coding-agent): forward active working directory on /restart #270 (comment)
  • 2026-12-01 09:07 UTC: Opened upstream as fix(coding-agent): forward active working directory on /restart can1357/oh-my-pi#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).
Technical details
  • Reviewed commit: 0cca3a8 on base b6cb669
  • Recheck of the commits since 69e4a03
  • Reviewed by: kimi-code/k3.1-pro
  • The AI's own grade: P0
  • Reviewed at: 2026-12-01 08:10 UTC

Keep the current folder on /restart and terminal restore after the latest upstream changes, and drop the old startup --cwd flag.
@robo-egg
robo-egg force-pushed the robo-egg/255-fix-coding-agent-drop-stale-cwd-flag-on branch from fdf3d39 to 69e4a03 Compare November 29, 2026 15:25
@robo-egg robo-egg added review:p1 Grade P1: the right fix; robo-egg is doing a touch-up risk:credentials Touches tokens, keys, logins or .env files labels Dec 1, 2026
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.
@robo-egg robo-egg added review:p0 Grade P0: safe to merge as it is and removed review:p1 Grade P1: the right fix; robo-egg is doing a touch-up labels Dec 1, 2026
@robo-egg

robo-egg commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator Author

This pull request is ready for can1357/oh-my-pi. Below is exactly what would be opened there from the eggpeat account. robo-egg sends it on its own with the suggested sentence (auto go).

Title and commit subject: fix(coding-agent): forward active working directory on /restart

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 {{SENTENCE}} line becomes your sentence):

## 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 (#N becomes the upstream pull request's number once it is open):

- `/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:

  • Reproduction: bun install --frozen-lockfile && bun test packages/coding-agent/test/interactive-mode-restart.test.ts packages/coding-agent/test/program-resume.test.ts fails on upstream-main without the change and passes with it.
  • Full test suite merged with upstream-main: passed.
  • Fork grade: P0 by kimi-code/k3.1-pro.

Already on can1357/oh-my-pi?

# Kind State Title Verdict
#10289 pull request closed feat(coding-agent): add in-session restart tool with SDK lifecycle callbacks related: This adds an in-session restart tool and lifecycle callbacks, not a fix for the working directory forwarded by /restart.
#21064 pull request open feat(coding-agent): let a launcher prefix the OSC 7577 resume command related: This changes the same OSC 7577 resume command path to support launcher prefixes, but does not fix stale --cwd forwarding.
#14150 pull request open feat(coding-agent): add startup.scratchDir and /scratch for home launches related: This changes home-launch directory selection, which this fix preserves; it does not repair the working directory in restart argv.
#20692 issue closed Support the Program Resume protocol (OSC 7577) so terminals can restore omp sessions after a restart related: This requested the terminal program resume feature whose shared argv builder is corrected here; it does not address stale --cwd.
#21062 pull request merged fix(coding-agent): unset osc7577 token from the os environment related: This fixes OSC 7577 token inheritance in the same resume reporting code, not the working directory in resume argv.
#21056 issue closed OSC7577_TOKEN still reaches bash tool commands: delete process.env doesn't remove it from the OS environment related: This reports the OSC 7577 token leak addressed by can1357#21062, a different resume protocol defect.
#18907 issue closed Tern relaunch never works for omp in WSL: session file reported as a POSIX path, and only when TERM_PROGRAM crosses WSL… related: This concerns WSL path reporting for terminal relaunch, while this change fixes the launch working directory forwarded in the resume command.
#7748 pull request open feat(coding-agent): restart persisted sessions after an executable update related: This restarts persisted sessions after executable updates and shares relaunch handling, but does not correct stale --cwd replay.
29 more found, none like this change
  • #18848 pull request, open: feat(tui): map file-link path prefixes to URIs with tui.linkMap
  • #19329 pull request, open: feat(antigravity-cli): shared agy acp processes across compatible sessions
  • #15393 pull request, open: feat(coding-agent): load subdirectory context files on first touch
  • #15857 issue, open: Tool and system prompts describe behavior the runtime does not have (52 text-only corrections)
  • #9833 pull request, open: feat(collab): opt-in auto-start hosting and write-link file
  • #15550 pull request, merged: fix(approval): honor approve timeouts and count untruncated lines
  • #5281 issue, open: Add masked in-session API-key registration and explicit paid-fallback policy to /login
  • #7381 pull request, closed: feat(cron): schedule prompts on a cron expression
  • #15404 pull request, closed: fix(session): keep persisting large sessions past 2 GiB
  • #11995 pull request, closed: feat(coding-agent): scope prompt history recall by session, cwd or repository
  • #7341 issue, closed: Factor out language-specific system prompt into skills
  • #15683 pull request, closed: fix(coding-agent): restore configured header models from cache reads
  • #12082 pull request, closed: feat(coding-agent): add producer-scoped artifact resolution
  • #2763 issue, closed: [FR] First-class recurring/scheduled task ("run X every N minutes") — cron-like, prior art Copilot CLI
  • #10005 pull request, closed: feat(state-broker): share agent state across machines
  • #8286 pull request, closed: feat(cli): load process-local provider key bundles
  • #10288 pull request, closed: feat(coding-agent): add in-session refresh tool for skills, rules, settings, and MCP
  • #9363 pull request, closed: fix(settings): respect project scope in /settings
  • #9631 pull request, merged: fix(cwd): Handle denied project directories
  • #20618 issue, open: feat(review): support explicit base/head PR-style review in CLI/headless mode
  • #21152 pull request, open: fix(tray): stop retaining ended subagent run data
  • #21139 pull request, open: fix(coding-agent): asked before suspending on Ctrl+Z while work is running
  • #20941 issue, open: Extension API: submit the composer or run a slash command programmatically
  • #20786 pull request, open: feat(tui,coding-agent): add clickable code-block [Copy] buttons and /copy code support
  • #18724 pull request, open: fix(tui): show a revived subagent as running in its settled task card
  • #21135 pull request, open: fix(coding-agent): ended an orphaned interactive session once its terminal is gone
  • #14981 pull request, open: feat(todo): add todo.sticky setting to unpin the todo HUD
  • #16190 pull request, open: fix(coding-agent): clear scrollback when rebuilding transcript from messages
  • #20860 issue, open: TUI crash ""term" in n" when a tool_call hook blocks a named task spawn (19.2.x regression)
… and 103 more found

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.ts
The 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 can1357/oh-my-pi from the eggpeat account with the suggested sentence, once its checks pass again (packet 3e80ab80c060, commit 0cca3a8). The robo:hold label stops it.

@robo-egg

robo-egg commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator Author

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).

@robo-egg robo-egg added the robo:upstream-open Open upstream: waiting for the upstream maintainers to merge it label Dec 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

review:p0 Grade P0: safe to merge as it is risk:credentials Touches tokens, keys, logins or .env files robo:upstream-open Open upstream: waiting for the upstream maintainers to merge it

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant