Follow up: validate pending agent title probes

Tie pending terminal title completions to exact fresh process probes and harden related e2e setup.
This commit is contained in:
Neil
2026-05-19 14:42:26 -07:00
committed by GitHub
parent 73ff6e43dd
commit 28e8981d10
4 changed files with 205 additions and 28 deletions
@@ -22,6 +22,17 @@ function createDeferred<T>(): { promise: Promise<T>; resolve: (value: T) => void
return { promise, resolve: resolveDeferred }
}
function createRejectableDeferred<T>(): {
promise: Promise<T>
reject: (reason?: unknown) => void
} {
let rejectDeferred!: (reason?: unknown) => void
const promise = new Promise<T>((_resolve, reject) => {
rejectDeferred = reject
})
return { promise, reject: rejectDeferred }
}
describe('agent completion coordinator', () => {
beforeEach(() => {
vi.useFakeTimers()
@@ -111,6 +122,131 @@ describe('agent completion coordinator', () => {
expect(dispatchCompletion).not.toHaveBeenCalled()
})
it('does not validate a pending cwd title with an already in-flight inspection', async () => {
const staleInspection = createDeferred<RuntimeTerminalProcessInspection>()
const freshInspection = createDeferred<RuntimeTerminalProcessInspection>()
const inspectProcess = vi
.fn()
.mockReturnValueOnce(staleInspection.promise)
.mockReturnValueOnce(freshInspection.promise)
const dispatchCompletion = vi.fn()
const coordinator = createAgentCompletionCoordinator({
paneKey: 'tab-1:leaf-1',
getPtyId: () => 'pty-1',
getSettings: () => null,
inspectProcess,
dispatchCompletion,
isLive: () => true
})
coordinator.startProcessTracking()
vi.advanceTimersByTime(2_000)
await flushAsyncTicks()
coordinator.observeTitle('Codex working')
coordinator.observeTitle('/tmp/orca-e2e-repo')
staleInspection.resolve(processResult('codex'))
await flushAsyncTicks()
expect(inspectProcess).toHaveBeenCalledTimes(2)
expect(dispatchCompletion).not.toHaveBeenCalledWith('/tmp/orca-e2e-repo')
freshInspection.resolve(processResult('zsh'))
await flushAsyncTicks()
expect(dispatchCompletion).not.toHaveBeenCalledWith('/tmp/orca-e2e-repo')
})
it('does not validate a replaced pending title with an older pending-title inspection', async () => {
const titleAInspection = createDeferred<RuntimeTerminalProcessInspection>()
const titleBInspection = createDeferred<RuntimeTerminalProcessInspection>()
const inspectProcess = vi
.fn()
.mockReturnValueOnce(titleAInspection.promise)
.mockReturnValueOnce(titleBInspection.promise)
const dispatchCompletion = vi.fn()
const coordinator = createAgentCompletionCoordinator({
paneKey: 'tab-1:leaf-1',
getPtyId: () => 'pty-1',
getSettings: () => null,
inspectProcess,
dispatchCompletion,
isLive: () => true
})
coordinator.observeTitle('Codex working')
coordinator.observeTitle('/tmp/title-a')
await flushAsyncTicks()
coordinator.observeTitle('Codex working')
coordinator.observeTitle('/tmp/title-b')
titleAInspection.resolve(processResult('codex'))
await flushAsyncTicks()
expect(inspectProcess).toHaveBeenCalledTimes(2)
expect(dispatchCompletion).not.toHaveBeenCalledWith('/tmp/title-b')
titleBInspection.resolve(processResult('zsh'))
await flushAsyncTicks()
expect(dispatchCompletion).not.toHaveBeenCalledWith('/tmp/title-b')
})
it('does not drop a replaced pending title from an older non-agent inspection', async () => {
const titleAInspection = createDeferred<RuntimeTerminalProcessInspection>()
const titleBInspection = createDeferred<RuntimeTerminalProcessInspection>()
const inspectProcess = vi
.fn()
.mockReturnValueOnce(titleAInspection.promise)
.mockReturnValueOnce(titleBInspection.promise)
const dispatchCompletion = vi.fn()
const coordinator = createAgentCompletionCoordinator({
paneKey: 'tab-1:leaf-1',
getPtyId: () => 'pty-1',
getSettings: () => null,
inspectProcess,
dispatchCompletion,
isLive: () => true
})
coordinator.observeTitle('Codex working')
coordinator.observeTitle('/tmp/title-a')
await flushAsyncTicks()
coordinator.observeTitle('Codex working')
coordinator.observeTitle('/tmp/title-b')
titleAInspection.resolve(processResult('zsh'))
await flushAsyncTicks()
expect(inspectProcess).toHaveBeenCalledTimes(2)
expect(dispatchCompletion).not.toHaveBeenCalledWith('/tmp/title-b')
titleBInspection.resolve(processResult('codex'))
await flushAsyncTicks()
expect(dispatchCompletion).toHaveBeenCalledWith('/tmp/title-b')
})
it('does not dispatch a pending cwd title when process inspection fails', async () => {
const inspection = createRejectableDeferred<RuntimeTerminalProcessInspection>()
const dispatchCompletion = vi.fn()
const coordinator = createAgentCompletionCoordinator({
paneKey: 'tab-1:leaf-1',
getPtyId: () => 'pty-1',
getSettings: () => null,
inspectProcess: vi.fn(() => inspection.promise),
dispatchCompletion,
isLive: () => true
})
coordinator.observeTitle('Codex working')
coordinator.observeTitle('/tmp/orca-e2e-repo')
inspection.reject(new Error('inspection failed'))
await flushAsyncTicks()
expect(dispatchCompletion).not.toHaveBeenCalled()
})
it('prefers a later explicit completion title over a pending cwd title', async () => {
const inspection = createDeferred<RuntimeTerminalProcessInspection>()
const dispatchCompletion = vi.fn()
@@ -51,11 +51,14 @@ export function createAgentCompletionCoordinator(
let requiresFreshWorking = false
let pollTimer: ReturnType<typeof setTimeout> | null = null
let pendingTitleTimer: ReturnType<typeof setTimeout> | null = null
let pendingTitleSequence = 0
let pendingTitle: {
id: number
title: string
expiresAt: number
maxExpiresAt: number
firstInspectionFinished: boolean
validatedByFreshInspection: boolean
} | null = null
let inspectionInFlight = false
let inspectionGeneration = 0
@@ -125,7 +128,12 @@ export function createAgentCompletionCoordinator(
}
function dispatchPendingTitleIfEligible(): void {
if (!pendingTitle || !agentIdentityEstablished || !hasAgentRunEvidence) {
if (
!pendingTitle ||
!pendingTitle.validatedByFreshInspection ||
!agentIdentityEstablished ||
!hasAgentRunEvidence
) {
return
}
const title = pendingTitle.title
@@ -165,10 +173,12 @@ export function createAgentCompletionCoordinator(
// Why: generic spinner titles can be just "⠋ cwd"; hold the completion
// only long enough for one foreground-process probe to prove an agent owns it.
pendingTitle = {
id: ++pendingTitleSequence,
title,
expiresAt: Math.min(now + PENDING_TITLE_TTL_MS, now + PENDING_TITLE_MAX_TTL_MS),
maxExpiresAt: now + PENDING_TITLE_MAX_TTL_MS,
firstInspectionFinished: false
firstInspectionFinished: false,
validatedByFreshInspection: false
}
schedulePendingTitleExpiry()
requestInspection('pending-title')
@@ -185,12 +195,14 @@ export function createAgentCompletionCoordinator(
establishAgentEvidence()
}
function handleProcessInspectionResult(result: RuntimeTerminalProcessInspection): void {
function handleProcessInspectionResult(result: RuntimeTerminalProcessInspection): boolean {
consecutiveInspectionErrors = 0
const recognized = recognizeAgentProcess(result.foregroundProcess)
if (recognized) {
handleRecognizedProcess(recognized)
} else if (lastForegroundAgent && hasAgentRunEvidence) {
return true
}
if (lastForegroundAgent && hasAgentRunEvidence) {
const exited = lastForegroundAgent
dispatchCompletion('process-exit', exited.processName)
lastForegroundAgent = null
@@ -199,6 +211,7 @@ export function createAgentCompletionCoordinator(
lastForegroundAgent = null
clearAgentRunEvidence()
}
return false
}
function requestInspection(priority: InspectionPriority): void {
@@ -211,13 +224,22 @@ export function createAgentCompletionCoordinator(
}
inspectionInFlight = true
const generationAtRequest = inspectionGeneration
const pendingTitleIdAtRequest = priority === 'pending-title' ? pendingTitle?.id : null
enqueueAgentProcessInspection({
priority,
run: async () => {
let inspectedRecognizedAgent = false
let inspectionSucceeded = false
try {
const result = await options.inspectProcess(options.getSettings(), ptyId)
if (!disposed && generationAtRequest === inspectionGeneration) {
handleProcessInspectionResult(result)
const appliesToCurrentPendingTitle =
!pendingTitle ||
(priority === 'pending-title' && pendingTitle.id === pendingTitleIdAtRequest)
if (appliesToCurrentPendingTitle) {
inspectedRecognizedAgent = handleProcessInspectionResult(result)
}
inspectionSucceeded = true
}
} catch {
consecutiveInspectionErrors += 1
@@ -231,9 +253,21 @@ export function createAgentCompletionCoordinator(
}
} else {
if (pendingTitle) {
pendingTitle.firstInspectionFinished = true
dispatchPendingTitleIfEligible()
schedulePendingTitleExpiry()
if (priority === 'pending-title' && pendingTitle.id === pendingTitleIdAtRequest) {
pendingTitle.firstInspectionFinished = true
if (inspectionSucceeded && inspectedRecognizedAgent) {
pendingTitle.validatedByFreshInspection = true
dispatchPendingTitleIfEligible()
} else if (!inspectionSucceeded) {
dropPendingTitle()
}
schedulePendingTitleExpiry()
} else {
// Why: only the probe requested for this exact pending title
// can prove it belongs to an agent; older in-flight probes are
// stale even when they were also pending-title inspections.
requestInspection('pending-title')
}
}
scheduleNextPoll()
}
+23 -10
View File
@@ -52,8 +52,8 @@ async function getNotificationDispatches(
})
}
async function createAndSwitchToOtherWorktree(page: Page): Promise<string> {
return page.evaluate(async () => {
async function switchToOtherExistingWorktree(page: Page): Promise<string> {
return page.evaluate(() => {
const store = window.__store
if (!store) {
throw new Error('Store unavailable')
@@ -69,13 +69,26 @@ async function createAndSwitchToOtherWorktree(page: Page): Promise<string> {
if (!activeWorktree) {
throw new Error(`Active worktree ${activeWorktreeId} not found`)
}
const result = await state.createWorktree(
activeWorktree.repoId,
`codex-hook-notify-${Date.now()}`
)
await state.fetchWorktrees(activeWorktree.repoId)
state.setActiveWorktree(result.worktree.id)
return result.worktree.id
const otherWorktree =
Object.values(state.worktreesByRepo)
.flat()
.find(
(worktree) =>
worktree.repoId === activeWorktree.repoId &&
worktree.id !== activeWorktreeId &&
worktree.branch.replace(/^refs\/heads\//, '') === 'e2e-secondary'
) ??
Object.values(state.worktreesByRepo)
.flat()
.find(
(worktree) =>
worktree.repoId === activeWorktree.repoId && worktree.id !== activeWorktreeId
)
if (!otherWorktree) {
throw new Error(`No inactive worktree found for repo ${activeWorktree.repoId}`)
}
state.setActiveWorktree(otherWorktree.id)
return otherWorktree.id
})
}
@@ -164,7 +177,7 @@ test.describe('Droid notifications', () => {
)
.toBe(true)
await createAndSwitchToOtherWorktree(orcaPage)
await switchToOtherExistingWorktree(orcaPage)
const finalMessage = `Codex hook completed ${Date.now()}`
await emitCodexHookStatus(endpoint, {
+4 -10
View File
@@ -80,18 +80,12 @@ async function seedCreatePREligibleBranch(
throw new Error('window.__store is not available')
}
const state = store.getState()
const worktreeId = state.activeWorktreeId
const worktrees = Object.values(state.worktreesByRepo).flat()
const activeWorktree = worktrees.find((entry) => entry.id === worktreeId)
const worktree =
worktrees.find((entry) => entry.branch.replace(/^refs\/heads\//, '') === 'e2e-secondary') ??
worktrees.find((entry) => {
const branchName = entry.branch.replace(/^refs\/heads\//, '')
return branchName !== 'main' && !entry.isMainWorktree
}) ??
activeWorktree
const worktree = worktrees.find(
(entry) => entry.branch.replace(/^refs\/heads\//, '') === 'e2e-secondary'
)
if (!worktree) {
throw new Error('active worktree not found')
throw new Error('seeded e2e-secondary worktree not found')
}
// Why: the worker-scoped test repo can accumulate extra non-main
// worktrees; use the seeded secondary worktree as the stable PR target.