Skip to content

fix(agents): resume an agent from the folder it ran in, not the pane's start folder - #33527

Merged
nwparker merged 3 commits into
mainfrom
nwparker/agint-resume-record-agent-cwd
Oct 25, 2026
Merged

nwparker merged 3 commits into
mainfrom
nwparker/agint-resume-record-agent-cwd

Conversation

@nwparker

@nwparker nwparker commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​75 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​74
Prod 10 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​90 $\color{#cf222e}{\Huge{\mathbf{−}}}$​13 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​77

ELI5

If you start an agent yourself from a different folder (cd pkg && claude), Orca remembered which session it was but not where it was running. After a restart or wake, Orca typed claude --resume <id> into a shell at the worktree root. Claude finds the session by id anyway, so nothing failed. The conversation just quietly carried on in the wrong folder. Now Orca records the folder the agent ran in and resumes from there.

Root cause

  • AgentProviderSessionMetadata / SleepingAgentSessionRecord stored no cwd (src/shared/agent-session-resume.ts). Every resume builder (buildAgentResumeStartupPlan) emitted a bare claude --resume <id>, which runs in whatever folder the pane's shell starts in. After a cold restore that is the pane's spawn folder (the worktree root). Orca's shell integration emits no OSC 7, and in cd X && claude the cd never reaches a prompt anyway.
  • Claude Code 2.1.310 (installed binary, checked live with an isolated CLAUDE_CONFIG_DIR and a fake Anthropic endpoint):

What changed

  • Capture: readPaneProviderSession attaches the agent's starting folder. This is done only for Claude and Codex, whose hook cwd is the session's own folder:

    • Codex sets it from turn_context.cwd (codex-rs/core/src/hook_runtime.rs:159,434).
    • Cursor's cwd is only sent on beforeShellExecution and names the shell command's folder, so Cursor is skipped. Other agents are skipped until verified.
    • Claude's hook cwd follows its Bash tool's cd. So the recorded folder is reused only for the same provider session id, or for a Claude SessionStart with source: clear or compact (same process). Any other new session id takes the hook's cwd: Codex /cd or /worktree forks, a relaunch from another folder, and claude --resume from elsewhere.
    • Live check with Claude 2.1.310: /clear resets Claude to its launch folder, SessionStart source: clear reports proj after the Bash tool had moved to proj/sub. In Orca, the record after /clear keeps repo/pkg.
  • Carry/persist: normalizeAgentProviderSession, the workspace-session zod schema, and the orcad export path-rewrite list now keep cwd.

  • Resume: buildAgentResumeStartupPlan takes launchCwd (the folder the resume shell starts in). When the recorded cwd differs from it (compared with the shared normalizeRuntimePathForComparison, mapping WSL UNC launch paths to their Linux path), the command is prefixed with cd <cwd> &&. This reuses buildAiVaultResumeShellCommand, so posix, cmd and PowerShell are all quoted correctly. Callers that pass it:

    • renderer cold restore
    • sleeping-session wake
    • host-owned resume (resolveMobileSessionResumeCommand, which also covers server-side restored panes and mobile)

    Agents started at the workspace root produce exactly the same command as before.

  • Mixed versions: the strict terminal.ensureAgentSession ProviderSession schema on older hosts would reject an unknown key. The two client send sites therefore strip cwd (agentProviderSessionForEnsure). Older desktops and relays already drop the field through normalizeAgentProviderSession.

How verified

Real Orca dev build, real Claude Code 2.1.310, isolated HOME/CLAUDE_CONFIG_DIR/userData, a fake local Anthropic server (no model spend), and a real restart (quit Orca, kill its terminal daemon, relaunch):

  • origin/main: after cd pkg && claude in the repo-root pane, the cold restore ran claude --resume <id> with process cwd /private/tmp/.../repo. Claude's header shows the repo root.
  • this branch, same flow plus a Bash-tool cd sub mid-session:
    • The record kept cwd: .../repo/pkg; the transcript shows Claude moved to pkg/sub.
    • After the restart, the resumed claude --resume <id> process cwd was .../repo/pkg, and the header shows repo/pkg.
  • Recorded folder deleted before restart: the pane shows cd: ...: No such file or directory and stays at a shell instead of resuming in the wrong folder.
  • Agent started at the root: no cd prefix.
  • Checks run: pnpm tc, targeted vitest suites (shared, terminal-pane, lib, runtime, ssh, rpc-contract), and check:code-quality:changed all pass. Two regression tests were added: hook cwd stickiness, and the resume cd prefix.

Before (main):
main-repro

After (this branch):
fix-verified

Risk / trade-offs

  • If the recorded folder no longer exists, resume now fails visibly in the shell (cd error) instead of silently resuming in the workspace root. This is the outcome [Bug]: Resume record binds the session to the pane's worktree, not the agent's cwd — the session is relaunched in the wrong directory (Claude and Codex) #16960 argues for. On PowerShell, Set-Location failing does not stop the next statement, so the resume falls back to the old wrong-folder behaviour there. -ErrorAction Stop was not added because it changes the shared AI vault resume line and I could not verify it on a Windows shell here.
  • When an agent survives an Orca restart (warm daemon) after its tool cd'd, the first hook in the new Orca run sets the folder. That is a subfolder of the original, and Claude still resolves the id.
  • Client-initiated resumes through a remote runtime's ensureAgentSession do not carry cwd yet. They behave as on main until a capability-gated field is added. A server's own pane restores do use it.
  • Unrelated and pre-existing: a failing cold-restore resume command is typed twice. It reproduces on a plain claude --resume with no cd prefix.

Fixes #16960
Refs #15485 (part 1, resume in a different cwd. Part 2, spinning subagent rows on relay, is separate.)

…s start folder

A sleeping/live resume record kept only the provider session id, so after a
restart Orca typed `claude --resume <id>` into a shell at the worktree root.
An agent started via `cd elsewhere && claude` was restored into the wrong
working directory (Claude resolves --resume by id across projects, so it does
not fail; it silently runs the conversation in the wrong folder).

Record the hook-reported cwd on the provider session (first value per session,
since Claude's hook cwd follows its Bash tool's cd), persist it, and prefix the
cold-restore / wake / host-owned resume with `cd <cwd> &&` when it differs
from the workspace root. Strip it from the strict ensureAgentSession wire so
older hosts keep accepting resumes.

Fixes #16960
@coderabbitai

coderabbitai Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Walkthrough

Provider-session metadata now records the agent’s working directory from hook data and retains it for the same session. Resume startup plans receive the workspace or worktree path and use the recorded directory when the paths differ, subject to the existing resume condition. Ensure requests remove cwd from provider-session metadata. Migration path fields and tests also cover cwd handling.

Priority: Pending latest changes

Severity of issue fixed: Medium

Merge Risk: Moderate · up to 4efe1

Some agents can resume in the wrong folder or fail to resume, and PowerShell can continue after a failed directory change. Resolve these paths before merging unless their impact is explicitly accepted.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 14 functions across 12 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title names the main change: agent resume now uses the folder the agent ran in instead of the pane's start folder. It matches the changeset. The title has 83 characters, which is within a reasonab…
Linked Issues check Passed Directly linked issue [#16960] requires that a sleeping or resumed agent record keep the agent's working directory, and that the resume run there. The reviewed head implements this:

- Capture: `readP…
Out of Scope Changes check Passed Each changed file supports capturing, persisting, carrying, or using the recorded agent cwd for resume:

- src/shared/agent-hook-listener/pane-provider-session.ts and src/shared/agent-session-resume…
Description check Passed The description follows the template closely. It covers ELI5, What Changed, Why (root cause and trade-offs), Testing with real-build verification and before/after images, and a Fixes link to #16960. T…
Full details: Title check

Explanation

The title names the main change: agent resume now uses the folder the agent ran in instead of the pane's start folder. It matches the changeset. The title has 83 characters, which is within a reasonable length. It uses the conventional prefix format.

Full details: Linked Issues check

Explanation

Directly linked issue [#16960] requires that a sleeping or resumed agent record keep the agent's working directory, and that the resume run there. The reviewed head implements this:

  • Capture: readPaneProviderSession (src/shared/agent-hook-listener/pane-provider-session.ts) attaches a cwd to the provider session. readAgentCwd reads it only for Claude and Codex hooks.
  • Stickiness (revised since the previous review): readAgentCwd keeps the prior same-source cwd for the pane. It takes a new hook cwd only on a Claude SessionStart with source === 'startup', or when no prior value exists. The previous assessment described first-per-session-id behavior. That description no longer holds. The current rule keeps the launch folder across /clear and new session ids. This matches Claude's transcript project directory, which follows the launch folder, so resume by id runs in the folder where the session was recorded.
  • Persist and carry: AgentProviderSessionMetadata gains optional cwd. normalizeAgentProviderSession and the workspace-session schema keep it. The orcad path-rewrite list covers it.
  • Resume: buildAgentResumeStartupPlan (src/shared/tui-agent-resume-startup.ts) prefixes cd &lt;cwd&gt; &amp;&amp; through buildAiVaultResumeShellCommand when the recorded cwd differs from launchCwd after normalization. WSL UNC launch paths are mapped to Linux paths first. Agents recorded at the launch folder get the unchanged command. Callers pass launchCwd for cold restore, sleeping-session wake, and host-owned resume.
  • Tests: the PR adds a hook cwd stickiness test (src/shared/agent-hook-listener-claude-turn-state.test.ts) and a resume cd prefix test (src/shared/tui-agent-startup.spec.ts). The PR reports an end-to-end restart check with Claude Code 2.1.310.

Residual gaps, not blocking:

  • Codex: the issue names Codex. The code relies on Codex hook cwd. The source for that claim is in the external codex-rs tree, which this repository does not contain. I did not verify it here. Codex resume with an explicit caller folder already uses tui.resume_cwd=current.
  • The issue suggests declining to resume when no cwd was captured. The code falls back to the launch folder. The issue presents this as a suggested direction, not a requirement.
  • Client-initiated resumes through a remote runtime's ensureAgentSession strip cwd. The issue scope excludes SSH and remote runtime, so this is outside the stated scope.
  • After /clear, Claude starts in its launch folder, but the record keeps the earlier folder. The PR states and tests this as intended behavior.
Full details: Out of Scope Changes check

Explanation

Each changed file supports capturing, persisting, carrying, or using the recorded agent cwd for resume:

  • src/shared/agent-hook-listener/pane-provider-session.ts and src/shared/agent-session-resume.ts: capture, stickiness, type, normalization, and the readPathFromKeys helper (renamed from readTranscriptPathFromKeys for reuse).
  • src/shared/tui-agent-resume-startup.ts: the launchCwd prefix logic for resume commands.
  • src/shared/workspace-session-sleeping-agents.ts and src/main/ssh/orcad-migration-path-fields.ts: schema acceptance and path-rewrite handling for the new field.
  • src/main/runtime/terminal/launch/mobile-terminal-startup.ts, src/renderer/src/components/terminal-pane/pty-connection/cold-restore-resume-startup.ts, src/renderer/src/lib/sleeping-agent-session-launch.ts: pass launchCwd to the resume builder.
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts and src/renderer/src/runtime/web-runtime-terminal-create-operation.ts: pass agentProviderSessionForEnsure output, which strips cwd for older strict ensureAgentSession schemas. This is a compatibility measure for the new field.
  • src/shared/agent-hook-listener-claude-turn-state.test.ts and src/shared/tui-agent-startup.spec.ts: regression tests for the new behavior.

No changed file I reviewed is unrelated to #16960. The PR description's note about a double-typed failing resume command is a reported pre-existing issue. It does not add a code change.

Full details: Description check

Explanation

The description follows the template closely. It covers ELI5, What Changed, Why (root cause and trade-offs), Testing with real-build verification and before/after images, and a Fixes link to #16960. The Linked Issue section is filled. Gaps: the Testing checkboxes are not ticked, the Visual Proof images are referenced by URL only, the Agent skill upstream boundary checkbox is blank, and the Checklist is not marked. The Notes section lists cross-platform and remote concerns but does not clearly confirm mobile, performance, or backwards-compat review. These gaps are minor.

Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 2d699e39-e68f-429a-b800-323fe9be8665
Commits

Reviewing files that changed from the base of the PR and between 526ffe3 and 9045e3f.

Files selected for processing: 12
  • src/main/runtime/terminal/launch/mobile-terminal-startup.ts
  • src/main/ssh/orcad-migration-path-fields.ts
  • src/renderer/src/components/terminal-pane/pty-connection/cold-restore-resume-startup.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
  • src/renderer/src/lib/sleeping-agent-session-launch.ts
  • src/renderer/src/runtime/web-runtime-terminal-create-operation.ts
  • src/shared/agent-hook-listener-claude-turn-state.test.ts
  • src/shared/agent-hook-listener/pane-provider-session.ts
  • src/shared/agent-session-resume.ts
  • src/shared/tui-agent-resume-startup.ts
  • src/shared/tui-agent-startup.spec.ts
  • src/shared/workspace-session-sleeping-agents.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.

const cwd =
previous?.id === providerSession.id && previous.cwd
? previous.cwd
: readPathFromKeys(hookPayload, ['cwd'])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Quick win

Preserve whitespace in the reported cwd.

readPathFromKeys returns raw.trim(). If the agent starts in a valid POSIX directory such as /repo/pkg , capture records /repo/pkg instead. If both directories exist, resume can silently use the wrong one. normalizeAgentProviderSession also calls this helper at src/shared/agent-session-resume.ts Line 182. Check for an empty path without changing the cwd’s bytes at either step.

Comment on lines +81 to +85
? buildAiVaultResumeShellCommand({
resumeCommand,
cwd: agentCwd,
platform: args.platform,
shell

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Functional Correctness · Quick win

🔎 Supported by static analysis

Script executed:

#!/bin/bash
ast-grep outline src/shared/ai-vault-resume-command.ts --view expanded
rg -n -C8 'Set-Location|buildResumeShellCommandForShell' src/shared

Repository: stablyai/orca

Length of output: 7730


Script executed:

sed -n '1,180p' src/shared/ai-vault-resume-command.ts
sed -n '230,300p' src/shared/ai-vault-resume-command.test.ts
rg -n -F -- 'function commandSeparator' src/shared

Repository: stablyai/orca

Length of output: 8501


Stop the PowerShell resume command when changing directories fails.

The PowerShell branch joins Set-Location and the resume command with ;. If the recorded folder was deleted, the resume command can run from the launch folder. Guard the resume command with the result of Set-Location.

Suggested fix
-  if (codexHome) {
-    segments.push(`$env:CODEX_HOME=${quoteStartupArg(codexHome, shell)}`)
-  }
-  segments.push(args.resumeCommand)
+  const resumeCommand = codexHome
+    ? `$env:CODEX_HOME=${quoteStartupArg(codexHome, shell)}${separator}${args.resumeCommand}`
+    : args.resumeCommand
+  segments.push(cwd ? `if ($?) { ${resumeCommand} }` : resumeCommand)

…re only Claude/Codex cwd

Claude's hook cwd follows its Bash tool's cd, so a new session id in the
same pane keeps the previous folder unless Claude reports a fresh
SessionStart startup. Only Claude and Codex hooks report the agent's own
folder (Cursor's cwd is a shell command's), so other agents skip capture.
Compare folders with the shared runtime path normalizer, mapping WSL UNC
launch paths to their Linux path.
A retained same-agent row outlives exits and restarts, so reusing its
folder for any new session id recorded the old folder after Codex /cd or
/worktree forks, a relaunch from another folder, or Claude --resume from
elsewhere. Keep it only for the same provider session id or a Claude
/clear or compact restart; otherwise take the hook's cwd.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

Major · Compare hook cwd when deciding whether a live recovery record… · agent-session-resume.ts:182

src/shared/agent-session-resume.ts:182
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Compare hook cwd when deciding whether a live recovery record changed.

A later status that adds only providerSession.cwd is treated as unchanged. The sleeping record keeps its earlier provider metadata, so the newly supplied cwd is not stored. A later resume then starts at launchCwd instead of the recorded directory. This can persist until a later capture replaces the record.

The live checkpoint path is:

  • The live recovery record copies the current providerSession, including cwd.
  • liveResumeRecordChange returns null when recoveryRecordMatches is true, so the sleeping record is not replaced.
  • recoveryRecordMatches relies on agentProviderSessionsEqual, which compares only key, id, and transcriptPath for Pi-family agents. It does not compare cwd.

Keep the identity check unchanged. Compare cwd only when the new record supplies one. A later status without cwd must not clear a stored value.

Suggested fix
     agentProviderSessionsEqual(existing.agent, existing.providerSession, next.providerSession) &&
+    (next.providerSession.cwd === undefined ||
+      existing.providerSession.cwd === next.providerSession.cwd) &&
     launchConfigsEqual(existing.launchConfig, next.launchConfig)

Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 5cff2338-a2aa-4b92-8d10-4ab76728f41e
Commits

Reviewing files that changed from the base of the PR and between 9045e3f and 4efe102.

Files selected for processing: 4
  • src/shared/agent-hook-listener-claude-turn-state.test.ts
  • src/shared/agent-hook-listener/pane-provider-session.ts
  • src/shared/tui-agent-resume-startup.ts
  • src/shared/tui-agent-startup.spec.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.

const resumeCommand = buildAgentResumeLaunchCommand(args.agent, baseCommand.command, argv, shell)
const agentCwd = args.providerSession.cwd
const launchCommand =
agentCwd && args.launchCwd && !args.resumeInLaunchCwd && !isSameFolder(agentCwd, args.launchCwd)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Functional Correctness · Heavy lift

Avoid changing directories twice for a cwd-changing command override.

If the launch directory is /repo and the configured command is cd pkg && claude, the hook records /repo/pkg. This branch then builds cd /repo/pkg && cd pkg && claude --resume …. The second cd targets /repo/pkg/pkg, so resume fails when that directory does not exist. Account for directory changes in the saved launch command before adding the cwd prefix. (raw.githubusercontent.com)

@nwparker
nwparker merged commit 4af4bc1 into main Oct 25, 2026
77 of 78 checks passed
nwparker added a commit that referenced this pull request Oct 25, 2026
…uuid ids when following a Claude job

- Carry providerSession.cwd into followed sessions so resume keeps the folder (#33527).
- Like Claude Code's own reader, drop a continued-in pointer that a later prompt or finished
  reply overtook, and remember a pending pointer so an unchanged transcript is not re-read.
- Require Claude's session-id shape for continuedInSessionId, resumeSessionId and the
  linkScanPath basename so ids cannot escape the project or jobs directory.
nwparker added a commit that referenced this pull request Oct 25, 2026
… it was started in (#33659)

Claude account-switch restarts now pass the folder the restarted shell opens in (tab start folder, else workspace), so #33527's `cd <start folder> &&` resume prefix applies and a session started in a subfolder resumes there. Codex account restarts benefit the same way.

Refs #31545
Supersedes #32033

Co-authored-by: ASH <[email protected]>
nachumi-a2zoperations added a commit to A2Z-Operations/orca that referenced this pull request Oct 28, 2026
… target account in place

Build the resume through the shared startup plan and replace the current pane through the runtime PTY controller on the named Claude account.
Resolve the current PTY cwd before planning and retain it as the spawned shell folder, allowing the builder to honor providerSession.cwd and recorded effort.
adapted from the plan: launchCwd from the recorded session folder, per stablyai#33527
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant