Skip to content

The agent that grows with you

fix(desktop): coalesce MCP reconnect sweeps

Xipong42f2067092a9
diff --git a/apps/desktop/src/store/mcp-health.test.ts b/apps/desktop/src/store/mcp-health.test.ts
index d753fbfc02c..f0249fa8a5a 100644
--- a/apps/desktop/src/store/mcp-health.test.ts
+++ b/apps/desktop/src/store/mcp-health.test.ts
@@ -1,10 +1,42 @@
-import { describe, expect, it, vi } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+const mocks = vi.hoisted(() => {
+ const makeAtom = <T>(initial: T) => {
+ let value = initial
+ const listeners = new Set<(value: T) => void>()
+
+ return {
+ get: () => value,
+ listen(listener: (value: T) => void) {
+ listeners.add(listener)
+
+ return () => listeners.delete(listener)
+ },
+ set(next: T) {
+ value = next
+
+ for (const listener of listeners) {
+ listener(value)
+ }
+ },
+ subscribe(listener: (value: T) => void) {
+ listener(value)
+
+ return this.listen(listener)
+ }
+ }
+ }
+
+ return {
+ activeProfile: makeAtom('default'),
+ gatewayState: makeAtom<'closed' | 'open'>('closed'),
+ getHermesConfigRecord: vi.fn(),
+ notify: vi.fn()
+ }
+})
-// The store wires itself to gateway/profile atoms and the REST layer at import
-// time paths; mock the seams (same shape as updates.test.ts) so this test only
-// exercises the pure transition state machine.
vi.mock('@/hermes', () => ({
- getHermesConfigRecord: vi.fn(),
+ getHermesConfigRecord: mocks.getHermesConfigRecord,
testMcpServer: vi.fn()
}))
@@ -13,44 +45,75 @@ vi.mock('@/i18n', () => ({
}))
vi.mock('@/store/notifications', () => ({
- notify: vi.fn()
+ notify: mocks.notify
}))
vi.mock('@/store/profile', () => ({
- $activeGatewayProfile: { get: () => 'default', listen: () => () => {} },
+ $activeGatewayProfile: mocks.activeProfile,
normalizeProfileKey: (name: string | null | undefined) => (name ?? '').trim() || 'default'
}))
vi.mock('@/store/session', () => ({
- $gatewayState: { get: () => 'closed', subscribe: () => () => {} }
+ $gatewayState: mocks.gatewayState
}))
-const { shouldNotifyOnTransition } = await import('./mcp-health')
+const { shouldNotifyOnTransition, startMcpHealthChecker, stopMcpHealthChecker } = await import('./mcp-health')
type Status = 'error' | 'needs-auth' | 'ok'
+const flush = () => new Promise(resolve => setTimeout(resolve, 0))
+
+afterEach(() => {
+ stopMcpHealthChecker()
+ mocks.gatewayState.set('closed')
+ mocks.activeProfile.set('default')
+ mocks.getHermesConfigRecord.mockReset()
+ mocks.notify.mockReset()
+})
+
describe('shouldNotifyOnTransition', () => {
- // The full previous × next decision table: notify only on a TRANSITION into
- // a bad state. Rechecks of an already-bad server stay quiet; ok never nudges.
it.each<[previous: Status | null, next: Status, notify: boolean]>([
- // First observation of the session (previous unknown).
[null, 'ok', false],
[null, 'needs-auth', true],
[null, 'error', true],
- // Healthy server stays healthy / breaks.
['ok', 'ok', false],
['ok', 'needs-auth', true],
['ok', 'error', true],
- // Already-broken server: rechecks must NOT re-notify…
['needs-auth', 'needs-auth', false],
['error', 'error', false],
- // …but flipping from one bad state to the other is a new transition.
['needs-auth', 'error', true],
['error', 'needs-auth', true],
- // Recovery is silent.
['needs-auth', 'ok', false],
['error', 'ok', false]
])('previous=%s next=%s → notify=%s', (previous, next, expected) => {
expect(shouldNotifyOnTransition(previous, next)).toBe(expected)
})
})
+
+it('coalesces reconnects during a sweep into one fresh follow-up sweep', async () => {
+ let releaseFirst!: (config: Record<string, unknown>) => void
+
+ const first = new Promise<Record<string, unknown>>(resolve => {
+ releaseFirst = resolve
+ })
+
+ mocks.getHermesConfigRecord.mockReturnValueOnce(first).mockResolvedValue({ mcp_servers: {} })
+
+ startMcpHealthChecker()
+ mocks.gatewayState.set('open')
+ await flush()
+ expect(mocks.getHermesConfigRecord).toHaveBeenCalledTimes(1)
+
+ for (let index = 0; index < 12; index += 1) {
+ mocks.gatewayState.set('closed')
+ mocks.gatewayState.set('open')
+ }
+
+ await flush()
+ expect(mocks.getHermesConfigRecord).toHaveBeenCalledTimes(1)
+
+ releaseFirst({ mcp_servers: {} })
+ await flush()
+ await flush()
+ expect(mocks.getHermesConfigRecord).toHaveBeenCalledTimes(2)
+})
diff --git a/apps/desktop/src/store/mcp-health.ts b/apps/desktop/src/store/mcp-health.ts
index 0e1dbeb90f7..bf64f5a9979 100644
--- a/apps/desktop/src/store/mcp-health.ts
+++ b/apps/desktop/src/store/mcp-health.ts
@@ -49,8 +49,10 @@ let timer: ReturnType<typeof setInterval> | null = null
// Bumped on profile switch; in-flight sweeps compare and bail so a slow
// profile-A probe can't record (or notify) into profile B's state.
let sweepEpoch = 0
-// Sweeps are chained, never concurrent — sequential probes, no parallel bursts.
-let sweepChain: Promise<void> = Promise.resolve()
+// At most one sweep runs and one follow-up is remembered. Reconnect storms
+// still request a fresh pass, but cannot append an unbounded backlog.
+let sweepInFlight: Promise<void> | null = null
+let sweepQueued = false
let offGatewayState: (() => void) | null = null
let offProfile: (() => void) | null = null
@@ -143,7 +145,24 @@ async function sweep(): Promise<void> {
}
function queueSweep(): void {
- sweepChain = sweepChain.then(sweep, sweep)
+ if (sweepInFlight) {
+ sweepQueued = true
+
+ return
+ }
+
+ sweepInFlight = sweep()
+
+ const settled = () => {
+ sweepInFlight = null
+
+ if (sweepQueued) {
+ sweepQueued = false
+ queueSweep()
+ }
+ }
+
+ sweepInFlight.then(settled, settled)
}
function arm(): void {