Skip to content

The agent that grows with you

feat(desktop): add status bar reconnect for offline gateways

fangliquanflqace85d63de06
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx
index 5603d70219a..c0ca28cde4a 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { $desktopBoot } from '@/store/boot'
import { closeSecondaryGateways, isActivePrimary } from '@/store/gateway'
+import { reconnectGateway } from '@/store/gateway-reconnect'
import { $activeGatewayProfile, $profiles, ensureGatewayProfile } from '@/store/profile'
import { $connection, $currentCwd, $gatewayState } from '@/store/session'
@@ -121,6 +122,7 @@ function fakeDesktop() {
}
}),
onPowerResume: vi.fn(() => () => undefined),
+ revalidateConnection: vi.fn(async () => ({ ok: true, rebuilt: false })),
onWindowStateChanged: vi.fn(() => () => undefined),
touchBackend: vi.fn(async () => undefined),
profile: { get: vi.fn(async () => ({ profile: 'default' })) }
@@ -391,6 +393,31 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>
expect($desktopBoot.get().error).toBeNull()
})
+ it('manual reconnect revalidates, re-resolves, re-mints, and re-dials the dropped socket', async () => {
+ const desktop = fakeDesktop()
+
+ ;(window as { hermesDesktop?: unknown }).hermesDesktop = desktop
+
+ render(<Harness />)
+ await flushAsync()
+
+ expect($gatewayState.get()).toBe('open')
+ act(() => FakeWebSocket.instances[0].drop())
+ FakeWebSocket.mode = 'open'
+
+ await act(async () => {
+ const reconnect = reconnectGateway()
+ await vi.advanceTimersByTimeAsync(0)
+ await reconnect
+ })
+
+ expect(desktop.revalidateConnection).toHaveBeenCalledOnce()
+ expect(desktop.getConnection).toHaveBeenLastCalledWith('default')
+ expect(desktop.getGatewayWsUrl).toHaveBeenCalledTimes(2)
+ expect(FakeWebSocket.instances).toHaveLength(2)
+ expect($gatewayState.get()).toBe('open')
+ })
+
it('FIX: a failed session-list fetch during boot is non-fatal — the app still boots', async () => {
// The version-skew report: gateway WS connects fine, but refreshSessions()
// rejects (e.g. older backend 404s an endpoint the fallback didn't cover,
diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
index 8c23f60bd61..73981edcb7f 100644
--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts
@@ -27,6 +27,7 @@ import {
setPrimaryGateway,
touchSecondaryGateways
} from '@/store/gateway'
+import { registerGatewayReconnect } from '@/store/gateway-reconnect'
import { $gatewaySwitching, wipeSessionListsForGatewaySwitch } from '@/store/gateway-switch'
import { notify, notifyError } from '@/store/notifications'
import {
@@ -259,7 +260,7 @@ export function useGatewayBoot({
}, delay)
}
- const reconnectNow = () => {
+ const reconnectNow = async () => {
if (cancelled || !bootCompleted || $gatewaySwitching.get()) {
return
}
@@ -271,7 +272,7 @@ export function useGatewayBoot({
reconnectSecondaryGateways()
if (!gatewayOpen()) {
- void attemptReconnect()
+ await attemptReconnect()
}
}
@@ -486,8 +487,9 @@ export function useGatewayBoot({
// Wake signals: power resume (macOS/Windows), network coming back, and the
// window regaining focus/visibility. Each nudges an immediate reconnect.
- const offPowerResume = desktop.onPowerResume?.(() => reconnectNow())
+ const offPowerResume = desktop.onPowerResume?.(() => void reconnectNow())
const offConnectionApplied = desktop.onConnectionApplied?.(() => void softSwitch())
+ const offGatewayReconnect = registerGatewayReconnect(reconnectNow)
// Registry lifecycle: a removed connection's secondaries must close NOW
// (remote/cloud have no local process whose death would drop the socket —
@@ -501,11 +503,11 @@ export function useGatewayBoot({
disposeSecondariesForConnection(payload.connectionId, { redial: payload.reason === 'updated' })
})
- const onOnline = () => reconnectNow()
+ const onOnline = () => void reconnectNow()
const onVisible = () => {
if (document.visibilityState === 'visible') {
- reconnectNow()
+ void reconnectNow()
}
}
@@ -708,6 +710,7 @@ export function useGatewayBoot({
offPowerResume?.()
offConnectionApplied?.()
offConnectionsChanged?.()
+ offGatewayReconnect()
offState()
offEvent()
offExit()
diff --git a/apps/desktop/src/app/shell/gateway-menu-panel.test.tsx b/apps/desktop/src/app/shell/gateway-menu-panel.test.tsx
new file mode 100644
index 00000000000..b33e6291f9e
--- /dev/null
+++ b/apps/desktop/src/app/shell/gateway-menu-panel.test.tsx
@@ -0,0 +1,101 @@
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const mocks = vi.hoisted(() => ({
+ notifyError: vi.fn(),
+ reconnectGateway: vi.fn<() => Promise<void>>()
+}))
+
+vi.mock('@/components/ui/tooltip', () => ({
+ Tip: ({ children }: { children: React.ReactNode }) => <>{children}</>
+}))
+
+vi.mock('@/hermes', () => ({
+ getLogs: vi.fn().mockResolvedValue({ lines: [] })
+}))
+
+vi.mock('@/i18n', () => ({
+ useI18n: () => ({
+ t: {
+ commandCenter: { restartGateway: 'Restart gateway' },
+ shell: {
+ gatewayMenu: {
+ checkingInference: 'Checking inference',
+ connected: 'Connected',
+ connecting: 'Connecting',
+ disconnected: 'Disconnected',
+ inferenceNotReady: 'Inference not ready',
+ inferenceReady: 'Inference ready',
+ messagingPlatforms: 'Messaging platforms',
+ offline: 'Offline',
+ openSystem: 'Open system panel',
+ recentActivity: 'Recent activity',
+ reconnectGateway: 'Reconnect gateway',
+ viewAllLogs: 'View all logs'
+ }
+ }
+ }
+ })
+}))
+
+vi.mock('@/store/gateway-reconnect', () => ({
+ reconnectGateway: mocks.reconnectGateway
+}))
+
+vi.mock('@/store/notifications', () => ({
+ notifyError: mocks.notifyError
+}))
+
+vi.mock('@/store/system-actions', () => ({
+ runGatewayRestart: vi.fn()
+}))
+
+import { GatewayMenuPanel } from './gateway-menu-panel'
+
+const renderPanel = (gatewayState: string) =>
+ render(
+ <GatewayMenuPanel
+ gatewayState={gatewayState}
+ inferenceStatus={null}
+ onClose={vi.fn()}
+ onOpenSystem={vi.fn()}
+ statusSnapshot={null}
+ />
+ )
+
+describe('GatewayMenuPanel reconnect action', () => {
+ beforeEach(() => {
+ mocks.reconnectGateway.mockReset().mockResolvedValue(undefined)
+ mocks.notifyError.mockReset()
+ })
+
+ afterEach(() => cleanup())
+
+ it('shows reconnect only while disconnected and disables it in flight', async () => {
+ let finish: (() => void) | undefined
+ mocks.reconnectGateway.mockImplementation(
+ () =>
+ new Promise<void>(resolve => {
+ finish = resolve
+ })
+ )
+
+ renderPanel('closed')
+
+ const reconnect = screen.getByRole('button', { name: 'Reconnect gateway' })
+ fireEvent.click(reconnect)
+ fireEvent.click(reconnect)
+
+ expect(mocks.reconnectGateway).toHaveBeenCalledOnce()
+ expect((reconnect as HTMLButtonElement).disabled).toBe(true)
+
+ await act(async () => finish?.())
+ })
+
+ it('hides reconnect while the socket is open', async () => {
+ renderPanel('open')
+ await act(async () => undefined)
+
+ expect(screen.queryByRole('button', { name: 'Reconnect gateway' })).toBeNull()
+ })
+})
diff --git a/apps/desktop/src/app/shell/gateway-menu-panel.tsx b/apps/desktop/src/app/shell/gateway-menu-panel.tsx
index bb753670bb6..8e1516b7bd5 100644
--- a/apps/desktop/src/app/shell/gateway-menu-panel.tsx
+++ b/apps/desktop/src/app/shell/gateway-menu-panel.tsx
@@ -9,6 +9,8 @@ import { useI18n } from '@/i18n'
import { LayoutDashboard, RefreshCw } from '@/lib/icons'
import type { RuntimeReadinessResult } from '@/lib/runtime-readiness'
import { cn } from '@/lib/utils'
+import { reconnectGateway } from '@/store/gateway-reconnect'
+import { notifyError } from '@/store/notifications'
import { runGatewayRestart } from '@/store/system-actions'
import type { StatusResponse } from '@/types/hermes'
@@ -96,6 +98,7 @@ export function GatewayMenuPanel({
}: GatewayMenuPanelProps) {
const { t } = useI18n()
const copy = t.shell.gatewayMenu
+ const [reconnecting, setReconnecting] = useState(false)
// Both jumps open the system panel, which owns the full view — so dismiss the
// little status popover on the way out.
@@ -111,6 +114,17 @@ export function GatewayMenuPanel({
void runGatewayRestart()
}
+ const reconnect = () => {
+ if (reconnecting) {
+ return
+ }
+
+ setReconnecting(true)
+ void reconnectGateway()
+ .catch(err => notifyError(err, copy.reconnectGateway))
+ .finally(() => setReconnecting(false))
+ }
+
const gatewayOpen = gatewayState === 'open'
const gatewayConnecting = gatewayState === 'connecting'
const inferenceReady = gatewayOpen && inferenceStatus?.ready === true
@@ -157,6 +171,20 @@ export function GatewayMenuPanel({
</span>
</div>
<div className="flex shrink-0 items-center gap-0.5">
+ {!gatewayOpen && (
+ <Tip label={copy.reconnectGateway}>
+ <Button
+ aria-label={copy.reconnectGateway}
+ className="text-muted-foreground hover:text-foreground"
+ disabled={reconnecting}
+ onClick={reconnect}
+ size="icon-xs"
+ variant="ghost"
+ >
+ <RefreshCw className={cn(reconnecting && 'animate-spin')} />
+ </Button>
+ </Tip>
+ )}
<Tip label={t.commandCenter.restartGateway}>
<Button
aria-label={t.commandCenter.restartGateway}
diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.ts
index 9d2f4439c0d..e6a1840cf53 100644
--- a/apps/desktop/src/i18n/ar.ts
+++ b/apps/desktop/src/i18n/ar.ts
@@ -2121,6 +2121,7 @@ export const ar = defineLocale({
inferenceNotReady: 'الاستدلال غير جاهز',
checkingInference: 'جار فحص الاستدلال',
disconnected: 'منقطع',
+ reconnectGateway: 'إعادة الاتصال بالبوابة',
openSystem: 'فتح النظام',
connection: label => `الاتصال: ${label}`,
recentActivity: 'النشاط الأخير',
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index 21441305db6..f9d2e73992b 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -2642,6 +2642,7 @@ export const en: Translations = {
inferenceNotReady: 'Inference not ready',
checkingInference: 'Checking inference',
disconnected: 'Disconnected',
+ reconnectGateway: 'Reconnect gateway',
openSystem: 'Open system panel',
connection: label => `Connection: ${label}`,
recentActivity: 'Recent activity',
diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts
index a8e2401cfe5..0f188bcad52 100644
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@ -2367,6 +2367,7 @@ export const ja = defineLocale({
inferenceNotReady: '推論準備未完了',
checkingInference: '推論を確認中',
disconnected: '切断済み',
+ reconnectGateway: 'ゲートウェイに再接続',
openSystem: 'システムパネルを開く',
connection: label => `接続: ${label}`,
recentActivity: '最近のアクティビティ',
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index 90fee9d5069..d016106f2b1 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -2224,6 +2224,7 @@ export interface Translations {
inferenceNotReady: string
checkingInference: string
disconnected: string
+ reconnectGateway: string
openSystem: string
connection: (label: string) => string
recentActivity: string
diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.ts
index 32c2ec0871c..08eab1e78c6 100644
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@ -2284,6 +2284,7 @@ export const zhHant = defineLocale({
inferenceNotReady: '推論未就緒',
checkingInference: '正在檢查推論',
disconnected: '已中斷連線',
+ reconnectGateway: '重新連線閘道',
openSystem: '開啟系統面板',
connection: label => `連線:${label}`,
recentActivity: '最近活動',
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index 1918b16bb8c..cdb668d480d 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -2813,6 +2813,7 @@ export const zh: Translations = {
inferenceNotReady: '推理未就绪',
checkingInference: '正在检查推理',
disconnected: '已断开',
+ reconnectGateway: '重连网关',
openSystem: '打开系统面板',
connection: label => `连接:${label}`,
recentActivity: '最近活动',
diff --git a/apps/desktop/src/store/gateway-reconnect.test.ts b/apps/desktop/src/store/gateway-reconnect.test.ts
new file mode 100644
index 00000000000..e1a8e09d2d8
--- /dev/null
+++ b/apps/desktop/src/store/gateway-reconnect.test.ts
@@ -0,0 +1,59 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+import { reconnectGateway, registerGatewayReconnect } from './gateway-reconnect'
+
+const disposers: Array<() => void> = []
+
+afterEach(() => {
+ while (disposers.length > 0) {
+ disposers.pop()?.()
+ }
+})
+
+describe('gateway reconnect controller', () => {
+ it('coalesces repeated requests onto one active reconnect', async () => {
+ let finish: (() => void) | undefined
+
+ const handler = vi
+ .fn()
+ .mockImplementationOnce(
+ () =>
+ new Promise<void>(resolve => {
+ finish = resolve
+ })
+ )
+ .mockResolvedValueOnce(undefined)
+
+ disposers.push(registerGatewayReconnect(handler))
+
+ const first = reconnectGateway()
+ const second = reconnectGateway()
+
+ expect(second).toBe(first)
+ await Promise.resolve()
+ expect(handler).toHaveBeenCalledTimes(1)
+
+ finish?.()
+ await first
+
+ await reconnectGateway()
+ expect(handler).toHaveBeenCalledTimes(2)
+ })
+
+ it('only lets the current registration remove itself', async () => {
+ const stale = vi.fn()
+ const current = vi.fn()
+ const disposeStale = registerGatewayReconnect(stale)
+ disposers.push(registerGatewayReconnect(current))
+
+ disposeStale()
+ await reconnectGateway()
+
+ expect(stale).not.toHaveBeenCalled()
+ expect(current).toHaveBeenCalledOnce()
+ })
+
+ it('rejects when the gateway boot owner is not mounted', async () => {
+ await expect(reconnectGateway()).rejects.toThrow('Gateway reconnect is unavailable')
+ })
+})
diff --git a/apps/desktop/src/store/gateway-reconnect.ts b/apps/desktop/src/store/gateway-reconnect.ts
new file mode 100644
index 00000000000..b9883aff877
--- /dev/null
+++ b/apps/desktop/src/store/gateway-reconnect.ts
@@ -0,0 +1,34 @@
+type GatewayReconnectHandler = () => Promise<void> | void
+
+let activeHandler: GatewayReconnectHandler | null = null
+let inFlight: Promise<void> | null = null
+
+export function registerGatewayReconnect(handler: GatewayReconnectHandler): () => void {
+ activeHandler = handler
+
+ return () => {
+ if (activeHandler === handler) {
+ activeHandler = null
+ }
+ }
+}
+
+export function reconnectGateway(): Promise<void> {
+ if (inFlight) {
+ return inFlight
+ }
+
+ const handler = activeHandler
+
+ if (!handler) {
+ return Promise.reject(new Error('Gateway reconnect is unavailable'))
+ }
+
+ inFlight = Promise.resolve()
+ .then(handler)
+ .finally(() => {
+ inFlight = null
+ })
+
+ return inFlight
+}