Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions apps/desktop/src/app/desktop-controller.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ import { ChatSidebar } from './chat/sidebar'
import { CommandPalette } from './command-palette'
import { useGatewayBoot } from './gateway/hooks/use-gateway-boot'
import { useGatewayRequest } from './gateway/hooks/use-gateway-request'
import { useReconnectReconciliation } from './gateway/hooks/use-reconnect-reconciliation'
import { useKeybinds } from './hooks/use-keybinds'
import { SIDEBAR_COLLAPSE_MEDIA_QUERY } from './layout-constants'
import { ModelPickerOverlay } from './model-picker-overlay'
Expand Down Expand Up @@ -397,19 +398,21 @@ export function DesktopController() {
loadMoreSessionsForProfile,
refreshCronJobs,
refreshMessagingSessions,
refreshSessions
refreshSessions,
scheduleSessionsRefresh
} = useSessionListActions({ profileScope })

// Another window mutated the shared session list (e.g. a chat started in the
// pop-out). Re-pull so the sidebar reflects it. Pop-outs have no sidebar, so
// only real windows bother.
// only real windows bother. Coalesced: a burst of completions in another
// window collapses to one refresh here.
useEffect(() => {
if (isSecondaryWindow()) {
return
}

return onSessionsChanged(() => void refreshSessions().catch(() => undefined))
}, [refreshSessions])
return onSessionsChanged(() => scheduleSessionsRefresh())
}, [scheduleSessionsRefresh])

const toggleSelectedPin = useCallback(() => {
const sessionId = $selectedStoredSessionId.get()
Expand Down Expand Up @@ -586,7 +589,7 @@ export function DesktopController() {
hydrateFromStoredSession,
queryClient,
refreshHermesConfig,
refreshSessions,
scheduleSessionsRefresh,
sessionStateByRuntimeIdRef,
updateSessionState
})
Expand Down Expand Up @@ -876,6 +879,11 @@ export function DesktopController() {
return $attentionSessionIds.listen(sync)
}, [])

const reconcileBusySessions = useReconnectReconciliation({
sessionStateByRuntimeIdRef,
updateSessionState
})

useGatewayBoot({
handleGatewayEvent: handleDesktopGatewayEvent,
onConnectionReady: c => {
Expand All @@ -884,6 +892,7 @@ export function DesktopController() {
onGatewayReady: g => {
gatewayRef.current = g
},
reconcileBusySessions,
refreshHermesConfig,
refreshSessions
})
Expand Down
121 changes: 120 additions & 1 deletion apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -104,11 +104,16 @@ function fakeDesktop() {
}
}

function Harness() {
function Harness({
reconcileBusySessions
}: {
reconcileBusySessions?: (gateway: unknown, profile: string) => Promise<void>
} = {}) {
useGatewayBoot({
handleGatewayEvent: () => undefined,
onConnectionReady: () => undefined,
onGatewayReady: () => undefined,
reconcileBusySessions,
refreshHermesConfig: async () => undefined,
refreshSessions: async () => undefined
})
Expand Down Expand Up @@ -266,4 +271,118 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>
expect($gatewayState.get()).toBe('open')
expect($desktopBoot.get().error).toBeNull()
})

it('runs the busy-state reconciliation after a successful reconnect', async () => {
const reconcile = vi.fn(async (_gateway: unknown, _profile: string) => undefined)
render(<Harness reconcileBusySessions={reconcile} />)
await flushAsync()
expect($gatewayState.get()).toBe('open')
// The initial boot is not a reconnect — nothing to reconcile yet.
expect(reconcile).not.toHaveBeenCalled()

act(() => FakeWebSocket.instances[0].drop())
await flushAsync()
await advanceBackoff()

expect($gatewayState.get()).toBe('open')
expect(reconcile).toHaveBeenCalledTimes(1)
expect(reconcile.mock.calls[0][1]).toBe('default')
})
})

describe('useGatewayBoot dead-at-launch boot retry (B2)', () => {
it('retries a transport-failed boot on backoff until the backend comes back', async () => {
// Backend unreachable at launch: getConnection rejects with the
// waitForHermes timeout twice, then the tunnel comes up.
const desktop = fakeDesktop()
const realGetConnection = desktop.getConnection
let failures = 2
desktop.getConnection = vi.fn(async () => {
if (failures > 0) {
failures -= 1
throw new Error('Hermes backend did not become ready: Timed out connecting to Hermes backend after 15000ms')
}

return realGetConnection()
})
;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop

render(<Harness />)
await flushAsync()

// First boot failed → failure overlay up, retry scheduled.
expect($desktopBoot.get().error).toBeTruthy()
expect(desktop.getConnection).toHaveBeenCalledTimes(1)

// First retry (~5s + jitter) also fails.
await act(async () => {
await vi.advanceTimersByTimeAsync(7_000)
})
expect(desktop.getConnection).toHaveBeenCalledTimes(2)
expect($desktopBoot.get().error).toBeTruthy()

// Second retry (~15s + jitter) succeeds → boot completes, error clears.
await act(async () => {
await vi.advanceTimersByTimeAsync(20_000)
})
expect(desktop.getConnection.mock.calls.length).toBeGreaterThanOrEqual(3)
expect($gatewayState.get()).toBe('open')
expect($desktopBoot.get().error).toBeNull()
})

it('latches a genuine auth failure: no automatic retry, sign-in stays required', async () => {
const desktop = fakeDesktop()
desktop.getConnection = vi.fn(async () => {
throw new Error('Your remote gateway session has expired. Open Settings → Gateway and click "Sign in" again.')
})
;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop

render(<Harness />)
await flushAsync()

expect($desktopBoot.get().error).toBeTruthy()
expect(desktop.getConnection).toHaveBeenCalledTimes(1)

// Minutes pass: a transport failure would have retried many times by now.
await act(async () => {
await vi.advanceTimersByTimeAsync(5 * 60_000)
})
expect(desktop.getConnection).toHaveBeenCalledTimes(1)

// Wake/online nudges must not thrash the latched auth failure either.
await act(async () => {
window.dispatchEvent(new Event('online'))
await vi.advanceTimersByTimeAsync(0)
})
expect(desktop.getConnection).toHaveBeenCalledTimes(1)
})

it('a wake/online nudge retries a transport-failed boot immediately', async () => {
const desktop = fakeDesktop()
const realGetConnection = desktop.getConnection
let failures = 1
desktop.getConnection = vi.fn(async () => {
if (failures > 0) {
failures -= 1
throw new Error('Timed out connecting to Hermes backend after 15000ms')
}

return realGetConnection()
})
;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop

render(<Harness />)
await flushAsync()
expect($desktopBoot.get().error).toBeTruthy()

// Network comes back well before the 5s backoff timer would fire.
await act(async () => {
window.dispatchEvent(new Event('online'))
await vi.advanceTimersByTimeAsync(0)
})
await flushAsync()

expect($gatewayState.get()).toBe('open')
expect($desktopBoot.get().error).toBeNull()
})
})
Loading