perf(windows): relax whole-process-table scans for terminals with no agent evidence (#7607)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Brennan Benson
2026-07-08 16:41:21 -07:00
committed by GitHub
co-authored by Orca
parent 685418d8e4
commit c8c5201145
8 changed files with 524 additions and 26 deletions
@@ -0,0 +1,185 @@
// Regression guard: bound the volume of whole-process-table scans the daemon
// schedules for persisted sessions. On Windows each agent-foreground refresh
// forks a powershell.exe/CIM whole-table scan (the daemon-side analogue of
// #6288), so an idle shell with no agent identity and no recent output must
// retry slowly no matter how often readers poll getForegroundProcess; PTY
// output re-arms the fast retry so agent starts still resolve promptly, and
// sessions with a cached agent identity keep the 1s refresh unrelaxed.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
const { spawnMock, isPwshAvailableMock, resolveAgentForegroundProcessMock } = vi.hoisted(() => ({
spawnMock: vi.fn(),
isPwshAvailableMock: vi.fn(),
resolveAgentForegroundProcessMock: vi.fn()
}))
vi.mock('node-pty', () => ({
spawn: spawnMock
}))
vi.mock('../pwsh', () => ({
isPwshAvailable: isPwshAvailableMock
}))
// Resolve PowerShell family names to deterministic absolute paths so these
// tests run on non-Windows CI (mirrors pty-subprocess.test.ts).
const PWSH7_ABS = 'C:\\Program Files\\PowerShell\\7\\pwsh.exe'
const WINDOWS_POWERSHELL_ABS = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'
const CMD_ABS = 'C:\\Windows\\System32\\cmd.exe'
vi.mock('../providers/windows-powershell-executable', () => ({
resolveWindowsPowerShellExecutablePath: (family: 'pwsh.exe' | 'powershell.exe') =>
family === 'pwsh.exe' ? PWSH7_ABS : WINDOWS_POWERSHELL_ABS,
resolveWindowsPowerShellSpawnChain: (family: 'pwsh.exe' | 'powershell.exe') =>
family === 'pwsh.exe'
? [PWSH7_ABS, WINDOWS_POWERSHELL_ABS, CMD_ABS]
: [WINDOWS_POWERSHELL_ABS, CMD_ABS],
getWindowsCmdPath: () => CMD_ABS
}))
vi.mock('../providers/agent-foreground-process', () => ({
resolveAgentForegroundProcess: resolveAgentForegroundProcessMock
}))
import { createPtySubprocess } from './pty-subprocess'
// Well past any hot window or retry throttle so t=0 reads behave as idle.
const BASE_TIME_MS = 1_000_000
function mockPtyProcess(processName: string, pid = 12345) {
const onDataListeners: ((data: string) => void)[] = []
return {
pid,
write: vi.fn(),
resize: vi.fn(),
kill: vi.fn(),
process: processName,
onData: vi.fn((cb: (data: string) => void) => {
onDataListeners.push(cb)
return { dispose: vi.fn() }
}),
onExit: vi.fn(() => ({ dispose: vi.fn() })),
_simulateData: (data: string) => onDataListeners.forEach((cb) => cb(data))
}
}
async function flushAsyncTicks(count = 6): Promise<void> {
for (let i = 0; i < count; i++) {
await Promise.resolve()
}
}
// One renderer/daemon reader poll: read the foreground and let the scheduled
// background refresh (if any) settle so its cache write lands before the next.
async function readForegroundAt(
handle: { getForegroundProcess: () => string | null },
atMs: number
): Promise<string | null> {
vi.setSystemTime(BASE_TIME_MS + atMs)
const foreground = handle.getForegroundProcess()
await flushAsyncTicks()
return foreground
}
describe('daemon pty foreground scan cadence', () => {
let platform: PropertyDescriptor | undefined
let previousUserDataPath: string | undefined
let userDataPath: string
beforeEach(() => {
spawnMock.mockReset()
isPwshAvailableMock.mockReset()
isPwshAvailableMock.mockReturnValue(false)
resolveAgentForegroundProcessMock.mockReset()
previousUserDataPath = process.env.ORCA_USER_DATA_PATH
userDataPath = mkdtempSync(join(tmpdir(), 'daemon-pty-scan-cadence-test-'))
process.env.ORCA_USER_DATA_PATH = userDataPath
platform = Object.getOwnPropertyDescriptor(process, 'platform')
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime(BASE_TIME_MS)
})
afterEach(() => {
vi.useRealTimers()
if (platform) {
Object.defineProperty(process, 'platform', platform)
}
if (previousUserDataPath === undefined) {
delete process.env.ORCA_USER_DATA_PATH
} else {
process.env.ORCA_USER_DATA_PATH = previousUserDataPath
}
rmSync(userDataPath, { recursive: true, force: true })
})
function spawnShellSubprocess(shellProcessName: string, targetPlatform: 'win32' | 'darwin') {
Object.defineProperty(process, 'platform', { configurable: true, value: targetPlatform })
const proc = mockPtyProcess(shellProcessName)
spawnMock.mockReturnValue(proc)
const handle = createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 })
return { proc, handle }
}
it('bounds scans for an idle Windows shell polled every 2s to the 15s retry tier', async () => {
resolveAgentForegroundProcessMock.mockResolvedValue('powershell.exe')
const { handle } = spawnShellSubprocess('powershell.exe', 'win32')
for (let atMs = 0; atMs <= 60_000; atMs += 2_000) {
expect(await readForegroundAt(handle, atMs)).toBe('powershell.exe')
}
// Scans at t=0s, 16s, 32s, 48s. Pre-fix (5s retry) the same 31 reads drove
// 11 whole-table scans; the 2s read cadence itself would drive 31.
expect(resolveAgentForegroundProcessMock).toHaveBeenCalledTimes(4)
})
it('re-arms the fast retry when PTY output appears on an idle Windows shell', async () => {
resolveAgentForegroundProcessMock.mockResolvedValueOnce('powershell.exe')
const { proc, handle } = spawnShellSubprocess('powershell.exe', 'win32')
await readForegroundAt(handle, 0)
await readForegroundAt(handle, 2_000)
await readForegroundAt(handle, 4_000)
await readForegroundAt(handle, 6_000)
// Idle: only the t=0 scan ran (6s is within the relaxed 15s retry).
expect(resolveAgentForegroundProcessMock).toHaveBeenCalledTimes(1)
// The user launches an agent; its startup output re-arms the 5s retry.
resolveAgentForegroundProcessMock.mockResolvedValue('claude')
vi.setSystemTime(BASE_TIME_MS + 6_500)
proc._simulateData('claude\r\n')
await readForegroundAt(handle, 8_000)
expect(resolveAgentForegroundProcessMock).toHaveBeenCalledTimes(2)
// The resolved identity is served from the cache on the next read.
expect(await readForegroundAt(handle, 8_500)).toBe('claude')
})
it('keeps the fast identity refresh for a Windows session with a cached agent', async () => {
resolveAgentForegroundProcessMock.mockResolvedValue('codex')
const { handle } = spawnShellSubprocess('powershell.exe', 'win32')
await readForegroundAt(handle, 0)
expect(await readForegroundAt(handle, 1_000)).toBe('codex')
await readForegroundAt(handle, 3_000)
await readForegroundAt(handle, 5_000)
// Every read past the 1s cache TTL refreshes (t=0s, 1s, 3s, 5s): agent-exit
// detection through the identity cache must not be relaxed by the idle tier.
expect(resolveAgentForegroundProcessMock).toHaveBeenCalledTimes(4)
})
it('keeps the 5s retry for an idle POSIX shell with no output', async () => {
resolveAgentForegroundProcessMock.mockResolvedValue('zsh')
const { handle } = spawnShellSubprocess('zsh', 'darwin')
for (let atMs = 0; atMs <= 30_000; atMs += 2_000) {
expect(await readForegroundAt(handle, atMs)).toBe('zsh')
}
// Scans at t=0s, 6s, 12s, 18s, 24s, 30s — the cheap `ps` path is unchanged.
expect(resolveAgentForegroundProcessMock).toHaveBeenCalledTimes(6)
})
})
+19 -3
View File
@@ -64,6 +64,12 @@ const PANE_IDENTITY_ENV_KEYS = [
] as const
const FOREGROUND_AGENT_CACHE_TTL_MS = 1000
const SHELL_FOREGROUND_REFRESH_RETRY_MS = 5_000
// Why: a Windows refresh forks a powershell.exe whole-process-table CIM scan
// (~10-40x heavier than POSIX `ps`). An idle shell with no agent identity and
// no recent output retries far slower; output re-arms the 5s retry so an agent
// start (which always prints) is still resolved promptly.
const WINDOWS_IDLE_SHELL_FOREGROUND_REFRESH_RETRY_MS = 15_000
const SHELL_FOREGROUND_OUTPUT_HOT_WINDOW_MS = 10_000
const STARTUP_AGENT_FOREGROUND_BOOTSTRAP_MS = 5_000
const PTY_SPAWN_HEALTH_TIMEOUT_MS = 4_000
// Why: a busy machine right after an upgrade can make one short-lived shell
@@ -840,7 +846,11 @@ export function createPtySubprocess(opts: PtySubprocessOptions): SubprocessHandl
}
}
let lastOutputAt = 0
proc.onData((data) => {
if (data.length > 0) {
lastOutputAt = Date.now()
}
if (onDataCb) {
onDataCb(data)
} else {
@@ -912,10 +922,16 @@ export function createPtySubprocess(opts: PtySubprocessOptions): SubprocessHandl
return
}
const now = Date.now()
const retryMs =
const idleNoEvidenceShell =
fallbackIsShell && !getActiveStartupAgentForeground(now) && !cachedAgentForeground
? SHELL_FOREGROUND_REFRESH_RETRY_MS
: FOREGROUND_AGENT_CACHE_TTL_MS
// Why: on Windows each refresh is a whole-table CIM scan; only shells with
// no agent evidence and no recent output relax, so agent-identity refresh
// (cached identity → 1s TTL) and post-output starts keep the fast retry.
const retryMs = !idleNoEvidenceShell
? FOREGROUND_AGENT_CACHE_TTL_MS
: process.platform === 'win32' && now - lastOutputAt > SHELL_FOREGROUND_OUTPUT_HOT_WINDOW_MS
? WINDOWS_IDLE_SHELL_FOREGROUND_REFRESH_RETRY_MS
: SHELL_FOREGROUND_REFRESH_RETRY_MS
if (foregroundRefreshInFlight || now - lastForegroundRefreshStartedAt < retryMs) {
return
}
@@ -29,6 +29,10 @@ export type AgentCompletionCoordinatorOptions = {
dispatchAttention?: (title: string, meta: AgentAttentionDispatchMeta) => void
isLive: () => boolean
shouldPollProcessCadence?: () => boolean
// Why: on hosts where one inspection forks a whole-process-table scan (local
// Windows PowerShell/CIM), panes without agent evidence relax to a slow
// cadence; cheap hosts (POSIX `ps`, SSH/remote-owned scans) keep full cadence.
isProcessInspectionCostly?: () => boolean
shouldSuppressHookCompletion?: (payload: AgentCompletionStatusSnapshot) => boolean
}
@@ -36,6 +40,7 @@ export type AgentCompletionCoordinator = {
observeTitle: (title: string) => void
observeClassifiedTitleCompletion: (title: string) => void
observeTitleWorking: () => void
observeOutputActivity: () => void
observeHookStatus: (payload: AgentCompletionStatusSnapshot) => void
startProcessTracking: () => void
hasPendingHookDoneCompletion: () => boolean
@@ -115,6 +115,7 @@ describe('agent completion coordinator', () => {
shouldPollProcessCadence: () => false
})
coordinator.startProcessTracking()
coordinator.observeTitle('Codex working')
await vi.advanceTimersByTimeAsync(60_000)
@@ -136,6 +137,7 @@ describe('agent completion coordinator', () => {
shouldPollProcessCadence: () => true
})
coordinator.startProcessTracking()
coordinator.observeTitle('Codex working')
await vi.advanceTimersByTimeAsync(60_000)
@@ -156,6 +158,7 @@ describe('agent completion coordinator', () => {
shouldPollProcessCadence: () => visible
})
coordinator.startProcessTracking()
coordinator.observeTitle('Codex working')
// First hidden poll runs and arms the next 3s backstop timer.
await vi.advanceTimersByTimeAsync(3_000)
@@ -188,6 +191,7 @@ describe('agent completion coordinator', () => {
shouldPollProcessCadence: () => false
})
coordinator.startProcessTracking()
coordinator.observeTitle('Codex working')
await vi.advanceTimersByTimeAsync(3_000)
@@ -25,6 +25,8 @@ import {
type CompletionSource = 'hook' | 'title' | 'process-exit'
type CompletionIdentitySource = 'hook' | 'title' | 'process-exit'
type PollCadenceTier = 'active' | 'idle' | 'hidden' | 'no-evidence'
type LastCompletionIdentity = {
source: CompletionIdentitySource
identity: string
@@ -43,12 +45,30 @@ const ACTIVE_POLL_INTERVAL_MS = 750
// shared SSH relays. Follow-up to #6288 / PR #6667, which deduped scans within a
// tick; this throttles the number of ticks. Visible panes keep full cadence.
const HIDDEN_POLL_INTERVAL_MS = 3_000
// Why: on hosts where one inspection is a whole-process-table scan (local
// Windows forks a powershell.exe CIM query, ~10-40x heavier than POSIX `ps`),
// a visible idle shell with no agent evidence must not pay that every 2s
// forever. It relaxes to this cadence; output/title/hook activity re-arms the
// hot cadence (see NO_EVIDENCE_ACTIVITY_HOT_WINDOW_MS), so agent starts are
// detected event-driven rather than by burning idle scans.
const NO_EVIDENCE_POLL_INTERVAL_MS = 15_000
// Why: pane activity (PTY output, title change, hook) means an agent may be
// starting; poll at the full idle cadence this long after the last activity so
// agent-start detection stays prompt without keeping idle panes hot.
const NO_EVIDENCE_ACTIVITY_HOT_WINDOW_MS = 10_000
const INSPECTION_TIMEOUT_MS = 15_000
const PENDING_TITLE_TTL_MS = Math.max(2_000, INSPECTION_TIMEOUT_MS + 500)
const PENDING_TITLE_MAX_TTL_MS = Math.max(30_000, PENDING_TITLE_TTL_MS)
const COMPLETION_REPLAY_GUARD_MS = 1_000
const HOOK_DONE_QUIET_MS = 1_500
const POLL_TIER_INTERVAL_MS: Record<PollCadenceTier, number> = {
active: ACTIVE_POLL_INTERVAL_MS,
idle: IDLE_POLL_INTERVAL_MS,
hidden: HIDDEN_POLL_INTERVAL_MS,
'no-evidence': NO_EVIDENCE_POLL_INTERVAL_MS
}
function isCompletionHookState(state: ParsedAgentStatusPayload['state']): boolean {
// Why: only a genuine 'done' ends a turn. 'waiting'/'blocked' are handled by
// isAttentionHookState below.
@@ -99,10 +119,15 @@ export function createAgentCompletionCoordinator(
let inspectionInFlight = false
let inspectionGeneration = 0
let consecutiveInspectionErrors = 0
// Why: tracks whether the armed poll timer is the slow hidden-backstop cadence,
// so a hidden→visible flip can re-arm it promptly instead of waiting out the
// Why: output/title activity can arrive before async PTY bind; it should
// only re-arm cadence after the bind path starts process tracking.
let pollTrackingStarted = false
// Why: tracks which cadence tier the armed poll timer was scheduled at, so a
// tier change toward a faster cadence (hidden→visible flip, no-evidence pane
// gaining activity or evidence) re-arms promptly instead of waiting out the
// long delay (scheduleNextPoll otherwise no-ops while a timer is pending).
let pollTimerIsHiddenBackstop = false
let pollTimerTier: PollCadenceTier | null = null
let lastPaneActivityAt = 0
function clearPollTimer(): void {
if (pollTimer === null) {
@@ -110,7 +135,7 @@ export function createAgentCompletionCoordinator(
}
clearTimeout(pollTimer)
pollTimer = null
pollTimerIsHiddenBackstop = false
pollTimerTier = null
}
function clearPendingTitleTimer(): void {
@@ -560,31 +585,57 @@ export function createAgentCompletionCoordinator(
return options.shouldPollProcessCadence?.() === false
}
function nextPollInterval(): number {
function paneActivityWithinHotWindow(): boolean {
return (
lastPaneActivityAt > 0 && Date.now() - lastPaneActivityAt < NO_EVIDENCE_ACTIVITY_HOT_WINDOW_MS
)
}
function currentPollTier(): PollCadenceTier {
if (isHiddenBackstop()) {
return 'hidden'
}
if (lastForegroundAgent) {
return 'active'
}
if (hasAgentRunEvidence) {
return 'idle'
}
// Why: only costly hosts relax the no-evidence cadence; recent pane
// activity keeps it hot so an agent start is inspected promptly.
if (options.isProcessInspectionCostly?.() === true && !paneActivityWithinHotWindow()) {
return 'no-evidence'
}
return 'idle'
}
function nextPollInterval(tier: PollCadenceTier): number {
// Why: a hidden pane polls slowly (backstop only); a visible pane keeps full
// cadence so the foreground experience is unchanged.
const base = isHiddenBackstop()
? HIDDEN_POLL_INTERVAL_MS
: lastForegroundAgent
? ACTIVE_POLL_INTERVAL_MS
: IDLE_POLL_INTERVAL_MS
const base = POLL_TIER_INTERVAL_MS[tier]
const backoff =
consecutiveInspectionErrors > 0
? Math.min(10_000, base * 2 ** consecutiveInspectionErrors)
? // Why: max(base, ...) keeps error backoff from *accelerating* tiers
// already slower than the 10s backoff ceiling (no-evidence is 15s).
Math.min(Math.max(10_000, base), base * 2 ** consecutiveInspectionErrors)
: base
const jitter = 1 + (Math.random() * 0.2 - 0.1)
return Math.round(backoff * jitter)
}
function scheduleNextPoll(): void {
if (disposed || !options.isLive() || pendingTitle) {
if (disposed || !pollTrackingStarted || !options.isLive() || pendingTitle) {
return
}
const tier = currentPollTier()
if (pollTimer !== null) {
// Why: a hidden pane that became visible has a slow backstop timer armed;
// re-arm it at full cadence now instead of waiting out the long delay.
// scheduleNextPoll runs on every visibility flip via startProcessTracking.
if (pollTimerIsHiddenBackstop && !isHiddenBackstop()) {
// Why: a pane whose tier moved to a faster cadence (hidden pane became
// visible, no-evidence pane saw activity or evidence) has a slow timer
// armed; re-arm at the faster cadence now instead of waiting it out.
if (
pollTimerTier !== null &&
POLL_TIER_INTERVAL_MS[tier] < POLL_TIER_INTERVAL_MS[pollTimerTier]
) {
clearPollTimer()
} else {
return
@@ -597,12 +648,26 @@ export function createAgentCompletionCoordinator(
if (!ptyId) {
return
}
pollTimerIsHiddenBackstop = isHiddenBackstop()
pollTimerTier = tier
pollTimer = setTimeout(() => {
pollTimer = null
pollTimerIsHiddenBackstop = false
pollTimerTier = null
requestInspection('cadence')
}, nextPollInterval())
}, nextPollInterval(tier))
}
function recordPaneActivity(): void {
lastPaneActivityAt = Date.now()
// Why: activity is the escalation signal that ends the relaxed no-evidence
// cadence — re-arm only when the armed timer is the slow tier (or none is
// armed) so per-output-chunk calls stay near-free on hot panes.
if (pollTimer === null || pollTimerTier === 'no-evidence') {
scheduleNextPoll()
}
}
function observeOutputActivity(): void {
recordPaneActivity()
}
function recordTitleWorking(): boolean {
@@ -628,6 +693,7 @@ export function createAgentCompletionCoordinator(
}
function observeTitle(title: string): void {
recordPaneActivity()
const status = detectAgentStatusFromTitle(title)
const isInconclusiveNativeDroidTitle = titleIsInconclusiveNativeDroidTitle(title)
const hasExplicitAgentIdentity =
@@ -701,6 +767,7 @@ export function createAgentCompletionCoordinator(
}
function observeHookStatus(payload: AgentCompletionStatusSnapshot): void {
recordPaneActivity()
if (options.shouldSuppressHookCompletion?.(payload)) {
// Why: a suppressed permission pause must still cancel a provisional 'done'
// so the quiet-window timer never fires a false completion notification.
@@ -792,6 +859,7 @@ export function createAgentCompletionCoordinator(
}
function startProcessTracking(): void {
pollTrackingStarted = true
scheduleNextPoll()
}
@@ -835,6 +903,7 @@ export function createAgentCompletionCoordinator(
observeTitle,
observeClassifiedTitleCompletion,
observeTitleWorking,
observeOutputActivity,
observeHookStatus,
startProcessTracking,
hasPendingHookDoneCompletion,
@@ -0,0 +1,208 @@
// Regression guard: bound the volume of cadence process inspections a visible,
// idle terminal with NO agent evidence drives on hosts where each inspection is
// a whole-process-table scan (local Windows forks powershell.exe/CIM — the
// scan-cost analogue of #6288). Pre-fix a single visible idle shell inspected
// every 2s forever (~30 scans/min); with the no-evidence tier it inspects every
// 15s, and pane activity (output/title/hook) or agent evidence re-arms the hot
// cadence so agent-start detection stays event-driven and agent-finish
// detection is unchanged.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
createAgentCompletionCoordinator,
resetAgentCompletionCoordinatorIdentitiesForTest
} from './agent-completion-coordinator'
import { resetAgentProcessInspectionQueueForTests } from './agent-process-inspection-queue'
import type { RuntimeTerminalProcessInspection } from '@/runtime/runtime-terminal-inspection'
import type { AgentCompletionCoordinatorOptions } from './agent-completion-coordinator-types'
function processResult(
foregroundProcess: string | null,
hasChildProcesses = foregroundProcess !== null
): RuntimeTerminalProcessInspection {
return { foregroundProcess, hasChildProcesses }
}
function createCoordinator(
inspectProcess: AgentCompletionCoordinatorOptions['inspectProcess'],
overrides: Partial<AgentCompletionCoordinatorOptions> = {}
) {
const dispatchCompletion = vi.fn()
const coordinator = createAgentCompletionCoordinator({
paneKey: 'tab-1:leaf-1',
getPtyId: () => 'pty-1',
getSettings: () => null,
inspectProcess,
dispatchCompletion,
isLive: () => true,
shouldPollProcessCadence: () => true,
isProcessInspectionCostly: () => true,
...overrides
})
return { coordinator, dispatchCompletion }
}
describe('agent completion no-evidence inspection cadence', () => {
beforeEach(() => {
vi.useFakeTimers()
// Math.random = 0.5 makes the ±10% jitter factor exactly 1.0, so tick
// counts below are exact.
vi.spyOn(Math, 'random').mockReturnValue(0.5)
})
afterEach(() => {
resetAgentProcessInspectionQueueForTests()
resetAgentCompletionCoordinatorIdentitiesForTest()
vi.useRealTimers()
vi.restoreAllMocks()
})
it('bounds a visible idle pane with no agent evidence to the 15s cadence on a costly host', async () => {
const inspectProcess = vi.fn(async () => processResult(null, false))
const { coordinator } = createCoordinator(inspectProcess)
coordinator.startProcessTracking()
await vi.advanceTimersByTimeAsync(60_000)
// 60s / 15s = 4. Pre-fix (2s idle cadence) this was 30.
expect(inspectProcess).toHaveBeenCalledTimes(4)
})
it('keeps the full 2s idle cadence on hosts where inspection is cheap', async () => {
const inspectProcess = vi.fn(async () => processResult(null, false))
const { coordinator } = createCoordinator(inspectProcess, {
isProcessInspectionCostly: () => false
})
coordinator.startProcessTracking()
await vi.advanceTimersByTimeAsync(60_000)
// 60s / 2s = 30: POSIX/SSH/remote panes must not be relaxed.
expect(inspectProcess).toHaveBeenCalledTimes(30)
})
it('keeps the full cadence when the coordinator has no cost source', async () => {
const inspectProcess = vi.fn(async () => processResult(null, false))
const { coordinator } = createCoordinator(inspectProcess, {
isProcessInspectionCostly: undefined
})
coordinator.startProcessTracking()
await vi.advanceTimersByTimeAsync(60_000)
expect(inspectProcess).toHaveBeenCalledTimes(30)
})
it('escalates to the hot cadence when PTY output appears mid-interval', async () => {
const inspectProcess = vi.fn(async () => processResult(null, false))
const { coordinator } = createCoordinator(inspectProcess)
coordinator.startProcessTracking()
// 14s into the 15s no-evidence interval: nothing has run yet.
await vi.advanceTimersByTimeAsync(14_000)
expect(inspectProcess).not.toHaveBeenCalled()
// Output (e.g. the user launched an agent) must re-arm the idle cadence
// instead of waiting out the remaining ~1s + another 15s round.
coordinator.observeOutputActivity()
await vi.advanceTimersByTimeAsync(2_000)
expect(inspectProcess).toHaveBeenCalledTimes(1)
})
it('escalates to the hot cadence when a title change appears mid-interval', async () => {
const inspectProcess = vi.fn(async () => processResult(null, false))
const { coordinator } = createCoordinator(inspectProcess)
coordinator.startProcessTracking()
await vi.advanceTimersByTimeAsync(14_000)
expect(inspectProcess).not.toHaveBeenCalled()
// A generic (non-agent) title change still signals shell activity.
coordinator.observeTitle('~/projects/app')
await vi.advanceTimersByTimeAsync(2_000)
expect(inspectProcess).toHaveBeenCalledTimes(1)
})
it('decays back to the 15s cadence when activity stops without agent evidence', async () => {
const inspectProcess = vi.fn(async () => processResult(null, false))
const { coordinator } = createCoordinator(inspectProcess)
coordinator.startProcessTracking()
coordinator.observeOutputActivity()
// Hot window: 2s cadence while within 10s of the last activity.
await vi.advanceTimersByTimeAsync(10_000)
expect(inspectProcess).toHaveBeenCalledTimes(5)
// No further activity and no evidence: the next 45s allow only the polls
// armed at the relaxed cadence (t=25s, 40s, 55s).
await vi.advanceTimersByTimeAsync(45_000)
expect(inspectProcess).toHaveBeenCalledTimes(8)
})
it('keeps cadence disarmed and the done quiet window intact when tracking never starts', async () => {
// Why: the hook-notification coordinator (agent-hook-completion-notifications)
// never calls startProcessTracking. Pre-gate, hook evidence armed stub polls
// whose null inspections cleared workingStatusObserved ~2s later, silently
// bypassing the designed done quiet window. The gate makes hook-only
// coordinators purely push-driven: no polls, quiet window preserved.
const inspectProcess = vi.fn(async () => processResult(null, false))
const { coordinator, dispatchCompletion } = createCoordinator(inspectProcess)
coordinator.observeHookStatus({ state: 'working', prompt: '', agentType: 'codex' })
await vi.advanceTimersByTimeAsync(5_000)
expect(inspectProcess).not.toHaveBeenCalled()
coordinator.observeHookStatus({ state: 'done', prompt: '', agentType: 'codex' })
expect(dispatchCompletion).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(1_500)
expect(dispatchCompletion).toHaveBeenCalledTimes(1)
})
it('does not accelerate the relaxed cadence when inspections keep erroring', async () => {
const inspectProcess = vi.fn(async () => {
throw new Error('scan failed')
})
const { coordinator } = createCoordinator(inspectProcess)
coordinator.startProcessTracking()
await vi.advanceTimersByTimeAsync(60_000)
// The error backoff ceiling (10s) must not undercut the 15s tier: erroring
// scans would otherwise poll MORE often than healthy ones (15s → 10s).
expect(inspectProcess).toHaveBeenCalledTimes(4)
})
it('keeps a recognized agent on the full active cadence on a costly host', async () => {
const inspectProcess = vi.fn(async () => processResult('codex'))
const { coordinator } = createCoordinator(inspectProcess)
coordinator.startProcessTracking()
coordinator.observeTitle('Codex working')
await vi.advanceTimersByTimeAsync(60_000)
// ~60s / 750ms ≈ 78: agent-finish detection must not be relaxed.
expect(inspectProcess.mock.calls.length).toBeGreaterThanOrEqual(70)
})
it('still detects an unannounced agent exit promptly after escalating from the relaxed tier', async () => {
let foregroundProcess: string | null = null
const inspectProcess = vi.fn(async () => processResult(foregroundProcess))
const { coordinator, dispatchCompletion } = createCoordinator(inspectProcess)
coordinator.startProcessTracking()
// Idle at the relaxed cadence, then an agent starts and prints output.
await vi.advanceTimersByTimeAsync(20_000)
foregroundProcess = 'codex'
coordinator.observeOutputActivity()
await vi.advanceTimersByTimeAsync(2_000)
expect(inspectProcess).toHaveBeenCalled()
// Agent exits with no completion title/hook — only the poll can notice.
// Two consecutive idle samples at the 750ms active cadence confirm it.
foregroundProcess = null
const callsAtExit = inspectProcess.mock.calls.length
await vi.advanceTimersByTimeAsync(3_000)
expect(inspectProcess.mock.calls.length).toBeGreaterThan(callsAtExit)
expect(dispatchCompletion).toHaveBeenCalledTimes(1)
expect(dispatchCompletion).toHaveBeenCalledWith('codex')
})
})
@@ -9278,11 +9278,8 @@ describe('connectPanePty', () => {
})
await flushAsyncTicks(4)
vi.advanceTimersByTime(750)
await vi.runAllTimersAsync()
await vi.advanceTimersByTimeAsync(750)
await flushAsyncTicks(20)
vi.advanceTimersByTime(0)
await flushAsyncTicks(10)
expect(pane.terminal.write).toHaveBeenCalledWith(
expect.stringContaining('main recovery was unavailable'),
@@ -1997,6 +1997,17 @@ export function connectPanePty(
}),
shouldPollProcessCadence: () =>
isAgentTaskCompleteTrackingEnabled() && deps.isVisibleRef.current,
isProcessInspectionCostly: () => {
// Why: local Windows inspection forks a powershell.exe whole-process-table
// CIM scan per poll (~10-40x heavier than POSIX `ps`); SSH/remote PTYs run
// their scans on the remote host, so only local Windows panes relax the
// no-evidence cadence.
if (!navigator.userAgent.includes('Windows')) {
return false
}
const ptyId = transport.getPtyId()
return ptyId !== null && !isRemoteRuntimePtyId(ptyId) && parseAppSshPtyId(ptyId) === null
},
isLive: () => {
if (disposed) {
return false
@@ -5246,6 +5257,9 @@ export function connectPanePty(
if (data.length > 0) {
hasReceivedPtyOutput = true
recordAgentHibernationPaneOutput(cacheKey)
// Why: output is the agent-start escalation signal that ends the relaxed
// no-evidence process-scan cadence (a starting agent always prints).
agentCompletionCoordinator.observeOutputActivity()
}
if (sshShellReadyMarkerScan) {
const scanned = scanForShellReadyMarker(sshShellReadyMarkerScan, data)