Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 44 additions & 4 deletions src/cli/runtime-client-deferral.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { readFileSync } from 'node:fs'
import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
import { join } from 'node:path'
import { tmpdir } from 'node:os'

const { constructorArgsMock, callMock, getCliStatusMock } = vi.hoisted(() => ({
const {
applyAgentStatusHooksEnabledMock,
constructorArgsMock,
callMock,
getCliStatusMock,
testUserDataPathRef
} = vi.hoisted(() => ({
applyAgentStatusHooksEnabledMock: vi.fn(async () => []),
constructorArgsMock: vi.fn(),
callMock: vi.fn(),
getCliStatusMock: vi.fn()
getCliStatusMock: vi.fn(),
testUserDataPathRef: { current: '' }
}))

// Why: `main` reaches RuntimeClient through `await import('./runtime-client.js')`
Expand All @@ -21,6 +30,20 @@ vi.mock('./runtime/environments', async (importOriginal) => {
}
})

// Why: this suite runs the REAL `main()`, and `agent hooks off` below reaches the production
// handler, which calls removeManagedAgentHooks() against the developer's OWN ~/.claude and
// ~/.cursor — a green test run silently deleted every Orca-managed hook on the machine, so agent
// status stopped reporting until the next Orca restart (STA-5679). The byte-for-byte equivalence
// twin already refuses these tokens for exactly this reason
// (config/scripts/cli-runtime-client-deferral-equivalence.mjs); this is the same guard for vitest.
// Stubbed, not dropped: the row is the only case that reads ctx.client, so it carries the
// null-vs-undefined coverage the rest of the table cannot.
vi.mock('../main/agent-hooks/managed-agent-hook-controls', () => ({
applyAgentStatusHooksEnabled: applyAgentStatusHooksEnabledMock,
getManagedAgentHookStatuses: vi.fn(() => []),
prepareManagedCodexHomeBeforeShellLaunch: vi.fn(async () => {})
}))

vi.mock('./runtime-client', () => {
class RuntimeClient {
call = callMock
Expand All @@ -31,7 +54,7 @@ vi.mock('./runtime-client', () => {
constructorArgsMock(...args)
}
}
return { RuntimeClient, getDefaultUserDataPath: () => '/tmp/orca-user-data' }
return { RuntimeClient, getDefaultUserDataPath: () => testUserDataPathRef.current }
})

import { main } from './index'
Expand All @@ -44,6 +67,8 @@ describe('RuntimeClient module-graph deferral', () => {
let errorSpy: ReturnType<typeof vi.spyOn>

beforeEach(() => {
testUserDataPathRef.current = mkdtempSync(join(tmpdir(), 'orca-runtime-deferral-userdata-'))
applyAgentStatusHooksEnabledMock.mockClear()
constructorArgsMock.mockClear()
callMock.mockReset()
getCliStatusMock.mockReset()
Expand All @@ -55,6 +80,7 @@ describe('RuntimeClient module-graph deferral', () => {
logSpy.mockRestore()
errorSpy.mockRestore()
vi.unstubAllEnvs()
rmSync(testUserDataPathRef.current, { recursive: true, force: true })
process.exitCode = 0
})

Expand Down Expand Up @@ -132,6 +158,20 @@ describe('RuntimeClient module-graph deferral', () => {
expect(call[2], `${argv.join(' ')} pairing code`).toBeNull()
expect(call[3], `${argv.join(' ')} environment`).toBeNull()
}
if (argv.join(' ') === 'agent hooks off') {
expect(
applyAgentStatusHooksEnabledMock,
`${argv.join(' ')} hook application`
).toHaveBeenCalledExactlyOnceWith(false, {
agentCmdOverrides: {},
disabledTuiAgents: []
})
} else {
expect(
applyAgentStatusHooksEnabledMock,
`${argv.join(' ')} hook application`
).not.toHaveBeenCalled()
}
}
)

Expand Down
67 changes: 67 additions & 0 deletions src/main/agent-hooks/managed-agent-hook-controls.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ import {
applyAgentStatusHooksEnabled,
installManagedAgentHooks,
removeManagedAgentHooksAsync,
resolveStartupManagedHookAction,
shouldInstallStartupManagedAgentHook,
shouldContinueManagedHookStartup
} from './managed-agent-hook-controls'

Expand Down Expand Up @@ -273,3 +275,68 @@ describe('managed agent hook controls', () => {
expect(results).toEqual([expect.objectContaining({ agent: 'codex', state: 'not_installed' })])
})
})

describe('startup managed hook reconciliation (STA-5679)', () => {
beforeEach(() => {
vi.clearAllMocks()
})

it('skips instead of removing when this profile has the off switch set', () => {
// Why this matters: the hook files are user-global. Startup removal here deleted the hooks that
// every other Orca instance depends on, and Cursor then reads as idle with no status at all.
expect(resolveStartupManagedHookAction({ agentStatusHooksEnabled: false })).toBe('skip')
})

it('installs when hooks are enabled or the setting is unset', () => {
expect(resolveStartupManagedHookAction({ agentStatusHooksEnabled: true })).toBe('install')
expect(resolveStartupManagedHookAction({})).toBe('install')
expect(resolveStartupManagedHookAction(null)).toBe('install')
})

it('only allows startup installs for globally enabled and agent-enabled hooks', () => {
expect(shouldInstallStartupManagedAgentHook({ agentStatusHooksEnabled: false }, 'codex')).toBe(
false
)
expect(
shouldInstallStartupManagedAgentHook(
{ agentStatusHooksEnabled: true, disabledTuiAgents: ['codex'] },
'codex'
)
).toBe(false)
expect(
shouldInstallStartupManagedAgentHook(
{ agentStatusHooksEnabled: true, disabledTuiAgents: ['claude'] },
'codex'
)
).toBe(true)
})

it('does not remove disabled agents during startup install reconciliation', async () => {
const settings = {
agentStatusHooksEnabled: true,
agentCmdOverrides: {},
disabledTuiAgents: ['claude' as const]
}
mocks.detect.mockResolvedValue({ codex: { state: 'found' } })

await installManagedAgentHooks(settings, {
shouldContinue: (agent) => shouldContinueManagedHookStartup(false, settings, agent)
})

expect(mocks.removeClaude).not.toHaveBeenCalled()
expect(mocks.installClaude).not.toHaveBeenCalled()
expect(mocks.installCodex).toHaveBeenCalledTimes(1)
})

it('still removes through the explicit Settings toggle', async () => {
// Anchors the assertion above: the removers really are wired, so 'skip' is a behavioral
// difference rather than a vacuous constant.
mocks.removeClaude.mockResolvedValue(status('claude', 'not_installed'))
mocks.removeCodex.mockResolvedValue(status('codex', 'not_installed'))

await applyAgentStatusHooksEnabled(false, { agentStatusHooksEnabled: false })

expect(mocks.removeClaude).toHaveBeenCalledTimes(1)
expect(mocks.removeCodex).toHaveBeenCalledTimes(1)
})
})
23 changes: 23 additions & 0 deletions src/main/agent-hooks/managed-agent-hook-controls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,29 @@ export function isAgentStatusHooksEnabled(
return settings?.agentStatusHooksEnabled !== false
}

export type StartupManagedHookAction = 'install' | 'skip'

// Why never 'remove': this reads THIS instance's settings, but the managed hook files are
// user-global (~/.claude/settings.json, ~/.cursor/hooks.json). A second Orca profile with the off
// switch set would delete the hooks every other instance depends on, and Cursor — the one agent
// with no title-derived status fallback — then goes silently idle (STA-5679). Honoring the off
// switch only requires skipping the install; explicit removal stays on the Settings toggle.
export function resolveStartupManagedHookAction(
settings: ManagedHookSettings
): StartupManagedHookAction {
return isAgentStatusHooksEnabled(settings) ? 'install' : 'skip'
}

export function shouldInstallStartupManagedAgentHook(
settings: ManagedHookSettings,
agent: AgentHookTarget
): boolean {
return (
resolveStartupManagedHookAction(settings) === 'install' &&
!normalizeDisabledTuiAgents(settings?.disabledTuiAgents).includes(agent)
)
}

export function shouldContinueManagedHookStartup(
isQuitting: boolean,
settings: ManagedHookSettings,
Expand Down
66 changes: 35 additions & 31 deletions src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,11 @@ import {
sweepRestoredSubagentsWithoutLiveAgent
} from './agent-hooks/restored-subagent-liveness-sweep'
import {
applyAgentStatusHooksEnabled,
installManagedAgentHooks,
isAgentStatusHooksEnabled,
removeManagedAgentHooks,
removeManagedAgentHooksAsync,
resolveStartupManagedHookAction,
shouldInstallStartupManagedAgentHook,
shouldContinueManagedHookStartup
} from './agent-hooks/managed-agent-hook-controls'
import { initCohortClassifier } from './telemetry/cohort-classifier'
Expand Down Expand Up @@ -3089,37 +3090,40 @@ void app.whenReady().then(async () => {
// ordered before managed-hook reconciliation — an incapable host must re-arm
// and complete the legacy real-home sweep first — but awaiting it inline
// stalled app init behind that session, so chain instead of blocking.
const realHomeCodexHookState = codexRuntimeHome.isHostSystemDefaultRealHomeSelected()
? ensureRealHomeCodexHookState({
hooksEnabled: isAgentStatusHooksEnabled(store.getSettings()),
userDataPath: app.getPath('userData')
}).catch((error: unknown) => {
console.warn('[codex-real-home-hooks] startup ensure failed:', error)
})
: Promise.resolve()
if (shouldInstallManagedHooks(is.dev)) {
// Why: check the persisted off switch before any auto-install so removed hooks don't silently reappear on launch.
if (isAgentStatusHooksEnabled(store.getSettings())) {
const managedHookStore = store
void realHomeCodexHookState
.then(() =>
applyAgentStatusHooksEnabled(true, managedHookStore.getSettings(), {
shouldHydrateShellPath: app.isPackaged,
onInstallError: recordManagedHookInstallFailure,
shouldContinue: (agent) => {
const settings = managedHookStore.getSettings()
return shouldContinueManagedHookStartup(isQuitting, settings, agent)
}
})
)
.catch((error: unknown) => {
console.warn('[agent-hooks] failed to reconcile managed hooks on startup:', error)
const startupManagedHookSettings = store.getSettings()
const shouldReconcileStartupManagedHooks =
shouldInstallManagedHooks(is.dev) &&
resolveStartupManagedHookAction(startupManagedHookSettings) === 'install'
const realHomeCodexHookState =
shouldReconcileStartupManagedHooks &&
shouldInstallStartupManagedAgentHook(startupManagedHookSettings, 'codex') &&
codexRuntimeHome.isHostSystemDefaultRealHomeSelected()
? ensureRealHomeCodexHookState({
hooksEnabled: true,
userDataPath: app.getPath('userData')
}).catch((error: unknown) => {
console.warn('[codex-real-home-hooks] startup ensure failed:', error)
})
} else {
void removeManagedAgentHooks().catch((error: unknown) => {
console.warn('[agent-hooks] failed to remove managed hooks on startup:', error)
: Promise.resolve()
// Why skip rather than remove when the off switch is set: the hook files are user-global but this
// decision reads only THIS profile's settings, so removing here deletes the hooks every other Orca
// instance depends on (STA-5679). Skipping already keeps removed hooks from reappearing on launch.
if (shouldReconcileStartupManagedHooks) {
const managedHookStore = store
void realHomeCodexHookState
.then(() =>
installManagedAgentHooks(managedHookStore.getSettings(), {
shouldHydrateShellPath: app.isPackaged,
onInstallError: recordManagedHookInstallFailure,
shouldContinue: (agent) => {
const settings = managedHookStore.getSettings()
return shouldContinueManagedHookStartup(isQuitting, settings, agent)
}
})
)
.catch((error: unknown) => {
console.warn('[agent-hooks] failed to reconcile managed hooks on startup:', error)
})
}
}
// Why: process-gone metrics only see survivors; retain a recent whole-app
// snapshot for comparison in crash reports.
Expand Down