From 1395b6f5160616eeafd4e7c1d4ccb1349e33cfd7 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Sun, 12 Apr 2026 01:20:20 -0700 Subject: [PATCH] Support Pi titlebar status tracking (#530) --- src/main/ipc/pty.test.ts | 48 ++++++- src/main/ipc/pty.ts | 52 ++++--- src/main/pi/titlebar-extension-service.ts | 167 ++++++++++++++++++++++ src/renderer/src/lib/agent-status.test.ts | 19 +++ src/shared/agent-detection.ts | 25 ++++ 5 files changed, 289 insertions(+), 22 deletions(-) create mode 100644 src/main/pi/titlebar-extension-service.ts diff --git a/src/main/ipc/pty.test.ts b/src/main/ipc/pty.test.ts index c56e5bd3d..c65179788 100644 --- a/src/main/ipc/pty.test.ts +++ b/src/main/ipc/pty.test.ts @@ -13,7 +13,9 @@ const { accessSyncMock, spawnMock, openCodeBuildPtyEnvMock, - openCodeClearPtyMock + openCodeClearPtyMock, + piBuildPtyEnvMock, + piClearPtyMock } = vi.hoisted(() => ({ handleMock: vi.fn(), onMock: vi.fn(), @@ -24,7 +26,9 @@ const { accessSyncMock: vi.fn(), spawnMock: vi.fn(), openCodeBuildPtyEnvMock: vi.fn(), - openCodeClearPtyMock: vi.fn() + openCodeClearPtyMock: vi.fn(), + piBuildPtyEnvMock: vi.fn(), + piClearPtyMock: vi.fn() })) vi.mock('electron', () => ({ @@ -56,6 +60,12 @@ vi.mock('../opencode/hook-service', () => ({ } })) +vi.mock('../pi/titlebar-extension-service', () => ({ + piTitlebarExtensionService: { + buildPtyEnv: piBuildPtyEnvMock, + clearPty: piClearPtyMock + } +})) import { registerPtyHandlers } from './pty' describe('registerPtyHandlers', () => { @@ -80,6 +90,8 @@ describe('registerPtyHandlers', () => { spawnMock.mockReset() openCodeBuildPtyEnvMock.mockReset() openCodeClearPtyMock.mockReset() + piBuildPtyEnvMock.mockReset() + piClearPtyMock.mockReset() mainWindow.webContents.on.mockReset() mainWindow.webContents.send.mockReset() @@ -94,6 +106,11 @@ describe('registerPtyHandlers', () => { ORCA_OPENCODE_PTY_ID: 'test-pty', OPENCODE_CONFIG_DIR: '/tmp/orca-opencode-config' }) + piBuildPtyEnvMock.mockImplementation((_ptyId: string, existingAgentDir?: string) => ({ + PI_CODING_AGENT_DIR: existingAgentDir + ? '/tmp/orca-pi-agent-overlay' + : '/tmp/orca-pi-agent-overlay' + })) spawnMock.mockReturnValue({ onData: vi.fn(), onExit: vi.fn(), @@ -182,6 +199,11 @@ describe('registerPtyHandlers', () => { expect(env.OPENCODE_CONFIG_DIR).toBe('/tmp/orca-opencode-config') }) + it('injects the Pi agent overlay env into Orca terminal PTYs', () => { + const env = spawnAndGetEnv(undefined, { PI_CODING_AGENT_DIR: '/tmp/user-pi-agent' }) + expect(piBuildPtyEnvMock).toHaveBeenCalledWith(expect.any(String), '/tmp/user-pi-agent') + expect(env.PI_CODING_AGENT_DIR).toBe('/tmp/orca-pi-agent-overlay') + }) it('leaves ambient CODEX_HOME untouched when system default is selected', () => { const env = spawnAndGetEnv(undefined, { CODEX_HOME: '/tmp/system-codex-home' }, () => null) expect(env.CODEX_HOME).toBe('/tmp/system-codex-home') @@ -346,4 +368,26 @@ describe('registerPtyHandlers', () => { } } }) + + it('cleans up provider-specific PTY overlays when a PTY is killed', () => { + const proc = { + onData: vi.fn(), + onExit: vi.fn(), + write: vi.fn(), + resize: vi.fn(), + kill: vi.fn() + } + spawnMock.mockReturnValue(proc) + + registerPtyHandlers(mainWindow as never) + const spawnResult = handlers.get('pty:spawn')!(null, { + cols: 80, + rows: 24 + }) as { id: string } + + handlers.get('pty:kill')!(null, { id: spawnResult.id }) + + expect(openCodeClearPtyMock).toHaveBeenCalledWith(spawnResult.id) + expect(piClearPtyMock).toHaveBeenCalledWith(spawnResult.id) + }) }) diff --git a/src/main/ipc/pty.ts b/src/main/ipc/pty.ts index a14a22b75..1f994c2b3 100644 --- a/src/main/ipc/pty.ts +++ b/src/main/ipc/pty.ts @@ -10,6 +10,7 @@ import * as pty from 'node-pty' import type { OrcaRuntimeService } from '../runtime/orca-runtime' import { parseWslPath } from '../wsl' import { openCodeHookService } from '../opencode/hook-service' +import { piTitlebarExtensionService } from '../pi/titlebar-extension-service' let ptyCounter = 0 const ptyProcesses = new Map() @@ -25,6 +26,20 @@ let loadGeneration = 0 const ptyLoadGeneration = new Map() let didEnsureSpawnHelperExecutable = false +function clearPtyState(id: string): void { + ptyProcesses.delete(id) + ptyShellName.delete(id) + ptyLoadGeneration.delete(id) +} + +function clearProviderPtyState(id: string): void { + // Why: OpenCode and Pi both allocate PTY-scoped runtime state outside the + // node-pty process table. Centralizing provider cleanup avoids drift where a + // new teardown path forgets to remove one provider's overlay/hook state. + openCodeHookService.clearPty(id) + piTitlebarExtensionService.clearPty(id) +} + function getShellValidationError(shellPath: string): string | null { if (!existsSync(shellPath)) { return ( @@ -110,10 +125,8 @@ export function registerPtyHandlers( } catch { // Process may already be dead } - ptyProcesses.delete(id) - ptyShellName.delete(id) - ptyLoadGeneration.delete(id) - openCodeHookService.clearPty(id) + clearPtyState(id) + clearProviderPtyState(id) // Why: notify runtime so the agent detector can close out any live // agent sessions. Without this, killed PTYs would remain in the // detector's liveAgents map and accumulate inflated durations. @@ -143,10 +156,8 @@ export function registerPtyHandlers( } catch { return false } - ptyProcesses.delete(ptyId) - ptyShellName.delete(ptyId) - ptyLoadGeneration.delete(ptyId) - openCodeHookService.clearPty(ptyId) + clearPtyState(ptyId) + clearProviderPtyState(ptyId) runtime?.onPtyExit(ptyId, -1) return true } @@ -235,6 +246,13 @@ export function registerPtyHandlers( delete openCodeHookEnv.OPENCODE_CONFIG_DIR } Object.assign(spawnEnv, openCodeHookEnv) + // Why: PI_CODING_AGENT_DIR owns Pi's full config/session root. Build a + // PTY-scoped overlay from the caller's chosen root so Pi sessions keep + // their user state without sharing a mutable overlay across terminals. + Object.assign( + spawnEnv, + piTitlebarExtensionService.buildPtyEnv(id, spawnEnv.PI_CODING_AGENT_DIR) + ) // Why: the selected Codex account should affect Codex launched inside // Orca terminals too, not just Orca's background quota fetches. Inject @@ -347,10 +365,8 @@ export function registerPtyHandlers( }) proc.onExit(({ exitCode }) => { - ptyProcesses.delete(id) - ptyShellName.delete(id) - ptyLoadGeneration.delete(id) - openCodeHookService.clearPty(id) + clearPtyState(id) + clearProviderPtyState(id) runtime?.onPtyExit(id, exitCode) if (!mainWindow.isDestroyed()) { mainWindow.webContents.send('pty:exit', { id, code: exitCode }) @@ -383,10 +399,8 @@ export function registerPtyHandlers( } catch { // Process may already be dead } - ptyProcesses.delete(args.id) - ptyShellName.delete(args.id) - ptyLoadGeneration.delete(args.id) - openCodeHookService.clearPty(args.id) + clearPtyState(args.id) + clearProviderPtyState(args.id) runtime?.onPtyExit(args.id, -1) } }) @@ -442,9 +456,7 @@ export function killAllPty(): void { } catch { // Process may already be dead } - ptyProcesses.delete(id) - ptyShellName.delete(id) - ptyLoadGeneration.delete(id) - openCodeHookService.clearPty(id) + clearPtyState(id) + clearProviderPtyState(id) } } diff --git a/src/main/pi/titlebar-extension-service.ts b/src/main/pi/titlebar-extension-service.ts new file mode 100644 index 000000000..1bb0f2f93 --- /dev/null +++ b/src/main/pi/titlebar-extension-service.ts @@ -0,0 +1,167 @@ +import { + cpSync, + existsSync, + linkSync, + mkdirSync, + readdirSync, + rmSync, + statSync, + symlinkSync, + writeFileSync +} from 'fs' +import { homedir } from 'os' +import { basename, join } from 'path' +import { app } from 'electron' + +const ORCA_PI_EXTENSION_FILE = 'orca-titlebar-spinner.ts' +const PI_AGENT_DIR_NAME = '.pi' +const PI_AGENT_SUBDIR = 'agent' +const PI_OVERLAY_DIR_NAME = 'pi-agent-overlays' + +function getPiTitlebarExtensionSource(): string { + return [ + 'const BRAILLE_FRAMES = [', + " '\\u280b',", + " '\\u2819',", + " '\\u2839',", + " '\\u2838',", + " '\\u283c',", + " '\\u2834',", + " '\\u2826',", + " '\\u2827',", + " '\\u2807',", + " '\\u280f'", + ']', + '', + 'function getBaseTitle(pi) {', + ' const cwd = process.cwd().split(/[\\\\/]/).filter(Boolean).at(-1) || process.cwd()', + ' const session = pi.getSessionName()', + ' return session ? `\\u03c0 - ${session} - ${cwd}` : `\\u03c0 - ${cwd}`', + '}', + '', + 'export default function (pi) {', + ' let timer = null', + ' let frameIndex = 0', + '', + ' function stopAnimation(ctx) {', + ' if (timer) {', + ' clearInterval(timer)', + ' timer = null', + ' }', + ' frameIndex = 0', + ' ctx.ui.setTitle(getBaseTitle(pi))', + ' }', + '', + ' function startAnimation(ctx) {', + ' stopAnimation(ctx)', + ' timer = setInterval(() => {', + ' const frame = BRAILLE_FRAMES[frameIndex % BRAILLE_FRAMES.length]', + ' const cwd = process.cwd().split(/[\\\\/]/).filter(Boolean).at(-1) || process.cwd()', + ' const session = pi.getSessionName()', + ' const title = session ? `${frame} \\u03c0 - ${session} - ${cwd}` : `${frame} \\u03c0 - ${cwd}`', + ' ctx.ui.setTitle(title)', + ' frameIndex++', + ' }, 80)', + ' }', + '', + " pi.on('agent_start', async (_event, ctx) => {", + ' startAnimation(ctx)', + ' })', + '', + " pi.on('agent_end', async (_event, ctx) => {", + ' stopAnimation(ctx)', + ' })', + '', + " pi.on('session_shutdown', async (_event, ctx) => {", + ' stopAnimation(ctx)', + ' })', + '}', + '' + ].join('\n') +} + +function getDefaultPiAgentDir(): string { + return join(homedir(), PI_AGENT_DIR_NAME, PI_AGENT_SUBDIR) +} + +function mirrorEntry(sourcePath: string, targetPath: string): void { + const sourceStats = statSync(sourcePath) + + if (process.platform === 'win32') { + if (sourceStats.isDirectory()) { + symlinkSync(sourcePath, targetPath, 'junction') + return + } + + try { + linkSync(sourcePath, targetPath) + return + } catch { + cpSync(sourcePath, targetPath) + return + } + } + + symlinkSync(sourcePath, targetPath, sourceStats.isDirectory() ? 'dir' : 'file') +} + +export class PiTitlebarExtensionService { + private getOverlayDir(ptyId: string): string { + return join(app.getPath('userData'), PI_OVERLAY_DIR_NAME, ptyId) + } + + private mirrorAgentDir(sourceAgentDir: string, overlayDir: string): void { + if (!existsSync(sourceAgentDir)) { + return + } + + for (const entry of readdirSync(sourceAgentDir, { withFileTypes: true })) { + const sourcePath = join(sourceAgentDir, entry.name) + + if (entry.name === 'extensions' && entry.isDirectory()) { + const overlayExtensionsDir = join(overlayDir, 'extensions') + mkdirSync(overlayExtensionsDir, { recursive: true }) + for (const extensionEntry of readdirSync(sourcePath, { withFileTypes: true })) { + mirrorEntry( + join(sourcePath, extensionEntry.name), + join(overlayExtensionsDir, extensionEntry.name) + ) + } + continue + } + + // Why: PI_CODING_AGENT_DIR controls Pi's entire state tree, not just + // extension discovery. Mirror the user's top-level Pi resources into the + // overlay so enabling Orca's titlebar extension preserves auth, sessions, + // skills, prompts, themes, and any future files Pi stores there. + mirrorEntry(sourcePath, join(overlayDir, basename(sourcePath))) + } + } + + buildPtyEnv(ptyId: string, existingAgentDir: string | undefined): Record { + const sourceAgentDir = existingAgentDir || getDefaultPiAgentDir() + const overlayDir = this.getOverlayDir(ptyId) + + rmSync(overlayDir, { recursive: true, force: true }) + mkdirSync(overlayDir, { recursive: true }) + this.mirrorAgentDir(sourceAgentDir, overlayDir) + + const extensionsDir = join(overlayDir, 'extensions') + mkdirSync(extensionsDir, { recursive: true }) + // Why: Pi auto-loads global extensions from PI_CODING_AGENT_DIR/extensions. + // Add Orca's titlebar extension alongside the user's existing extensions + // instead of replacing that directory, otherwise Orca terminals would + // silently disable the user's Pi customization inside Orca only. + writeFileSync(join(extensionsDir, ORCA_PI_EXTENSION_FILE), getPiTitlebarExtensionSource()) + + return { + PI_CODING_AGENT_DIR: overlayDir + } + } + + clearPty(ptyId: string): void { + rmSync(this.getOverlayDir(ptyId), { recursive: true, force: true }) + } +} + +export const piTitlebarExtensionService = new PiTitlebarExtensionService() diff --git a/src/renderer/src/lib/agent-status.test.ts b/src/renderer/src/lib/agent-status.test.ts index 1648a6370..31d1dd4fe 100644 --- a/src/renderer/src/lib/agent-status.test.ts +++ b/src/renderer/src/lib/agent-status.test.ts @@ -153,6 +153,11 @@ describe('detectAgentStatusFromTitle', () => { expect(detectAgentStatusFromTitle('opencode')).toBe('idle') }) + it('detects Pi idle titles', () => { + expect(detectAgentStatusFromTitle('π - my-project')).toBe('idle') + expect(detectAgentStatusFromTitle('π - session-name - my-project')).toBe('idle') + }) + // --- Case insensitivity --- it('is case-insensitive for agent names', () => { expect(detectAgentStatusFromTitle('CLAUDE')).toBe('idle') @@ -205,6 +210,11 @@ describe('normalizeTerminalTitle', () => { expect(normalizeTerminalTitle('⠂ Claude Code')).toBe('⠂ Claude Code') expect(normalizeTerminalTitle('bash')).toBe('bash') }) + + it('collapses Pi spinner and idle titles to stable labels', () => { + expect(normalizeTerminalTitle('⠋ π - my-project')).toBe('⠋ Pi') + expect(normalizeTerminalTitle('π - my-project')).toBe('Pi') + }) }) describe('isGeminiTerminalTitle', () => { @@ -292,6 +302,15 @@ describe('createAgentStatusTracker', () => { expect(onBecameIdle).toHaveBeenCalledTimes(1) }) + it('fires on Pi working → idle', () => { + const onBecameIdle = vi.fn() + const tracker = createAgentStatusTracker(onBecameIdle) + + tracker.handleTitle('⠋ π - my-project') + tracker.handleTitle('π - my-project') + expect(onBecameIdle).toHaveBeenCalledTimes(1) + }) + // --- Multiple cycles --- it('fires on each working → idle cycle', () => { const onBecameIdle = vi.fn() diff --git a/src/shared/agent-detection.ts b/src/shared/agent-detection.ts index ae0f31dc5..0cad21f47 100644 --- a/src/shared/agent-detection.ts +++ b/src/shared/agent-detection.ts @@ -17,6 +17,7 @@ const GEMINI_IDLE = '\u25C7' // ◇ const GEMINI_PERMISSION = '\u270B' // ✋ export const AGENT_NAMES = ['claude', 'codex', 'gemini', 'opencode', 'aider'] +const PI_IDLE_PREFIX = '\u03c0 - ' // π - (Pi titlebar extension idle format) // eslint-disable-next-line no-control-regex -- intentional terminal escape sequence matching const OSC_TITLE_RE = /\x1b\]([012]);([^\x07\x1b]*?)(?:\x07|\x1b\\)/g @@ -47,6 +48,10 @@ export function isGeminiTerminalTitle(title: string): boolean { ) } +export function isPiTerminalTitle(title: string): boolean { + return title.startsWith(PI_IDLE_PREFIX) +} + function containsBrailleSpinner(title: string): boolean { for (const char of title) { const codePoint = char.codePointAt(0) @@ -167,6 +172,22 @@ export function normalizeTerminalTitle(title: string): string { } } + // Why: Pi's titlebar extension animates every 80ms with different braille + // frames. Collapsing those frames into one stable label avoids renderer + // churn while preserving the working/idle transition Orca keys off. + if ( + isPiTerminalTitle(title) || + (containsBrailleSpinner(title) && title.includes(PI_IDLE_PREFIX)) + ) { + const status = detectAgentStatusFromTitle(title) + if (status === 'working') { + return '\u280b Pi' + } + if (status === 'idle') { + return 'Pi' + } + } + return title } @@ -227,6 +248,10 @@ export function detectAgentStatusFromTitle(title: string): AgentStatus | null { return 'idle' } + if (isPiTerminalTitle(title)) { + return 'idle' + } + if (containsBrailleSpinner(title)) { return 'working' }