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
7 changes: 7 additions & 0 deletions src/main/agent-hooks/wsl-hook-relay-manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,13 @@ describe('WslHookRelayManager', () => {
return { manager: new WslHookRelayManager(deps), deps }
}

it('exposes the stable guest endpoint instance key with a port fallback', () => {
expect(createManager({}).manager.getInstanceKey()).toBe('testinstance')
expect(createManager({ instanceKey: () => 'unsafe/key' }).manager.getInstanceKey()).toBe(
'port43117'
)
})

it('starts one relay per distro, installs hooks, exposes the guest endpoint path, and forwards envelopes', async () => {
const { manager, deps } = createManager({})
manager.ensureForDistro('Ubuntu')
Expand Down
12 changes: 10 additions & 2 deletions src/main/agent-hooks/wsl-hook-relay-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,15 @@ export class WslHookRelayManager {
return this.stateFor(distro)?.opencodeOverlayDir ?? null
}

getInstanceKey(): string | null {
const stableKey = sanitizeWslHookInstanceKey(this.deps.instanceKey() ?? undefined)
if (stableKey) {
return stableKey
}
const port = Number(this.deps.hookCoordsEnv().ORCA_AGENT_HOOK_PORT ?? '')
return Number.isInteger(port) && port > 0 ? `port${port}` : null
}

/** Kills every live relay. Non-permanent (hooks switched off mid-session) leaves the
* manager reusable, so re-enabling hooks can start relays again without an app restart. */
disposeAll({ permanent = true }: { permanent?: boolean } = {}): void {
Expand Down Expand Up @@ -172,8 +181,7 @@ export class WslHookRelayManager {
}
// Why: restart-stable instance identity keeps the guest endpoint file at
// ONE path across restarts so daemon-surviving agents re-coordinate.
const instanceKey =
sanitizeWslHookInstanceKey(this.deps.instanceKey() ?? undefined) ?? `port${port}`
const instanceKey = this.getInstanceKey() ?? `port${port}`
if (existing) {
this.recovery.clearTimers(existing)
}
Expand Down
5 changes: 5 additions & 0 deletions src/main/daemon/shell-ready.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,8 @@ describePosix('daemon shell-ready launch config', () => {
'[[ -n "${ORCA_CODEX_HOME:-}" ]] && export CODEX_HOME="${ORCA_CODEX_HOME}"'
const agentTeamsPathRestoreLine = '[[ -n "${ORCA_AGENT_TEAMS_SHIM_DIR:-}" ]] || return 0'
const ompWrapperLine = 'command omp --extension "${ORCA_OMP_STATUS_EXTENSION}" "$@"'
const primeWrapperLine =
'command prime-agent --extension "${ORCA_PRIME_AGENT_STATUS_EXTENSION}" "$@"'
expect(zshrc).toContain(restoreLine)
expect(zlogin).toContain(restoreLine)
expect(bashRc).toContain(restoreLine)
Expand All @@ -625,6 +627,9 @@ describePosix('daemon shell-ready launch config', () => {
expect(zshrc).toContain(ompWrapperLine)
expect(zlogin).toContain(ompWrapperLine)
expect(bashRc).toContain(ompWrapperLine)
expect(zshrc).toContain(primeWrapperLine)
expect(zlogin).toContain(primeWrapperLine)
expect(bashRc).toContain(primeWrapperLine)
})

// Why: regression guard for issue #2422 — bash wrapper must emit OSC 133 C/D so SSH sessions clear stale 'working' agent rows.
Expand Down
4 changes: 4 additions & 0 deletions src/main/daemon/shell-ready.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
isPowerShellExecutableName
} from '../powershell-osc133-bootstrap'
import { getPosixOmpShellWrapper } from '../pty/omp-shell-wrapper'
import { getPosixPrimeAgentShellWrapper } from '../pty/prime-agent-shell-wrapper'
import {
getFishShellReadyInitCommand,
getZshEnvTemplate,
Expand Down Expand Up @@ -122,6 +123,7 @@ __orca_restore_agent_teams_path
[[ -n "\${ORCA_OPENCODE_CONFIG_DIR:-}" ]] && export OPENCODE_CONFIG_DIR="\${ORCA_OPENCODE_CONFIG_DIR}"
[[ -n "\${ORCA_MIMOCODE_HOME:-}" ]] && export MIMOCODE_HOME="\${ORCA_MIMOCODE_HOME}"
${getPosixOmpShellWrapper()}
${getPosixPrimeAgentShellWrapper()}
# Why: Codex must keep using Orca's runtime CODEX_HOME after profile scripts.
[[ -n "\${ORCA_CODEX_HOME:-}" ]] && export CODEX_HOME="\${ORCA_CODEX_HOME}"
# Why: emit OSC 133 C/D so terminal-command-lifecycle can drop stale agent
Expand Down Expand Up @@ -243,6 +245,7 @@ if [[ ! -o login ]]; then
[[ -n "\${ORCA_OPENCODE_CONFIG_DIR:-}" ]] && export OPENCODE_CONFIG_DIR="\${ORCA_OPENCODE_CONFIG_DIR}"
[[ -n "\${ORCA_MIMOCODE_HOME:-}" ]] && export MIMOCODE_HOME="\${ORCA_MIMOCODE_HOME}"
${getPosixOmpShellWrapper()}
${getPosixPrimeAgentShellWrapper()}
[[ -n "\${ORCA_CODEX_HOME:-}" ]] && export CODEX_HOME="\${ORCA_CODEX_HOME}"
fi
__orca_osc133_precmd() {
Expand Down Expand Up @@ -306,6 +309,7 @@ __orca_restore_agent_teams_path
[[ -n "\${ORCA_OPENCODE_CONFIG_DIR:-}" ]] && export OPENCODE_CONFIG_DIR="\${ORCA_OPENCODE_CONFIG_DIR}"
[[ -n "\${ORCA_MIMOCODE_HOME:-}" ]] && export MIMOCODE_HOME="\${ORCA_MIMOCODE_HOME}"
${getPosixOmpShellWrapper()}
${getPosixPrimeAgentShellWrapper()}
[[ -n "\${ORCA_CODEX_HOME:-}" ]] && export CODEX_HOME="\${ORCA_CODEX_HOME}"
${getZshShellReadyMarkerRegistrationBlock(SHELL_READY_MARKER)}
${getZshFinalZdotdirRestoreBlock()}
Expand Down
36 changes: 35 additions & 1 deletion src/main/ipc/pty.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ const {
clearAgentHookPaneStateMock,
registerPaneKeyAliasMock,
piBuildPtyEnvMock,
piBuildStatusOnlyPtyEnvMock,
piClearPtyMock,
isPwshAvailableMock,
trackMock,
Expand Down Expand Up @@ -91,6 +92,7 @@ const {
clearAgentHookPaneStateMock: vi.fn(),
registerPaneKeyAliasMock: vi.fn(),
piBuildPtyEnvMock: vi.fn(),
piBuildStatusOnlyPtyEnvMock: vi.fn(),
piClearPtyMock: vi.fn(),
trackMock: vi.fn(),
classifyErrorMock: vi.fn(),
Expand Down Expand Up @@ -175,6 +177,7 @@ vi.mock('../agent-hooks/server', () => ({
vi.mock('../pi/titlebar-extension-service', () => ({
piTitlebarExtensionService: {
buildPtyEnv: piBuildPtyEnvMock,
buildStatusOnlyPtyEnv: piBuildStatusOnlyPtyEnvMock,
clearPty: piClearPtyMock
}
}))
Expand Down Expand Up @@ -333,6 +336,7 @@ describe('registerPtyHandlers', () => {
const savedOrcaOmpStatusExtension = process.env.ORCA_OMP_STATUS_EXTENSION
const savedPrimeAgentDir = process.env.PRIME_AGENT_CODING_AGENT_DIR
const savedOrcaPrimeAgentSourceDir = process.env.ORCA_PRIME_AGENT_SOURCE_AGENT_DIR
const savedOrcaPrimeAgentStatusExtension = process.env.ORCA_PRIME_AGENT_STATUS_EXTENSION
const savedOrcaClaudeAgentStatusSettings = process.env.ORCA_CLAUDE_AGENT_STATUS_SETTINGS
const savedProcessPlatform = Object.getOwnPropertyDescriptor(process, 'platform')
const savedDisableMacosLoginShell = process.env.ORCA_DISABLE_MACOS_LOGIN_SHELL
Expand Down Expand Up @@ -360,6 +364,7 @@ describe('registerPtyHandlers', () => {
delete process.env.ORCA_OMP_STATUS_EXTENSION
delete process.env.PRIME_AGENT_CODING_AGENT_DIR
delete process.env.ORCA_PRIME_AGENT_SOURCE_AGENT_DIR
delete process.env.ORCA_PRIME_AGENT_STATUS_EXTENSION
handlers.clear()
handleMock.mockReset()
onMock.mockReset()
Expand All @@ -382,6 +387,7 @@ describe('registerPtyHandlers', () => {
clearAgentHookPaneStateMock.mockReset()
registerPaneKeyAliasMock.mockReset()
piBuildPtyEnvMock.mockReset()
piBuildStatusOnlyPtyEnvMock.mockReset()
piClearPtyMock.mockReset()
isPwshAvailableMock.mockReset()
trackMock.mockReset()
Expand Down Expand Up @@ -481,6 +487,10 @@ describe('registerPtyHandlers', () => {
}
}
)
piBuildStatusOnlyPtyEnvMock.mockReturnValue({
ORCA_PRIME_AGENT_STATUS_EXTENSION:
'C:\\Users\\test\\AppData\\Roaming\\Orca\\prime-agent-managed-status-extension\\orca-agent-status.ts'
})
isPwshAvailableMock.mockReturnValue(false)
spawnMock.mockReturnValue({
onData: vi.fn(() => makeDisposable()),
Expand Down Expand Up @@ -586,6 +596,11 @@ describe('registerPtyHandlers', () => {
} else {
delete process.env.ORCA_PRIME_AGENT_SOURCE_AGENT_DIR
}
if (savedOrcaPrimeAgentStatusExtension !== undefined) {
process.env.ORCA_PRIME_AGENT_STATUS_EXTENSION = savedOrcaPrimeAgentStatusExtension
} else {
delete process.env.ORCA_PRIME_AGENT_STATUS_EXTENSION
}
if (savedOrcaClaudeAgentStatusSettings === undefined) {
delete process.env.ORCA_CLAUDE_AGENT_STATUS_SETTINGS
} else {
Expand Down Expand Up @@ -4196,7 +4211,7 @@ describe('registerPtyHandlers', () => {
})
})

it('does not materialize Windows-host Prime extensions for a WSL launch', async () => {
it('bridges a host-managed Prime status extension into WSL without redirecting Prime home', async () => {
await withWin32Platform(async () => {
const env = await daemonSpawnAndGetEnv(
{ PRIME_AGENT_CODING_AGENT_DIR: 'C:\\Users\\test\\.prime\\agent' },
Expand All @@ -4207,11 +4222,30 @@ describe('registerPtyHandlers', () => {
)

expect(piBuildPtyEnvMock).not.toHaveBeenCalled()
expect(piBuildStatusOnlyPtyEnvMock).toHaveBeenCalledWith('prime-agent')
expect(env.ORCA_PRIME_AGENT_SOURCE_AGENT_DIR).toBeUndefined()
expect(env.ORCA_PRIME_AGENT_STATUS_EXTENSION).toBe(
'C:\\Users\\test\\AppData\\Roaming\\Orca\\prime-agent-managed-status-extension\\orca-agent-status.ts'
)
expect(env.ORCA_WSL_HOOK_INSTANCE).toBe('port5678')
expect(env.PRIME_AGENT_CODING_AGENT_DIR).toBe('C:\\Users\\test\\.prime\\agent')
})
})

it('prepares the Prime bridge for a typed launch in a bare WSL shell', async () => {
await withWin32Platform(async () => {
const env = await daemonSpawnAndGetEnv({}, undefined, undefined, undefined, {
shellOverride: 'wsl.exe'
})

expect(piBuildStatusOnlyPtyEnvMock).toHaveBeenCalledWith('prime-agent')
expect(env.ORCA_PRIME_AGENT_STATUS_EXTENSION).toContain(
'prime-agent-managed-status-extension'
)
expect(env.PRIME_AGENT_CODING_AGENT_DIR).toBeUndefined()
})
})

it('points OPENCODE_CONFIG_DIR at the guest overlay when the WSL relay reports it', async () => {
const guestDir = '/home/jin/.orca-relay/opencode-overlays/abc'
const spy = vi.spyOn(wslHookRelayManager, 'getOpenCodeOverlayDir').mockReturnValue(guestDir)
Expand Down
30 changes: 23 additions & 7 deletions src/main/ipc/pty.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1513,6 +1513,7 @@ function clearPiAgentShadowEnv(baseEnv: Record<string, string>, kind: PiAgentKin
}
if (kind === 'prime-agent') {
delete baseEnv.ORCA_PRIME_AGENT_SOURCE_AGENT_DIR
delete baseEnv.ORCA_PRIME_AGENT_STATUS_EXTENSION
return
}
delete baseEnv.ORCA_PI_CODING_AGENT_DIR
Expand Down Expand Up @@ -1544,6 +1545,11 @@ function exposePiManagedExtensionEnv(
} else {
delete baseEnv.ORCA_PRIME_AGENT_SOURCE_AGENT_DIR
}
if (managedEnv.ORCA_PRIME_AGENT_STATUS_EXTENSION) {
baseEnv.ORCA_PRIME_AGENT_STATUS_EXTENSION = managedEnv.ORCA_PRIME_AGENT_STATUS_EXTENSION
} else {
delete baseEnv.ORCA_PRIME_AGENT_STATUS_EXTENSION
}
return
}
delete baseEnv.ORCA_PI_CODING_AGENT_DIR
Expand Down Expand Up @@ -1686,6 +1692,8 @@ export function buildPtyHostEnv(
})

const shouldPrepareOmpShadow = piAgentKind === 'omp' || !hasLaunchCommand
const shouldPreparePrimeStatus =
piAgentKind === 'prime-agent' || (opts.isWsl && !hasLaunchCommand)
// Why: source shadows are agent-scoped; trusting the other kind's source reintroduces Pi/OMP extension-state shadowing.
const preexistingPiAgentDir = resolvePiAgentSourceDir(baseEnv, 'pi')
const preexistingOmpAgentDir =
Expand Down Expand Up @@ -1744,6 +1752,12 @@ export function buildPtyHostEnv(
if (opts.isWsl === true) {
// Why: hook POSTs to 127.0.0.1 die inside WSL's NAT namespace; use the guest-resident relay's endpoint instead of the Windows one.
const distro = opts.wslDistro ?? null
const hookInstance = wslHookRelayManager.getInstanceKey()
if (hookInstance) {
baseEnv.ORCA_WSL_HOOK_INSTANCE = hookInstance
} else {
delete baseEnv.ORCA_WSL_HOOK_INSTANCE
}
wslHookRelayManager.ensureForDistro(distro)
const guestEndpoint = wslHookRelayManager.getGuestEndpointFilePath(distro)
if (guestEndpoint) {
Expand Down Expand Up @@ -1790,13 +1804,14 @@ export function buildPtyHostEnv(
exposePiManagedExtensionEnv(baseEnv, 'omp', ompEnv)
}

if (piAgentKind === 'prime-agent' && !opts.isWsl) {
const primeEnv = piTitlebarExtensionService.buildPtyEnv(
id,
preexistingPrimeAgentDir,
'prime-agent',
{ materializeDefaultHome: explicitPiAgentKind === 'prime-agent' }
)
if (shouldPreparePrimeStatus) {
// Why: the Windows host cannot safely resolve or write Prime's guest
// config root; WSL loads the host-managed status file explicitly.
const primeEnv = opts.isWsl
? piTitlebarExtensionService.buildStatusOnlyPtyEnv('prime-agent')
: piTitlebarExtensionService.buildPtyEnv(id, preexistingPrimeAgentDir, 'prime-agent', {
materializeDefaultHome: explicitPiAgentKind === 'prime-agent'
})
Object.assign(baseEnv, primeEnv)
exposePiManagedExtensionEnv(baseEnv, 'prime-agent', primeEnv)
}
Expand All @@ -1814,6 +1829,7 @@ export function buildPtyHostEnv(
})
delete baseEnv.ORCA_OMP_STATUS_EXTENSION
delete baseEnv.ORCA_PRIME_AGENT_SOURCE_AGENT_DIR
delete baseEnv.ORCA_PRIME_AGENT_STATUS_EXTENSION
}

// Why: keep the Codex home override PTY-scoped so dev/prod Orcas don't share hooks through ~/.codex.
Expand Down
33 changes: 33 additions & 0 deletions src/main/pi/agent-status-extension-source.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ type Harness = {
fsMock: {
existsSync: ReturnType<typeof vi.fn>
readFileSync: ReturnType<typeof vi.fn>
statSync: ReturnType<typeof vi.fn>
}
handlers: Record<string, HookHandler>
processEnv: Record<string, string | undefined>
Expand Down Expand Up @@ -62,6 +63,7 @@ function createHarness(args: {
argv?: string[]
existsSync?: (path: string) => boolean
readFileSync?: (path: string, encoding: string) => string
statSync?: (path: string) => { mtimeMs: number; size: number; ino: number }
fetchImpl?: (...params: Parameters<typeof fetch>) => Promise<unknown>
}): Harness {
const fetchMock = vi.fn(
Expand All @@ -86,6 +88,12 @@ function createHarness(args: {

const fsMock = {
existsSync: vi.fn(args.existsSync ?? (() => false)),
statSync: vi.fn(
args.statSync ??
((path: string) => {
throw Object.assign(new Error(`ENOENT: ${path}`), { code: 'ENOENT' })
})
),
readFileSync: vi.fn(
args.readFileSync ??
((path: string) => {
Expand Down Expand Up @@ -562,6 +570,31 @@ describe('getPiAgentStatusExtensionSource', () => {
)
})

it('uses current Windows coordinates when a same-token guest endpoint is stale', async () => {
const endpointPath = '/home/u/.orca-wsl/agent-hooks/instance-test/endpoint.env'
const harness = createHarness({
kind: 'prime-agent',
env: { WSL_DISTRO_NAME: 'Ubuntu', ORCA_AGENT_HOOK_ENDPOINT: endpointPath },
existsSync: (path) => path === '/mnt/c/Windows/System32/curl.exe',
statSync: () => ({ mtimeMs: 1, size: 80, ino: 1 }),
readFileSync: (path) => {
if (path === endpointPath) {
return 'ORCA_AGENT_HOOK_PORT=9999\nORCA_AGENT_HOOK_TOKEN=token-1\n'
}
throw Object.assign(new Error(`ENOENT: ${path}`), { code: 'ENOENT' })
},
fetchImpl: vi.fn(async () => {
throw new Error('stale guest relay')
})
})

await harness.callHook('agent_start')

expect(harness.fetchMock.mock.calls[0]?.[0]).toBe('http://127.0.0.1:9999/hook/prime-agent')
await vi.waitFor(() => expect(harness.spawnMock).toHaveBeenCalledTimes(1))
expect(harness.spawnMock.mock.calls[0]?.[1]).toContain('http://127.0.0.1:4321/hook/prime-agent')
})

it('probes WSL evidence and the curl path once per process', async () => {
const harness = createHarness({
kind: 'omp',
Expand Down
Loading
Loading