diff --git a/src/main/ipc/pty.test.ts b/src/main/ipc/pty.test.ts index 59b69ea25..c0798fe39 100644 --- a/src/main/ipc/pty.test.ts +++ b/src/main/ipc/pty.test.ts @@ -17,9 +17,10 @@ import { PtyWriteUnavailableError } from '../providers/pty-write-unavailable-err const isWindowsHost = process.platform === 'win32' const posixOnlyIt = isWindowsHost ? it.skip : it +// Why: bare shells no longer mkdir ~/.omp; OMP status lives under userData (#10196). const expectedOmpStatusExtension = posix.join( - '/tmp/default-omp-agent', - 'extensions', + '/tmp/orca-user-data', + 'omp-managed-status-extension', 'orca-agent-status.ts' ) function expectedAttributionShimDir(): string { @@ -418,15 +419,33 @@ describe('registerPtyHandlers', () => { ORCA_AGENT_HOOK_TOKEN: 'agent-token' }) piBuildPtyEnvMock.mockImplementation( - (_ptyId: string, existingAgentDir?: string, kind?: string) => - kind === 'omp' - ? { - ORCA_OMP_SOURCE_AGENT_DIR: existingAgentDir ?? '/tmp/default-omp-agent', - ORCA_OMP_STATUS_EXTENSION: `${existingAgentDir ?? '/tmp/default-omp-agent'}/extensions/orca-agent-status.ts` - } - : { - ORCA_PI_SOURCE_AGENT_DIR: existingAgentDir ?? '/tmp/default-pi-agent' + ( + _ptyId: string, + existingAgentDir?: string, + kind?: string, + options?: { materializeDefaultHome?: boolean } + ) => { + const materializeDefaultHome = options?.materializeDefaultHome !== false + if (kind === 'omp') { + // Why: bare shells no longer create ~/.omp; only a userData status path is set (#10196). + if (!existingAgentDir && !materializeDefaultHome) { + return { + ORCA_OMP_STATUS_EXTENSION: + '/tmp/orca-user-data/omp-managed-status-extension/orca-agent-status.ts' } + } + return { + ORCA_OMP_SOURCE_AGENT_DIR: existingAgentDir ?? '/tmp/default-omp-agent', + ORCA_OMP_STATUS_EXTENSION: `${existingAgentDir ?? '/tmp/default-omp-agent'}/extensions/orca-agent-status.ts` + } + } + if (!existingAgentDir && !materializeDefaultHome) { + return {} + } + return { + ORCA_PI_SOURCE_AGENT_DIR: existingAgentDir ?? '/tmp/default-pi-agent' + } + } ) isPwshAvailableMock.mockReturnValue(false) spawnMock.mockReturnValue({ @@ -2430,15 +2449,58 @@ describe('registerPtyHandlers', () => { it('installs Pi managed extensions without redirecting Orca terminal PTY homes', async () => { const env = await spawnAndGetEnv(undefined, { PI_CODING_AGENT_DIR: '/tmp/user-pi-agent' }) - expect(piBuildPtyEnvMock).toHaveBeenCalledWith(expect.any(String), '/tmp/user-pi-agent', 'pi') - expect(piBuildPtyEnvMock).toHaveBeenCalledWith(expect.any(String), undefined, 'omp') + expect(piBuildPtyEnvMock).toHaveBeenCalledWith( + expect.any(String), + '/tmp/user-pi-agent', + 'pi', + { + materializeDefaultHome: false + } + ) + expect(piBuildPtyEnvMock).toHaveBeenCalledWith(expect.any(String), undefined, 'omp', { + materializeDefaultHome: false + }) expect(env.PI_CODING_AGENT_DIR).toBe('/tmp/user-pi-agent') expect(env.ORCA_PI_CODING_AGENT_DIR).toBeUndefined() expect(env.ORCA_PI_SOURCE_AGENT_DIR).toBe('/tmp/user-pi-agent') expect(env.ORCA_OMP_CODING_AGENT_DIR).toBeUndefined() expect(env.ORCA_OMP_STATUS_EXTENSION).toBe( - '/tmp/default-omp-agent/extensions/orca-agent-status.ts' + '/tmp/orca-user-data/omp-managed-status-extension/orca-agent-status.ts' ) + expect(env.ORCA_OMP_SOURCE_AGENT_DIR).toBeUndefined() + }) + + it('does not materialize a missing Pi home when another agent mentions Pi', async () => { + const env = await spawnAndGetEnv( + undefined, + undefined, + undefined, + undefined, + 'codex "ask about pi"', + 'codex' + ) + + expect(piBuildPtyEnvMock).toHaveBeenCalledTimes(1) + expect(piBuildPtyEnvMock).toHaveBeenCalledWith(expect.any(String), undefined, 'pi', { + materializeDefaultHome: false + }) + expect(env.ORCA_PI_SOURCE_AGENT_DIR).toBeUndefined() + }) + + it('materializes Pi home for an explicit Pi launch through a custom command', async () => { + const env = await spawnAndGetEnv( + undefined, + undefined, + undefined, + undefined, + 'custom-pi-wrapper', + 'pi' + ) + + expect(piBuildPtyEnvMock).toHaveBeenCalledWith(expect.any(String), undefined, 'pi', { + materializeDefaultHome: true + }) + expect(env.ORCA_PI_SOURCE_AGENT_DIR).toBe('/tmp/default-pi-agent') }) it('threads command: "omp" through to piBuildPtyEnv and emits OMP status metadata', async () => { @@ -2453,7 +2515,8 @@ describe('registerPtyHandlers', () => { expect(piBuildPtyEnvMock).toHaveBeenCalledWith( expect.any(String), '/tmp/user-omp-agent', - 'omp' + 'omp', + { materializeDefaultHome: true } ) expect(env.PI_CODING_AGENT_DIR).toBe('/tmp/user-omp-agent') expect(env.ORCA_OMP_CODING_AGENT_DIR).toBeUndefined() @@ -2481,7 +2544,8 @@ describe('registerPtyHandlers', () => { expect(piBuildPtyEnvMock).toHaveBeenCalledWith( expect.any(String), '/tmp/user-omp-agent', - 'omp' + 'omp', + { materializeDefaultHome: true } ) expect(env.ORCA_OMP_STATUS_EXTENSION).toBe( '/tmp/user-omp-agent/extensions/orca-agent-status.ts' @@ -2494,7 +2558,14 @@ describe('registerPtyHandlers', () => { PI_CODING_AGENT_DIR: '/tmp/parent-orca-pi-overlay', ORCA_PI_SOURCE_AGENT_DIR: '/tmp/user-pi-agent' }) - expect(piBuildPtyEnvMock).toHaveBeenCalledWith(expect.any(String), '/tmp/user-pi-agent', 'pi') + expect(piBuildPtyEnvMock).toHaveBeenCalledWith( + expect.any(String), + '/tmp/user-pi-agent', + 'pi', + { + materializeDefaultHome: false + } + ) expect(env.PI_CODING_AGENT_DIR).toBe('/tmp/parent-orca-pi-overlay') expect(env.ORCA_PI_CODING_AGENT_DIR).toBeUndefined() expect(env.ORCA_PI_SOURCE_AGENT_DIR).toBe('/tmp/user-pi-agent') @@ -2513,7 +2584,9 @@ describe('registerPtyHandlers', () => { 'omp' ) - expect(piBuildPtyEnvMock).toHaveBeenCalledWith(expect.any(String), undefined, 'omp') + expect(piBuildPtyEnvMock).toHaveBeenCalledWith(expect.any(String), undefined, 'omp', { + materializeDefaultHome: true + }) expect(env.ORCA_OMP_CODING_AGENT_DIR).toBeUndefined() expect(env.ORCA_OMP_SOURCE_AGENT_DIR).toBe('/tmp/default-omp-agent') expect(env.ORCA_PI_CODING_AGENT_DIR).toBeUndefined() @@ -2533,7 +2606,9 @@ describe('registerPtyHandlers', () => { 'pi' ) - expect(piBuildPtyEnvMock).toHaveBeenCalledWith(expect.any(String), undefined, 'pi') + expect(piBuildPtyEnvMock).toHaveBeenCalledWith(expect.any(String), undefined, 'pi', { + materializeDefaultHome: true + }) expect(env.ORCA_PI_CODING_AGENT_DIR).toBeUndefined() expect(env.ORCA_PI_SOURCE_AGENT_DIR).toBe('/tmp/default-pi-agent') expect(env.ORCA_OMP_CODING_AGENT_DIR).toBeUndefined() @@ -2575,7 +2650,8 @@ describe('registerPtyHandlers', () => { expect(piBuildPtyEnvMock).toHaveBeenCalledWith( expect.any(String), '/home/tester/.config/pi-agent', - 'pi' + 'pi', + { materializeDefaultHome: false } ) expect(env.PI_CODING_AGENT_DIR).toBeUndefined() expect(env.ORCA_PI_CODING_AGENT_DIR).toBeUndefined() @@ -2977,8 +3053,17 @@ describe('registerPtyHandlers', () => { it('installs Pi managed extensions without redirecting homes on the daemon path', async () => { const env = await daemonSpawnAndGetEnv({ PI_CODING_AGENT_DIR: '/user/.pi/agent' }) - expect(piBuildPtyEnvMock).toHaveBeenCalledWith(expect.any(String), '/user/.pi/agent', 'pi') - expect(piBuildPtyEnvMock).toHaveBeenCalledWith(expect.any(String), undefined, 'omp') + expect(piBuildPtyEnvMock).toHaveBeenCalledWith( + expect.any(String), + '/user/.pi/agent', + 'pi', + { + materializeDefaultHome: false + } + ) + expect(piBuildPtyEnvMock).toHaveBeenCalledWith(expect.any(String), undefined, 'omp', { + materializeDefaultHome: false + }) expect(env.PI_CODING_AGENT_DIR).toBe('/user/.pi/agent') expect(env.ORCA_PI_CODING_AGENT_DIR).toBeUndefined() expect(env.ORCA_PI_SOURCE_AGENT_DIR).toBe('/user/.pi/agent') @@ -2986,6 +3071,19 @@ describe('registerPtyHandlers', () => { expect(env.ORCA_OMP_STATUS_EXTENSION).toBe(expectedOmpStatusExtension) }) + it('does not materialize agent homes when another daemon agent mentions OMP', async () => { + const env = await daemonSpawnAndGetEnv(undefined, undefined, undefined, undefined, { + command: 'codex "ask about omp"', + launchAgent: 'codex' + }) + + expect(piBuildPtyEnvMock).toHaveBeenCalledTimes(1) + expect(piBuildPtyEnvMock).toHaveBeenCalledWith(expect.any(String), undefined, 'pi', { + materializeDefaultHome: false + }) + expect(env.ORCA_PI_SOURCE_AGENT_DIR).toBeUndefined() + }) + it('threads command: "omp" through to piBuildPtyEnv on the daemon path with OMP status metadata', async () => { // Why: mirror of the local-spawn OMP threading assertion; the daemon path's `command` forwarding could silently regress otherwise. const env = await daemonSpawnAndGetEnv( @@ -2998,7 +3096,8 @@ describe('registerPtyHandlers', () => { expect(piBuildPtyEnvMock).toHaveBeenCalledWith( expect.any(String), '/user/.omp/agent', - 'omp' + 'omp', + { materializeDefaultHome: true } ) expect(env.PI_CODING_AGENT_DIR).toBe('/user/.omp/agent') expect(env.ORCA_OMP_CODING_AGENT_DIR).toBeUndefined() @@ -3025,7 +3124,8 @@ describe('registerPtyHandlers', () => { expect(piBuildPtyEnvMock).toHaveBeenCalledWith( expect.any(String), '/user/.omp/agent', - 'omp' + 'omp', + { materializeDefaultHome: true } ) expect(env.ORCA_OMP_STATUS_EXTENSION).toBe( '/user/.omp/agent/extensions/orca-agent-status.ts' @@ -3966,7 +4066,9 @@ describe('registerPtyHandlers', () => { expect(sessionId).toEqual(expect.any(String)) expect((sessionId ?? '').length).toBeGreaterThan(0) expect(spawnOpts.isNewSession).toBe(true) - expect(piBuildPtyEnvMock).toHaveBeenCalledWith(sessionId, undefined, 'pi') + expect(piBuildPtyEnvMock).toHaveBeenCalledWith(sessionId, undefined, 'pi', { + materializeDefaultHome: false + }) }) it('respects a caller-provided sessionId instead of minting a new one', async () => { @@ -3981,7 +4083,9 @@ describe('registerPtyHandlers', () => { }) expect(daemonSpawn.mock.calls.at(-1)![0].sessionId).toBe('user-session-42') expect(daemonSpawn.mock.calls.at(-1)![0].isNewSession).toBeUndefined() - expect(piBuildPtyEnvMock).toHaveBeenCalledWith('user-session-42', undefined, 'pi') + expect(piBuildPtyEnvMock).toHaveBeenCalledWith('user-session-42', undefined, 'pi', { + materializeDefaultHome: false + }) }) it('prefixes a minted sessionId with the worktreeId when provided', async () => { @@ -3997,7 +4101,9 @@ describe('registerPtyHandlers', () => { }) const sessionId = daemonSpawn.mock.calls.at(-1)![0].sessionId ?? '' expect(sessionId).toMatch(/^wt-alpha@@[0-9a-f]{8}$/) - expect(piBuildPtyEnvMock).toHaveBeenCalledWith(sessionId, undefined, 'pi') + expect(piBuildPtyEnvMock).toHaveBeenCalledWith(sessionId, undefined, 'pi', { + materializeDefaultHome: false + }) }) it('reuses one attach-style daemon session for fresh-agent operation retries', async () => { @@ -4076,7 +4182,8 @@ describe('registerPtyHandlers', () => { expect(piBuildPtyEnvMock).toHaveBeenCalledWith( expect.any(String), '/ambient/pi/agent', - 'pi' + 'pi', + { materializeDefaultHome: false } ) expect(env.PI_CODING_AGENT_DIR).toBeUndefined() expect(env.ORCA_PI_CODING_AGENT_DIR).toBeUndefined() @@ -8862,11 +8969,14 @@ describe('registerPtyHandlers', () => { 'ORCA_CLI_COMMAND/u', 'ORCA_AGENT_HOOK_PORT/u', 'ORCA_AGENT_HOOK_TOKEN/u', - 'ORCA_OMP_SOURCE_AGENT_DIR/p', + // Why: bare WSL shells no longer create ~/.omp; only status extension is exported (#10196). 'ORCA_OMP_STATUS_EXTENSION/p', 'POWERLEVEL9K_DISABLE_CONFIGURATION_WIZARD' ]) ) + expect(env.WSLENV?.split(':')).not.toEqual( + expect.arrayContaining(['ORCA_OMP_SOURCE_AGENT_DIR/p']) + ) }) it('forces managed ORCA_USER_DATA_PATH for WSL spawns even when the caller provides a stale root', async () => { diff --git a/src/main/ipc/pty.ts b/src/main/ipc/pty.ts index ad0b68cda..bf17fc0a0 100644 --- a/src/main/ipc/pty.ts +++ b/src/main/ipc/pty.ts @@ -59,7 +59,11 @@ import { agentHookServer } from '../agent-hooks/server' import { wslHookRelayManager } from '../agent-hooks/wsl-hook-relay-manager' import { isAgentStatusHooksEnabled } from '../agent-hooks/managed-agent-hook-controls' import { piTitlebarExtensionService } from '../pi/titlebar-extension-service' -import { detectPiAgentKindFromCommand, type PiAgentKind } from '../../shared/pi-agent-kind' +import { + detectExplicitPiAgentKindFromCommand, + isPiCompatibleAgentType, + type PiAgentKind +} from '../../shared/pi-agent-kind' import { isPwshAvailable } from '../pwsh' import { LocalPtyProvider } from '../providers/local-pty-provider' import type { IPtyProvider, PtySpawnOptions, PtySpawnResult } from '../providers/types' @@ -1089,7 +1093,12 @@ export function buildPtyHostEnv( // Why: local path's baseEnv includes process.env but the daemon path doesn't (fork inheritance, not IPC); check both sources so guards stay in lock-step across spawn paths. const preexistingOpenCodeConfigDir = resolveOpenCodeSourceConfigDir(baseEnv) const launchCommandHint = resolveSetupAgentSequenceLaunchCommand(baseEnv, opts.launchCommand) - const piAgentKind = detectPiAgentKindFromCommand(launchCommandHint) + const explicitPiAgentKind = isPiCompatibleAgentType(opts.launchAgent) + ? opts.launchAgent + : opts.launchAgent === undefined + ? detectExplicitPiAgentKindFromCommand(launchCommandHint) + : null + const piAgentKind = explicitPiAgentKind ?? 'pi' const hasLaunchCommand = typeof launchCommandHint === 'string' && launchCommandHint.trim().length > 0 @@ -1179,14 +1188,23 @@ export function buildPtyHostEnv( if (opts.agentStatusHooksEnabled) { clearPiAgentShadowEnv(baseEnv, 'pi') clearPiAgentShadowEnv(baseEnv, 'omp') + // Why: bare shells historically defaulted to Pi + OMP shadow prep and + // created ~/./agent even when the user never launches those agents + // (#10196). Only create default homes on an explicit Pi/OMP launch; + // otherwise install only into an existing agent dir (or userData for OMP + // status so a typed `omp` still gets the shell wrapper extension). if (piAgentKind === 'pi') { - const piEnv = piTitlebarExtensionService.buildPtyEnv(id, preexistingPiAgentDir, 'pi') + const piEnv = piTitlebarExtensionService.buildPtyEnv(id, preexistingPiAgentDir, 'pi', { + materializeDefaultHome: explicitPiAgentKind === 'pi' + }) Object.assign(baseEnv, piEnv) exposePiManagedExtensionEnv(baseEnv, 'pi', piEnv) } if (shouldPrepareOmpShadow) { - const ompEnv = piTitlebarExtensionService.buildPtyEnv(id, preexistingOmpAgentDir, 'omp') + const ompEnv = piTitlebarExtensionService.buildPtyEnv(id, preexistingOmpAgentDir, 'omp', { + materializeDefaultHome: explicitPiAgentKind === 'omp' + }) Object.assign(baseEnv, ompEnv) exposePiManagedExtensionEnv(baseEnv, 'omp', ompEnv) } diff --git a/src/main/pi/titlebar-extension-service.test.ts b/src/main/pi/titlebar-extension-service.test.ts index 7516f04da..43af655aa 100644 --- a/src/main/pi/titlebar-extension-service.test.ts +++ b/src/main/pi/titlebar-extension-service.test.ts @@ -643,6 +643,35 @@ describe('PiTitlebarExtensionService', () => { rmSync(fakeHome, { recursive: true, force: true }) } }) + + it('bare-shell prep does not create missing ~/.pi or ~/.omp homes (#10196)', () => { + const fakeHome = mkdtempSync(join(tmpdir(), 'orca-no-eager-agent-home-')) + expect(existsSync(join(fakeHome, '.pi'))).toBe(false) + expect(existsSync(join(fakeHome, '.omp'))).toBe(false) + + homedirOverride.current = fakeHome + try { + const svc = new PiTitlebarExtensionService() + const piEnv = svc.buildPtyEnv('pty-bare-pi', undefined, 'pi', { + materializeDefaultHome: false + }) + const ompEnv = svc.buildPtyEnv('pty-bare-omp', undefined, 'omp', { + materializeDefaultHome: false + }) + + expect(piEnv).toEqual({}) + expect(existsSync(join(fakeHome, '.pi'))).toBe(false) + expect(existsSync(join(fakeHome, '.omp'))).toBe(false) + expect(ompEnv.ORCA_OMP_SOURCE_AGENT_DIR).toBeUndefined() + expect(ompEnv.ORCA_OMP_STATUS_EXTENSION).toEqual( + expect.stringContaining('omp-managed-status-extension') + ) + expect(existsSync(ompEnv.ORCA_OMP_STATUS_EXTENSION!)).toBe(true) + } finally { + homedirOverride.current = '' + rmSync(fakeHome, { recursive: true, force: true }) + } + }) }) describe('isSafeDescendCandidate (Windows junction regression guard)', () => { diff --git a/src/main/pi/titlebar-extension-service.ts b/src/main/pi/titlebar-extension-service.ts index 37d030b5e..538d0a0be 100644 --- a/src/main/pi/titlebar-extension-service.ts +++ b/src/main/pi/titlebar-extension-service.ts @@ -169,7 +169,8 @@ export class PiTitlebarExtensionService { buildPtyEnv( ptyId: string, existingAgentDir: string | undefined, - kind: PiAgentKind + kind: PiAgentKind, + options?: { materializeDefaultHome?: boolean } ): Record { const sourceAgentDir = existingAgentDir || getDefaultPiAgentDir(kind) try { @@ -180,6 +181,20 @@ export class PiTitlebarExtensionService { // directory should not prevent the terminal from starting. } + // Why: bare shells used to mkdir ~/./agent for every terminal so a + // later typed `pi`/`omp` got hooks. That recreates deleted unused agent + // homes on every open (#10196). Only materialize the default home when the + // caller opts in (explicit agent launch) or the dir already exists. + const materializeDefaultHome = options?.materializeDefaultHome !== false + if (!existsSync(sourceAgentDir) && !materializeDefaultHome) { + if (kind === 'omp') { + const statusSource = withOrcaManagedExtensionMarker(getPiAgentStatusExtensionSource(kind)) + const statusExtensionPath = this.writeOmpFallbackStatusExtension(statusSource) + return statusExtensionPath ? { ORCA_OMP_STATUS_EXTENSION: statusExtensionPath } : {} + } + return {} + } + if (kind === 'omp') { migrateLegacyOmpOverlayState(sourceAgentDir, this.getSourceOverlayDir(sourceAgentDir, 'omp')) } diff --git a/src/relay/plugin-overlay.test.ts b/src/relay/plugin-overlay.test.ts index 9b90692cd..4f5cf7cac 100644 --- a/src/relay/plugin-overlay.test.ts +++ b/src/relay/plugin-overlay.test.ts @@ -72,9 +72,10 @@ describe('PluginOverlayManager', () => { it('installs Pi extension into the real agent extensions dir', () => { manager.setSources({ piExtensionSource: '// pi extension' }) - const dir = manager.materializePi('tab-2:0') - expect(dir).not.toBeNull() - const file = join(dir!, 'extensions', 'orca-agent-status.ts') + const result = manager.materializePi('tab-2:0') + expect(result?.sourceAgentDir).toBeDefined() + const file = join(result!.sourceAgentDir!, 'extensions', 'orca-agent-status.ts') + expect(result?.statusExtensionPath).toBe(file) expect(existsSync(file)).toBe(true) expect(readFileSync(file, 'utf8')).toContain('@orca-managed-pi-extension') }) @@ -96,17 +97,17 @@ describe('PluginOverlayManager', () => { ompExtensionSource: '// omp extension' }) - const piDir = manager.materializePi('tab-kind-pi:0', undefined, 'pi') - const ompDir = manager.materializePi('tab-kind-omp:0', undefined, 'omp') + const piResult = manager.materializePi('tab-kind-pi:0', undefined, 'pi') + const ompResult = manager.materializePi('tab-kind-omp:0', undefined, 'omp') - expect(piDir).not.toBeNull() - expect(ompDir).not.toBeNull() - expect(readFileSync(join(piDir!, 'extensions', 'orca-agent-status.ts'), 'utf8')).toContain( - '// pi extension' - ) - expect(readFileSync(join(ompDir!, 'extensions', 'orca-agent-status.ts'), 'utf8')).toContain( - '// omp extension' - ) + expect(piResult?.sourceAgentDir).toBeDefined() + expect(ompResult?.sourceAgentDir).toBeDefined() + expect( + readFileSync(join(piResult!.sourceAgentDir!, 'extensions', 'orca-agent-status.ts'), 'utf8') + ).toContain('// pi extension') + expect( + readFileSync(join(ompResult!.sourceAgentDir!, 'extensions', 'orca-agent-status.ts'), 'utf8') + ).toContain('// omp extension') }) it('installs Orca status extension into the remote default Pi agent dir', () => { @@ -129,9 +130,10 @@ describe('PluginOverlayManager', () => { ) manager.setSources({ piExtensionSource: '// pi extension' }) - const dir = manager.materializePi('tab-pi:0') + const result = manager.materializePi('tab-pi:0') + const dir = result?.sourceAgentDir - expect(dir).not.toBeNull() + expect(dir).toBeDefined() expect(readFileSync(join(dir!, 'auth.json'), 'utf8')).toBe('secret token') expect(readFileSync(join(dir!, 'skills', 'my-skill', 'SKILL.md'), 'utf8')).toBe( 'critical user skill' @@ -171,9 +173,10 @@ describe('PluginOverlayManager', () => { writeFileSync(join(customAgentDir, 'extensions', 'custom.ts'), 'custom extension') manager.setSources({ piExtensionSource: '// pi extension' }) - const dir = manager.materializePi('tab-custom-pi:0', customAgentDir) + const result = manager.materializePi('tab-custom-pi:0', customAgentDir) + const dir = result?.sourceAgentDir - expect(dir).not.toBeNull() + expect(dir).toBeDefined() expect(readFileSync(join(dir!, 'auth.json'), 'utf8')).toBe('custom token') expect(readFileSync(join(dir!, 'extensions', 'custom.ts'), 'utf8')).toBe('custom extension') expect(readFileSync(join(dir!, 'extensions', 'orca-agent-status.ts'), 'utf8')).toContain( @@ -184,10 +187,9 @@ describe('PluginOverlayManager', () => { it('leaves lazy OMP agent.db in the real remote home on the relay', () => { manager.setSources({ piExtensionSource: '// pi extension' }) const sourceDir = join(homeDir, '.omp', 'agent') - const firstDir = manager.materializePi('tab-relay-omp-sqlite:0', undefined, 'omp') + const first = manager.materializePi('tab-relay-omp-sqlite:0', undefined, 'omp') - expect(firstDir).not.toBeNull() - expect(firstDir).toBe(sourceDir) + expect(first?.sourceAgentDir).toBe(sourceDir) const sourcePath = join(sourceDir, 'agent.db') const content = 'agent.db relay credentials' @@ -198,10 +200,10 @@ describe('PluginOverlayManager', () => { expect(readFileSync(sourcePath, 'utf8')).toBe(content) - const secondDir = manager.materializePi('tab-relay-omp-sqlite:0', undefined, 'omp') + const second = manager.materializePi('tab-relay-omp-sqlite:0', undefined, 'omp') - expect(secondDir).toBe(firstDir) - expect(readFileSync(join(secondDir!, 'agent.db'), 'utf8')).toBe(content) + expect(second?.sourceAgentDir).toBe(first?.sourceAgentDir) + expect(readFileSync(join(second!.sourceAgentDir!, 'agent.db'), 'utf8')).toBe(content) }) // Why: per-agent source dir. The renderer picks Pi or OMP per @@ -222,9 +224,9 @@ describe('PluginOverlayManager', () => { seedAgentDir('.omp', 'omp') manager.setSources({ piExtensionSource: '// pi extension' }) - const dir = manager.materializePi('tab-relay-pi-both:0', undefined, 'pi') + const result = manager.materializePi('tab-relay-pi-both:0', undefined, 'pi') + const dir = result?.sourceAgentDir - expect(dir).not.toBeNull() expect(dir).toBe(join(homeDir, '.pi', 'agent')) expect(readFileSync(join(dir!, 'auth.json'), 'utf8')).toBe('pi token') const extensions = readdirSync(join(dir!, 'extensions')).sort() @@ -238,9 +240,9 @@ describe('PluginOverlayManager', () => { seedAgentDir('.omp', 'omp') manager.setSources({ piExtensionSource: '// pi extension' }) - const dir = manager.materializePi('tab-relay-omp-both:0', undefined, 'omp') + const result = manager.materializePi('tab-relay-omp-both:0', undefined, 'omp') + const dir = result?.sourceAgentDir - expect(dir).not.toBeNull() expect(dir).toBe(join(homeDir, '.omp', 'agent')) // Even though ~/.pi/agent exists, the OMP launch MUST mirror OMP's // source dir. Cross-agent fallback would silently shadow the user's @@ -259,15 +261,42 @@ describe('PluginOverlayManager', () => { expect(existsSync(join(homeDir, '.omp'))).toBe(false) manager.setSources({ piExtensionSource: '// pi extension' }) - const dir = manager.materializePi('tab-relay-omp-empty:0', undefined, 'omp') + const result = manager.materializePi('tab-relay-omp-empty:0', undefined, 'omp') + const dir = result?.sourceAgentDir - expect(dir).not.toBeNull() expect(dir).toBe(join(homeDir, '.omp', 'agent')) // Pi-only home must NOT leak into the OMP home. expect(existsSync(join(dir!, 'auth.json'))).toBe(false) const extensions = readdirSync(join(dir!, 'extensions')).sort() expect(extensions).toEqual(['orca-agent-status.ts']) }) + + it('bare-shell prep does not create missing remote agent homes (#10196)', () => { + expect(existsSync(join(homeDir, '.pi'))).toBe(false) + expect(existsSync(join(homeDir, '.omp'))).toBe(false) + manager.setSources({ + piExtensionSource: '// pi extension', + ompExtensionSource: '// omp extension' + }) + + expect( + manager.materializePi('tab-bare-pi:0', undefined, 'pi', { + materializeDefaultHome: false + }) + ).toBeNull() + const bareOmp = manager.materializePi('tab-bare-omp:0', undefined, 'omp', { + materializeDefaultHome: false + }) + // Why: bare OMP keeps status via ~/.orca-relay/… without SOURCE_AGENT_DIR or ~/.omp. + expect(bareOmp?.sourceAgentDir).toBeUndefined() + expect(bareOmp?.statusExtensionPath).toEqual( + expect.stringContaining(join('.orca-relay', 'omp-managed-status-extension')) + ) + expect(existsSync(bareOmp!.statusExtensionPath!)).toBe(true) + expect(readFileSync(bareOmp!.statusExtensionPath!, 'utf8')).toContain('// omp extension') + expect(existsSync(join(homeDir, '.pi'))).toBe(false) + expect(existsSync(join(homeDir, '.omp'))).toBe(false) + }) }) it('does not override a missing preexisting Pi agent dir', () => { @@ -283,8 +312,8 @@ describe('PluginOverlayManager', () => { ompExtensionSource: 'omp' }) const opencodeDir = manager.materializeOpenCode('tab-3:0')! - const piDir = manager.materializePi('tab-3:0', undefined, 'pi')! - const ompDir = manager.materializePi('tab-3:0', undefined, 'omp')! + const piDir = manager.materializePi('tab-3:0', undefined, 'pi')!.sourceAgentDir! + const ompDir = manager.materializePi('tab-3:0', undefined, 'omp')!.sourceAgentDir! expect(piDir).not.toBe(ompDir) expect(existsSync(opencodeDir)).toBe(true) expect(existsSync(piDir)).toBe(true) diff --git a/src/relay/plugin-overlay.ts b/src/relay/plugin-overlay.ts index ada88830b..b5a0cb249 100644 --- a/src/relay/plugin-overlay.ts +++ b/src/relay/plugin-overlay.ts @@ -41,6 +41,9 @@ const PI_OVERLAY_SUBDIR_BY_KIND: Record = { const OPENCODE_PLUGIN_FILE = 'orca-opencode-status.js' const PI_EXTENSION_FILE = 'orca-agent-status.ts' const PI_AGENT_SUBDIR = 'agent' +// Why: bare-shell OMP still needs ORCA_OMP_STATUS_EXTENSION without mkdir ~/.omp. +// Mirror local userData/omp-managed-status-extension under the relay home root. +const OMP_MANAGED_STATUS_EXTENSION_DIR = 'omp-managed-status-extension' const ORCA_MANAGED_EXTENSION_MARKER = '@orca-managed-pi-extension' function withOrcaManagedPiExtensionMarker(source: string): string { @@ -79,8 +82,12 @@ export type PluginSources = { ompExtensionSource?: string } -export function getRelayPiStatusExtensionPath(agentDir: string): string { - return join(agentDir, 'extensions', PI_EXTENSION_FILE) +/** Result of installing Pi/OMP status into a real agent home or OMP fallback path. */ +export type MaterializePiResult = { + /** Real agent dir when extensions were installed there. Absent for OMP status-only fallback. */ + sourceAgentDir?: string + /** Absolute path to orca-agent-status.ts (real home or relay-managed fallback). */ + statusExtensionPath?: string } /** Presence of this file is what makes an overlay usable — a rebuild that failed @@ -236,10 +243,38 @@ export class PluginOverlayManager { } } - /** Install the Pi/OMP status extension into the remote real agent dir and - * return that directory. `kind` selects which Pi-compatible agent's default - * dir to use when `existingAgentDir` is not supplied. */ - materializePi(id: string, existingAgentDir?: string, kind: PiAgentKind = 'pi'): string | null { + private writeOmpManagedStatusExtension(extensionSource: string): string | null { + const fallbackDir = join(this.homeDir, RELAY_HOOKS_DIR, OMP_MANAGED_STATUS_EXTENSION_DIR) + try { + mkdirSync(fallbackDir, { recursive: true }) + const fallbackPath = join(fallbackDir, PI_EXTENSION_FILE) + if (!this.canOverwritePiExtension(fallbackPath)) { + return null + } + writeFileSync(fallbackPath, extensionSource) + return fallbackPath + } catch (err) { + process.stderr.write( + `[plugin-overlay] failed to write OMP managed status extension: ${err instanceof Error ? err.message : String(err)}\n` + ) + return null + } + } + + /** Install the Pi/OMP status extension into the remote real agent dir. + * `kind` selects which Pi-compatible agent's default dir to use when + * `existingAgentDir` is not supplied. + * + * When `materializeDefaultHome` is false (bare shells), missing default + * homes are left alone so unused agents do not recreate `~/.` (#10196). + * For OMP, a relay-owned status file is still written so bare shells can + * export ORCA_OMP_STATUS_EXTENSION without ORCA_OMP_SOURCE_AGENT_DIR. */ + materializePi( + id: string, + existingAgentDir?: string, + kind: PiAgentKind = 'pi', + options?: { materializeDefaultHome?: boolean } + ): MaterializePiResult | null { const extensionSource = this.getPiExtensionSource(kind) if (!extensionSource || !isUsableId(id)) { return null @@ -249,6 +284,16 @@ export class PluginOverlayManager { if (existingAgentDir && !existsSync(existingAgentDir)) { return null } + const materializeDefaultHome = options?.materializeDefaultHome !== false + if (!existingAgentDir && !existsSync(sourceAgentDir) && !materializeDefaultHome) { + // Why: match local titlebar-extension-service bare-shell OMP policy — + // status wrapper only, never mkdir ~/.omp for unused agents. + if (kind === 'omp') { + const statusExtensionPath = this.writeOmpManagedStatusExtension(extensionSource) + return statusExtensionPath ? { statusExtensionPath } : null + } + return null + } const extensionsDir = join(sourceAgentDir, 'extensions') mkdirSync(extensionsDir, { recursive: true }) const extensionPath = join(extensionsDir, PI_EXTENSION_FILE) @@ -256,7 +301,10 @@ export class PluginOverlayManager { return null } writeFileSync(extensionPath, extensionSource) - return sourceAgentDir + return { + sourceAgentDir, + statusExtensionPath: extensionPath + } } catch (err) { process.stderr.write( `[plugin-overlay] failed to install ${kind} extension: ${err instanceof Error ? err.message : String(err)}\n` diff --git a/src/relay/pty-handler.test.ts b/src/relay/pty-handler.test.ts index ab853aed5..1a204088a 100644 --- a/src/relay/pty-handler.test.ts +++ b/src/relay/pty-handler.test.ts @@ -2271,8 +2271,13 @@ describe('PtyHandler', () => { expect(callArgs.env.ORCA_TAB_ID).toBe('tab-1') }) - it('passes the PTY id and renderer paneKey to env augmenters', async () => { - const seenContexts: { id: string; paneKey?: string; env: Record }[] = [] + it('passes PTY and explicit launch identity to env augmenters', async () => { + const seenContexts: { + id: string + paneKey?: string + launchAgent?: string + env: Record + }[] = [] handler.addEnvAugmenter((ctx) => { seenContexts.push(ctx) return { @@ -2281,7 +2286,8 @@ describe('PtyHandler', () => { }) await dispatcher.callRequest('pty.spawn', { - env: { ORCA_PANE_KEY: 'tab-context:0' } + env: { ORCA_PANE_KEY: 'tab-context:0' }, + launchAgent: 'pi' }) await dispatcher.callRequest('pty.spawn', {}) @@ -2290,6 +2296,7 @@ describe('PtyHandler', () => { expect(seenContexts[0]).toMatchObject({ id: 'pty-1', paneKey: 'tab-context:0', + launchAgent: 'pi', env: { ORCA_PANE_KEY: 'tab-context:0' } }) expect(seenContexts[1]).toMatchObject({ id: 'pty-2', paneKey: undefined }) diff --git a/src/relay/pty-handler.ts b/src/relay/pty-handler.ts index 4bd805c15..552c1e8b9 100644 --- a/src/relay/pty-handler.ts +++ b/src/relay/pty-handler.ts @@ -39,6 +39,7 @@ import { mergeGitConfigEnvProtocol } from '../shared/git-credential-prompt-env' import { isTuiAgent } from '../shared/tui-agent-config' +import type { TuiAgent } from '../shared/types' import { forceKillPosixPtyProcessGroups } from '../main/pty/posix-pty-process-groups' import { stripInheritedBuildModeEnv } from '../main/pty/build-mode-env' import { @@ -338,6 +339,7 @@ export type PtyEnvAugmenter = (ctx: { shell: string env: Record command?: string + launchAgent?: TuiAgent }) => Record export type RelayPtyWorktreeRemovalCoordinator = { @@ -507,7 +509,13 @@ export class PtyHandler { /** Build augmented spawn env; augmenter values win over process.env/renderer env. Shared by spawn()/revive() so precedence can't drift. */ private buildSpawnEnv( rendererEnv: Record | undefined, - ctx: { id: string; paneKey?: string; shell: string; command?: string }, + ctx: { + id: string + paneKey?: string + shell: string + command?: string + launchAgent?: TuiAgent + }, envToDelete: readonly string[] = [] ): Record { const baseEnv = mergeGitConfigEnvProtocol( @@ -1324,16 +1332,21 @@ export class PtyHandler { const terminalHandle = typeof env?.ORCA_TERMINAL_HANDLE === 'string' ? env.ORCA_TERMINAL_HANDLE : undefined const command = typeof params.command === 'string' ? params.command : undefined + const launchAgent = isTuiAgent(params.launchAgent) ? params.launchAgent : undefined const terminalWindowsWslDistro = typeof params.terminalWindowsWslDistro === 'string' ? params.terminalWindowsWslDistro : null const commandDelivery = params.commandDelivery === 'provider' ? 'provider' : 'renderer' const shouldProviderDeliverCommand = commandDelivery === 'provider' && command !== undefined - const spawnEnv = this.buildSpawnEnv(env, { id, paneKey, shell, command }, envToDelete) + const spawnEnv = this.buildSpawnEnv( + env, + { id, paneKey, shell, command, launchAgent }, + envToDelete + ) const launchCommandHint = resolveSetupAgentSequenceLaunchCommand(spawnEnv, command) // Why: SSH PTYs bypass main's host-env builder, so apply the guard after the relay merges its authoritative env. const gitCredentialPromptGuarded = applyTerminalGitCredentialPromptGuard(spawnEnv, { launchCommand: launchCommandHint, - isUnattended: isTuiAgent(params.launchAgent), + isUnattended: launchAgent !== undefined, platform: process.platform }) const shouldEmitShellReadyMarker = diff --git a/src/relay/relay.ts b/src/relay/relay.ts index ab485f713..f282cbb48 100644 --- a/src/relay/relay.ts +++ b/src/relay/relay.ts @@ -33,7 +33,7 @@ import { PortScanHandler } from './port-scan-handler' import { AgentExecHandler } from './agent-exec-handler' import { WorkspaceSessionHandler } from './workspace-session-handler' import { endpointDirForRelaySocket, RelayAgentHookServer } from './agent-hook-server' -import { PluginOverlayManager, getRelayPiStatusExtensionPath } from './plugin-overlay' +import { PluginOverlayManager } from './plugin-overlay' import { AGENT_HOOK_INSTALL_PLUGINS_METHOD, AGENT_HOOK_NOTIFICATION_METHOD, @@ -45,7 +45,10 @@ import { } from '../shared/ssh-types' import { assertPluginSourceUnderByteCap } from './plugin-source-limit' import { resolveOpenCodeSourceConfigDir, resolvePiSourceAgentDir } from './plugin-overlay-env' -import { detectPiAgentKindFromCommand } from '../shared/pi-agent-kind' +import { + detectExplicitPiAgentKindFromCommand, + isPiCompatibleAgentType +} from '../shared/pi-agent-kind' import { resolveSetupAgentSequenceLaunchCommand } from '../shared/setup-agent-sequencing' import { pickRemoteCliEnv } from './remote-cli-env' import { relayLogLine } from './relay-diagnostic-log' @@ -734,15 +737,24 @@ async function main(): Promise { if (pluginOverlay.hasPiSource()) { // Why: install Orca's guarded extension into the launched agent's (Pi vs OMP) real remote dir without redirecting PI_CODING_AGENT_DIR. const launchCommandHint = resolveSetupAgentSequenceLaunchCommand(ctx.env, ctx.command) - const kind = detectPiAgentKindFromCommand(launchCommandHint) + const explicitKind = isPiCompatibleAgentType(ctx.launchAgent) + ? ctx.launchAgent + : ctx.launchAgent === undefined + ? detectExplicitPiAgentKindFromCommand(launchCommandHint) + : null + const kind = explicitKind ?? 'pi' const hasLaunchCommand = typeof launchCommandHint === 'string' && launchCommandHint.trim().length > 0 const shouldPrepareOmpShadow = kind === 'omp' || !hasLaunchCommand if (kind === 'pi') { const sourceDir = resolvePiSourceAgentDir(ctx.env, ctx.shell, 'pi') - const dir = pluginOverlay.materializePi(overlayId, sourceDir, 'pi') - if (dir) { - env.ORCA_PI_SOURCE_AGENT_DIR = dir + // Why: do not mkdir ~/. on bare shells when the agent home is + // missing — unused agents kept recreating deleted homes (#10196). + const result = pluginOverlay.materializePi(overlayId, sourceDir, 'pi', { + materializeDefaultHome: explicitKind === 'pi' + }) + if (result?.sourceAgentDir) { + env.ORCA_PI_SOURCE_AGENT_DIR = result.sourceAgentDir } } if (shouldPrepareOmpShadow) { @@ -751,10 +763,16 @@ async function main(): Promise { kind === 'omp' ? resolvePiSourceAgentDir(ctx.env, ctx.shell, 'omp') : ctx.env.ORCA_OMP_SOURCE_AGENT_DIR - const dir = pluginOverlay.materializePi(overlayId, sourceDir, 'omp') - if (dir) { - env.ORCA_OMP_STATUS_EXTENSION = getRelayPiStatusExtensionPath(dir) - env.ORCA_OMP_SOURCE_AGENT_DIR = dir + const result = pluginOverlay.materializePi(overlayId, sourceDir, 'omp', { + materializeDefaultHome: explicitKind === 'omp' + }) + // Why: status-only fallback (no sourceAgentDir) is intentional for bare + // shells without ~/.omp — still export ORCA_OMP_STATUS_EXTENSION (#10196). + if (result?.statusExtensionPath) { + env.ORCA_OMP_STATUS_EXTENSION = result.statusExtensionPath + } + if (result?.sourceAgentDir) { + env.ORCA_OMP_SOURCE_AGENT_DIR = result.sourceAgentDir } } } diff --git a/src/shared/pi-agent-kind.test.ts b/src/shared/pi-agent-kind.test.ts index a05aef186..afef68c7b 100644 --- a/src/shared/pi-agent-kind.test.ts +++ b/src/shared/pi-agent-kind.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { detectPiAgentKindFromCommand } from './pi-agent-kind' +import { detectExplicitPiAgentKindFromCommand, detectPiAgentKindFromCommand } from './pi-agent-kind' describe('detectPiAgentKindFromCommand', () => { it('returns "pi" for undefined or empty commands', () => { @@ -49,3 +49,25 @@ describe('detectPiAgentKindFromCommand', () => { expect(detectPiAgentKindFromCommand('PI.CMD')).toBe('pi') }) }) + +describe('detectExplicitPiAgentKindFromCommand', () => { + it('identifies explicit Pi and OMP launches', () => { + expect(detectExplicitPiAgentKindFromCommand('pi --resume')).toBe('pi') + expect(detectExplicitPiAgentKindFromCommand('/usr/local/bin/omp.sh')).toBe('omp') + expect(detectExplicitPiAgentKindFromCommand('PI.CMD')).toBe('pi') + }) + + it('does not classify bare shells or other agents as Pi launches', () => { + expect(detectExplicitPiAgentKindFromCommand(undefined)).toBeNull() + expect(detectExplicitPiAgentKindFromCommand('')).toBeNull() + expect(detectExplicitPiAgentKindFromCommand('codex --resume session-a')).toBeNull() + expect(detectExplicitPiAgentKindFromCommand('codex "ask about pi"')).toBeNull() + expect(detectExplicitPiAgentKindFromCommand('claude')).toBeNull() + expect(detectExplicitPiAgentKindFromCommand('python3 script.py')).toBeNull() + }) + + it('classifies the launched agent instead of mentions in its arguments', () => { + expect(detectExplicitPiAgentKindFromCommand('pi "compare omp"')).toBe('pi') + expect(detectExplicitPiAgentKindFromCommand('omp "compare pi"')).toBe('omp') + }) +}) diff --git a/src/shared/pi-agent-kind.ts b/src/shared/pi-agent-kind.ts index 109f0caae..82bd60aff 100644 --- a/src/shared/pi-agent-kind.ts +++ b/src/shared/pi-agent-kind.ts @@ -24,30 +24,24 @@ export function isPiCompatibleAgentType( return agentType === 'pi' || agentType === 'omp' } -const OMP_LAUNCH_CMD = TUI_AGENT_CONFIG.omp.launchCmd - -// Why: regex carved to avoid matching `pi` inside `pip`, `mpi`, `api`, -// `python`, or `omp` inside `comp`, `omp.sh` (acceptable - that's literally -// the binary), `omp-foo`, etc. The leading boundary excludes alnum/underscore -// AND `-`/`.`/`/`/`\\` so that `~/bin/pi` or `./omp` still match but -// `mpi`/`pomp` do not. Trailing boundary allows whitespace, end-of-string, -// shell separators, or argv-style flags (`pi -v`, `omp --help`). -const BOUNDARY_BEFORE = `(?:^|[\\s;&|('"\`])` -const BOUNDARY_AFTER = `(?:$|[\\s;&|)'"\`])` -const PATH_PREFIX = `(?:[^\\s;&|('"\`]*[\\\\/])?` - -function makeLaunchCmdRegex(launchCmd: string): RegExp { - // Why: launchCmd may be a multi-token string ("hermes --tui"); only the - // first token is the binary name. Use that for matching. - const binary = getCommandTokenPathBasename(getFirstCommandToken(launchCmd)) - const escaped = binary.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') - return new RegExp( - `${BOUNDARY_BEFORE}${PATH_PREFIX}${escaped}(?:\\.cmd|\\.exe|\\.sh)?${BOUNDARY_AFTER}`, - 'i' - ) +function getLaunchBinary(command: string): string { + return getCommandTokenPathBasename(getFirstCommandToken(command)) + .toLowerCase() + .replace(/\.(?:cmd|exe|sh)$/, '') } -const OMP_REGEX = makeLaunchCmdRegex(OMP_LAUNCH_CMD) +const PI_LAUNCH_BINARY = getLaunchBinary(TUI_AGENT_CONFIG.pi.launchCmd) +const OMP_LAUNCH_BINARY = getLaunchBinary(TUI_AGENT_CONFIG.omp.launchCmd) + +export function detectExplicitPiAgentKindFromCommand( + command: string | undefined +): PiAgentKind | null { + const binary = getLaunchBinary(command ?? '') + if (binary === OMP_LAUNCH_BINARY) { + return 'omp' + } + return binary === PI_LAUNCH_BINARY ? 'pi' : null +} /** * Identify the Pi-compatible agent kind a launch command targets. @@ -62,9 +56,11 @@ const OMP_REGEX = makeLaunchCmdRegex(OMP_LAUNCH_CMD) * be substituted. */ export function detectPiAgentKindFromCommand(command: string | undefined): PiAgentKind { - if (typeof command === 'string' && OMP_REGEX.test(command)) { - return 'omp' + const explicitKind = detectExplicitPiAgentKindFromCommand(command) + if (explicitKind) { + return explicitKind } + // Why: PI launches and the no-command (bare-shell) fallback both resolve to // 'pi'. A bare shell that later invokes `pi` keeps the historical default; // if it later invokes `omp`, the status extension re-routes at runtime based