Fix attribution daemon follow-up (#1088)

This commit is contained in:
Neil
2026-04-25 14:04:08 -07:00
committed by GitHub
parent fef3f7d2f8
commit 15918d64d5
13 changed files with 605 additions and 67 deletions
+6 -5
View File
@@ -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 <help@stably.ai>'
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 {
+27 -2
View File
@@ -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<void>; 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
+38 -8
View File
@@ -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<void> {
const runtimeDir = getRuntimeDir()
await cleanupPreviousProtocolDaemons(runtimeDir)
const newSpawner = new DaemonSpawner({
runtimeDir,
@@ -191,9 +191,21 @@ export async function initDaemonPtyProvider(): Promise<void> {
}
})
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<void> {
async function createLegacyDaemonAdapters(runtimeDir: string): Promise<DaemonPtyAdapter[]> {
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
+3 -1
View File
@@ -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
+156
View File
@@ -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<PtySpawnResult> => {
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()
})
})
+199
View File
@@ -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<string, DaemonPtyAdapter>()
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<void> {
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<PtySpawnResult> {
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<void> {
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<void> {
await this.adapterFor(id).shutdown(id, immediate)
this.sessionAdapters.delete(id)
}
async sendSignal(id: string, signal: string): Promise<void> {
await this.adapterFor(id).sendSignal(id, signal)
}
async getCwd(id: string): Promise<string> {
return this.adapterFor(id).getCwd(id)
}
async getInitialCwd(id: string): Promise<string> {
return this.adapterFor(id).getInitialCwd(id)
}
async clearBuffer(id: string): Promise<void> {
await this.adapterFor(id).clearBuffer(id)
}
acknowledgeDataEvent(id: string, charCount: number): void {
this.adapterFor(id).acknowledgeDataEvent(id, charCount)
}
async hasChildProcesses(id: string): Promise<boolean> {
return this.adapterFor(id).hasChildProcesses(id)
}
async getForegroundProcess(id: string): Promise<string | null> {
return this.adapterFor(id).getForegroundProcess(id)
}
async serialize(ids: string[]): Promise<string> {
return this.current.serialize(ids)
}
async revive(state: string): Promise<void> {
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<string> {
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<string>): 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]
}
}
+20
View File
@@ -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)
+13 -5
View File
@@ -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
+62 -18
View File
@@ -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<string, string>): boolean
return shellName === 'zsh' || shellName === 'bash'
}
export function getShellReadyLaunchConfig(shellPath: string): {
type ShellLaunchConfig = {
args: string[] | null
env: Record<string, string>
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 })
}
+4 -4
View File
@@ -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'
+2 -2
View File
@@ -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 <help@stably.ai>')
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')
})
+14 -3
View File
@@ -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<string, string> = {
...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
+61 -19
View File
@@ -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(