Skip to content
Merged
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

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 22 additions & 0 deletions src/main/__fixtures__/shell-wrapper-snapshots/local-zsh-zshenv.txt

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions src/main/daemon/daemon-pty-adapter-wsl-sleep-cwd.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,27 @@ describe('a sleeping bridge WSL pane keeps its shell folder', () => {
expect(checkpointCwd(id)).toBe(WSL_CWD)
})

// verify-18 (e): `cd deep`, then the distro was terminated: no Sleep read ran, and the restore
// reopened at the root. The bridge shell's OSC 7 now carries the folder into every checkpoint.
it('checkpoints the folder the shell last reported, with no read of the distro', async () => {
readRows.mockResolvedValue(null)
adapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() })
const { id } = await adapter.spawn({
cols: 80,
rows: 24,
cwd: WSL_CWD,
env: { ORCA_PANE_KEY: PANE_KEY },
sessionId: 'repo::/repo@@reported'
})
lastSubprocess._simulateData(
'$ cd "deep er"\r\n\x1b]7;file:///home/jin/repo/deep%20er/d%C3%A9j%C3%A0\x07$ '
)

await adapter.shutdown(id, { immediate: true, keepHistory: true })

expect(checkpointCwd(id)).toBe(`${WSL_CWD}\\deep er\\déjà`)
})

