perf(agent-status): coalesce live status bursts into one render pass (STA-3328) (#12377)
* perf(agent-status): coalesce live status bursts into one render pass (STA-3328) Each live agent-status event arrives as its own IPC task, so a multi-agent burst paid one full React render pass per event (200-488ms main-thread tasks under heavy orchestration). Same-task store commits batch to a single render pass, so buffer a burst for one 33ms window and apply it in one task. The leading event still applies synchronously (zero added latency for single events), only an applied event arms the window (dropped/pending events stay immediate), and both clear paths purge queued sets so a coalesced event cannot resurrect a removed status. * fix(agent-status): preserve queued completion on teardown
This commit is contained in:
@@ -6160,6 +6160,202 @@ describe('useIpcEvents agent status snapshot integration', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('applies a burst leading-edge first, then coalesces the rest into one deferred batch', async () => {
|
||||
// Why: each live status event is its own IPC task, so N events used to pay
|
||||
// N full render passes (STA-3328 mechanism 2). The leading event must stay
|
||||
// synchronous (zero added latency); followers within the burst window must
|
||||
// apply together on one later task, in arrival order.
|
||||
vi.useFakeTimers()
|
||||
const setAgentStatus = vi.fn()
|
||||
const onSetListenerRef: { current: ((data: AgentStatusSetData) => void) | null } = {
|
||||
current: null
|
||||
}
|
||||
const storeState: StoreLike = buildStoreState({
|
||||
setAgentStatus,
|
||||
workspaceSessionReady: true,
|
||||
tabsByWorktree: {
|
||||
'wt-1': [{ id: 'tab-future', ptyId: 'pty-1', worktreeId: 'wt-1', title: 'Future Tab' }]
|
||||
},
|
||||
terminalLayoutsByTabId: {
|
||||
'tab-future': {
|
||||
root: { type: 'leaf', leafId: FUTURE_LEAF_ID },
|
||||
activeLeafId: FUTURE_LEAF_ID,
|
||||
expandedLeafId: null
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
stubReactSyncEffect()
|
||||
vi.doMock('../store', () => ({
|
||||
useAppStore: {
|
||||
subscribe: vi.fn(() => () => {}),
|
||||
getState: () => storeState
|
||||
}
|
||||
}))
|
||||
stubAuxiliaryModules()
|
||||
vi.stubGlobal(
|
||||
'window',
|
||||
buildWindowApi({
|
||||
onSet: (cb) => {
|
||||
onSetListenerRef.current = cb
|
||||
return () => {}
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
try {
|
||||
const { useIpcEvents } = await import('./useIpcEvents')
|
||||
useIpcEvents()
|
||||
if (typeof onSetListenerRef.current !== 'function') {
|
||||
throw new Error('Expected agentStatus.onSet listener to be registered')
|
||||
}
|
||||
const emit = (receivedAt: number, prompt: string): void => {
|
||||
onSetListenerRef.current!({
|
||||
paneKey: FUTURE_PANE_KEY,
|
||||
state: 'working',
|
||||
prompt,
|
||||
agentType: 'claude',
|
||||
receivedAt,
|
||||
stateStartedAt: receivedAt
|
||||
})
|
||||
}
|
||||
|
||||
emit(1_700_000_000_000, 'first')
|
||||
expect(setAgentStatus).toHaveBeenCalledTimes(1)
|
||||
|
||||
emit(1_700_000_000_001, 'second')
|
||||
emit(1_700_000_000_002, 'third')
|
||||
expect(setAgentStatus).toHaveBeenCalledTimes(1)
|
||||
|
||||
vi.advanceTimersByTime(40)
|
||||
expect(setAgentStatus).toHaveBeenCalledTimes(3)
|
||||
expect(setAgentStatus.mock.calls[1][1]).toEqual(expect.objectContaining({ prompt: 'second' }))
|
||||
expect(setAgentStatus.mock.calls[2][1]).toEqual(expect.objectContaining({ prompt: 'third' }))
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('preserves queued set-clear order for working removal and done retention', async () => {
|
||||
vi.useFakeTimers()
|
||||
let storeState: StoreLike
|
||||
const setAgentStatus = vi.fn(
|
||||
(
|
||||
paneKey: string,
|
||||
payload: { state: string },
|
||||
_title: unknown,
|
||||
timing: { updatedAt: number }
|
||||
) => {
|
||||
storeState.agentStatusByPaneKey = {
|
||||
...(storeState.agentStatusByPaneKey as Record<string, unknown>),
|
||||
[paneKey]: { ...payload, updatedAt: timing.updatedAt }
|
||||
}
|
||||
}
|
||||
)
|
||||
const removeAgentStatus = vi.fn((paneKey: string) => {
|
||||
const next = { ...(storeState.agentStatusByPaneKey as Record<string, unknown>) }
|
||||
delete next[paneKey]
|
||||
storeState.agentStatusByPaneKey = next
|
||||
})
|
||||
const onSetListenerRef: { current: ((data: AgentStatusSetData) => void) | null } = {
|
||||
current: null
|
||||
}
|
||||
const onClearListenerRef: { current: ((data: { paneKey: string }) => void) | null } = {
|
||||
current: null
|
||||
}
|
||||
storeState = buildStoreState({
|
||||
setAgentStatus,
|
||||
removeAgentStatus,
|
||||
workspaceSessionReady: true,
|
||||
tabsByWorktree: {
|
||||
'wt-1': [{ id: 'tab-future', ptyId: 'pty-1', worktreeId: 'wt-1', title: 'Future Tab' }]
|
||||
},
|
||||
terminalLayoutsByTabId: {
|
||||
'tab-future': {
|
||||
root: { type: 'leaf', leafId: FUTURE_LEAF_ID },
|
||||
activeLeafId: FUTURE_LEAF_ID,
|
||||
expandedLeafId: null
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
stubReactSyncEffect()
|
||||
vi.doMock('../store', () => ({
|
||||
useAppStore: {
|
||||
subscribe: vi.fn(() => () => {}),
|
||||
getState: () => storeState
|
||||
}
|
||||
}))
|
||||
stubAuxiliaryModules()
|
||||
vi.stubGlobal(
|
||||
'window',
|
||||
buildWindowApi({
|
||||
onSet: (cb) => {
|
||||
onSetListenerRef.current = cb
|
||||
return () => {}
|
||||
},
|
||||
onClear: (cb) => {
|
||||
onClearListenerRef.current = cb as (data: { paneKey: string }) => void
|
||||
return () => {}
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
try {
|
||||
const { useIpcEvents } = await import('./useIpcEvents')
|
||||
useIpcEvents()
|
||||
if (
|
||||
typeof onSetListenerRef.current !== 'function' ||
|
||||
typeof onClearListenerRef.current !== 'function'
|
||||
) {
|
||||
throw new Error('Expected agentStatus listeners to be registered')
|
||||
}
|
||||
const emit = (
|
||||
receivedAt: number,
|
||||
prompt: string,
|
||||
state: AgentStatusSetData['state'] = 'working'
|
||||
): void => {
|
||||
onSetListenerRef.current!({
|
||||
paneKey: FUTURE_PANE_KEY,
|
||||
state,
|
||||
prompt,
|
||||
agentType: 'claude',
|
||||
receivedAt,
|
||||
stateStartedAt: receivedAt
|
||||
})
|
||||
}
|
||||
|
||||
emit(1_700_000_000_000, 'leading')
|
||||
emit(1_700_000_000_001, 'queued')
|
||||
expect(setAgentStatus).toHaveBeenCalledTimes(1)
|
||||
|
||||
onClearListenerRef.current({ paneKey: FUTURE_PANE_KEY })
|
||||
expect(removeAgentStatus).toHaveBeenCalledWith(FUTURE_PANE_KEY)
|
||||
expect(storeState.agentStatusByPaneKey).toEqual({})
|
||||
|
||||
vi.advanceTimersByTime(40)
|
||||
expect(setAgentStatus).toHaveBeenCalledTimes(2)
|
||||
expect(storeState.agentStatusByPaneKey).toEqual({})
|
||||
|
||||
emit(1_700_000_000_002, 'task')
|
||||
emit(1_700_000_000_003, 'task', 'done')
|
||||
expect(setAgentStatus).toHaveBeenCalledTimes(3)
|
||||
|
||||
onClearListenerRef.current({ paneKey: FUTURE_PANE_KEY })
|
||||
|
||||
expect(setAgentStatus).toHaveBeenCalledTimes(4)
|
||||
expect(setAgentStatus.mock.calls[3][1]).toEqual(expect.objectContaining({ state: 'done' }))
|
||||
expect(removeAgentStatus).toHaveBeenCalledTimes(1)
|
||||
expect(storeState.agentStatusByPaneKey).toEqual({
|
||||
[FUTURE_PANE_KEY]: expect.objectContaining({ state: 'done' })
|
||||
})
|
||||
vi.advanceTimersByTime(40)
|
||||
expect(setAgentStatus).toHaveBeenCalledTimes(4)
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it('does not recurse when flushing a pending status re-enters via the store subscriber', async () => {
|
||||
// Repro for crash 9fc89529 (RangeError: Maximum call stack size exceeded):
|
||||
// the store subscriber calls flushPendingAgentStatuses() on every update.
|
||||
|
||||
@@ -288,6 +288,11 @@ export { resolveZoomTarget } from './resolve-zoom-target'
|
||||
const PENDING_AGENT_STATUS_RETRY_MS = 100
|
||||
const PENDING_AGENT_STATUS_TTL_MS = 15_000
|
||||
const MAX_PENDING_AGENT_STATUS_EVENTS = 100
|
||||
// Why: each live status event is its own IPC task, so a multi-agent burst pays
|
||||
// one full render pass per event; same-task commits batch to ONE pass (React
|
||||
// flushes external-store updates at the microtask boundary). One frame of
|
||||
// buffering collapses a burst; the leading event still applies immediately.
|
||||
const LIVE_AGENT_STATUS_BURST_WINDOW_MS = 33
|
||||
// Why: mobile driver hydration is async; cap replay so a stuck IPC snapshot can't retain an unbounded startup buffer.
|
||||
const MAX_PENDING_MOBILE_STATE_EVENTS = 300
|
||||
// Why: a rename's event burst lags the on-disk move; shield both ids from the deletion diff for a grace window.
|
||||
@@ -758,6 +763,9 @@ export function useIpcEvents(): void {
|
||||
let pendingAgentStatusRetryTimer: ReturnType<typeof setTimeout> | null = null
|
||||
// Why: setAgentStatus notifies synchronously and re-enters this flush mid-drain; guard re-entrancy (crash 9fc89529).
|
||||
let isFlushingAgentStatuses = false
|
||||
const liveAgentStatusBurstQueue: AgentStatusIpcPayload[] = []
|
||||
let liveAgentStatusBurstTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let lastLiveAgentStatusApplyAt = 0
|
||||
|
||||
unsubs.push(attachMobileMarkdownBridge())
|
||||
|
||||
@@ -3337,9 +3345,67 @@ export function useIpcEvents(): void {
|
||||
})
|
||||
}
|
||||
|
||||
function flushLiveAgentStatusBurst(): void {
|
||||
liveAgentStatusBurstTimer = null
|
||||
lastLiveAgentStatusApplyAt = Date.now()
|
||||
// Why: splice before applying — applyAgentStatus can synchronously
|
||||
// re-enter the queue via subscribers, and it must not see this batch.
|
||||
const batch = liveAgentStatusBurstQueue.splice(0)
|
||||
let anyApplied = false
|
||||
for (const data of batch) {
|
||||
if (applyAgentStatus(data) === 'applied') {
|
||||
anyApplied = true
|
||||
}
|
||||
}
|
||||
if (!anyApplied) {
|
||||
lastLiveAgentStatusApplyAt = 0
|
||||
}
|
||||
}
|
||||
|
||||
function drainQueuedLiveAgentStatusesForPane(paneKey: string): void {
|
||||
const queuedForPane: AgentStatusIpcPayload[] = []
|
||||
const remaining: AgentStatusIpcPayload[] = []
|
||||
for (const queued of liveAgentStatusBurstQueue) {
|
||||
if (queued.paneKey === paneKey) {
|
||||
queuedForPane.push(queued)
|
||||
} else {
|
||||
remaining.push(queued)
|
||||
}
|
||||
}
|
||||
liveAgentStatusBurstQueue.length = 0
|
||||
liveAgentStatusBurstQueue.push(...remaining)
|
||||
for (const queued of queuedForPane) {
|
||||
applyAgentStatus(queued)
|
||||
}
|
||||
}
|
||||
|
||||
function enqueueLiveAgentStatus(data: AgentStatusIpcPayload): void {
|
||||
const now = Date.now()
|
||||
if (
|
||||
liveAgentStatusBurstTimer === null &&
|
||||
now - lastLiveAgentStatusApplyAt >= LIVE_AGENT_STATUS_BURST_WINDOW_MS
|
||||
) {
|
||||
lastLiveAgentStatusApplyAt = now
|
||||
// Why: only an applied event commits state and costs a render pass —
|
||||
// a dropped/pending leading edge must not make its successor pay
|
||||
// burst latency (startup replay and unmounted panes stay immediate).
|
||||
if (applyAgentStatus(data) !== 'applied') {
|
||||
lastLiveAgentStatusApplyAt = 0
|
||||
}
|
||||
return
|
||||
}
|
||||
liveAgentStatusBurstQueue.push(data)
|
||||
if (liveAgentStatusBurstTimer === null) {
|
||||
liveAgentStatusBurstTimer = globalThis.setTimeout(
|
||||
flushLiveAgentStatusBurst,
|
||||
LIVE_AGENT_STATUS_BURST_WINDOW_MS
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
unsubs.push(
|
||||
window.api.agentStatus.onSet((data) => {
|
||||
applyAgentStatus(data)
|
||||
enqueueLiveAgentStatus(data)
|
||||
})
|
||||
)
|
||||
const unsubscribeAgentStatusClear = window.api.agentStatus.onClear?.(
|
||||
@@ -3368,12 +3434,30 @@ export function useIpcEvents(): void {
|
||||
pendingAgentStatusEvents.splice(index, 1)
|
||||
}
|
||||
}
|
||||
for (let index = liveAgentStatusBurstQueue.length - 1; index >= 0; index -= 1) {
|
||||
const queued = liveAgentStatusBurstQueue[index]
|
||||
if (
|
||||
queued.connectionId === data.connectionId &&
|
||||
queued.receivedAt <= effectiveWatermark
|
||||
) {
|
||||
liveAgentStatusBurstQueue.splice(index, 1)
|
||||
}
|
||||
}
|
||||
useAppStore.getState().clearTransientAgentStatuses(data.connectionId, effectiveWatermark)
|
||||
return
|
||||
}
|
||||
if (!('paneKey' in data) || typeof data.paneKey !== 'string') {
|
||||
return
|
||||
}
|
||||
// Why: preserve set→clear FIFO so a queued completion still survives pane teardown.
|
||||
if (liveAgentStatusBurstQueue.some((queued) => queued.paneKey === data.paneKey)) {
|
||||
drainQueuedLiveAgentStatusesForPane(data.paneKey)
|
||||
}
|
||||
for (let index = pendingAgentStatusEvents.length - 1; index >= 0; index -= 1) {
|
||||
if (pendingAgentStatusEvents[index].data.paneKey === data.paneKey) {
|
||||
pendingAgentStatusEvents.splice(index, 1)
|
||||
}
|
||||
}
|
||||
const store = useAppStore.getState()
|
||||
if (store.agentStatusByPaneKey[data.paneKey]?.state === 'done') {
|
||||
return
|
||||
@@ -3565,6 +3649,11 @@ export function useIpcEvents(): void {
|
||||
globalThis.clearTimeout(pendingAgentStatusRetryTimer)
|
||||
}
|
||||
pendingAgentStatusEvents.length = 0
|
||||
if (liveAgentStatusBurstTimer !== null) {
|
||||
globalThis.clearTimeout(liveAgentStatusBurstTimer)
|
||||
liveAgentStatusBurstTimer = null
|
||||
}
|
||||
liveAgentStatusBurstQueue.length = 0
|
||||
mobileStateHydrationDisposed = true
|
||||
pendingMobileStateEvents.length = 0
|
||||
unsubscribeRuntimeEnvironmentStore()
|
||||
|
||||
Reference in New Issue
Block a user