From 15918d64d52fa3229372415cb7f3b887d6005585 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sat, 25 Apr 2026 14:04:08 -0700 Subject: [PATCH] Fix attribution daemon follow-up (#1088) --- src/main/attribution/terminal-attribution.ts | 11 +- src/main/daemon/daemon-init.test.ts | 29 ++- src/main/daemon/daemon-init.ts | 46 ++++- src/main/daemon/daemon-pty-adapter.ts | 4 +- src/main/daemon/daemon-pty-router.test.ts | 156 +++++++++++++++ src/main/daemon/daemon-pty-router.ts | 199 +++++++++++++++++++ src/main/daemon/pty-subprocess.test.ts | 20 ++ src/main/daemon/pty-subprocess.ts | 18 +- src/main/daemon/shell-ready.ts | 80 ++++++-- src/main/daemon/types.ts | 8 +- src/main/ipc/pty.test.ts | 4 +- src/main/providers/local-pty-provider.ts | 17 +- src/main/providers/local-pty-shell-ready.ts | 80 ++++++-- 13 files changed, 605 insertions(+), 67 deletions(-) create mode 100644 src/main/daemon/daemon-pty-router.test.ts create mode 100644 src/main/daemon/daemon-pty-router.ts diff --git a/src/main/attribution/terminal-attribution.ts b/src/main/attribution/terminal-attribution.ts index 7801d7aae..f0270fb92 100644 --- a/src/main/attribution/terminal-attribution.ts +++ b/src/main/attribution/terminal-attribution.ts @@ -7,7 +7,7 @@ import { join } from 'path' const ATTRIBUTION_ROOT_DIR = 'orca-terminal-attribution' const ATTRIBUTION_SHIM_VERSION = '6' -const ORCA_PRODUCT_URL = 'https://github.com/orca-ide' +const ORCA_PRODUCT_URL = 'https://github.com/stablyai/orca' const ORCA_GIT_COMMIT_TRAILER = 'Co-authored-by: Orca ' const ORCA_GH_FOOTER = `Made with [Orca](${ORCA_PRODUCT_URL}) ๐Ÿ‹` const SHELL_DOLLAR = '$' @@ -69,6 +69,7 @@ export function applyTerminalAttributionEnv( baseEnv.ORCA_GIT_COMMIT_TRAILER = ORCA_GIT_COMMIT_TRAILER baseEnv.ORCA_GH_PR_FOOTER = ORCA_GH_FOOTER baseEnv.ORCA_GH_ISSUE_FOOTER = ORCA_GH_FOOTER + baseEnv.ORCA_ATTRIBUTION_SHIM_DIR = posixDir if (process.platform === 'win32') { if (resolvedGit) { @@ -497,7 +498,7 @@ if [[ "\${ORCA_ENABLE_GIT_ATTRIBUTION:-0}" != "1" || "\${ORCA_ATTRIBUTION_BYPASS fi if [[ "\${1:-}" == "pr" && "\${2:-}" == "create" ]]; then - footer="\${ORCA_GH_PR_FOOTER:-Made with [Orca](https://github.com/orca-ide) ๐Ÿ‹}" + footer="\${ORCA_GH_PR_FOOTER:-Made with [Orca](https://github.com/stablyai/orca) ๐Ÿ‹}" if has_passthrough_create_args "$@"; then PATH="$real_path" exec "$real_gh" "$@" fi @@ -531,7 +532,7 @@ if [[ "\${1:-}" == "pr" && "\${2:-}" == "create" ]]; then fi if [[ "\${1:-}" == "issue" && "\${2:-}" == "create" ]]; then - footer="\${ORCA_GH_ISSUE_FOOTER:-Made with [Orca](https://github.com/orca-ide) ๐Ÿ‹}" + footer="\${ORCA_GH_ISSUE_FOOTER:-Made with [Orca](https://github.com/stablyai/orca) ๐Ÿ‹}" if has_passthrough_create_args "$@"; then PATH="$real_path" exec "$real_gh" "$@" fi @@ -906,7 +907,7 @@ if ($isPrCreate) { if ($LASTEXITCODE -ne 0) { $body = $null } - $footer = if ($env:ORCA_GH_PR_FOOTER) { $env:ORCA_GH_PR_FOOTER } else { 'Made with [Orca](https://github.com/orca-ide) ๐Ÿ‹' } + $footer = if ($env:ORCA_GH_PR_FOOTER) { $env:ORCA_GH_PR_FOOTER } else { 'Made with [Orca](https://github.com/stablyai/orca) ๐Ÿ‹' } if ($null -ne $body -and $body -notmatch [Regex]::Escape($footer)) { $tmpFile = [System.IO.Path]::GetTempFileName() try { @@ -937,7 +938,7 @@ if ($isIssueCreate) { if ($LASTEXITCODE -ne 0) { $body = $null } - $footer = if ($env:ORCA_GH_ISSUE_FOOTER) { $env:ORCA_GH_ISSUE_FOOTER } else { 'Made with [Orca](https://github.com/orca-ide) ๐Ÿ‹' } + $footer = if ($env:ORCA_GH_ISSUE_FOOTER) { $env:ORCA_GH_ISSUE_FOOTER } else { 'Made with [Orca](https://github.com/stablyai/orca) ๐Ÿ‹' } if ($null -ne $body -and $body -notmatch [Regex]::Escape($footer)) { $tmpFile = [System.IO.Path]::GetTempFileName() try { diff --git a/src/main/daemon/daemon-init.test.ts b/src/main/daemon/daemon-init.test.ts index 44ae6bf0d..b02a51ed7 100644 --- a/src/main/daemon/daemon-init.test.ts +++ b/src/main/daemon/daemon-init.test.ts @@ -48,7 +48,8 @@ function writeNdjson(socket: Socket, message: unknown): void { async function startLegacyDaemonStub( socketPath: string, - tokenPath: string + tokenPath: string, + protocolVersion = 1 ): Promise<{ shutdown: () => Promise; shutdownRequested: () => boolean }> { mkdirSync(join(tokenPath, '..'), { recursive: true }) writeFileSync(tokenPath, 'legacy-token', { mode: 0o600 }) @@ -71,7 +72,7 @@ async function startLegacyDaemonStub( greeted = true expect(message).toMatchObject({ type: 'hello', - version: 1, + version: protocolVersion, token: 'legacy-token' }) writeNdjson(socket, { type: 'hello', ok: true }) @@ -239,6 +240,30 @@ describe('cleanupOrphanedDaemon', () => { } }) + it('cleans up v2 daemon sessions when daemon mode is disabled', async () => { + const { cleanupOrphanedDaemon } = await importFreshDaemonInit() + const { getDaemonPidPath, getDaemonSocketPath, getDaemonTokenPath } = + await import('./daemon-spawner') + + const runtimeDir = join(userDataDir, 'daemon') + mkdirSync(runtimeDir, { recursive: true }) + const v2SocketPath = getDaemonSocketPath(runtimeDir, 2) + const v2TokenPath = getDaemonTokenPath(runtimeDir, 2) + const v2PidPath = getDaemonPidPath(runtimeDir, 2) + writeFileSync(v2PidPath, String(process.pid), { mode: 0o600 }) + const v2Daemon = await startLegacyDaemonStub(v2SocketPath, v2TokenPath, 2) + + try { + const result = await cleanupOrphanedDaemon() + + expect(result).toEqual({ cleaned: true, killedCount: 1 }) + expect(v2Daemon.shutdownRequested()).toBe(true) + expect(existsSync(v2PidPath)).toBe(false) + } finally { + await v2Daemon.shutdown() + } + }) + it('does not report cleaned when fallback cleanup preserves an unowned live socket', async () => { if (process.platform === 'win32') { return diff --git a/src/main/daemon/daemon-init.ts b/src/main/daemon/daemon-init.ts index b1714b76b..43c3d8b52 100644 --- a/src/main/daemon/daemon-init.ts +++ b/src/main/daemon/daemon-init.ts @@ -11,6 +11,7 @@ import { type DaemonLauncher } from './daemon-spawner' import { DaemonPtyAdapter } from './daemon-pty-adapter' +import { DaemonPtyRouter } from './daemon-pty-router' import { DaemonClient } from './client' import { PREVIOUS_DAEMON_PROTOCOL_VERSIONS, @@ -21,7 +22,7 @@ import { healthCheckDaemon, killStaleDaemon } from './daemon-health' import { setLocalPtyProvider } from '../ipc/pty' let spawner: DaemonSpawner | null = null -let adapter: DaemonPtyAdapter | null = null +let adapter: DaemonPtyRouter | DaemonPtyAdapter | null = null function getRuntimeDir(): string { const dir = join(app.getPath('userData'), 'daemon') @@ -164,7 +165,6 @@ function createOutOfProcessLauncher(runtimeDir: string): DaemonLauncher { export async function initDaemonPtyProvider(): Promise { const runtimeDir = getRuntimeDir() - await cleanupPreviousProtocolDaemons(runtimeDir) const newSpawner = new DaemonSpawner({ runtimeDir, @@ -191,9 +191,21 @@ export async function initDaemonPtyProvider(): Promise { } }) + const legacyAdapters = await createLegacyDaemonAdapters(runtimeDir) + const routedAdapter = + legacyAdapters.length > 0 + ? new DaemonPtyRouter({ + current: newAdapter, + legacy: legacyAdapters + }) + : newAdapter + if (routedAdapter instanceof DaemonPtyRouter) { + await routedAdapter.discoverLegacySessions() + } + spawner = newSpawner - adapter = newAdapter - setLocalPtyProvider(adapter) + adapter = routedAdapter + setLocalPtyProvider(routedAdapter) } // Why: disconnect from the daemon without killing it. The daemon runs as a @@ -301,12 +313,30 @@ async function cleanupDaemonForProtocol( return { cleaned: didRequestShutdown || didKillStaleDaemon, killedCount } } -async function cleanupPreviousProtocolDaemons(runtimeDir: string): Promise { +async function createLegacyDaemonAdapters(runtimeDir: string): Promise { + const adapters: DaemonPtyAdapter[] = [] for (const protocolVersion of PREVIOUS_DAEMON_PROTOCOL_VERSIONS) { - await cleanupDaemonForProtocol(runtimeDir, protocolVersion).catch((error) => { - console.warn(`[daemon] Failed to clean up v${protocolVersion} daemon`, error) - }) + const socketPath = getDaemonSocketPath(runtimeDir, protocolVersion) + const tokenPath = getDaemonTokenPath(runtimeDir, protocolVersion) + if (!(await probeSocket(socketPath))) { + continue + } + // Why: old daemon PTYs can be running long-lived agents during an app + // upgrade. Keep those sessions routed to their original daemon while new + // terminals use the current protocol, instead of killing background work. + // Legacy adapters intentionally do not respawn: respawning an old protocol + // daemon from new code would recreate stale env semantics and can be less + // predictable than letting the session fail if that old daemon dies. + adapters.push( + new DaemonPtyAdapter({ + socketPath, + tokenPath, + protocolVersion, + historyPath: getHistoryDir() + }) + ) } + return adapters } /** Detect and tear down an orphaned daemon left behind by a previous app diff --git a/src/main/daemon/daemon-pty-adapter.ts b/src/main/daemon/daemon-pty-adapter.ts index f11c88beb..46ce6bf73 100644 --- a/src/main/daemon/daemon-pty-adapter.ts +++ b/src/main/daemon/daemon-pty-adapter.ts @@ -14,6 +14,7 @@ import type { IPtyProvider, PtySpawnOptions, PtySpawnResult } from '../providers export type DaemonPtyAdapterOptions = { socketPath: string tokenPath: string + protocolVersion?: number /** Directory for disk-based terminal history. When set, the adapter writes * raw PTY output to disk for cold restore on daemon crash. */ historyPath?: string @@ -59,7 +60,8 @@ export class DaemonPtyAdapter implements IPtyProvider { constructor(opts: DaemonPtyAdapterOptions) { this.client = new DaemonClient({ socketPath: opts.socketPath, - tokenPath: opts.tokenPath + tokenPath: opts.tokenPath, + protocolVersion: opts.protocolVersion }) this.historyManager = opts.historyPath ? new HistoryManager(opts.historyPath) : null this.historyReader = opts.historyPath ? new HistoryReader(opts.historyPath) : null diff --git a/src/main/daemon/daemon-pty-router.test.ts b/src/main/daemon/daemon-pty-router.test.ts new file mode 100644 index 000000000..5273440d1 --- /dev/null +++ b/src/main/daemon/daemon-pty-router.test.ts @@ -0,0 +1,156 @@ +import { describe, expect, it, vi } from 'vitest' +import { DaemonPtyRouter } from './daemon-pty-router' +import type { DaemonPtyAdapter } from './daemon-pty-adapter' +import type { PtySpawnOptions, PtySpawnResult } from '../providers/types' + +type AdapterMock = DaemonPtyAdapter & { + emitData: (id: string, data: string) => void + emitExit: (id: string, code: number) => void +} + +function createAdapter( + label: string, + sessions: string[] = [], + reconcileResult?: { alive: string[]; killed: string[] } +): AdapterMock { + const writes: { id: string; data: string }[] = [] + const dataListeners: ((payload: { id: string; data: string }) => void)[] = [] + const exitListeners: ((payload: { id: string; code: number }) => void)[] = [] + return { + spawn: vi.fn(async (opts: PtySpawnOptions): Promise => { + const id = opts.sessionId ?? `${label}-new` + sessions.push(id) + return { id } + }), + listProcesses: vi.fn(async () => + sessions.map((id) => ({ + id, + cwd: '', + title: label + })) + ), + write: vi.fn((id: string, data: string) => { + writes.push({ id, data }) + }), + resize: vi.fn(), + shutdown: vi.fn(async (id: string) => { + const idx = sessions.indexOf(id) + if (idx !== -1) { + sessions.splice(idx, 1) + } + }), + attach: vi.fn(async () => {}), + sendSignal: vi.fn(async () => {}), + getCwd: vi.fn(async () => ''), + getInitialCwd: vi.fn(async () => ''), + clearBuffer: vi.fn(async () => {}), + acknowledgeDataEvent: vi.fn(), + hasChildProcesses: vi.fn(async () => false), + getForegroundProcess: vi.fn(async () => null), + serialize: vi.fn(async () => '{}'), + revive: vi.fn(async () => {}), + getDefaultShell: vi.fn(async () => '/bin/zsh'), + getProfiles: vi.fn(async () => []), + onData: vi.fn((callback: (payload: { id: string; data: string }) => void) => { + dataListeners.push(callback) + return () => { + const idx = dataListeners.indexOf(callback) + if (idx !== -1) { + dataListeners.splice(idx, 1) + } + } + }), + onExit: vi.fn((callback: (payload: { id: string; code: number }) => void) => { + exitListeners.push(callback) + return () => { + const idx = exitListeners.indexOf(callback) + if (idx !== -1) { + exitListeners.splice(idx, 1) + } + } + }), + ackColdRestore: vi.fn(), + clearTombstone: vi.fn(), + reconcileOnStartup: vi.fn(async () => reconcileResult ?? { alive: sessions, killed: [] }), + dispose: vi.fn(), + disconnectOnly: vi.fn(), + emitData: (id: string, data: string) => { + for (const listener of dataListeners) { + listener({ id, data }) + } + }, + emitExit: (id: string, code: number) => { + for (const listener of exitListeners) { + listener({ id, code }) + } + }, + _writes: writes + } as unknown as AdapterMock +} + +describe('DaemonPtyRouter', () => { + it('routes existing legacy sessions to their old daemon and new sessions to current daemon', async () => { + const current = createAdapter('current') + const legacy = createAdapter('legacy', ['legacy-session']) + const router = new DaemonPtyRouter({ current, legacy: [legacy] }) + + await router.discoverLegacySessions() + + await router.spawn({ sessionId: 'legacy-session', cols: 80, rows: 24 }) + const fresh = await router.spawn({ cols: 80, rows: 24 }) + router.write('legacy-session', 'old\n') + router.write(fresh.id, 'new\n') + + expect(legacy.spawn).toHaveBeenCalledWith({ sessionId: 'legacy-session', cols: 80, rows: 24 }) + expect(current.spawn).toHaveBeenCalledWith({ cols: 80, rows: 24 }) + expect(legacy.write).toHaveBeenCalledWith('legacy-session', 'old\n') + expect(current.write).toHaveBeenCalledWith(fresh.id, 'new\n') + }) + + it('drops a legacy mapping after the routed session exits', async () => { + const current = createAdapter('current') + const legacy = createAdapter('legacy', ['legacy-session']) + const router = new DaemonPtyRouter({ current, legacy: [legacy] }) + + await router.discoverLegacySessions() + + legacy.emitExit('legacy-session', 0) + await router.spawn({ sessionId: 'legacy-session', cols: 80, rows: 24 }) + + expect(current.spawn).toHaveBeenCalledWith({ sessionId: 'legacy-session', cols: 80, rows: 24 }) + }) + + it('merges startup reconciliation and updates route mappings', async () => { + const current = createAdapter('current', [], { + alive: ['current-alive'], + killed: ['current-killed'] + }) + const legacy = createAdapter('legacy', [], { + alive: ['legacy-alive'], + killed: ['legacy-killed'] + }) + const router = new DaemonPtyRouter({ current, legacy: [legacy] }) + + const result = await router.reconcileOnStartup(new Set(['wt'])) + router.write('legacy-alive', 'old\n') + router.write('current-alive', 'new\n') + + expect(result).toEqual({ + alive: ['current-alive', 'legacy-alive'], + killed: ['current-killed', 'legacy-killed'] + }) + expect(legacy.write).toHaveBeenCalledWith('legacy-alive', 'old\n') + expect(current.write).toHaveBeenCalledWith('current-alive', 'new\n') + }) + + it('disposes current and legacy adapters', () => { + const current = createAdapter('current') + const legacy = createAdapter('legacy') + const router = new DaemonPtyRouter({ current, legacy: [legacy] }) + + router.dispose() + + expect(current.dispose).toHaveBeenCalled() + expect(legacy.dispose).toHaveBeenCalled() + }) +}) diff --git a/src/main/daemon/daemon-pty-router.ts b/src/main/daemon/daemon-pty-router.ts new file mode 100644 index 000000000..03edb07fd --- /dev/null +++ b/src/main/daemon/daemon-pty-router.ts @@ -0,0 +1,199 @@ +import type { DaemonPtyAdapter } from './daemon-pty-adapter' +import type { IPtyProvider, PtySpawnOptions, PtySpawnResult } from '../providers/types' + +export class DaemonPtyRouter implements IPtyProvider { + private current: DaemonPtyAdapter + private legacy: DaemonPtyAdapter[] + private sessionAdapters = new Map() + private unsubscribers: (() => void)[] = [] + private dataListeners: ((payload: { id: string; data: string }) => void)[] = [] + private exitListeners: ((payload: { id: string; code: number }) => void)[] = [] + + constructor(opts: { current: DaemonPtyAdapter; legacy: DaemonPtyAdapter[] }) { + this.current = opts.current + this.legacy = opts.legacy + + for (const adapter of this.allAdapters()) { + this.unsubscribers.push( + adapter.onData((payload) => { + for (const listener of this.dataListeners) { + listener(payload) + } + }), + adapter.onExit((payload) => { + this.sessionAdapters.delete(payload.id) + for (const listener of this.exitListeners) { + listener(payload) + } + }) + ) + } + } + + async discoverLegacySessions(): Promise { + for (const adapter of this.legacy) { + try { + const sessions = await adapter.listProcesses() + for (const session of sessions) { + this.sessionAdapters.set(session.id, adapter) + } + } catch (error) { + console.warn('[daemon] Failed to discover legacy daemon sessions', error) + } + } + } + + async spawn(opts: PtySpawnOptions): Promise { + const adapter = opts.sessionId ? this.sessionAdapters.get(opts.sessionId) : undefined + const target = adapter ?? this.current + const result = await target.spawn(opts) + this.sessionAdapters.set(result.id, target) + return result + } + + async attach(id: string): Promise { + await this.adapterFor(id).attach(id) + } + + write(id: string, data: string): void { + this.adapterFor(id).write(id, data) + } + + resize(id: string, cols: number, rows: number): void { + this.adapterFor(id).resize(id, cols, rows) + } + + async shutdown(id: string, immediate: boolean): Promise { + await this.adapterFor(id).shutdown(id, immediate) + this.sessionAdapters.delete(id) + } + + async sendSignal(id: string, signal: string): Promise { + await this.adapterFor(id).sendSignal(id, signal) + } + + async getCwd(id: string): Promise { + return this.adapterFor(id).getCwd(id) + } + + async getInitialCwd(id: string): Promise { + return this.adapterFor(id).getInitialCwd(id) + } + + async clearBuffer(id: string): Promise { + await this.adapterFor(id).clearBuffer(id) + } + + acknowledgeDataEvent(id: string, charCount: number): void { + this.adapterFor(id).acknowledgeDataEvent(id, charCount) + } + + async hasChildProcesses(id: string): Promise { + return this.adapterFor(id).hasChildProcesses(id) + } + + async getForegroundProcess(id: string): Promise { + return this.adapterFor(id).getForegroundProcess(id) + } + + async serialize(ids: string[]): Promise { + return this.current.serialize(ids) + } + + async revive(state: string): Promise { + await this.current.revive(state) + } + + async listProcesses(): Promise<{ id: string; cwd: string; title: string }[]> { + const results = await Promise.allSettled( + this.allAdapters().map((adapter) => adapter.listProcesses()) + ) + return results.flatMap((result) => (result.status === 'fulfilled' ? result.value : [])) + } + + async getDefaultShell(): Promise { + return this.current.getDefaultShell() + } + + async getProfiles(): Promise<{ name: string; path: string }[]> { + return this.current.getProfiles() + } + + onData(callback: (payload: { id: string; data: string }) => void): () => void { + this.dataListeners.push(callback) + return () => { + const idx = this.dataListeners.indexOf(callback) + if (idx !== -1) { + this.dataListeners.splice(idx, 1) + } + } + } + + onReplay(_callback: (payload: { id: string; data: string }) => void): () => void { + return () => {} + } + + onExit(callback: (payload: { id: string; code: number }) => void): () => void { + this.exitListeners.push(callback) + return () => { + const idx = this.exitListeners.indexOf(callback) + if (idx !== -1) { + this.exitListeners.splice(idx, 1) + } + } + } + + ackColdRestore(sessionId: string): void { + this.adapterFor(sessionId).ackColdRestore(sessionId) + } + + clearTombstone(sessionId: string): void { + this.adapterFor(sessionId).clearTombstone(sessionId) + } + + async reconcileOnStartup(validWorktreeIds: Set): Promise<{ + alive: string[] + killed: string[] + }> { + const alive: string[] = [] + const killed: string[] = [] + for (const adapter of this.allAdapters()) { + const result = await adapter.reconcileOnStartup(validWorktreeIds) + alive.push(...result.alive) + killed.push(...result.killed) + for (const id of result.alive) { + this.sessionAdapters.set(id, adapter) + } + for (const id of result.killed) { + this.sessionAdapters.delete(id) + } + } + return { alive, killed } + } + + dispose(): void { + for (const unsubscribe of this.unsubscribers.splice(0)) { + unsubscribe() + } + for (const adapter of this.allAdapters()) { + adapter.dispose() + } + } + + disconnectOnly(): void { + for (const unsubscribe of this.unsubscribers.splice(0)) { + unsubscribe() + } + for (const adapter of this.allAdapters()) { + adapter.disconnectOnly() + } + } + + private adapterFor(sessionId: string): DaemonPtyAdapter { + return this.sessionAdapters.get(sessionId) ?? this.current + } + + private allAdapters(): DaemonPtyAdapter[] { + return [this.current, ...this.legacy] + } +} diff --git a/src/main/daemon/pty-subprocess.test.ts b/src/main/daemon/pty-subprocess.test.ts index 61c633d7e..1c89be299 100644 --- a/src/main/daemon/pty-subprocess.test.ts +++ b/src/main/daemon/pty-subprocess.test.ts @@ -200,6 +200,26 @@ describe('createPtySubprocess', () => { expect(spawnEnv.MY_VAR).toBe('test-value') }) + it('uses shell wrapper when attribution shims must survive shell startup', () => { + const proc = mockPtyProcess() + spawnMock.mockReturnValue(proc) + + createPtySubprocess({ + sessionId: 'test', + cols: 80, + rows: 24, + env: { + SHELL: '/bin/zsh', + ORCA_ATTRIBUTION_SHIM_DIR: '/tmp/orca-terminal-attribution/posix' + } + }) + + const lastCall = spawnMock.mock.calls.at(-1)! + expect(lastCall[1]).toEqual(['-l']) + expect(lastCall[2].env.ZDOTDIR).toContain('shell-ready/zsh') + expect(lastCall[2].env.ORCA_SHELL_READY_MARKER).toBe('0') + }) + it('combines HOMEDRIVE and HOMEPATH for Windows default cwd', () => { const proc = mockPtyProcess() spawnMock.mockReturnValue(proc) diff --git a/src/main/daemon/pty-subprocess.ts b/src/main/daemon/pty-subprocess.ts index 8aa73e277..4f8a67546 100644 --- a/src/main/daemon/pty-subprocess.ts +++ b/src/main/daemon/pty-subprocess.ts @@ -1,6 +1,10 @@ import * as pty from 'node-pty' import type { SubprocessHandle } from './session' -import { getShellReadyLaunchConfig, resolvePtyShellPath } from './shell-ready' +import { + getAttributionShellLaunchConfig, + getShellReadyLaunchConfig, + resolvePtyShellPath +} from './shell-ready' import { isValidPtySize, normalizePtySize } from './daemon-pty-size' import { ensureNodePtySpawnHelperExecutable } from '../providers/local-pty-utils' @@ -52,11 +56,15 @@ export function createPtySubprocess(opts: PtySubprocessOptions): SubprocessHandl if (process.platform === 'win32') { shellArgs = [] } else { - const shellReadyLaunch = opts.command ? getShellReadyLaunchConfig(shellPath) : null - if (shellReadyLaunch) { - Object.assign(env, shellReadyLaunch.env) + const shellLaunch = opts.command + ? getShellReadyLaunchConfig(shellPath) + : env.ORCA_ATTRIBUTION_SHIM_DIR + ? getAttributionShellLaunchConfig(shellPath) + : null + if (shellLaunch) { + Object.assign(env, shellLaunch.env) } - shellArgs = shellReadyLaunch?.args ?? ['-l'] + shellArgs = shellLaunch?.args ?? ['-l'] } // Why: asar packaging can strip the +x bit from node-pty's spawn-helper diff --git a/src/main/daemon/shell-ready.ts b/src/main/daemon/shell-ready.ts index 428518207..004cfbbba 100644 --- a/src/main/daemon/shell-ready.ts +++ b/src/main/daemon/shell-ready.ts @@ -59,16 +59,34 @@ _orca_home="\${ORCA_ORIG_ZDOTDIR:-$HOME}" if [[ -o interactive && -f "$_orca_home/.zshrc" ]]; then source "$_orca_home/.zshrc" fi +__orca_restore_attribution_path() { + [[ -n "\${ORCA_ATTRIBUTION_SHIM_DIR:-}" ]] || return 0 + case "$PATH" in + "\${ORCA_ATTRIBUTION_SHIM_DIR}"|"\${ORCA_ATTRIBUTION_SHIM_DIR}:"*) return 0 ;; + esac + export PATH="\${ORCA_ATTRIBUTION_SHIM_DIR}:$PATH" +} +[[ ! -o login ]] && __orca_restore_attribution_path ` const zshLogin = `# Orca daemon zsh shell-ready wrapper _orca_home="\${ORCA_ORIG_ZDOTDIR:-$HOME}" if [[ -o interactive && -f "$_orca_home/.zlogin" ]]; then source "$_orca_home/.zlogin" fi -__orca_prompt_mark() { - printf "${SHELL_READY_MARKER}" +__orca_restore_attribution_path() { + [[ -n "\${ORCA_ATTRIBUTION_SHIM_DIR:-}" ]] || return 0 + case "$PATH" in + "\${ORCA_ATTRIBUTION_SHIM_DIR}"|"\${ORCA_ATTRIBUTION_SHIM_DIR}:"*) return 0 ;; + esac + export PATH="\${ORCA_ATTRIBUTION_SHIM_DIR}:$PATH" } -precmd_functions=(\${precmd_functions[@]} __orca_prompt_mark) +__orca_restore_attribution_path +if [[ "\${ORCA_SHELL_READY_MARKER:-0}" == "1" ]]; then + __orca_prompt_mark() { + printf "${SHELL_READY_MARKER}" + } + precmd_functions=(\${precmd_functions[@]} __orca_prompt_mark) +fi ` const bashRc = `# Orca daemon bash shell-ready wrapper [[ -f /etc/profile ]] && source /etc/profile @@ -79,17 +97,27 @@ elif [[ -f "$HOME/.bash_login" ]]; then elif [[ -f "$HOME/.profile" ]]; then source "$HOME/.profile" fi -__orca_prompt_mark() { - printf "${SHELL_READY_MARKER}" +__orca_restore_attribution_path() { + [[ -n "\${ORCA_ATTRIBUTION_SHIM_DIR:-}" ]] || return 0 + case "$PATH" in + "\${ORCA_ATTRIBUTION_SHIM_DIR}"|"\${ORCA_ATTRIBUTION_SHIM_DIR}:"*) return 0 ;; + esac + export PATH="\${ORCA_ATTRIBUTION_SHIM_DIR}:$PATH" } -if [[ "$(declare -p PROMPT_COMMAND 2>/dev/null)" == "declare -a"* ]]; then - PROMPT_COMMAND=("\${PROMPT_COMMAND[@]}" "__orca_prompt_mark") -else - _orca_prev_prompt_command="\${PROMPT_COMMAND}" - if [[ -n "\${_orca_prev_prompt_command}" ]]; then - PROMPT_COMMAND="\${_orca_prev_prompt_command};__orca_prompt_mark" +__orca_restore_attribution_path +if [[ "\${ORCA_SHELL_READY_MARKER:-0}" == "1" ]]; then + __orca_prompt_mark() { + printf "${SHELL_READY_MARKER}" + } + if [[ "$(declare -p PROMPT_COMMAND 2>/dev/null)" == "declare -a"* ]]; then + PROMPT_COMMAND=("\${PROMPT_COMMAND[@]}" "__orca_prompt_mark") else - PROMPT_COMMAND="__orca_prompt_mark" + _orca_prev_prompt_command="\${PROMPT_COMMAND}" + if [[ -n "\${_orca_prev_prompt_command}" ]]; then + PROMPT_COMMAND="\${_orca_prev_prompt_command};__orca_prompt_mark" + else + PROMPT_COMMAND="__orca_prompt_mark" + fi fi fi ` @@ -124,11 +152,16 @@ export function supportsPtyStartupBarrier(env: Record): boolean return shellName === 'zsh' || shellName === 'bash' } -export function getShellReadyLaunchConfig(shellPath: string): { +type ShellLaunchConfig = { args: string[] | null env: Record supportsReadyMarker: boolean -} { +} + +function getWrappedShellLaunchConfig( + shellPath: string, + options: { emitReadyMarker: boolean } +): ShellLaunchConfig { const shellName = basename(shellPath).toLowerCase() if (shellName === 'zsh') { @@ -138,9 +171,10 @@ export function getShellReadyLaunchConfig(shellPath: string): { args: ['-l'], env: { ORCA_ORIG_ZDOTDIR: process.env.ZDOTDIR || process.env.HOME || '', - ZDOTDIR: join(root, 'zsh') + ZDOTDIR: join(root, 'zsh'), + ORCA_SHELL_READY_MARKER: options.emitReadyMarker ? '1' : '0' }, - supportsReadyMarker: true + supportsReadyMarker: options.emitReadyMarker } } @@ -149,8 +183,10 @@ export function getShellReadyLaunchConfig(shellPath: string): { const root = getShellReadyWrapperRoot() return { args: ['--rcfile', join(root, 'bash', 'rcfile')], - env: {}, - supportsReadyMarker: true + env: { + ORCA_SHELL_READY_MARKER: options.emitReadyMarker ? '1' : '0' + }, + supportsReadyMarker: options.emitReadyMarker } } @@ -160,3 +196,11 @@ export function getShellReadyLaunchConfig(shellPath: string): { supportsReadyMarker: false } } + +export function getShellReadyLaunchConfig(shellPath: string): ShellLaunchConfig { + return getWrappedShellLaunchConfig(shellPath, { emitReadyMarker: true }) +} + +export function getAttributionShellLaunchConfig(shellPath: string): ShellLaunchConfig { + return getWrappedShellLaunchConfig(shellPath, { emitReadyMarker: false }) +} diff --git a/src/main/daemon/types.ts b/src/main/daemon/types.ts index b182bc9a3..2c896e89c 100644 --- a/src/main/daemon/types.ts +++ b/src/main/daemon/types.ts @@ -1,8 +1,8 @@ // โ”€โ”€โ”€ Protocol Version โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ -// Why: v1 daemons can survive app updates and keep using tmp-backed -// shell-ready rcfiles. v2 forces a fresh daemon with durable wrapper paths. -export const PROTOCOL_VERSION = 2 -export const PREVIOUS_DAEMON_PROTOCOL_VERSIONS = [1] as const +// Why: daemons can survive app updates with long-lived shell env. Bump when +// spawn-time env semantics change so stale sessions cannot bypass new behavior. +export const PROTOCOL_VERSION = 3 +export const PREVIOUS_DAEMON_PROTOCOL_VERSIONS = [1, 2] as const // โ”€โ”€โ”€ Session State Machine โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ export type SessionState = 'created' | 'spawning' | 'running' | 'exiting' | 'exited' diff --git a/src/main/ipc/pty.test.ts b/src/main/ipc/pty.test.ts index dfd44fa27..6f3754d6a 100644 --- a/src/main/ipc/pty.test.ts +++ b/src/main/ipc/pty.test.ts @@ -340,8 +340,8 @@ describe('registerPtyHandlers', () => { expect(env.ORCA_ENABLE_GIT_ATTRIBUTION).toBe('1') expect(env.ORCA_GIT_COMMIT_TRAILER).toBe('Co-authored-by: Orca ') - expect(env.ORCA_GH_PR_FOOTER).toBe('Made with [Orca](https://github.com/orca-ide) ๐Ÿ‹') - expect(env.ORCA_GH_ISSUE_FOOTER).toBe('Made with [Orca](https://github.com/orca-ide) ๐Ÿ‹') + expect(env.ORCA_GH_PR_FOOTER).toBe('Made with [Orca](https://github.com/stablyai/orca) ๐Ÿ‹') + expect(env.ORCA_GH_ISSUE_FOOTER).toBe('Made with [Orca](https://github.com/stablyai/orca) ๐Ÿ‹') expect(env.PATH).toContain('/tmp/orca-user-data/orca-terminal-attribution/posix') }) diff --git a/src/main/providers/local-pty-provider.ts b/src/main/providers/local-pty-provider.ts index c429e580f..3871aa00b 100644 --- a/src/main/providers/local-pty-provider.ts +++ b/src/main/providers/local-pty-provider.ts @@ -18,6 +18,7 @@ import { spawnShellWithFallback } from './local-pty-utils' import { + getAttributionShellLaunchConfig, getShellReadyLaunchConfig, createShellReadyScanState, scanForShellReady, @@ -162,8 +163,7 @@ export class LocalPtyProvider implements IPtyProvider { validationCwd = cwd } else { shellPath = args.env?.SHELL || process.env.SHELL || '/bin/zsh' - shellReadyLaunch = args.command ? getShellReadyLaunchConfig(shellPath) : null - shellArgs = shellReadyLaunch?.args ?? ['-l'] + shellArgs = ['-l'] effectiveCwd = cwd validationCwd = cwd } @@ -174,7 +174,6 @@ export class LocalPtyProvider implements IPtyProvider { const spawnEnv: Record = { ...process.env, ...args.env, - ...shellReadyLaunch?.env, TERM: 'xterm-256color', COLORTERM: 'truecolor', TERM_PROGRAM: 'Orca', @@ -200,6 +199,18 @@ export class LocalPtyProvider implements IPtyProvider { } const finalEnv = this.opts.buildSpawnEnv ? this.opts.buildSpawnEnv(id, spawnEnv) : spawnEnv + if (!wslInfo && process.platform !== 'win32') { + const shellLaunch = args.command + ? getShellReadyLaunchConfig(shellPath) + : finalEnv.ORCA_ATTRIBUTION_SHIM_DIR + ? getAttributionShellLaunchConfig(shellPath) + : null + if (shellLaunch) { + Object.assign(finalEnv, shellLaunch.env) + shellArgs = shellLaunch.args ?? shellArgs + shellReadyLaunch = args.command ? shellLaunch : null + } + } // โ”€โ”€ Worktree-scoped shell history (ยง7โ€“ยง10 of terminal-history-scope-design) โ”€โ”€ // Why: without this, all worktree terminals share a single global HISTFILE diff --git a/src/main/providers/local-pty-shell-ready.ts b/src/main/providers/local-pty-shell-ready.ts index 388d23ba8..b51759468 100644 --- a/src/main/providers/local-pty-shell-ready.ts +++ b/src/main/providers/local-pty-shell-ready.ts @@ -87,19 +87,29 @@ fi # Why: preserve bash's normal login-shell contract. Many users already source # ~/.bashrc from ~/.bash_profile; forcing ~/.bashrc again here would duplicate # PATH edits, hooks, and prompt init in Orca startup-command shells. +__orca_restore_attribution_path() { + [[ -n "\${ORCA_ATTRIBUTION_SHIM_DIR:-}" ]] || return 0 + case "$PATH" in + "\${ORCA_ATTRIBUTION_SHIM_DIR}"|"\${ORCA_ATTRIBUTION_SHIM_DIR}:"*) return 0 ;; + esac + export PATH="\${ORCA_ATTRIBUTION_SHIM_DIR}:$PATH" +} +__orca_restore_attribution_path # Why: append the marker through PROMPT_COMMAND so it fires after the login # startup files have rebuilt the prompt, without re-running user rc files. -__orca_prompt_mark() { - printf "\\033]133;A\\007" -} -if [[ "$(declare -p PROMPT_COMMAND 2>/dev/null)" == "declare -a"* ]]; then - PROMPT_COMMAND=("\${PROMPT_COMMAND[@]}" "__orca_prompt_mark") -else - _orca_prev_prompt_command="\${PROMPT_COMMAND}" - if [[ -n "\${_orca_prev_prompt_command}" ]]; then - PROMPT_COMMAND="\${_orca_prev_prompt_command};__orca_prompt_mark" +if [[ "\${ORCA_SHELL_READY_MARKER:-0}" == "1" ]]; then + __orca_prompt_mark() { + printf "\\033]133;A\\007" + } + if [[ "$(declare -p PROMPT_COMMAND 2>/dev/null)" == "declare -a"* ]]; then + PROMPT_COMMAND=("\${PROMPT_COMMAND[@]}" "__orca_prompt_mark") else - PROMPT_COMMAND="__orca_prompt_mark" + _orca_prev_prompt_command="\${PROMPT_COMMAND}" + if [[ -n "\${_orca_prev_prompt_command}" ]]; then + PROMPT_COMMAND="\${_orca_prev_prompt_command};__orca_prompt_mark" + else + PROMPT_COMMAND="__orca_prompt_mark" + fi fi fi ` @@ -129,18 +139,36 @@ _orca_home="\${ORCA_ORIG_ZDOTDIR:-$HOME}" if [[ -o interactive && -f "$_orca_home/.zshrc" ]]; then source "$_orca_home/.zshrc" fi +__orca_restore_attribution_path() { + [[ -n "\${ORCA_ATTRIBUTION_SHIM_DIR:-}" ]] || return 0 + case "$PATH" in + "\${ORCA_ATTRIBUTION_SHIM_DIR}"|"\${ORCA_ATTRIBUTION_SHIM_DIR}:"*) return 0 ;; + esac + export PATH="\${ORCA_ATTRIBUTION_SHIM_DIR}:$PATH" +} +[[ ! -o login ]] && __orca_restore_attribution_path ` const zshLogin = `# Orca zsh shell-ready wrapper _orca_home="\${ORCA_ORIG_ZDOTDIR:-$HOME}" if [[ -o interactive && -f "$_orca_home/.zlogin" ]]; then source "$_orca_home/.zlogin" fi +__orca_restore_attribution_path() { + [[ -n "\${ORCA_ATTRIBUTION_SHIM_DIR:-}" ]] || return 0 + case "$PATH" in + "\${ORCA_ATTRIBUTION_SHIM_DIR}"|"\${ORCA_ATTRIBUTION_SHIM_DIR}:"*) return 0 ;; + esac + export PATH="\${ORCA_ATTRIBUTION_SHIM_DIR}:$PATH" +} +__orca_restore_attribution_path # Why: emit OSC 133;A only after the user's startup hooks finish so Orca knows # the prompt is actually ready for a long startup command paste. -__orca_prompt_mark() { - printf "\\033]133;A\\007" -} -precmd_functions=(\${precmd_functions[@]} __orca_prompt_mark) +if [[ "\${ORCA_SHELL_READY_MARKER:-0}" == "1" ]]; then + __orca_prompt_mark() { + printf "\\033]133;A\\007" + } + precmd_functions=(\${precmd_functions[@]} __orca_prompt_mark) +fi ` const bashRc = getBashShellReadyRcfileContent() @@ -168,7 +196,10 @@ export type ShellReadyLaunchConfig = { supportsReadyMarker: boolean } -export function getShellReadyLaunchConfig(shellPath: string): ShellReadyLaunchConfig { +function getWrappedShellLaunchConfig( + shellPath: string, + options: { emitReadyMarker: boolean } +): ShellReadyLaunchConfig { const shellName = basename(shellPath).toLowerCase() if (shellName === 'zsh') { @@ -177,9 +208,10 @@ export function getShellReadyLaunchConfig(shellPath: string): ShellReadyLaunchCo args: ['-l'], env: { ORCA_ORIG_ZDOTDIR: process.env.ZDOTDIR || process.env.HOME || '', - ZDOTDIR: `${getShellReadyWrapperRoot()}/zsh` + ZDOTDIR: `${getShellReadyWrapperRoot()}/zsh`, + ORCA_SHELL_READY_MARKER: options.emitReadyMarker ? '1' : '0' }, - supportsReadyMarker: true + supportsReadyMarker: options.emitReadyMarker } } @@ -187,8 +219,10 @@ export function getShellReadyLaunchConfig(shellPath: string): ShellReadyLaunchCo ensureShellReadyWrappers() return { args: ['--rcfile', `${getShellReadyWrapperRoot()}/bash/rcfile`], - env: {}, - supportsReadyMarker: true + env: { + ORCA_SHELL_READY_MARKER: options.emitReadyMarker ? '1' : '0' + }, + supportsReadyMarker: options.emitReadyMarker } } @@ -199,6 +233,14 @@ export function getShellReadyLaunchConfig(shellPath: string): ShellReadyLaunchCo } } +export function getShellReadyLaunchConfig(shellPath: string): ShellReadyLaunchConfig { + return getWrappedShellLaunchConfig(shellPath, { emitReadyMarker: true }) +} + +export function getAttributionShellLaunchConfig(shellPath: string): ShellReadyLaunchConfig { + return getWrappedShellLaunchConfig(shellPath, { emitReadyMarker: false }) +} + // โ”€โ”€ Startup command writer โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ export function writeStartupCommandWhenShellReady(