Skip to content

The agent that grows with you

fix(desktop): defer heavy sessions.changed list refresh while typing

Bruno Bza01e9b9abb1f1
diff --git a/apps/desktop/src/app/contrib/hooks/use-background-sync.test.ts b/apps/desktop/src/app/contrib/hooks/use-background-sync.test.ts
index e645d29209d..bef2c22ffba 100644
--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.test.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.test.ts
@@ -22,9 +22,12 @@ import {
import {
type ActiveTranscriptRefreshDeps,
+ isTypingBurstActive,
+ noteRendererKeyboardActivity,
reconcileActiveTranscript,
reconcileTileTranscripts as reconcileTileTranscriptsForTest,
rehydrateLiveSessionStatuses,
+ resetTypingActivityTracking,
resolveActiveTranscriptSession,
useBackgroundSync,
windowIsActivelyViewed
@@ -155,6 +158,7 @@ afterEach(() => {
vi.clearAllMocks()
vi.restoreAllMocks()
clearAllSessionStates()
+ resetTypingActivityTracking()
})
describe('active transcript refresh', () => {
@@ -634,3 +638,177 @@ describe('rehydrateLiveSessionStatuses', () => {
expect($stalledSessionIds.get()).toEqual([])
})
})
+
+describe('typing-aware sessions.changed deferral', () => {
+ // Dedicated harness: the sessions-list spy must be the exact fn handed to
+ // the hook (the shared harness above wires inner vi.fn()s and its outer spy
+ // observes the transcript path instead), and EVERY param must keep a stable
+ // identity across the tick-driven re-renders — an unstable prop would
+ // re-run the connect-reseed effect and re-subscribe the throttle each
+ // render, polluting the counts under observation.
+ function renderTypingSync(refreshSessions: () => Promise<void>) {
+ const stable = {
+ refreshActiveTranscript: async () => undefined,
+ refreshCronJobs: vi.fn(),
+ refreshCurrentModel: vi.fn(),
+ refreshHermesConfig: vi.fn(),
+ refreshMessagingSessions: vi.fn(),
+ requestGateway: vi.fn(async () => ({ sessions: [] })) as never
+ }
+
+ return renderHook(() => {
+ useBackgroundSync({
+ activeConnectionId: 'local',
+ activeGatewayProfile: 'default',
+ activeIsMessaging: false,
+ activeSessionId: null,
+ activeStoredSessionId: null,
+ freshDraftReady: false,
+ gatewayState: 'open',
+ ...stable,
+ refreshSessions
+ })
+ })
+ }
+
+ const typeKey = (): void => {
+ window.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'a' }))
+ }
+
+ /** Mount, land one full throttle cycle so lastRunAt sits at a known clock
+ * position, then clear the spy. */
+ async function primeThrottle(refreshSessions: ReturnType<typeof vi.fn>): Promise<void> {
+ act(() => notifySessionsChanged())
+ await act(async () => {
+ // One SESSIONS_LIST_TICK_GAP_MS covers both the immediate first tick
+ // and any trailing timer the burst armed.
+ vi.advanceTimersByTime(10_000)
+ await Promise.resolve()
+ })
+ refreshSessions.mockClear()
+ }
+
+ it('holds the trailing sessions.changed refresh while a typing burst is live, then lands it once after the keyboard quiets', async () => {
+ vi.useFakeTimers()
+ $changeEventsAvailable.set(true)
+ const refreshSessions = vi.fn(async () => undefined)
+
+ renderTypingSync(refreshSessions)
+ await primeThrottle(refreshSessions)
+
+ // A ~6s continuous burst: keys every 200ms, broadcasts every ~1s. The
+ // first broadcast finds the throttle gap already elapsed (primed), so the
+ // deferral engages immediately and must hold for the whole burst — well
+ // short of the one-gap starvation cap.
+ for (let index = 0; index < 30; index += 1) {
+ typeKey()
+
+ if (index % 5 === 0) {
+ act(() => notifySessionsChanged())
+ }
+
+ await act(async () => {
+ vi.advanceTimersByTime(200)
+ await Promise.resolve()
+ })
+ }
+
+ // The heavy list pass must not have landed under the keystrokes.
+ expect(refreshSessions).not.toHaveBeenCalled()
+
+ // Last key at ~5.8s; quiet threshold elapses ~7.3s → the held pass lands
+ // exactly once shortly after.
+ await act(async () => {
+ vi.advanceTimersByTime(2_000)
+ await Promise.resolve()
+ })
+
+ expect(refreshSessions).toHaveBeenCalledTimes(1)
+
+ // ...and nothing extra afterwards without further broadcasts — mid-burst
+ // ticks must not have stacked trailing timers behind the promised pass.
+ await act(async () => {
+ vi.advanceTimersByTime(10_000)
+ await Promise.resolve()
+ })
+
+ expect(refreshSessions).toHaveBeenCalledTimes(1)
+ })
+
+ it('caps the typing deferral at one throttle gap so continuous typing cannot starve list freshness', async () => {
+ vi.useFakeTimers()
+ $changeEventsAvailable.set(true)
+ const refreshSessions = vi.fn(async () => undefined)
+
+ renderTypingSync(refreshSessions)
+ await primeThrottle(refreshSessions)
+
+ // Keys every 200ms for ~22s straight — a burst that outlives one full
+ // SESSIONS_LIST_TICK_GAP_MS of deferral. Broadcasts keep flowing.
+ for (let index = 0; index < 110; index += 1) {
+ typeKey()
+
+ if (index % 10 === 0) {
+ act(() => notifySessionsChanged())
+ }
+
+ await act(async () => {
+ vi.advanceTimersByTime(200)
+ await Promise.resolve()
+ })
+ }
+
+ // The starvation cap forces exactly ONE mid-burst pass (~one gap after
+ // the deferral began) — worst-case freshness equals the plain cadence.
+ expect(refreshSessions).toHaveBeenCalledTimes(1)
+
+ // Burst ends → the still-held pass lands once more, then silence.
+ await act(async () => {
+ vi.advanceTimersByTime(2_000)
+ await Promise.resolve()
+ })
+
+ expect(refreshSessions).toHaveBeenCalledTimes(2)
+
+ await act(async () => {
+ vi.advanceTimersByTime(10_000)
+ await Promise.resolve()
+ })
+
+ expect(refreshSessions).toHaveBeenCalledTimes(2)
+ })
+
+ it('does not defer anything when the keyboard has been idle', async () => {
+ vi.useFakeTimers()
+ $changeEventsAvailable.set(true)
+ const refreshSessions = vi.fn(async () => undefined)
+
+ renderTypingSync(refreshSessions)
+ await primeThrottle(refreshSessions)
+
+ act(() => notifySessionsChanged())
+
+ await act(async () => {
+ vi.advanceTimersByTime(11_000)
+ await Promise.resolve()
+ })
+
+ expect(refreshSessions).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('isTypingBurstActive', () => {
+ it('marks a burst warm for the quiet threshold and cold at it', () => {
+ resetTypingActivityTracking()
+
+ // No keyboard history → nothing to defer for.
+ expect(isTypingBurstActive(1_000_000)).toBe(false)
+
+ noteRendererKeyboardActivity(1_000_000)
+ expect(isTypingBurstActive(1_000_000)).toBe(true)
+ expect(isTypingBurstActive(1_000_000 + 1_499)).toBe(true)
+
+ // Exactly one quiet threshold after the last key the keyboard is cold.
+ expect(isTypingBurstActive(1_000_000 + 1_500)).toBe(false)
+ })
+})
diff --git a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
index 12164d7e313..26f95109a23 100644
--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts
@@ -273,6 +273,18 @@ const LIVE_SESSION_STATUS_BACKSTOP_INTERVAL_MS = 30_000
// full list refresh is heavier than the active_list snapshot. Trailing-edge
// scheduled, so the burst's last write always lands.
const SESSIONS_LIST_TICK_GAP_MS = 10_000
+// A typing burst keeps the composer's contentEditable input handling on the
+// same renderer main thread as the list refresh above (#95033): with a large
+// session store, one refresh pass can block keystroke echo long enough that
+// input visibly stalls. While the keyboard is warm, hold that pass and land it
+// once shortly after the last keypress — mirroring the throttle's own trailing
+// edge. Two guardrails keep this from costing freshness: the deferral never
+// outlives SESSIONS_LIST_TICK_GAP_MS (worst case equals the plain cadence,
+// even for someone typing continuously), and the lighter polls (active_list
+// snapshot, cron, transcript backstops) are untouched — they carry liveness
+// signals, not the heavy list reconciliation.
+const TYPING_BURST_QUIET_MS = 1_500
+const TYPING_DEFER_RECHECK_MS = 300
interface LiveSessionStatusItem {
id?: string
@@ -291,6 +303,30 @@ interface LiveSessionStatusResponse {
// so an unscoped reap would dark out every other profile's running rows.
const liveRuntimeIdsByProfile = new Map<string, Set<string>>()
+// Renderer-wide keyboard warmth, tracked at module scope like the live-runtime
+// bookkeeping above: any keydown anywhere in the window marks activity, and a
+// burst stays warm for TYPING_BURST_QUIET_MS after the last key. IME
+// composition still emits keydown (keyCode 229), so one listener covers both.
+let lastRendererInputAt = 0
+
+/** Record renderer-wide keyboard activity (wired to a capture-phase window
+ * keydown listener by useBackgroundSync). */
+export function noteRendererKeyboardActivity(nowMs = Date.now()): void {
+ lastRendererInputAt = nowMs
+}
+
+/** True while a typing burst is still warm enough to hold the heavy list
+ * refresh (see TYPING_BURST_QUIET_MS). */
+export function isTypingBurstActive(nowMs = Date.now()): boolean {
+ return nowMs - lastRendererInputAt < TYPING_BURST_QUIET_MS
+}
+
+/** Forget keyboard history — test isolation only (mirrors
+ * resetLiveRuntimeTracking). */
+export function resetTypingActivityTracking(): void {
+ lastRendererInputAt = 0
+}
+
/** Restore sidebar liveness after a renderer/backend reconnect. Stream events
* normally own these states, but events emitted while Desktop was disconnected
* cannot be replayed. `session.active_list` is the authoritative in-memory
@@ -647,6 +683,8 @@ export function useBackgroundSync({
let lastRunAt = 0
let timer: null | number = null
+ let typingDeferTimer: null | number = null
+ let deferStartedAt = 0
const run = () => {
lastRunAt = Date.now()
@@ -669,15 +707,56 @@ export function useBackgroundSync({
})
}
+ // Land one coalesced refresh pass — but hold it while a typing burst is
+ // warm (#95033), so the heavy list pass never lands under the user's
+ // keystrokes. A single recheck timer services every caller: ticks that
+ // arrive mid-deferral just find the timer already armed and return.
+ const runWhenKeyboardQuiet = () => {
+ const now = Date.now()
+
+ // Starvation cap: a deferral never outlives one full throttle gap, so
+ // worst-case list freshness equals the plain cadence even if the user
+ // types continuously.
+ if (!isTypingBurstActive(now) || (deferStartedAt > 0 && now - deferStartedAt >= SESSIONS_LIST_TICK_GAP_MS)) {
+ deferStartedAt = 0
+
+ // A tick may hit the terminal branch while a recheck is still pending
+ // (cap reached mid-burst); retire it so it cannot land a second pass.
+ if (typingDeferTimer !== null) {
+ window.clearTimeout(typingDeferTimer)
+ typingDeferTimer = null
+ }
+
+ run()
+
+ return
+ }
+
+ if (typingDeferTimer === null) {
+ if (deferStartedAt === 0) {
+ deferStartedAt = now
+ }
+
+ typingDeferTimer = window.setTimeout(() => {
+ typingDeferTimer = null
+ runWhenKeyboardQuiet()
+ }, TYPING_DEFER_RECHECK_MS)
+ }
+ }
+
const unsubscribe = $sessionsChangeTick.listen(() => {
const since = Date.now() - lastRunAt
if (since >= SESSIONS_LIST_TICK_GAP_MS) {
- run()
- } else if (timer === null) {
+ runWhenKeyboardQuiet()
+ } else if (typingDeferTimer === null && timer === null) {
+ // Within the gap a pass is already scheduled — either the plain
+ // trailing timer or a typing deferral that will land no later than
+ // this tick's own deadline. Arming another one here would only stack
+ // extra passes behind the promised one.
timer = window.setTimeout(() => {
timer = null
- run()
+ runWhenKeyboardQuiet()
}, SESSIONS_LIST_TICK_GAP_MS - since)
}
})
@@ -688,6 +767,12 @@ export function useBackgroundSync({
if (timer !== null) {
window.clearTimeout(timer)
}
+
+ if (typingDeferTimer !== null) {
+ window.clearTimeout(typingDeferTimer)
+ }
+
+ deferStartedAt = 0
}
}, [
changeEventsAvailable,
@@ -698,6 +783,19 @@ export function useBackgroundSync({
updateSessionState
])
+ // Keyboard warmth for the deferral above: capture phase on window catches
+ // keydowns targeted at any focused element (composer included) on the way
+ // down. Pure timestamp write — no React state, negligible per-key cost.
+ useEffect(() => {
+ const markInput = (): void => noteRendererKeyboardActivity()
+
+ window.addEventListener('keydown', markInput, true)
+
+ return () => {
+ window.removeEventListener('keydown', markInput, true)
+ }
+ }, [])
+
// Keep the cron-jobs section live without a user action (scheduler ticks in
// the background). cron.changed (jobs.json moved: CRUD or a scheduler tick's
// bookkeeping) drives the refresh; the visible poll is the backstop.