Repository navigation
feat(wsl): a WSL bridge shell reports its folder, so restores follow cd #35385
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
fde11e2
9610830
39709f9
bffce90
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,73 @@ | ||
| import { describe, expect, it, vi } from 'vitest' | ||
| import { readFileSync } from 'node:fs' | ||
| import { join } from 'node:path' | ||
| import type * as LocalPtyUtils from '../providers/local-pty-utils' | ||
|
|
||
| const { | ||
| spawnMock, | ||
| isPwshAvailableMock, | ||
| validateWorkingDirectoryMock, | ||
| resolveUnixShellPathMock, | ||
| resolveAgentForegroundProcessMock | ||
| } = vi.hoisted(() => ({ | ||
| spawnMock: vi.fn(), | ||
| isPwshAvailableMock: vi.fn(), | ||
| resolveUnixShellPathMock: vi.fn((shellPath: string) => shellPath), | ||
| resolveAgentForegroundProcessMock: vi.fn(), | ||
| validateWorkingDirectoryMock: vi.fn() | ||
| })) | ||
|
|
||
| vi.mock('node-pty', () => ({ spawn: spawnMock })) | ||
| vi.mock('../pwsh', () => ({ isPwshAvailable: isPwshAvailableMock })) | ||
| vi.mock('../providers/local-pty-utils', async (importOriginal) => ({ | ||
| ...(await importOriginal<typeof LocalPtyUtils>()), | ||
| resolveUnixShellPath: resolveUnixShellPathMock, | ||
| validateWorkingDirectory: validateWorkingDirectoryMock, | ||
| validateWorkingDirectoryAsync: validateWorkingDirectoryMock | ||
| })) | ||
| vi.mock('../providers/windows-pty-job-membership', () => ({ | ||
| readWindowsPtyJobProcessIds: () => new Set([12345]), | ||
| isWindowsPtyJobReadable: () => true | ||
| })) | ||
|
|
||
| import { createPtySubprocess } from './pty-subprocess' | ||
| import { mockPtyProcess, useDaemonPtySubprocessEnv } from './pty-subprocess-test-harness' | ||
|
|
||
| // The daemon's bridge spawn must point the guest at the wrappers that carry the folder report, | ||
| // not the daemon's own Unix fileset (daemon-shell-ready-wrapper-fileset.ts). | ||
| describe('a daemon-spawned WSL bridge pane', () => { | ||
| useDaemonPtySubprocessEnv({ | ||
| spawnMock, | ||
| isPwshAvailableMock, | ||
| resolveUnixShellPathMock, | ||
| resolveAgentForegroundProcessMock, | ||
| validateWorkingDirectoryMock | ||
| }) | ||
|
|
||
| it('sources wrappers that report its folder', async () => { | ||
| spawnMock.mockReturnValue(mockPtyProcess()) | ||
| const platform = Object.getOwnPropertyDescriptor(process, 'platform') | ||
| Object.defineProperty(process, 'platform', { value: 'win32' }) | ||
| try { | ||
| await createPtySubprocess({ | ||
| sessionId: 'test', | ||
| cols: 80, | ||
| rows: 24, | ||
| cwd: '\\\\wsl.localhost\\Ubuntu\\home\\jin\\repo' | ||
| }) | ||
| } finally { | ||
| if (platform) { | ||
| Object.defineProperty(process, 'platform', platform) | ||
| } | ||
| } | ||
|
|
||
| const [file, args, options] = spawnMock.mock.calls.at(-1)! | ||
| expect(file).toBe('wsl.exe') | ||
| expect(args.at(-1)).toContain('"${_orca_shell_ready_root}/bash/rcfile"') | ||
| expect(args.at(-1)).toContain('ZDOTDIR="${_orca_shell_ready_root}/zsh"') | ||
| const root: string = options.env.ORCA_SHELL_READY_ROOT | ||
| expect(options.env.WSLENV.split(':')).toContain('ORCA_SHELL_READY_ROOT/p') | ||
| expect(readFileSync(join(root, 'bash', 'rcfile'), 'utf8')).toContain('__orca_wsl_cwd_report') | ||
| expect(readFileSync(join(root, 'zsh', '.zshenv'), 'utf8')).toContain('__orca_wsl_cwd_report') | ||
| }) | ||
| }) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -9,6 +9,7 @@ import { getPosixClaudeShellFunction } from '../../shared/claude-shell-function' | |
| import { getBashStartupCommandPromptBlock } from '../pty/posix-shell-startup-command' | ||
| import { BASH_FEATURE_CHANNEL_BLOCK, SHELL_STARTUP_IDENTITY_MARKER_BLOCK } from '../shell-templates' | ||
| import { SHELL_READY_MARKER_ESCAPED } from './local-pty-shell-ready-marker' | ||
| import { BASH_WSL_CWD_REPORT_BLOCK } from '../wsl-shell-cwd-report' | ||
|
|
||
| export function getBashShellReadyRcfileContent(): string { | ||
| return `# Orca bash shell-ready wrapper | ||
|
|
@@ -48,6 +49,7 @@ ${getPosixOmpShellWrapper()} | |
| # Profile scripts must not replace Orca's runtime CODEX_HOME. | ||
| [[ -n "\${ORCA_CODEX_HOME:-}" ]] && export CODEX_HOME="\${ORCA_CODEX_HOME}" | ||
| ${getPosixCodexShellLaunchPreflight() + getPosixClaudeShellFunction()} | ||
| ${BASH_WSL_CWD_REPORT_BLOCK} | ||
| # OSC 133 C/D clears agent status after interrupted CLIs exit without sending Stop/SessionEnd hooks. | ||
| __orca_initializing_wrapper=1 | ||
| __orca_osc133_precmd() { | ||
|
|
@@ -58,6 +60,7 @@ __orca_osc133_precmd() { | |
| unset __orca_in_command | ||
| fi | ||
| printf "\\033]133;A\\007" | ||
| __orca_wsl_cwd_report | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
The new report runs inside Run the report after the user hooks while preserving the command's exit status. |
||
| return "$exit_code" | ||
| } | ||
| __orca_osc133_prompt_done() { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| import { spawnSync } from 'node:child_process' | ||
| import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' | ||
| import { tmpdir } from 'node:os' | ||
| import { join } from 'node:path' | ||
| import { afterEach, beforeEach, describe, expect, it } from 'vitest' | ||
| import { getBashShellReadyRcfileContent } from './providers/local-pty-shell-ready-bash-rcfile' | ||
| import { getLocalZshWrapperSpec } from './providers/local-pty-shell-ready-wrapper-fileset' | ||
| import { buildZshStartupHook } from './zsh-startup-wrapper-builder' | ||
| import { parseFileUriPath } from './daemon/osc7-file-uri' | ||
|
|
||
| const hasShell = (shell: string) => | ||
| process.platform !== 'win32' && spawnSync(shell, ['--version']).status === 0 | ||
|
|
||
| // The OSC 7 URIs a run printed, read the way the daemon reads a WSL pane's. | ||
| function reportedFolders(output: string): string[] { | ||
| return output | ||
| .split('\x1b]7;') | ||
| .slice(1) | ||
| .map((report) => report.slice(0, report.indexOf('\x07'))) | ||
| .map((uri) => parseFileUriPath(uri, { wslDistro: 'Ubuntu' }) ?? 'unparsed') | ||
| } | ||
|
|
||
| describe('a WSL bridge shell reports its folder', () => { | ||
| let home: string | ||
| let deep: string | ||
| beforeEach(() => { | ||
| // Real path: the shell's PWD is resolved (macOS /tmp is /private/tmp). | ||
| home = realpathSync(mkdtempSync(join(tmpdir(), 'wsl-cwd-report-'))) | ||
| deep = join(home, 'deep er', 'déjà a%b#c') | ||
| mkdirSync(deep, { recursive: true }) | ||
| }) | ||
| afterEach(() => rmSync(home, { recursive: true, force: true })) | ||
|
|
||
| const unc = (path: string) => `\\\\wsl.localhost\\Ubuntu${path.replaceAll('/', '\\')}` | ||
| // A foreign report (from an ssh session) lands between prompts; the next prompt corrects it. | ||
| const session = () => | ||
| `cd ${JSON.stringify(deep)}\ncd .\nprintf '\\033]7;file:///elsewhere\\007'\nexit 0\n` | ||
| const expected = () => [unc(home), unc(deep), unc(deep), unc('/elsewhere'), unc(deep)] | ||
|
|
||
| function runBash(env: Record<string, string>): string { | ||
| const rcfile = join(home, 'rcfile') | ||
| writeFileSync(rcfile, getBashShellReadyRcfileContent()) | ||
| // The user's own prompt hook keeps running alongside Orca's. | ||
| writeFileSync(join(home, '.bash_profile'), "PROMPT_COMMAND='echo USER_PROMPT_HOOK'\n") | ||
| const result = spawnSync('bash', ['--noprofile', '--rcfile', rcfile, '-i'], { | ||
| cwd: home, | ||
| input: session(), | ||
| encoding: 'utf8', | ||
| env: { | ||
| PATH: process.env.PATH ?? '/usr/bin:/bin', | ||
| HOME: home, | ||
| TERM: 'xterm', | ||
| // bash 3.2's readline drops typed non-ASCII bytes under the C locale. | ||
| LANG: 'en_US.UTF-8', | ||
| ...env | ||
| }, | ||
| timeout: 5000 | ||
| }) | ||
| expect(result.status).toBe(0) | ||
| return `${result.stdout}${result.stderr}` | ||
| } | ||
|
|
||
| it.skipIf(!hasShell('bash'))('from bash, at every prompt, keeping the user prompt hook', () => { | ||
| const output = runBash({ WSL_DISTRO_NAME: 'Ubuntu' }) | ||
| expect(reportedFolders(output)).toEqual(expected()) | ||
| expect(output).toContain('USER_PROMPT_HOOK') | ||
| }) | ||
|
|
||
| it.skipIf(!hasShell('bash'))('from bash only inside WSL', () => { | ||
| expect(reportedFolders(runBash({}))).toEqual([unc('/elsewhere')]) | ||
| }) | ||
|
|
||
| it.skipIf(!hasShell('zsh'))('from zsh, at every prompt', () => { | ||
| const zdotdir = join(home, 'zsh') | ||
| mkdirSync(zdotdir) | ||
| writeFileSync(join(zdotdir, '.zshenv'), buildZshStartupHook(getLocalZshWrapperSpec())) | ||
| const result = spawnSync('zsh', ['-i'], { | ||
| cwd: home, | ||
| input: session(), | ||
| encoding: 'utf8', | ||
| env: { | ||
| PATH: process.env.PATH ?? '/usr/bin:/bin', | ||
| HOME: home, | ||
| TERM: 'xterm', | ||
| LANG: 'en_US.UTF-8', | ||
| ZDOTDIR: zdotdir, | ||
| WSL_DISTRO_NAME: 'Ubuntu' | ||
| }, | ||
| timeout: 5000 | ||
| }) | ||
| expect(reportedFolders(`${result.stdout}${result.stderr}`)).toEqual(expected()) | ||
| }) | ||
| }) |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| /** | ||
| * A WSL bridge shell reports its folder at each prompt (OSC 7), so the terminal daemon's emulator, | ||
| * and every checkpoint, follows `cd` without a guest probe. Bridge bash and zsh send none | ||
| * themselves. Only inside WSL. The path is encoded only when it changes, and re-sent every | ||
| * prompt so a foreign report (an ssh session that set its own) cannot stick. Bytes outside the | ||
| * URI's unreserved set are percent-encoded as UTF-8, masked for bash 3.2's signed chars. | ||
| */ | ||
| export const BASH_WSL_CWD_REPORT_BLOCK = `__orca_wsl_cwd_report() { | ||
| [[ -n "\${WSL_DISTRO_NAME:-}" ]] || return 0 | ||
| if [[ "$PWD" != "\${__orca_wsl_cwd_reported-}" ]]; then | ||
| __orca_wsl_cwd_reported=$PWD | ||
| local LC_ALL=C __orca_e= __orca_c __orca_i | ||
| for (( __orca_i = 0; __orca_i < \${#PWD}; __orca_i++ )); do | ||
| __orca_c=\${PWD:__orca_i:1} | ||
| case $__orca_c in | ||
| [A-Za-z0-9/._~-]) __orca_e+=$__orca_c ;; | ||
| *) printf -v __orca_c '%d' "'$__orca_c"; printf -v __orca_c '%%%02X' $(( __orca_c & 255 )); __orca_e+=$__orca_c ;; | ||
| esac | ||
| done | ||
| __orca_wsl_cwd_encoded=$__orca_e | ||
| fi | ||
| printf '\\033]7;file://%s\\007' "\${__orca_wsl_cwd_encoded-}" | ||
| }` | ||
|
|
||
| export const ZSH_WSL_CWD_REPORT_BLOCK = `__orca_wsl_cwd_report() { | ||
| builtin emulate -L zsh | ||
| builtin setopt no_multibyte | ||
| [[ -n \${WSL_DISTRO_NAME:-} ]] || return 0 | ||
| if [[ $PWD != \${__orca_wsl_cwd_reported-} ]]; then | ||
| builtin typeset -g __orca_wsl_cwd_reported=$PWD | ||
| local __orca_e= __orca_c __orca_i | ||
| for (( __orca_i = 1; __orca_i <= $#PWD; __orca_i++ )); do | ||
| __orca_c=$PWD[__orca_i] | ||
| case $__orca_c in | ||
| ([A-Za-z0-9/._~-]) __orca_e+=$__orca_c ;; | ||
| (*) builtin printf -v __orca_c '%d' "'$__orca_c"; builtin printf -v __orca_c '%%%02X' $(( __orca_c & 255 )); __orca_e+=$__orca_c ;; | ||
| esac | ||
| done | ||
| builtin typeset -g __orca_wsl_cwd_encoded=$__orca_e | ||
| fi | ||
| builtin printf '\\033]7;file://%s\\007' "\${__orca_wsl_cwd_encoded-}" | ||
| }` |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -17,6 +17,7 @@ import { | |
| ZSH_USER_ZSHENV_SOURCE_BLOCK, | ||
| ZSH_ZDOTDIR_HANDBACK_BLOCK | ||
| } from './shell-templates' | ||
| import { ZSH_WSL_CWD_REPORT_BLOCK } from './wsl-shell-cwd-report' | ||
|
|
||
| export type ZshWrapperRestoreSpec = { | ||
| /** Local-only PATH restore; inert outside WSL. */ | ||
|
|
@@ -35,6 +36,8 @@ export type ZshStartupHookSpec = { | |
| osc133CommandMarkers: boolean | ||
| /** Local-only command delivery from the first zle line editor. */ | ||
| startupCommandDelivery: boolean | ||
| /** WSL bridge panes report their folder (OSC 7) at each prompt. */ | ||
| wslCwdReports?: boolean | ||
| overlayRestoreComment: string | ||
| restores: ZshWrapperRestoreSpec | ||
| } | ||
|
|
@@ -130,7 +133,15 @@ ${indentBlock(getZshShellReadyMarkerRegistrationBlock(spec.readyMarkerEscaped, t | |
| builtin typeset -g _orca_deferred_init_done=1 | ||
| builtin typeset -g precmd_functions | ||
| ${ZSH_DEFERRED_LINE_INIT_RETIRE_BLOCK} | ||
| ${permanentPrecmd} | ||
| ${permanentPrecmd}${ | ||
| spec.wslCwdReports | ||
| ? ` | ||
| if [[ -n \${WSL_DISTRO_NAME:-} ]]; then | ||
| (( \${precmd_functions[(Ie)__orca_wsl_cwd_report]} )) || precmd_functions+=(__orca_wsl_cwd_report) | ||
| __orca_wsl_cwd_report | ||
| fi` | ||
| : '' | ||
| } | ||
|
Comment on lines
+136
to
+144
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| ${joinBlocks([ | ||
| spec.restores.managedWslCli ? indentBlock(WSL_MANAGED_CLI_PATH_RESTORE, ' ') : null, | ||
| indentBlock(ORCA_CLI_POSIX_PATH_RESTORE, ' ').replace(/\n$/, ''), | ||
|
|
@@ -163,6 +174,7 @@ export function buildZshStartupHook(spec: ZshStartupHookSpec): string { | |
| ZSH_FEATURE_CHANNEL_BLOCK, | ||
| SHELL_STARTUP_IDENTITY_MARKER_BLOCK, | ||
| spec.osc133CommandMarkers ? ZSH_OSC133_FUNCTION_BLOCK : null, | ||
| spec.wslCwdReports ? ZSH_WSL_CWD_REPORT_BLOCK : null, | ||
| ZSH_DEFERRED_LINE_INIT_BLOCK, | ||
| buildDeferredInit(spec), | ||
| ZSH_USER_ZSHENV_SOURCE_BLOCK | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Report the folder after user prompt hooks.
__orca_osc133_precmdruns before the user'sPROMPT_COMMAND. If that command changes directories, OSC 7 reports the previous folder. A checkpoint taken before the next prompt then restores the wrong folder. Move the report to a prompt hook that runs after the user command.