Prefer agent completion over terminal bell notifications (#2174)

This commit is contained in:
Jinjing
2026-05-17 15:45:29 -07:00
committed by GitHub
parent 5b6f373769
commit d5f4904cb0
2 changed files with 328 additions and 26 deletions
@@ -41,7 +41,17 @@ type StoreState = {
repos: { id: string; connectionId?: string | null; displayName?: string }[]
sshConnectionStates: Map<string, { status: string }>
cacheTimerByKey: Record<string, number | null>
settings: { promptCacheTimerEnabled?: boolean; activeRuntimeEnvironmentId?: string | null } | null
settings: {
promptCacheTimerEnabled?: boolean
activeRuntimeEnvironmentId?: string | null
notifications?: {
enabled?: boolean
agentTaskComplete?: boolean
terminalBell?: boolean
suppressWhenFocused?: boolean
customSoundPath?: string | null
}
} | null
codexRestartNoticeByPtyId: Record<
string,
{ previousAccountLabel: string; nextAccountLabel: string }
@@ -1150,6 +1160,7 @@ describe('connectPanePty', () => {
const transport = createMockTransport()
transportFactoryQueue.push(transport)
vi.useFakeTimers()
const pane = createPane(1)
const manager = createManager(1)
const deps = createDeps()
@@ -1165,9 +1176,139 @@ describe('connectPanePty', () => {
expect(deps.markWorktreeUnread).toHaveBeenCalledTimes(1)
expect(deps.markTerminalTabUnread).toHaveBeenCalledWith('tab-1')
expect(deps.dispatchNotification).not.toHaveBeenCalled()
vi.advanceTimersByTime(250)
expect(deps.dispatchNotification).toHaveBeenCalledWith({ source: 'terminal-bell' })
})
it('lets concurrent agent-complete notifications win over terminal bell notifications', async () => {
const { connectPanePty } = await import('./pty-connection')
const { useNotificationDispatch } = await vi.importActual<typeof UseNotificationDispatchModule>(
'./use-notification-dispatch'
)
const transport = createMockTransport()
transportFactoryQueue.push(transport)
vi.useFakeTimers()
const dispatchNotification = useNotificationDispatch('wt-1')
const paneKey = makePaneKey('tab-1', LEAF_1)
mockStoreState.agentStatusByPaneKey[paneKey] = {
state: 'done',
prompt: 'Fix notification payloads',
updatedAt: Date.now(),
stateStartedAt: Date.now(),
agentType: 'codex',
paneKey,
terminalTitle: '* Codex done',
stateHistory: [],
lastAssistantMessage: 'Implemented the formatter.'
}
const pane = createPane(1)
const manager = createManager(1)
const deps = createDeps({ dispatchNotification })
connectPanePty(pane as never, manager as never, deps as never)
const bellHandler = createdTransportOptions[0]?.onBell as (() => void) | undefined
const idleHandler = createdTransportOptions[0]?.onAgentBecameIdle as
| ((title: string) => void)
| undefined
if (!bellHandler || !idleHandler) {
throw new Error('Expected bell and idle handlers to be registered')
}
bellHandler()
idleHandler('* Codex done')
vi.advanceTimersByTime(250)
await flushAsyncTicks()
expect(window.api.notifications.dispatch).toHaveBeenCalledTimes(1)
expect(window.api.notifications.dispatch).toHaveBeenCalledWith(
expect.objectContaining({
source: 'agent-task-complete',
terminalTitle: '* Codex done',
agentType: 'codex',
agentLastAssistantMessage: 'Implemented the formatter.'
})
)
})
it('does not suppress terminal bell notifications when agent-complete notifications are disabled', async () => {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport()
transportFactoryQueue.push(transport)
vi.useFakeTimers()
mockStoreState.settings = {
...mockStoreState.settings,
notifications: {
enabled: true,
agentTaskComplete: false,
terminalBell: true,
suppressWhenFocused: false,
customSoundPath: null
}
}
const pane = createPane(1)
const manager = createManager(1)
const deps = createDeps()
connectPanePty(pane as never, manager as never, deps as never)
const bellHandler = createdTransportOptions[0]?.onBell as (() => void) | undefined
const idleHandler = createdTransportOptions[0]?.onAgentBecameIdle as
| ((title: string) => void)
| undefined
if (!bellHandler || !idleHandler) {
throw new Error('Expected bell and idle handlers to be registered')
}
bellHandler()
idleHandler('* Codex done')
vi.advanceTimersByTime(250)
expect(deps.dispatchNotification).toHaveBeenCalledWith({ source: 'terminal-bell' })
vi.advanceTimersByTime(1000)
expect(deps.dispatchNotification).not.toHaveBeenCalledWith(
expect.objectContaining({ source: 'agent-task-complete' })
)
})
it('restores a suppressed terminal bell when the pending agent completion is canceled', async () => {
const { connectPanePty } = await import('./pty-connection')
const transport = createMockTransport()
transportFactoryQueue.push(transport)
vi.useFakeTimers()
const pane = createPane(1)
const manager = createManager(1)
const deps = createDeps()
connectPanePty(pane as never, manager as never, deps as never)
const bellHandler = createdTransportOptions[0]?.onBell as (() => void) | undefined
const idleHandler = createdTransportOptions[0]?.onAgentBecameIdle as
| ((title: string) => void)
| undefined
const workingHandler = createdTransportOptions[0]?.onAgentBecameWorking as
| (() => void)
| undefined
if (!bellHandler || !idleHandler || !workingHandler) {
throw new Error('Expected bell, idle, and working handlers to be registered')
}
bellHandler()
idleHandler('* Codex done')
workingHandler()
vi.advanceTimersByTime(250)
expect(deps.dispatchNotification).toHaveBeenCalledWith({ source: 'terminal-bell' })
expect(deps.dispatchNotification).not.toHaveBeenCalledWith(
expect.objectContaining({ source: 'agent-task-complete' })
)
})
// Why: show-until-interact — a real keystroke through xterm onData is the
// canonical "user is here" signal that dismisses the bell. Guarded by the
// replay and codex-stale checks (see separate tests) so synthetic xterm
@@ -1568,6 +1709,62 @@ describe('connectPanePty', () => {
)
})
it('waits past the grace delay when the assistant message arrives shortly after it', async () => {
const { connectPanePty } = await import('./pty-connection')
const { useNotificationDispatch } = await vi.importActual<typeof UseNotificationDispatchModule>(
'./use-notification-dispatch'
)
const transport = createMockTransport()
transportFactoryQueue.push(transport)
vi.useFakeTimers()
const dispatchNotification = useNotificationDispatch('wt-1')
const paneKey = makePaneKey('tab-1', LEAF_1)
const pane = createPane(1)
const manager = createManager(1)
const deps = createDeps({ dispatchNotification })
connectPanePty(pane as never, manager as never, deps as never)
const idleHandler = createdTransportOptions[0]?.onAgentBecameIdle as
| ((title: string) => void)
| undefined
if (!idleHandler) {
throw new Error('Expected onAgentBecameIdle to be registered')
}
idleHandler('* Codex done')
vi.advanceTimersByTime(250)
await flushAsyncTicks()
expect(window.api.notifications.dispatch).not.toHaveBeenCalled()
vi.advanceTimersByTime(100)
mockStoreState.agentStatusByPaneKey[paneKey] = {
state: 'done',
prompt: 'Use the late hook status in notification',
updatedAt: Date.now(),
stateStartedAt: Date.now(),
agentType: 'codex',
paneKey,
terminalTitle: '* Codex done',
stateHistory: [],
lastAssistantMessage: 'Late status arrived.'
}
notifyStoreSubscribers()
await flushAsyncTicks()
expect(window.api.notifications.dispatch).toHaveBeenCalledWith(
expect.objectContaining({
source: 'agent-task-complete',
terminalTitle: '* Codex done',
agentType: 'codex',
agentState: 'done',
agentPrompt: 'Use the late hook status in notification',
agentLastAssistantMessage: 'Late status arrived.'
})
)
})
it('does not use stale agent status from an earlier turn in task-complete notifications', async () => {
const { connectPanePty } = await import('./pty-connection')
const { useNotificationDispatch } = await vi.importActual<typeof UseNotificationDispatchModule>(
@@ -1606,7 +1803,7 @@ describe('connectPanePty', () => {
}
idleHandler('* Codex done')
vi.advanceTimersByTime(250)
vi.advanceTimersByTime(1000)
await flushAsyncTicks()
const dispatchArgs = (window.api.notifications.dispatch as ReturnType<typeof vi.fn>).mock
@@ -1655,7 +1852,9 @@ describe('connectPanePty', () => {
throw new Error('Expected onBell to be registered')
}
vi.useFakeTimers()
bellHandler()
vi.advanceTimersByTime(250)
const dispatchArgs = (window.api.notifications.dispatch as ReturnType<typeof vi.fn>).mock
.calls[0]?.[0] as Record<string, unknown> | undefined
@@ -27,12 +27,28 @@ import {
import { makePaneKey } from '../../../../shared/stable-pane-id'
import { createTerminalCommandLifecycle } from './terminal-command-lifecycle'
import { e2eConfig } from '@/lib/e2e-config'
import type { AgentStatusEntry } from '../../../../shared/agent-status-types'
const pendingSpawnByPaneKey = new Map<string, Promise<string | null>>()
const SSH_SESSION_EXPIRED_ERROR = 'SSH_SESSION_EXPIRED'
const REMOTE_PTY_ID_PREFIX = 'remote:'
const PTY_CONNECT_DIAG_LIMIT = 200
const AGENT_TASK_COMPLETE_NOTIFICATION_GRACE_MS = 250
const AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS = 1000
const AGENT_TASK_COMPLETE_NOTIFICATION_DETAIL_MAX_AGE_MS = 10_000
function isAgentTaskCompleteNotificationEnabled(): boolean {
const notifications = useAppStore.getState().settings?.notifications
return notifications?.enabled !== false && notifications?.agentTaskComplete !== false
}
function hasAgentNotificationDetail(entry: AgentStatusEntry | undefined): boolean {
return Boolean(
entry &&
Date.now() - entry.updatedAt <= AGENT_TASK_COMPLETE_NOTIFICATION_DETAIL_MAX_AGE_MS &&
(entry.lastAssistantMessage || entry.toolName || entry.toolInput)
)
}
function recordPtyConnectDiagnostic(message: string): void {
if (!e2eConfig.exposeStore) {
@@ -147,7 +163,11 @@ export function connectPanePty(
let disposed = false
let connectFrame: number | null = null
let startupInjectTimer: ReturnType<typeof setTimeout> | null = null
let agentTaskCompleteNotificationTimer: ReturnType<typeof setTimeout> | null = null
let agentTaskCompleteNotificationGraceTimer: ReturnType<typeof setTimeout> | null = null
let agentTaskCompleteNotificationMaxTimer: ReturnType<typeof setTimeout> | null = null
let agentTaskCompleteStatusUnsubscribe: (() => void) | null = null
let terminalBellNotificationTimer: ReturnType<typeof setTimeout> | null = null
let pendingTerminalBellNotification = false
// Why: passphrase-gate waits register a teardown here so dispose() can
// actively unsubscribe + resolve them. Without this, a pane disposed
// mid-wait leaks its zustand subscriber and the surrounding async IIFE
@@ -281,7 +301,101 @@ export function connectPanePty(
// decision higher up, not a transport-layer guess.
deps.markWorktreeUnread(deps.worktreeId)
deps.markTerminalTabUnread(deps.tabId)
deps.dispatchNotification({ source: 'terminal-bell' })
// Why: agent CLIs often emit BEL in the same completion burst as their
// working->idle title change. Delay only the OS notification so the richer
// agent-complete notification can win the main-process worktree cooldown.
pendingTerminalBellNotification = true
if (!hasPendingAgentTaskCompleteNotification()) {
scheduleTerminalBellNotification()
}
}
const clearTerminalBellNotificationTimer = (): void => {
if (terminalBellNotificationTimer !== null) {
clearTimeout(terminalBellNotificationTimer)
terminalBellNotificationTimer = null
}
}
const scheduleTerminalBellNotification = (): void => {
if (terminalBellNotificationTimer !== null) {
return
}
terminalBellNotificationTimer = setTimeout(() => {
terminalBellNotificationTimer = null
if (disposed) {
pendingTerminalBellNotification = false
return
}
if (hasPendingAgentTaskCompleteNotification()) {
return
}
pendingTerminalBellNotification = false
deps.dispatchNotification({ source: 'terminal-bell' })
}, AGENT_TASK_COMPLETE_NOTIFICATION_GRACE_MS)
}
const hasPendingAgentTaskCompleteNotification = (): boolean =>
isAgentTaskCompleteNotificationEnabled() &&
(agentTaskCompleteNotificationGraceTimer !== null ||
agentTaskCompleteNotificationMaxTimer !== null ||
agentTaskCompleteStatusUnsubscribe !== null)
const clearPendingAgentTaskCompleteNotification = (): void => {
if (agentTaskCompleteNotificationGraceTimer !== null) {
clearTimeout(agentTaskCompleteNotificationGraceTimer)
agentTaskCompleteNotificationGraceTimer = null
}
if (agentTaskCompleteNotificationMaxTimer !== null) {
clearTimeout(agentTaskCompleteNotificationMaxTimer)
agentTaskCompleteNotificationMaxTimer = null
}
if (agentTaskCompleteStatusUnsubscribe !== null) {
agentTaskCompleteStatusUnsubscribe()
agentTaskCompleteStatusUnsubscribe = null
}
}
const scheduleAgentTaskCompleteNotification = (title: string): void => {
clearPendingAgentTaskCompleteNotification()
let graceElapsed = false
const dispatch = (): void => {
clearPendingAgentTaskCompleteNotification()
pendingTerminalBellNotification = false
clearTerminalBellNotificationTimer()
if (disposed) {
return
}
deps.dispatchNotification({
source: 'agent-task-complete',
terminalTitle: title,
paneKey: cacheKey
})
}
const dispatchIfDetailed = (): void => {
if (!graceElapsed) {
return
}
const entry = useAppStore.getState().agentStatusByPaneKey[cacheKey]
if (hasAgentNotificationDetail(entry)) {
dispatch()
}
}
agentTaskCompleteStatusUnsubscribe = useAppStore.subscribe(dispatchIfDetailed)
agentTaskCompleteNotificationGraceTimer = setTimeout(() => {
agentTaskCompleteNotificationGraceTimer = null
graceElapsed = true
dispatchIfDetailed()
}, AGENT_TASK_COMPLETE_NOTIFICATION_GRACE_MS)
// Why: some agents never surface assistant text through hooks. Keep a hard
// cap so task-complete notifications still fire instead of waiting forever.
agentTaskCompleteNotificationMaxTimer = setTimeout(
dispatch,
AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS
)
}
// ─── Agent task-complete: OS notification, not tab attention ──────────
@@ -296,8 +410,9 @@ export function connectPanePty(
// signals. OS notifications are a separate channel: not every agent CLI
// reliably emits BEL on completion (Gemini, some Codex flows), and
// without this dispatch the Settings toggle would have zero producers.
// Double-firing with a concurrent BEL is handled by the 5 s per-worktree
// dedupe in main/ipc/notifications.ts.
// Double-firing with a concurrent BEL is handled by delaying the BEL OS
// notification below; main still keeps a 5 s per-worktree dedupe as the
// final guard.
const onAgentBecameIdle = (title: string): void => {
// Why: only start the prompt-cache countdown for Claude agents — other
// agents have different (or no) prompt-caching semantics and showing a
@@ -320,28 +435,17 @@ export function connectPanePty(
// worktree into a single notification.
// Why: title idle can beat the final hook status update by one event-loop
// turn; delay slightly so the notification can snapshot the richer status.
if (agentTaskCompleteNotificationTimer !== null) {
clearTimeout(agentTaskCompleteNotificationTimer)
if (isAgentTaskCompleteNotificationEnabled()) {
scheduleAgentTaskCompleteNotification(title)
}
agentTaskCompleteNotificationTimer = setTimeout(() => {
agentTaskCompleteNotificationTimer = null
if (disposed) {
return
}
deps.dispatchNotification({
source: 'agent-task-complete',
terminalTitle: title,
paneKey: cacheKey
})
}, AGENT_TASK_COMPLETE_NOTIFICATION_GRACE_MS)
}
const onAgentBecameWorking = (): void => {
// Why: a new API call refreshes the prompt-cache TTL, so clear any running
// countdown. The timer will restart when the agent becomes idle again.
deps.setCacheTimerStartedAt(cacheKey, null)
if (agentTaskCompleteNotificationTimer !== null) {
clearTimeout(agentTaskCompleteNotificationTimer)
agentTaskCompleteNotificationTimer = null
clearPendingAgentTaskCompleteNotification()
if (pendingTerminalBellNotification) {
scheduleTerminalBellNotification()
}
}
const onAgentExited = (): void => {
@@ -1306,10 +1410,9 @@ export function connectPanePty(
clearTimeout(startupInjectTimer)
startupInjectTimer = null
}
if (agentTaskCompleteNotificationTimer !== null) {
clearTimeout(agentTaskCompleteNotificationTimer)
agentTaskCompleteNotificationTimer = null
}
clearPendingAgentTaskCompleteNotification()
pendingTerminalBellNotification = false
clearTerminalBellNotificationTimer()
discardTerminalOutput(pane.terminal)
if (connectFrame !== null) {
// Why: StrictMode and split-group remounts can dispose a pane binding