it('never reads a distro for a pane that is not a WSL pane', async () => {
adapter = new DaemonPtyAdapter({ socketPath, tokenPath, historyPath: historyDir() })
const { id } = await adapter.spawn({
Expand Down
73 changes: 73 additions & 0 deletions src/main/daemon/pty-subprocess-wsl-cwd-report.test.ts
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')
})
})
3 changes: 3 additions & 0 deletions src/main/providers/local-pty-shell-ready-bash-rcfile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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() {
Expand All @@ -58,6 +60,7 @@ __orca_osc133_precmd() {
unset __orca_in_command
fi
printf "\\033]133;A\\007"
__orca_wsl_cwd_report

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

Report the folder after user prompt hooks.

__orca_osc133_precmd runs before the user's PROMPT_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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Folder report misses hook changes

The new report runs inside __orca_osc133_precmd, before the user's PROMPT_COMMAND hooks. If a user hook changes directories, Orca saves the folder from before that hook, not the folder where the prompt appears. Quitting or terminating WSL before another prompt can therefore restore the wrong folder.

Run the report after the user hooks while preserving the command's exit status.

return "$exit_code"
}
__orca_osc133_prompt_done() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export function getLocalZshWrapperSpec(): ZshStartupHookSpec {
readyMarkerEscaped: SHELL_READY_MARKER_ESCAPED,
osc133CommandMarkers: true,
startupCommandDelivery: true,
wslCwdReports: true,
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
overlayRestoreComment:
"# Why: ~/.zshrc can export the user's default OpenCode config after spawn.",
restores: {
Expand Down
93 changes: 93 additions & 0 deletions src/main/wsl-shell-cwd-report.test.ts
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())
})
})
42 changes: 42 additions & 0 deletions src/main/wsl-shell-cwd-report.ts
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-}"
}`
14 changes: 13 additions & 1 deletion src/main/zsh-startup-wrapper-builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand All @@ -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
}
Expand Down Expand Up @@ -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

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

Supported by static analysis

Script executed:

sed -n '100,200p' src/main/zsh-startup-wrapper-builder.ts
sed -n '1,120p' src/main/wsl-shell-cwd-report.test.ts

Repository: stablyai/orca

Length of output: 6898


Script executed:

set -o pipefail
printf '%s\n' '--- zsh builder definitions ---'
sed -n '1,115p' src/main/zsh-startup-wrapper-builder.ts
printf '%s\n' '--- wrapper/spec references ---'
rg -n -F --glob '*.ts' -e 'wslCwdReports' -e 'getLocalZshWrapperSpec' -e 'ZSH_USER_ZSHENV_SOURCE_BLOCK' -e '__orca_wsl_cwd_report' src/main
printf '%s\n' '--- focused tests and relevant source ---'
rg -n -F --glob '*.ts' -e 'precmd' -e 'WSL_DISTRO_NAME' -e 'wsl-cwd' src/main/zsh-startup-wrapper-builder.test.ts src/main/wsl-shell-cwd-report.test.ts src/main/providers src/main/daemon 2>/dev/null || true
printf '%s\n' '--- diff against requested base ---'
git diff --unified=80 88e23db6b5403732e6ffd034ceaf7f492249b732 fde11e29698e749905f7226998927412b21cae12 -- src/main/zsh-startup-wrapper-builder.ts src/main/providers/local-pty-shell-ready-wrapper-fileset.ts src/main/wsl-shell-cwd-report.test.ts

Repository: stablyai/orca

Length of output: 25141


Script executed:

set -o pipefail
printf '%s\n' '--- reporter ---'
sed -n '1,90p' src/main/wsl-shell-cwd-report.ts
printf '%s\n' '--- user zshenv source block ---'
sed -n '1,100p' src/main/shell-templates.ts
printf '%s\n' '--- deferred line-init block ---'
sed -n '1,220p' src/main/zsh-deferred-startup-line-init.ts
printf '%s\n' '--- wrapper generation tests around zsh ordering ---'
sed -n '230,330p' src/main/providers/local-pty-shell-ready-wrapper-generation.test.ts
printf '%s\n' '--- all direct user-hook references ---'
rg -n -F --glob '*.ts' -e 'precmd_functions+=' -e 'precmd_functions=(' -e 'precmd()' -e 'precmd_functions' src/main | head -160

Repository: stablyai/orca

Length of output: 17310


Web query:

zsh official documentation precmd_functions execution order

Result:

<source_evidence>
<source kind="open_page">
<title>9 Functions (zsh)</title>
<location>https://zsh.sourceforge.io/Doc/Release/Functions.html</location>
<excerpt>citeturn1view0 [wordlim: 200] Crawled: today; Content type: text/html; Source: open({&quot;ref_id&quot;:&quot;turn0search0&quot;,&quot;lineno&quot;:null}); Total lines: 204
L12: ## 9.1 Autoloading Functions 【2†¶】
L13: 
L18: The usual alias expansion during reading will be suppressed if the `autoload` builtin or its equivalent is given the option `-U`. This is recommended for the use of functions supplied with the zsh distribution. Note that for functions precompiled with the `zcompile` builtin command the flag `-U` must be provided when the `.zwc` file is created, as the corresponding information is compiled into the latter.
L19: For each `element` in `fpath`, the shell looks for three possible files, the newest of which is used to load the definition for the function:
L20: 
L21: `element``.zwc`
L22: A file created with the `zcompile` builtin command, which is expected to contain the definitions for all functions in the directory named `element`. The file is treated in the same manner as a directory containing files for functions and is searched for the definition of the function. If the definition is not found, the search for a definition proceeds with the other two possibilities described below.
L23: If `element` already includes a `.zwc` extension (i.e. the extension was explicitly given by the user), `element` is searched for the definition of the function without comparing its age to that of other files; in fact, there does not need to be any directory named `element` without the suffix.
L24: Thus including an element such as ‘`/usr/local/funcs.zwc`’ in `fpath` will speed up the search for functions, with the disadvantage that functions included must be explicitly recompiled by hand before the shell notices any changes.
L25: `element``/``function``.zwc`
L26: 
L27: 
L28: A file created with `zcompile`, which is expected to contain the definition for `function`. It may include other function definitions as well, but those are neither loaded nor executed; a file found in this way is searched only for the definition of `function`.
L29: 
L30: `element``/``function`
L31: 
L32: 
L33: A file of zsh command text, taken to be the definition for `function`.
L34: In summary, the order of searching is, first, in the parents of directories in `fpath` for the newer of either a compiled directory or a directory in `fpath`; second, if more than one of these contains a definition for the function that is sought, the leftmost in the `fpath` is chosen; and third, within a directory, the newer of either a compiled function or an ordinary function definition is used.
L35: If the `KSH_AUTOLOAD` option is set, or the file contains only a simple definition of the function, the file’s contents will be executed. This will normally define the function in question, but may also perform initialization, which is executed in the context of the function execution, and may therefore define local parameters. It is an error if the function is not defined by loading the file.
L36: Otherwise, the function body (with no surrounding ‘`funcname``() {``...``}`’) is taken to be the complete contents of the file. This form allows the file to be used directly as an executable shell script. If processing of the file results in the function being re-defined, the function itself is not re-executed.
L37: To force the shell to perform initialization and then call the function defined, the file should contain initialization code (which will be executed then discarded) in addition to a complete function definition (which will be retained for subsequent calls to the function), and a call to the shell function, including any arguments, at the end.
L38: For example, suppose the autoload file `func` contains
L39: 
L40:     func() { print This is func; }
L41:     print func is initialized
L42: 
L43: 
L44: then ‘`func; func`’ with `KSH_AUTOLOAD` set will produce both messages on the first call, but only the message ‘`This is func`’ on the second and subsequent calls. Without `KSH_AUTOLOAD` set, it will produce the initialization message on the first call, and the other message on the second and subsequent calls.
L45: It is also possible to create a function that is not marked as autoloaded, but which loads its own definition by searching `fpath`, by using ‘`autoload -X`’ within a shell function. For example, the following are equivalent:
L46: 
L47:     myfunc() {
L48:       autoload -X
L49:     }
L50:     myfunc args...
L51: 
L52: 
L53: and
L54: 
L55:     unfunction myfunc   # if myfunc was defined
L56:     autoload myfunc
L57:     myfunc args...
L58: In fact, the `functions` command outputs ‘`builtin autoload -X`’ as the body of an autoloaded function. This is done so that
L59: 
L60:     eval &quot;$(functions)&quot;
L61: 
L62: 
L63: produces a reasonable result. A true autoloaded function can be identified by the presence of the comment ‘`# undefined`’ in the body, because all comments are discarded from defined functions.
L64: 
L65: To load the definition of an autoloaded function `myfunc` without executing `myfunc`, use:
L66: 
L67:     autoload +X myfunc
L68: 
L69: 
L70: * * *
L71: [ 【8†&lt;&lt;】 ]  | [ 【2†&lt;】 ]  | [ 【8†Up】 ]  | [ 【10†&gt;】 ]  | [ 【3†&gt;&gt;】 ]  |    |    |    |    | [【1†Top】]  | [【4†Contents】]  | [【5†Index】]  | [ 【6†?】 ]
L72: ## 9.2 Anonymous Functions 【9†¶】
L73: 
L74: If no name is given for a function, it is ‘anonymous’ and is handled specially. Either form of function definition may be used: a ‘`()`’ with no preceding name, or a ‘`function`’ with an immediately following open brace. The function is executed immediately at the point of definition and is not stored for future use. The function name is set to ‘`(anon)`’.
L75: Arguments to the function may be specified as words following the closing brace defining the function, hence if there are none no arguments (other than `$0`) are set. This is a difference from the way other functions are parsed: normal function definitions may be followed by certain keywords such as ‘`else`’ or ‘`fi`’, which will be treated as arguments to anonymous functions, so that a newline or semicolon is needed to force keyword interpretation.
L76: Note also that the argument list of any enclosing script or function is hidden (as would be the case for any other function called at this point).
L77: 
L78: Redirections may be applied to the anonymous function in the same manner as to a current-shell structure enclosed in braces. The main use of anonymous functions is to provide a scope for local variables. This is particularly convenient in start-up files as these do not provide their own local variable scope.
L79: For example,
L80: 
L81:     variable=outside
L82:     function {
L83:       local variable=inside
L84:       print &quot;I am $variable with arguments $*&quot;
L85:     } this and that
L86:     print &quot;I am $variable&quot;
L87: 
L88: 
L89: outputs the following:
L90: 
L91:     I am inside with arguments this and that
L92:     I am outside
L93: Note that function definitions with arguments that expand to nothing, for example ‘`name=; function $name { ``...`` }`’, are not treated as anonymous functions. Instead, they are treated as normal function definitions where the definition is silently discarded.
L94: 
L95: * * *
L96: 
L97: [ 【8†&lt;&lt;】 ]  | [ 【9†&lt;】 ]  | [ 【8†Up】 ]  | [ 【11†&gt;】 ]  | [ 【3†&gt;&gt;】 ]  |    |    |    |    | [【1†Top】]  | [【4†Contents】]  | [【5†Index】]  | [ 【6†?】 ]
L98: ## 9.3 Special Functions 【10†¶】
L99: 
L100: Certain functions, if defined, have special meaning to the shell.
L101: 
L102: * * *
L103: 
L104: [ 【8†&lt;&lt;】 ]  | [ 【10†&lt;】 ]  | [ 【10†Up】 ]  | [ 【12†&gt;】 ]  | [ 【3†&gt;&gt;】 ]  |    |    |    |    | [【1†Top】]  | [【4†Contents】]  | [【5†Index】]  | [ 【6†?】 ]
L105: ### 9.3.1 Hook Functions 【11†¶】
L106: For the functions below, it is possible to define an array that has the same name as the function with ‘`_functions`’ appended. Any element in such an array is taken as the name of a function to execute; it is executed in the same context and with the same arguments and same initial value of `$?` as the basic function.
L107: For example, if `$chpwd_functions` is an array containing the values ‘`mychpwd`’, ‘`chpwd_save_dirstack`’, then the shell attempts to execute the functions ‘`chpwd`’, ‘`mychpwd`’ and ‘`chpwd_save_dirstack`’, in that order. Any function that does not exist is silently ignored. A function found by this mechanism is referred to elsewhere as a hook function. An error in any function causes subsequent functions not to be run.
L108: Note further that an error in a `precmd` hook causes an immediately following `periodic` function not to run (though it may run at the next opportunity).
L109: `chpwd` 【13†¶】
L110: 
L111: 
L112: Executed whenever the current working directory is changed.
L113: 
L114: `periodic` 【14†¶】
L115: 
L116: 
L117: If the parameter `PERIOD` is set, this function is executed every `$PERIOD` seconds, just before a prompt. Note that if multiple functions are defined using the array `periodic_functions` only one period is applied to the complete set of functions, and the scheduled time is not reset if the list of functions is altered. Hence the set of functions is always called together.
L118: 
L119: `precmd` 【15†¶】
L120: Executed before each prompt. Note that precommand functions are not re-executed simply because the command line is redrawn, as happens, for example, when a notification about an exiting job is displayed.
L121: 
L122: `preexec` 【16†¶】
L123: Executed just after a command has been read and is about to be executed. If the history mechanism is active (regardless of whether the line was discarded from the history buffer), the string that the user typed is passed as the first argument, otherwise it is an empty string.
L124: The actual command that will be executed (including expanded aliases) is passed in two different forms: the second argument is a single-line, size-limited version of the command (with things like function bodies elided); the third argument contains the full text that is being executed.
L125: `zshaddhistory` 【17†¶】
L126: 
L127: 
L128: Executed when a history line has been read interactively, but before it is executed. The sole argument is the complete history line (so that any terminating newline will still be present).
L129: If any of the hook functions returns status 1 (or any non-zero value other than 2, though this is not guaranteed for future versions of the shell) the history line will not be saved, although it lingers in the history until the next line is executed, allowing you to reuse or edit it immediately.
L130: 
L131: If any of the hook functions returns status 2 the history line will be saved on the internal history list, but not written to the history file. In case of a conflict, the first non-zero status value is taken.
L132: A hook function may call ‘`fc -p` `...`’ to switch the history context so that the history is saved in a different file from that in the global `HISTFILE` parameter. This is handled specially: the history context is automatically restored after the processing of the history line is finished.
L133: The following example function works with one of the options `INC_APPEND_HISTORY` or `SHARE_HISTORY` set, in order that the line is written out immediately after the history entry is added. It first adds the history line to the normal history with the newline stripped, which is usually the correct behaviour. Then it switches the history context so that the line will be written to a history file in the current directory.
L134: 
L135:     zshaddhistory() {
L136:       print -sr -- ${1%%$&#39;\n&#39;}
L137:       fc -p .zsh_local_history
L138:     }
L139: `zshexit` 【18†¶】
L140: 
L141: 
L142: Executed at the point where the main shell is about to exit normally. This is not called by exiting subshells, nor when the `exec` precommand modifier is used before an external command. Also, unlike `TRAPEXIT`, it is not called when functions exit.
L143: 
L144: * * *
L145: 
L146: [ 【8†&lt;&lt;】 ]  | [ 【11†&lt;】 ]  | [ 【10†Up】 ]  | [ 【3†&gt;】 ]  | [ 【3†&gt;&gt;】 ]  |    |    |    |    | [【1†Top】]  | [【4†Contents】]  | [【5†Index】]  | [ 【6†?】 ]
L147: ### 9.3.2 Trap Functions 【12†¶】
L148: 
L149: The functions below are treated specially but do not have corresponding hook arrays.
L150: 
L151: `TRAP``NAL` 【19†¶】
L152: 
L153: 
L154: If defined and non-null, this function will be executed whenever the shell catches a signal `SIG``NAL`, where `NAL` is a signal name as specified for the `kill` builtin. The signal number will be passed as the first parameter to the function.
L155: 
L156: If a function of this form is defined and null, the shell and processes spawned by it will ignore `SIG``NAL`.
L157: The return status from the function is handled specially. If it is zero, the signal is assumed to have been handled, and execution continues normally. Otherwise, the shell will behave as interrupted except that the return status of the trap is retained.
L158: Programs terminated by uncaught signals typically return the status 128 plus the signal number. Hence the following causes the handler for `SIGINT` to print a message, then mimic the usual effect of the signal.
L159: 
L160:     TRAPINT() {
L161:       print &quot;Caught SIGINT, aborting.&quot;
L162:       return $(( 128 + $1 ))
L163:     }
L164: 
L165: 
L166: The functions `TRAPZERR`, `TRAPDEBUG` and `TRAPEXIT` are never executed inside other traps.
L167: 
L168: `TRAPDEBUG` 【20†¶】
L169: If the option `DEBUG_BEFORE_CMD` is set (as it is by default), executed before each command; otherwise executed after each command. See the description of the `trap` builtin in 【21†Shell Builtin Commands】 for details of additional features provided in debug traps.
L170: 
L171: `TRAPEXIT` 【22†¶】
L172: 
L173: 
L174: Executed when the shell exits, or when the current function exits if defined inside a function. The value of `$?` at the start of execution is the exit status of the shell or the return status of the function exiting.
L175: `TRAPZERR` 【23†¶】
L176: 
L177: 
L178: Executed whenever a command has a non-zero exit status. However, the function is not executed if the command occurred in a sublist followed by ‘`&amp;&amp;`’ or ‘`||`’; only the final command in a sublist of this type causes the trap to be executed. The function `TRAPERR` acts the same as `TRAPZERR` on systems where there is no `SIGERR` (this is the usual case).
L179: The functions beginning ‘`TRAP`’ may alternatively be defined with the `trap` builtin: this may be preferable for some uses. Setting a trap with one form removes any trap of the other form for the same signal; removing a trap in either form removes all traps for the same signal. The forms
L180: 
L181:     TRAPNAL() {
L182:      # code
L183:     }
L184: 
L185: 
L186: (’function traps’) and
L187: 
L188:     trap &#39;
L189:      # code
L190:     &#39; NAL
L191: 
L192: 
L193: (’list traps’) are equivalent in most ways, the exceptions being the following:
</excerpt>
</source>
<source kind="open_page">
<title>26 User Contributions (zsh)</title>
<location>https://zsh.sourceforge.io/Doc/Release/User-Contributions.html</location>
<excerpt>citeturn1view1 [wordlim: 200] Crawled: today; Content type: text/html; Source: open({&quot;ref_id&quot;:&quot;turn0search2&quot;,&quot;lineno&quot;:null}); Total lines: 3302
L138: `all`
L139: 
L140: 
L141: Output everything listed below.
L142: 
L143: `aliases`
L144: 
L145: 
L146: Output alias definitions.
L147: 
L148: `bindings`
L149: 
L150: 
L151: Output ZLE key maps and bindings.
L152: 
L153: `completion`
L154: 
L155: 
L156: Output old-style `compctl` commands. New completion is covered by `functions` and `zstyles`.
L157: 
L158: `functions`
L159: 
L160: 
L161: Output autoloads and function definitions.
L162: 
L163: `limits`
L164: 
L165: 
L166: Output `limit` commands.
L167: 
L168: `options`
L169: 
L170: 
L171: Output `setopt` commands.
L172: 
L173: `styles`
L174: 
L175: 
L176: Same as `zstyles`.
L177: 
L178: `variables`
L179: Output shell parameter assignments, plus `export` commands for any environment variables.
L180: 
L181: `zstyles`
L182: 
L183: 
L184: Output `zstyle` commands.
L185: 
L186: If the `state` is omitted, `all` is assumed.
L187: 
L188: With the exception of ‘`all`’, every `state` can be abbreviated by any prefix, even a single letter; thus `a` is the same as `aliases`, `z` is the same as `zstyles`, etc.
L189: 
L190: * * *
L191: 
L192: [ 【9†&lt;&lt;】 ]  | [ 【28†&lt;】 ]  | [ 【10†Up】 ]  | [ 【11†&gt;】 ]  | [ 【4†&gt;&gt;】 ]  |    |    |    |    | [【2†Top】]  | [【5†Contents】]  | [【6†Index】]  | [ 【7†?】 ]
L193: ### 26.2.5 Manipulating Hook Functions 【29†¶】
L194: 
L195: `add-zsh-hook` [ `-L` | `-dD` ] [ `-Uzk` ] `hook` `function` 【33†¶】
L196: Several functions are special to the shell, as described in the section Special Functions, 【34†Functions】, in that they are automatically called at specific points during shell execution. Each has an associated array consisting of names of functions to be called at the same point; these are so-called ‘hook functions’. The shell function `add-zsh-hook` provides a simple way of adding or removing functions from the array.
L197: `hook` is one of `chpwd`, `periodic`, `precmd`, `preexec`, `zshaddhistory`, `zshexit`, or `zsh_directory_name`, the special functions in question. Note that `zsh_directory_name` is called in a different way from the other functions, but may still be manipulated as a hook.
L198: 
L199: `function` is name of an ordinary shell function. If no options are given this will be added to the array of functions to be executed in the given context. Functions are invoked in the order they were added.
L200: If the option `-L` is given, the current values for the hook arrays are listed with `typeset`.
L201: 
L202: If the option `-d` is given, the `function` is removed from the array of functions to be executed.
L203: 
L204: If the option `-D` is given, the `function` is treated as a pattern and any matching names of functions are removed from the array of functions to be executed.
L205: The options `-U`, `-z` and `-k` are passed as arguments to `autoload` for `function`. For functions contributed with zsh, the options `-Uz` are appropriate.
L206: 
L207: `add-zle-hook-widget` [ `-L` | `-dD` ] [ `-Uzk` ] `hook` `widgetname` 【35†¶】
L208: Several widget names are special to the line editor, as described in the section Special Widgets, 【36†Zle Widgets】, in that they are automatically called at specific points during editing. Unlike function hooks, these do not use a predefined array of other names to call at the same point; the shell function `add-zle-hook-widget` maintains a similar array and arranges for the special widget to invoke those additional widgets.
L209: `hook` is one of `isearch-exit`, `isearch-update`, `line-pre-redraw`, `line-init`, `line-finish`, `history-line-set`, or `keymap-select`, corresponding to each of the special widgets `zle-isearch-exit`, etc. The special widget names are also accepted as the `hook` argument.
L210: `widgetname` is the name of a ZLE widget. If no options are given this is added to the array of widgets to be invoked in the given hook context. Widgets are invoked in the order they were added, with
L211: 
L212:     `zle ``widgetname`` -Nw -f &quot;nolast&quot; -- &quot;$@&quot;`
L213: 
L214: 
L215: Note that this means that the ‘`WIDGET`’ special parameter tracks the `widgetname` when the widget function is called, rather than tracking the name of the corresponding special hook widget.
L216: If the option `-d` is given, the `widgetname` is removed from the array of widgets to be executed.
L217: 
L218: If the option `-D` is given, the `widgetname` is treated as a pattern and any matching names of widgets are removed from the array.
L219: If `widgetname` does not name an existing widget when added to the array, it is assumed that a shell function also named `widgetname` is meant to provide the implementation of the widget. This name is therefore marked for autoloading, and the options `-U`, `-z` and `-k` are passed as arguments to `autoload` as with `add-zsh-hook`. The widget is also created with ‘`zle -N ``widgetname`’ to cause the corresponding function to be loaded the first time the hook is called.
L220: The arrays of `widgetname` are currently maintained in `zstyle` contexts, one for each `hook` context, with a style of ‘`widgets`’. If the `-L` option is given, this set of styles is listed with ‘`zstyle -L`’. This implementation may change, and the special widgets that refer to the styles are created only if `add-zle-hook-widget` is called to add at least one widget, so if this function is used for any hooks, then all hooks should be managed only via this function.
L221: 
L222: * * *
L223: [ 【9†&lt;&lt;】 ]  | [ 【29†&lt;】 ]  | [ 【9†Up】 ]  | [ 【37†&gt;】 ]  | [ 【4†&gt;&gt;】 ]  |    |    |    |    | [【2†Top】]  | [【5†Contents】]  | [【6†Index】]  | [ 【7†?】 ]
L224: ## 26.3 Remembering Recent Directories 【38†¶】
L225: The function `cdr` allows you to change the working directory to a previous working directory from a list maintained automatically. It is similar in concept to the directory stack controlled by the `pushd`, `popd` and `dirs` builtins, but is more configurable, and as it stores all entries in files it is maintained across sessions and (by default) between terminal emulators in the current session. Duplicates are automatically removed, so that the list reflects the single most recent use of each directory.
L226: Note that the `pushd` directory stack is not actually modified or used by `cdr` unless you configure it to do so as described in the configuration section below.
L227: 
L228: * * *
L229: 
L230: [ 【9†&lt;&lt;】 ]  | [ 【11†&lt;】 ]  | [ 【11†Up】 ]  | [ 【39†&gt;】 ]  | [ 【4†&gt;&gt;】 ]  |    |    |    |    | [【2†Top】]  | [【5†Contents】]  | [【6†Index】]  | [ 【7†?】 ]
L231: ### 26.3.1 Installation 【37†¶】
L232: 
L233: The system works by means of a hook function that is called every time the directory changes. To install the system, autoload the required functions and use the `add-zsh-hook` function described above:
L234: 
L235:     autoload -Uz chpwd_recent_dirs cdr add-zsh-hook
L236:     add-zsh-hook chpwd chpwd_recent_dirs
L237: 
L238: 
L239: Now every time you change directly interactively, no matter which command you use, the directory to which you change will be remembered in most-recent-first order.
L240: 
L241: * * *
</excerpt>
</source>
<source kind="search">
<title>9 Functions (zsh)</title>
<location>https://zsh.sourceforge.io/Doc/Release/Functions.html</location>
<excerpt>citeturn0search0 [wordlim: 200] Crawled: 3 months ago; A file of zsh command text, taken to be the definition for `function`. ... This will normally define the function in question, but may also perform initialization, which is executed in the context of the function execution, and may therefore define local parameters. ... For example, if `$chpwd_functions` is an array containing the values ‘`mychpwd`’, ‘`chpwd_save_dirstack`’, then the shell attempts to execute the functions ‘`chpwd`’, ‘`mychpwd`’ and ‘`chpwd_save_dirstack`’, in that order. ... Note further that an error in a `precmd` hook causes an immediately following `periodic` function not to run (though it may run at the next opportunity).

`chpwd` ¶
    

Executed whenever the current working directory is changed.

`periodic` ¶
    

If the parameter `PERIOD` is set, this function is executed every `$PERIOD` seconds, just before a prompt. Note that if multiple functions are defined using the array `periodic_functions` only one period is applied to the complete set of functions, and the scheduled time is not reset if the list of functions is altered. Hence the set of functions is always called together.

`precmd` ¶
    

Executed before each prompt. Note that precommand functions are not re-executed simply because the command line is redrawn, as happens, for example, when a notification about an exiting job is displayed.

`preexec` ¶
    

Executed just after a command has been read and is about to be executed. If the history mechanism is active (regardless of whether the line was discarded from the history buffer), the string that the user typed is passed as the first argument, otherwise it is an empty string. </excerpt>
</source>
<source kind="search">
<title>26 User Contributions (zsh)</title>
<location>https://zsh.sourceforge.io/Doc/Release/User-Contributions.html</location>
<excerpt>citeturn0search2 [wordlim: 200] Crawled: 3 months ago; The shell function `add-zsh-hook` provides a simple way of adding or removing functions from the array.

`hook` is one of `chpwd`, `periodic`, `precmd`, `preexec`, `zshaddhistory`, `zshexit`, or `zsh_directory_name`, the special functions in question. ... Functions are invoked in the order they were added.
</excerpt>
</source>
<source kind="search">
<title>The Z Shell Manual (zsh)</title>
<location>https://zsh.sourceforge.io/Doc/Release/index.html</location>
<excerpt>citeturn0search1 [wordlim: 200] Published: 3 months ago; Crawled: 3 months ago; This Info file documents Zsh, a freely available UNIX command interpreter (shell), which of the standard shells most closely resembles the Korn shell (ksh), although it is not completely compatible. ... 8 Command Execution  | ... 23 Calendar Function System  |
</excerpt>
</source>
<omitted_sources count="24">Additional source records were omitted from this bounded result.</omitted_sources>
</source_evidence>

Citations:

- 1: https://zsh.sourceforge.io/Doc/Release/Functions.html
- 2: https://zsh.sourceforge.io/Doc/Release/User-Contributions.html

Script executed:

set -o pipefail
printf '%s\n' '--- OSC 7 consumers ---'
rg -n -F --glob '*.ts' -e 'osc7' -e 'OSC 7' -e 'parseFileUriPath' -e 'wslDistro' src/main | head -240
printf '%s\n' '--- checkpoint and folder consumers ---'
rg -n -F --glob '*.ts' -e 'checkpoint' -e 'workingDirectory' -e 'cwd' src/main/daemon src/main/terminal src/main 2>/dev/null | grep -E 'osc|wsl|checkpoint|folder|workingDirectory|cwd' | head -260

Repository: stablyai/orca

Length of output: 41626


Script executed:

set -o pipefail
printf '%s\n' '--- OSC cwd scanner ---'
sed -n '1,180p' src/main/daemon/terminal-osc-cwd-title-scanner.ts
printf '%s\n' '--- scanner bindings ---'
rg -n -F --glob '*.ts' -e 'TerminalOscCwdTitleScanner' -e 'oscCwdTitleScanner' -e 'scanOsc' -e '.cwd =' src/main/daemon src/main/terminal
printf '%s\n' '--- WSL checkpoint test context ---'
sed -n '200,255p' src/main/daemon/daemon-pty-adapter-wsl-sleep-cwd.test.ts

Repository: stablyai/orca

Length of output: 5657


Script executed:

set -o pipefail
printf '%s\n' '--- headless emulator scanner and snapshot binding ---'
sed -n '50,105p' src/main/daemon/headless-emulator.ts
sed -n '300,365p' src/main/daemon/headless-emulator.ts
rg -n -F --glob '*.ts' -e 'oscText.cwd' -e 'getSnapshot()' -e 'snapshot.cwd' -e 'checkpoint(session' src/main/daemon | head -160
printf '%s\n' '--- changed zsh block with line numbers ---'
nl -ba src/main/zsh-startup-wrapper-builder.ts | sed -n '128,150p'
nl -ba src/main/wsl-shell-cwd-report.ts | sed -n '20,38p'

Repository: stablyai/orca

Length of output: 24027


Register the WSL reporter as a chpwd hook.

A user precmd hook can run after __orca_wsl_cwd_report and change directory. The reporter has already recorded and emitted the previous directory, and __orca_deferred_init has no later report. The emulator and subsequent checkpoint can therefore retain the previous directory until the next prompt.

Suggested fix
   builtin typeset -g precmd_functions
+  builtin typeset -g chpwd_functions
...
-    (( \${precmd_functions[(Ie)__orca_wsl_cwd_report]} )) || precmd_functions+=(__orca_wsl_cwd_report)
+    (( \${chpwd_functions[(Ie)__orca_wsl_cwd_report]} )) || chpwd_functions+=(__orca_wsl_cwd_report)

${joinBlocks([
spec.restores.managedWslCli ? indentBlock(WSL_MANAGED_CLI_PATH_RESTORE, ' ') : null,
indentBlock(ORCA_CLI_POSIX_PATH_RESTORE, ' ').replace(/\n$/, ''),
Expand Down Expand Up @@ -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
Expand Down
Loading