feat: scope terminal shell history per worktree (#620)

* feat: scope terminal shell history per worktree

Each worktree gets its own HISTFILE so ArrowUp only surfaces commands
from the current worktree. Integrates with the new LocalPtyProvider
architecture: history env injection runs after buildSpawnEnv but before
spawnShellWithFallback, and onBeforeFallbackSpawn keeps HISTFILE in
sync when the shell falls back.

* fix: align preload type declaration with implementation

Add missing command field to PtyApi.spawn in index.d.ts to match
the runtime index.ts signature, fixing TS2769 overload conflict.

* chore: remove terminal-history-scope-design.md from tracked files

* fix: mock terminal-history in worktrees test

The deleteWorktreeHistoryDir import pulls in electron's app module.
Add a vi.mock so the test doesn't hit the real electron export.
This commit is contained in:
Jinjing
2026-04-13 22:42:53 -07:00
committed by GitHub
parent 28a1c93c8c
commit 130c3e9697
17 changed files with 867 additions and 8 deletions
+7 -2
View File
@@ -6,6 +6,7 @@ process behavior across files without a cleaner ownership seam. */
import { type BrowserWindow, ipcMain } from 'electron'
export { getBashShellReadyRcfileContent } from '../providers/local-pty-shell-ready'
import type { OrcaRuntimeService } from '../runtime/orca-runtime'
import type { GlobalSettings } from '../../shared/types'
import { openCodeHookService } from '../opencode/hook-service'
import { piTitlebarExtensionService } from '../pi/titlebar-extension-service'
import { LocalPtyProvider } from '../providers/local-pty-provider'
@@ -114,7 +115,8 @@ let didFinishLoadHandler: (() => void) | null = null
export function registerPtyHandlers(
mainWindow: BrowserWindow,
runtime?: OrcaRuntimeService,
getSelectedCodexHomePath?: () => string | null
getSelectedCodexHomePath?: () => string | null,
getSettings?: () => GlobalSettings
): void {
// Remove any previously registered handlers so we can re-register them
// (e.g. when macOS re-activates the app and creates a new window).
@@ -127,6 +129,7 @@ export function registerPtyHandlers(
// Configure the local provider with app-specific hooks
localProvider.configure({
isHistoryEnabled: () => getSettings?.()?.terminalScopeHistoryByWorktree ?? true,
buildSpawnEnv: (id, baseEnv) => {
const selectedCodexHomePath = getSelectedCodexHomePath?.() ?? null
@@ -234,6 +237,7 @@ export function registerPtyHandlers(
env?: Record<string, string>
command?: string
connectionId?: string | null
worktreeId?: string
}
) => {
const provider = getProvider(args.connectionId)
@@ -242,7 +246,8 @@ export function registerPtyHandlers(
rows: args.rows,
cwd: args.cwd,
env: args.env,
command: args.command
command: args.command,
worktreeId: args.worktreeId
})
ptyOwnership.set(result.id, args.connectionId ?? null)
return result
+9
View File
@@ -90,6 +90,14 @@ vi.mock('./worktree-logic', async (importOriginal) => {
}
})
const { deleteWorktreeHistoryDirMock } = vi.hoisted(() => ({
deleteWorktreeHistoryDirMock: vi.fn()
}))
vi.mock('../terminal-history', () => ({
deleteWorktreeHistoryDir: deleteWorktreeHistoryDirMock
}))
import { registerWorktreeHandlers } from './worktrees'
type HandlerMap = Record<string, (_event: unknown, args: unknown) => unknown>
@@ -407,6 +415,7 @@ describe('registerWorktreeHandlers', () => {
cwd: '/workspace/repo'
})
expect(store.removeWorktreeMeta).toHaveBeenCalledWith('repo-1::/workspace/feature-wt')
expect(deleteWorktreeHistoryDirMock).toHaveBeenCalledWith('repo-1::/workspace/feature-wt')
expect(mainWindow.webContents.send).toHaveBeenCalledWith('worktrees:changed', {
repoId: 'repo-1'
})
+4
View File
@@ -3,6 +3,7 @@ import { ipcMain } from 'electron'
import { rm } from 'fs/promises'
import type { Store } from '../persistence'
import { isFolderRepo } from '../../shared/repo-kind'
import { deleteWorktreeHistoryDir } from '../terminal-history'
import type {
CreateWorktreeArgs,
CreateWorktreeResult,
@@ -154,6 +155,7 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store
}
await provider.removeWorktree(worktreePath, args.force)
store.removeWorktreeMeta(args.worktreeId)
deleteWorktreeHistoryDir(args.worktreeId)
notifyWorktreesChanged(mainWindow, repoId)
return
}
@@ -180,6 +182,7 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store
// remains locked — other worktrees cannot check it out.
await gitExecFileAsync(['worktree', 'prune'], { cwd: repo.path }).catch(() => {})
store.removeWorktreeMeta(args.worktreeId)
deleteWorktreeHistoryDir(args.worktreeId)
await rebuildAuthorizedRootsCache(store)
notifyWorktreesChanged(mainWindow, repoId)
return
@@ -187,6 +190,7 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store
throw new Error(formatWorktreeRemovalError(error, worktreePath, args.force ?? false))
}
store.removeWorktreeMeta(args.worktreeId)
deleteWorktreeHistoryDir(args.worktreeId)
await rebuildAuthorizedRootsCache(store)
notifyWorktreesChanged(mainWindow, repoId)
+29 -1
View File
@@ -6,6 +6,11 @@ import { basename, win32 as pathWin32 } from 'path'
import { existsSync } from 'fs'
import * as pty from 'node-pty'
import { parseWslPath } from '../wsl'
import {
injectHistoryEnv,
updateHistFileForFallback,
logHistoryInjection
} from '../terminal-history'
import type { IPtyProvider, PtySpawnOptions, PtySpawnResult } from './types'
import {
ensureNodePtySpawnHelperExecutable,
@@ -67,6 +72,9 @@ function safeKillAndClean(id: string, proc: pty.IPty): void {
export type LocalPtyProviderOptions = {
buildSpawnEnv?: (id: string, baseEnv: Record<string, string>) => Record<string, string>
/** Whether worktree-scoped shell history is enabled. When true (or absent)
* and a worktreeId is provided, HISTFILE is scoped per-worktree. */
isHistoryEnabled?: () => boolean
onSpawned?: (id: string) => void
onExit?: (id: string, code: number) => void
onData?: (id: string, data: string, timestamp: number) => void
@@ -168,6 +176,20 @@ export class LocalPtyProvider implements IPtyProvider {
const finalEnv = this.opts.buildSpawnEnv ? this.opts.buildSpawnEnv(id, spawnEnv) : spawnEnv
// ── Worktree-scoped shell history (§7–§10 of terminal-history-scope-design) ──
// Why: without this, all worktree terminals share a single global HISTFILE
// so ArrowUp in worktree B surfaces commands from worktree A.
const worktreeId = args.worktreeId
const historyEnabled = worktreeId && (this.opts.isHistoryEnabled?.() ?? true)
// Resolve the effective shell kind for history injection. For WSL, the
// outer executable is wsl.exe but the inner login shell is bash.
const effectiveShellPath = wslInfo ? 'bash' : shellPath
let historyResult: ReturnType<typeof injectHistoryEnv> | null = null
if (historyEnabled) {
historyResult = injectHistoryEnv(finalEnv, worktreeId, effectiveShellPath, cwd)
logHistoryInjection(worktreeId, historyResult)
}
const spawnResult = spawnShellWithFallback({
shellPath,
shellArgs,
@@ -176,7 +198,13 @@ export class LocalPtyProvider implements IPtyProvider {
cwd: effectiveCwd,
env: finalEnv,
ptySpawn: pty.spawn,
getShellReadyConfig: args.command ? (shell) => getShellReadyLaunchConfig(shell) : undefined
getShellReadyConfig: args.command ? (shell) => getShellReadyLaunchConfig(shell) : undefined,
// Why: if zsh failed and bash took over, HISTFILE still points to
// zsh_history. Update it *before* spawn so the child inherits the
// correct filename (see design doc §8).
onBeforeFallbackSpawn: historyResult?.histFile
? (env, fallbackShell) => updateHistFileForFallback(env, fallbackShell)
: undefined
})
shellPath = spawnResult.shellPath
+15 -1
View File
@@ -97,6 +97,9 @@ export type ShellSpawnParams = {
getShellReadyConfig?: (
shell: string
) => { args: string[] | null; env: Record<string, string> } | null
/** Called before each fallback shell spawn so callers can update env vars
* (e.g. HISTFILE) that depend on which shell is about to run. */
onBeforeFallbackSpawn?: (env: Record<string, string>, fallbackShell: string) => void
}
export type ShellSpawnResult = {
@@ -109,7 +112,17 @@ export type ShellSpawnResult = {
* try common fallback shells before giving up.
*/
export function spawnShellWithFallback(params: ShellSpawnParams): ShellSpawnResult {
const { shellPath, shellArgs, cols, rows, cwd, env, ptySpawn, getShellReadyConfig } = params
const {
shellPath,
shellArgs,
cols,
rows,
cwd,
env,
ptySpawn,
getShellReadyConfig,
onBeforeFallbackSpawn
} = params
let primaryError: string | null = null
if (process.platform !== 'win32') {
@@ -137,6 +150,7 @@ export function spawnShellWithFallback(params: ShellSpawnParams): ShellSpawnResu
try {
const fallbackReady = getShellReadyConfig?.(fallback)
env.SHELL = fallback
onBeforeFallbackSpawn?.(env, fallback)
Object.assign(env, fallbackReady?.env ?? {})
const proc = ptySpawn(fallback, fallbackReady?.args ?? ['-l'], {
name: 'xterm-256color',
+3
View File
@@ -18,6 +18,9 @@ export type PtySpawnOptions = {
cwd?: string
env?: Record<string, string>
command?: string
/** Orca worktree identity. When present, the local provider scopes shell
* history to this worktree so ArrowUp only surfaces local commands. */
worktreeId?: string
}
export type PtySpawnResult = {
+400
View File
@@ -0,0 +1,400 @@
/* eslint-disable max-lines -- Why: history scoping touches shell detection, env
injection, fallback patching, WSL translation, cleanup, and GC with a TOCTOU age
guard — covering each path in one test file keeps assertions co-located with the
shared mock harness rather than splitting across files. */
import { beforeEach, describe, expect, it, vi } from 'vitest'
const {
existsSyncMock,
mkdirSyncMock,
writeFileSyncMock,
readFileSyncMock,
rmSyncMock,
readdirSyncMock,
statSyncMock,
getPathMock
} = vi.hoisted(() => ({
existsSyncMock: vi.fn(),
mkdirSyncMock: vi.fn(),
writeFileSyncMock: vi.fn(),
readFileSyncMock: vi.fn(),
rmSyncMock: vi.fn(),
readdirSyncMock: vi.fn(),
statSyncMock: vi.fn(),
getPathMock: vi.fn()
}))
vi.mock('fs', () => ({
existsSync: existsSyncMock,
mkdirSync: mkdirSyncMock,
writeFileSync: writeFileSyncMock,
readFileSync: readFileSyncMock,
rmSync: rmSyncMock,
readdirSync: readdirSyncMock,
statSync: statSyncMock
}))
vi.mock('electron', () => ({
app: {
getPath: getPathMock
}
}))
const { parseWslPathMock, toLinuxPathMock } = vi.hoisted(() => ({
parseWslPathMock: vi.fn((_path: string) => null as { distro: string; linuxPath: string } | null),
toLinuxPathMock: vi.fn((p: string) => p)
}))
vi.mock('./wsl', () => ({
parseWslPath: parseWslPathMock,
toLinuxPath: toLinuxPathMock
}))
import {
resolveShellKind,
hashWorktreeId,
ensureHistoryDir,
injectHistoryEnv,
updateHistFileForFallback,
deleteWorktreeHistoryDir,
runHistoryGc
} from './terminal-history'
describe('terminal-history', () => {
beforeEach(() => {
vi.clearAllMocks()
getPathMock.mockReturnValue('/fake/userData')
existsSyncMock.mockReturnValue(true)
statSyncMock.mockReturnValue({ isDirectory: () => true, size: 100 })
})
describe('resolveShellKind', () => {
it('detects zsh', () => {
expect(resolveShellKind('/bin/zsh')).toBe('zsh')
})
it('detects bash', () => {
expect(resolveShellKind('/bin/bash')).toBe('bash')
})
it('detects versioned bash (bash-5.2)', () => {
expect(resolveShellKind('/usr/local/bin/bash-5.2')).toBe('bash')
})
it('detects versioned zsh (zsh-5.9)', () => {
expect(resolveShellKind('/usr/local/bin/zsh-5.9')).toBe('zsh')
})
it('detects nix-store zsh path', () => {
expect(resolveShellKind('/nix/store/abc123/bin/zsh')).toBe('zsh')
})
it('detects fish', () => {
expect(resolveShellKind('/usr/bin/fish')).toBe('fish')
})
it('detects pwsh', () => {
expect(resolveShellKind('pwsh')).toBe('pwsh')
expect(resolveShellKind('pwsh.exe')).toBe('pwsh')
})
it('detects cmd.exe', () => {
expect(resolveShellKind('cmd.exe')).toBe('cmd')
})
it('returns unknown for unrecognized shells', () => {
expect(resolveShellKind('/bin/tcsh')).toBe('unknown')
expect(resolveShellKind('/bin/dash')).toBe('unknown')
expect(resolveShellKind('/bin/elvish')).toBe('unknown')
})
})
describe('hashWorktreeId', () => {
it('produces deterministic output for the same input', () => {
const a = hashWorktreeId('repo-1::/Users/foo/worktree-a')
const b = hashWorktreeId('repo-1::/Users/foo/worktree-a')
expect(a).toBe(b)
})
it('produces different output for different inputs', () => {
const a = hashWorktreeId('repo-1::/Users/foo/worktree-a')
const b = hashWorktreeId('repo-1::/Users/foo/worktree-b')
expect(a).not.toBe(b)
})
it('produces a 16-character hex string', () => {
const hash = hashWorktreeId('repo-1::/Users/foo/worktree-a')
expect(hash).toMatch(/^[0-9a-f]{16}$/)
})
})
describe('ensureHistoryDir', () => {
it('creates directory with mode 0o700', () => {
ensureHistoryDir('abcdef0123456789')
expect(mkdirSyncMock).toHaveBeenCalledWith(
'/fake/userData/terminal-history/abcdef0123456789',
{ recursive: true, mode: 0o700 }
)
})
it('returns null on mkdir failure', () => {
mkdirSyncMock.mockImplementation(() => {
throw new Error('permission denied')
})
const result = ensureHistoryDir('abcdef0123456789')
expect(result).toBeNull()
})
})
describe('injectHistoryEnv', () => {
it('injects HISTFILE for zsh', () => {
mkdirSyncMock.mockReturnValue(undefined)
const env: Record<string, string> = {}
const result = injectHistoryEnv(env, 'repo-1::/path/wt', '/bin/zsh', '/path/wt')
expect(result.shell).toBe('zsh')
expect(result.histFile).toContain('terminal-history')
expect(result.histFile).toContain('zsh_history')
expect(env.HISTFILE).toBe(result.histFile)
})
it('injects HISTFILE for bash', () => {
mkdirSyncMock.mockReturnValue(undefined)
const env: Record<string, string> = {}
const result = injectHistoryEnv(env, 'repo-1::/path/wt', '/bin/bash', '/path/wt')
expect(result.shell).toBe('bash')
expect(result.histFile).toContain('bash_history')
expect(env.HISTFILE).toBe(result.histFile)
})
it('produces different HISTFILE for different worktreeIds', () => {
mkdirSyncMock.mockReturnValue(undefined)
existsSyncMock.mockReturnValue(true)
const envA: Record<string, string> = {}
injectHistoryEnv(envA, 'repo-1::/path/wt-a', '/bin/zsh', '/path/wt-a')
const envB: Record<string, string> = {}
injectHistoryEnv(envB, 'repo-1::/path/wt-b', '/bin/zsh', '/path/wt-b')
expect(envA.HISTFILE).not.toBe(envB.HISTFILE)
})
it('preserves caller-provided HISTFILE (check-before-set)', () => {
const env: Record<string, string> = { HISTFILE: '/my/custom/histfile' }
const result = injectHistoryEnv(env, 'repo-1::/path/wt', '/bin/zsh', '/path/wt')
expect(env.HISTFILE).toBe('/my/custom/histfile')
expect(result.histFile).toBeNull()
})
it('does not inject HISTFILE for unknown shells', () => {
const env: Record<string, string> = {}
const result = injectHistoryEnv(env, 'repo-1::/path/wt', '/bin/tcsh', '/path/wt')
expect(env.HISTFILE).toBeUndefined()
expect(result.shell).toBe('unknown')
expect(result.histFile).toBeNull()
})
it('does not inject HISTFILE for cmd.exe', () => {
const env: Record<string, string> = {}
const result = injectHistoryEnv(env, 'repo-1::/path/wt', 'cmd.exe', '/path/wt')
expect(env.HISTFILE).toBeUndefined()
expect(result.shell).toBe('cmd')
expect(result.histFile).toBeNull()
})
it('does not inject HISTFILE for fish (Phase 2)', () => {
const env: Record<string, string> = {}
const result = injectHistoryEnv(env, 'repo-1::/path/wt', '/usr/bin/fish', '/path/wt')
expect(env.HISTFILE).toBeUndefined()
expect(result.shell).toBe('fish')
})
it('degrades gracefully when directory creation fails', () => {
mkdirSyncMock.mockImplementation(() => {
throw new Error('disk full')
})
const env: Record<string, string> = {}
const result = injectHistoryEnv(env, 'repo-1::/path/wt', '/bin/zsh', '/path/wt')
expect(env.HISTFILE).toBeUndefined()
expect(result.histFile).toBeNull()
})
})
describe('updateHistFileForFallback', () => {
it('updates HISTFILE to match fallback shell', () => {
const env: Record<string, string> = {
HISTFILE: '/fake/userData/terminal-history/abc123/zsh_history'
}
updateHistFileForFallback(env, '/bin/bash')
expect(env.HISTFILE).toBe('/fake/userData/terminal-history/abc123/bash_history')
})
it('removes HISTFILE for unknown fallback shell', () => {
const env: Record<string, string> = {
HISTFILE: '/fake/userData/terminal-history/abc123/zsh_history'
}
updateHistFileForFallback(env, '/bin/sh')
expect(env.HISTFILE).toBeUndefined()
})
it('is a no-op when HISTFILE is not set', () => {
const env: Record<string, string> = {}
updateHistFileForFallback(env, '/bin/bash')
expect(env.HISTFILE).toBeUndefined()
})
})
describe('deleteWorktreeHistoryDir', () => {
it('removes the history directory for a worktree', () => {
existsSyncMock.mockReturnValue(true)
deleteWorktreeHistoryDir('repo-1::/path/wt')
expect(rmSyncMock).toHaveBeenCalledWith(expect.stringContaining('terminal-history'), {
recursive: true,
force: true
})
})
it('does not throw on deletion failure', () => {
existsSyncMock.mockReturnValue(true)
rmSyncMock.mockImplementation(() => {
throw new Error('permission denied')
})
expect(() => deleteWorktreeHistoryDir('repo-1::/path/wt')).not.toThrow()
})
})
describe('runHistoryGc', () => {
it('prunes orphaned directories', () => {
existsSyncMock.mockImplementation((p: string) => {
// WSL root doesn't exist, so GC skips it
if (p.includes('terminal-history-wsl')) {
return false
}
return true
})
readdirSyncMock.mockImplementation((dir: string) => {
if (dir.endsWith('terminal-history')) {
return ['dir1', 'dir2']
}
return ['meta.json']
})
statSyncMock.mockReturnValue({ isDirectory: () => true, size: 100 })
readFileSyncMock.mockImplementation((p: string) => {
// Use a createdAt old enough to pass the GC age threshold
const oldDate = new Date(Date.now() - 10 * 60 * 1000).toISOString()
if (p.includes('dir1')) {
return JSON.stringify({ worktreeId: 'live-wt', createdAt: oldDate })
}
return JSON.stringify({ worktreeId: 'dead-wt', createdAt: oldDate })
})
const liveIds = new Set(['live-wt'])
runHistoryGc(liveIds)
// Should only prune dir2 (dead-wt), not dir1 (live-wt)
expect(rmSyncMock).toHaveBeenCalledTimes(1)
expect(rmSyncMock).toHaveBeenCalledWith(expect.stringContaining('dir2'), {
recursive: true,
force: true
})
})
it('skips recently-created directories to avoid TOCTOU race', () => {
existsSyncMock.mockImplementation((p: string) => {
if (p.includes('terminal-history-wsl')) {
return false
}
return true
})
readdirSyncMock.mockImplementation((dir: string) => {
if (dir.endsWith('terminal-history')) {
return ['fresh-dir']
}
return ['meta.json']
})
statSyncMock.mockReturnValue({ isDirectory: () => true, size: 100 })
// createdAt is just now — younger than the 5-minute GC threshold
readFileSyncMock.mockReturnValue(
JSON.stringify({ worktreeId: 'unknown-wt', createdAt: new Date().toISOString() })
)
runHistoryGc(new Set())
// Should NOT prune because the directory is too young
expect(rmSyncMock).not.toHaveBeenCalled()
})
it('does not throw when history root does not exist', () => {
existsSyncMock.mockReturnValue(false)
expect(() => runHistoryGc(new Set())).not.toThrow()
expect(readdirSyncMock).not.toHaveBeenCalled()
})
})
describe('WSL path conversion', () => {
it('converts HISTFILE to Linux path for WSL cwd', () => {
const originalPlatform = process.platform
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
try {
parseWslPathMock.mockReturnValue({ distro: 'Ubuntu', linuxPath: '/home/user/project' })
toLinuxPathMock.mockReturnValue(
'/mnt/c/Users/user/AppData/Roaming/Orca/terminal-history-wsl/Ubuntu/abc123/bash_history'
)
mkdirSyncMock.mockReturnValue(undefined)
existsSyncMock.mockReturnValue(true)
const env: Record<string, string> = {}
const result = injectHistoryEnv(
env,
'repo-1::/wsl/path',
'/bin/bash',
'\\\\wsl.localhost\\Ubuntu\\home\\user\\project'
)
expect(toLinuxPathMock).toHaveBeenCalled()
expect(result.histFile).toContain('/mnt/')
expect(env.HISTFILE).toBe(result.histFile)
} finally {
Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform })
}
})
it('stores WSL history under terminal-history-wsl/<distro>/', () => {
const originalPlatform = process.platform
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
try {
parseWslPathMock.mockReturnValue({ distro: 'Ubuntu', linuxPath: '/home/user' })
toLinuxPathMock.mockImplementation((p: string) => p)
mkdirSyncMock.mockReturnValue(undefined)
existsSyncMock.mockReturnValue(true)
const env: Record<string, string> = {}
injectHistoryEnv(
env,
'repo-1::/wsl/path',
'/bin/bash',
'\\\\wsl.localhost\\Ubuntu\\home\\user'
)
expect(mkdirSyncMock).toHaveBeenCalledWith(
expect.stringContaining('terminal-history-wsl/Ubuntu'),
expect.any(Object)
)
} finally {
Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform })
}
})
})
})
+366
View File
@@ -0,0 +1,366 @@
import { createHash } from 'crypto'
import { join, basename } from 'path'
import {
mkdirSync,
existsSync,
readFileSync,
writeFileSync,
readdirSync,
rmSync,
statSync
} from 'fs'
import { app } from 'electron'
import { parseWslPath, toLinuxPath } from './wsl'
// ─── Constants ─────────────────────────────────────────────────────
const HISTORY_DIR_NAME = 'terminal-history'
const HISTORY_DIR_NAME_WSL = 'terminal-history-wsl'
type ShellKind = 'zsh' | 'bash' | 'fish' | 'pwsh' | 'powershell' | 'cmd' | 'unknown'
// ─── Shell Detection ───────────────────────────────────────────────
/** Resolve the shell kind from a shell binary path.
* Uses basename + prefix matching to handle versioned names like `bash-5.2`
* and nix-store paths like `/nix/store/.../bin/zsh`. */
export function resolveShellKind(shellPath: string): ShellKind {
const name = basename(shellPath).toLowerCase()
if (name.startsWith('zsh')) {
return 'zsh'
}
if (name.startsWith('bash')) {
return 'bash'
}
if (name.startsWith('fish')) {
return 'fish'
}
if (name === 'pwsh' || name === 'pwsh.exe') {
return 'pwsh'
}
if (name === 'powershell' || name === 'powershell.exe') {
return 'powershell'
}
if (name === 'cmd' || name === 'cmd.exe') {
return 'cmd'
}
return 'unknown'
}
// ─── Hash & Path Helpers ───────────────────────────────────────────
/** First 16 hex chars of SHA-256 of the worktreeId. */
export function hashWorktreeId(worktreeId: string): string {
return createHash('sha256').update(worktreeId).digest('hex').slice(0, 16)
}
/** Map shell kind to the filename used inside the history directory. */
function historyFilename(shell: ShellKind): string | null {
switch (shell) {
case 'zsh':
return 'zsh_history'
case 'bash':
return 'bash_history'
// Phase 2: fish and PowerShell use different mechanisms
default:
return null
}
}
// ─── Directory Management ──────────────────────────────────────────
function getHistoryRoot(): string {
return join(app.getPath('userData'), HISTORY_DIR_NAME)
}
function getHistoryRootWsl(distro: string): string {
return join(app.getPath('userData'), HISTORY_DIR_NAME_WSL, distro)
}
/** Ensure the history directory exists for a given worktree hash.
* Returns the directory path, or null if creation failed. */
export function ensureHistoryDir(worktreeHash: string, wslDistro?: string): string | null {
try {
const root = wslDistro ? getHistoryRootWsl(wslDistro) : getHistoryRoot()
const dir = join(root, worktreeHash)
mkdirSync(dir, { recursive: true, mode: 0o700 })
return dir
} catch (err) {
console.warn(
`[pty:history] Failed to create history directory: ${err instanceof Error ? err.message : String(err)}`
)
return null
}
}
/** Write meta.json alongside history files for debuggability. */
function writeMetaFile(dir: string, worktreeId: string): void {
try {
const metaPath = join(dir, 'meta.json')
if (!existsSync(metaPath)) {
writeFileSync(metaPath, JSON.stringify({ worktreeId, createdAt: new Date().toISOString() }), {
mode: 0o600
})
}
} catch {
// Non-fatal — meta.json is purely for diagnostics.
}
}
// ─── Environment Injection ─────────────────────────────────────────
export type HistoryInjectionResult = {
shell: ShellKind
histFile: string | null
}
/** Build shell-specific history env overrides for a PTY spawn.
* Returns the injection result for diagnostics logging.
*
* Why this is the industry-standard approach: Ghostty, Kitty, and VS Code
* all use check-before-set for HISTFILE. The major zsh frameworks (oh-my-zsh,
* Prezto) guard their HISTFILE assignments, so env-var injection works for
* the vast majority of users (see design doc §9). */
export function injectHistoryEnv(
spawnEnv: Record<string, string>,
worktreeId: string,
shellPath: string,
cwd: string
): HistoryInjectionResult {
const shell = resolveShellKind(shellPath)
const result: HistoryInjectionResult = { shell, histFile: null }
const filename = historyFilename(shell)
if (!filename) {
// Unknown shell or Phase 2 shell (fish, pwsh, cmd) — leave unchanged.
return result
}
// Check-before-set: if the caller already provided HISTFILE, preserve it.
// This follows the pattern used by Ghostty, Kitty, and VS Code (§6).
if (spawnEnv.HISTFILE) {
return result
}
const worktreeHash = hashWorktreeId(worktreeId)
// WSL: store under a separate root keyed by distro, and convert the
// HISTFILE path to a Linux-visible /mnt/... path for the inner shell.
const wslInfo = process.platform === 'win32' ? parseWslPath(cwd) : null
const histDir = ensureHistoryDir(worktreeHash, wslInfo?.distro)
if (!histDir) {
// Directory creation failed — degrade gracefully to shared history.
return result
}
writeMetaFile(histDir, worktreeId)
const histFilePath = join(histDir, filename)
// For WSL, convert the Windows path to a Linux-visible path.
spawnEnv.HISTFILE = wslInfo ? toLinuxPath(histFilePath) : histFilePath
result.histFile = spawnEnv.HISTFILE
return result
}
/** Update HISTFILE in spawnEnv when shell fallback changes the shell kind.
* For example, if zsh fails and bash takes over, the HISTFILE should point
* to bash_history instead of zsh_history. */
export function updateHistFileForFallback(
spawnEnv: Record<string, string>,
fallbackShellPath: string
): void {
if (!spawnEnv.HISTFILE) {
return
}
const newShell = resolveShellKind(fallbackShellPath)
const newFilename = historyFilename(newShell)
if (!newFilename) {
// Fallback to an unknown shell — remove HISTFILE override entirely
// so the shell uses its own default.
delete spawnEnv.HISTFILE
return
}
// Replace the filename portion of the HISTFILE path.
const dir = spawnEnv.HISTFILE.replace(/[/\\][^/\\]+$/, '')
spawnEnv.HISTFILE = `${dir}/${newFilename}`
}
/** Log the history injection result for diagnostics. */
export function logHistoryInjection(worktreeId: string, result: HistoryInjectionResult): void {
const truncatedId = worktreeId.length > 60 ? `${worktreeId.slice(0, 60)}...` : worktreeId
console.log(
`[pty:history] worktreeId=${truncatedId} shell=${result.shell} histFile=${result.histFile ?? 'none'}`
)
}
// ─── Cleanup ───────────────────────────────────────────────────────
/** Delete the history directory for a removed worktree. Non-fatal. */
export function deleteWorktreeHistoryDir(worktreeId: string): void {
const worktreeHash = hashWorktreeId(worktreeId)
const dir = join(getHistoryRoot(), worktreeHash)
try {
if (existsSync(dir)) {
rmSync(dir, { recursive: true, force: true })
console.log(`[pty:history] Deleted history for worktree ${worktreeId}`)
}
} catch (err) {
console.warn(
`[pty:history] Failed to delete history dir: ${err instanceof Error ? err.message : String(err)}`
)
}
// Also clean up WSL directories if any exist.
if (process.platform === 'win32') {
try {
const wslRoot = join(app.getPath('userData'), HISTORY_DIR_NAME_WSL)
if (existsSync(wslRoot)) {
for (const distro of readdirSync(wslRoot)) {
const wslDir = join(wslRoot, distro, worktreeHash)
if (existsSync(wslDir)) {
rmSync(wslDir, { recursive: true, force: true })
}
}
}
} catch {
// Non-fatal.
}
}
}
// ─── Garbage Collection ────────────────────────────────────────────
// Why 5 minutes: GC runs ~10s after startup, and the live-worktree snapshot is
// taken just before. A worktree created between the snapshot and GC execution
// won't appear in liveWorktreeIds, so without an age guard GC would delete its
// freshly-created history directory (TOCTOU race). 5 minutes is generous enough
// to cover any realistic snapshot-to-scan delay.
const GC_MIN_AGE_MS = 5 * 60 * 1000
/** Scan a single history root directory, pruning orphaned entries.
* Returns { totalDirs, orphaned, pruned, totalSizeKB }. */
function gcScanRoot(
root: string,
liveWorktreeIds: Set<string>
): { totalDirs: number; orphaned: number; pruned: number; totalSizeKB: number } {
const result = { totalDirs: 0, orphaned: 0, pruned: 0, totalSizeKB: 0 }
if (!existsSync(root)) {
return result
}
const now = Date.now()
for (const entry of readdirSync(root)) {
const entryPath = join(root, entry)
try {
const stat = statSync(entryPath)
if (!stat.isDirectory()) {
continue
}
result.totalDirs++
// Estimate directory size from meta.json + history files.
try {
for (const file of readdirSync(entryPath)) {
result.totalSizeKB += Math.ceil(statSync(join(entryPath, file)).size / 1024)
}
} catch {
// Skip size estimation on error.
}
const metaPath = join(entryPath, 'meta.json')
if (!existsSync(metaPath)) {
// No meta.json — can't determine ownership, skip.
continue
}
const meta = JSON.parse(readFileSync(metaPath, 'utf-8')) as {
worktreeId?: string
createdAt?: string
}
if (!meta.worktreeId) {
continue
}
if (!liveWorktreeIds.has(meta.worktreeId)) {
// Why: avoid a TOCTOU race where a worktree is created after the
// live-ID snapshot but before GC runs. Directories younger than
// GC_MIN_AGE_MS are presumed still live and skipped.
if (meta.createdAt) {
const ageMs = now - new Date(meta.createdAt).getTime()
if (ageMs < GC_MIN_AGE_MS) {
continue
}
}
result.orphaned++
rmSync(entryPath, { recursive: true, force: true })
result.pruned++
console.log(`[pty:history:gc] Pruned orphaned history: ${meta.worktreeId}`)
}
} catch {
// Skip individual entries that fail.
}
}
return result
}
/** Run background GC to prune history directories for worktrees that no
* longer exist. Must be called after live worktree enumeration is complete
* to avoid deleting history for worktrees that haven't been discovered yet. */
export function runHistoryGc(liveWorktreeIds: Set<string>): void {
try {
const main = gcScanRoot(getHistoryRoot(), liveWorktreeIds)
// Also scan WSL history directories (each distro has its own subdirectory).
const wslRoot = join(app.getPath('userData'), HISTORY_DIR_NAME_WSL)
let wslTotals = { totalDirs: 0, orphaned: 0, pruned: 0, totalSizeKB: 0 }
if (existsSync(wslRoot)) {
try {
for (const distro of readdirSync(wslRoot)) {
const distroRoot = join(wslRoot, distro)
const r = gcScanRoot(distroRoot, liveWorktreeIds)
wslTotals.totalDirs += r.totalDirs
wslTotals.orphaned += r.orphaned
wslTotals.pruned += r.pruned
wslTotals.totalSizeKB += r.totalSizeKB
}
} catch {
// Non-fatal.
}
}
const totalDirs = main.totalDirs + wslTotals.totalDirs
const orphaned = main.orphaned + wslTotals.orphaned
const pruned = main.pruned + wslTotals.pruned
const totalSizeKB = main.totalSizeKB + wslTotals.totalSizeKB
console.log(
`[pty:history:gc] totalDirs=${totalDirs} orphaned=${orphaned} pruned=${pruned} totalSizeKB=${totalSizeKB}`
)
} catch (err) {
console.warn(`[pty:history:gc] GC failed: ${err instanceof Error ? err.message : String(err)}`)
}
}
/** Schedule GC after a delay so it runs after workspace hydration completes.
* `getLiveWorktreeIds` should enumerate all currently known worktree IDs
* (e.g. by listing repos and their git worktrees). */
export function scheduleHistoryGc(getLiveWorktreeIds: () => Promise<Set<string>>): void {
// Why 10s: avoids competing with startup-critical I/O while still running
// early enough to clean up before the user notices disk usage (§7.6).
setTimeout(async () => {
try {
const liveIds = await getLiveWorktreeIds()
runHistoryGc(liveIds)
} catch (err) {
console.warn(
`[pty:history:gc] Failed to enumerate live worktrees for GC: ${err instanceof Error ? err.message : String(err)}`
)
}
}, 10_000)
}
+17 -1
View File
@@ -20,6 +20,8 @@ import {
setupAutoUpdater,
dismissNudge
} from '../updater'
import { scheduleHistoryGc } from '../terminal-history'
import { listRepoWorktrees } from '../repo-worktrees'
export function attachMainWindowServices(
mainWindow: BrowserWindow,
@@ -29,7 +31,21 @@ export function attachMainWindowServices(
): void {
registerRepoHandlers(mainWindow, store)
registerWorktreeHandlers(mainWindow, store)
registerPtyHandlers(mainWindow, runtime, getSelectedCodexHomePath)
registerPtyHandlers(mainWindow, runtime, getSelectedCodexHomePath, () => store.getSettings())
// Why: GC runs on a 10s delay so live worktree enumeration completes first.
// Uses git worktree list (not store.getWorktreeMeta) because untouched
// worktrees have no metadata entries — see design doc §7.6.
scheduleHistoryGc(async () => {
const repos = store.getRepos()
const ids = new Set<string>()
for (const repo of repos) {
const worktrees = await listRepoWorktrees(repo)
for (const wt of worktrees) {
ids.add(`${repo.id}::${wt.path}`)
}
}
return ids
})
registerSshHandlers(store, () => mainWindow)
registerFileDropRelay(mainWindow)
setupAutoUpdater(mainWindow, {
+2
View File
@@ -51,7 +51,9 @@ type PtyApi = {
rows: number
cwd?: string
env?: Record<string, string>
command?: string
connectionId?: string | null
worktreeId?: string
}) => Promise<{ id: string }>
write: (id: string, data: string) => void
resize: (id: string, cols: number, rows: number) => void
+1
View File
@@ -252,6 +252,7 @@ const api = {
env?: Record<string, string>
command?: string
connectionId?: string | null
worktreeId?: string
}): Promise<{ id: string }> => ipcRenderer.invoke('pty:spawn', opts),
write: (id: string, data: string): void => {
@@ -159,6 +159,7 @@ export function connectPanePty(
env: paneStartup?.env,
command: paneStartup?.command,
connectionId,
worktreeId: deps.worktreeId,
onPtyExit: onExit,
onTitleChange,
onPtySpawn,
@@ -153,6 +153,8 @@ export type IpcPtyTransportOptions = {
env?: Record<string, string>
command?: string
connectionId?: string | null
/** Orca worktree identity for scoped shell history. */
worktreeId?: string
onPtyExit?: (ptyId: string) => void
onTitleChange?: (title: string, rawTitle: string) => void
onPtySpawn?: (ptyId: string) => void
@@ -31,6 +31,7 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra
env,
command,
connectionId,
worktreeId,
onPtyExit,
onTitleChange,
onPtySpawn,
@@ -179,7 +180,8 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra
cwd,
env,
command,
...(connectionId ? { connectionId } : {})
...(connectionId ? { connectionId } : {}),
worktreeId
})
// If destroyed while spawn was in flight, kill the new pty and bail
+2 -1
View File
@@ -957,7 +957,8 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
const { id: ptyId } = await window.api.pty.spawn({
cols: 80,
rows: 24,
cwd: worktree.path
cwd: worktree.path,
worktreeId
})
spawnedPtyIds.push(ptyId)
+2 -1
View File
@@ -116,7 +116,8 @@ export function getDefaultSettings(homedir: string): GlobalSettings {
promptCacheTimerEnabled: false,
promptCacheTtlMs: 300_000,
codexManagedAccounts: [],
activeCodexManagedAccountId: null
activeCodexManagedAccountId: null,
terminalScopeHistoryByWorktree: true
}
}
+4
View File
@@ -491,6 +491,10 @@ export type GlobalSettings = {
* analytics and external terminal sessions. */
codexManagedAccounts: CodexManagedAccount[]
activeCodexManagedAccountId: string | null
/** When true, each worktree gets its own shell history file so ArrowUp
* does not surface commands from other worktrees. Defaults to true.
* Disable to revert to shared global shell history. */
terminalScopeHistoryByWorktree: boolean
}
export type NotificationEventSource = 'agent-task-complete' | 'terminal-bell' | 'test'