Skip to content

The agent that grows with you

fix(webapp-access): "Restart gateway" in Web Access only restarts the gateway

emozilla47dec3ba199e
diff --git a/apps/desktop/electron/connection-config.ts b/apps/desktop/electron/connection-config.ts
index 0040eb9028f..45a0b4f3ebc 100644
--- a/apps/desktop/electron/connection-config.ts
+++ b/apps/desktop/electron/connection-config.ts
@@ -710,7 +710,8 @@ const LOCAL_PRIMARY_SCOPED_ROUTES = new Set([
// Web Access: each handler takes `?profile=` and acts on the gateway serving it.
'GET /api/webapp-access/status',
'POST /api/webapp-access/start',
- 'POST /api/webapp-access/stop'
+ 'POST /api/webapp-access/stop',
+ 'POST /api/webapp-access/restart'
])
function localPrimaryRequestScope(opts: ProfileRouteOptions): boolean | null {
diff --git a/apps/desktop/src/api/webapp-access.ts b/apps/desktop/src/api/webapp-access.ts
index b8571d9fe8e..5758998f215 100644
--- a/apps/desktop/src/api/webapp-access.ts
+++ b/apps/desktop/src/api/webapp-access.ts
@@ -45,3 +45,8 @@ export function startWebAccess(mode: WebAccessMode, publicUrl?: string): Promise
export function stopWebAccess(): Promise<WebAccessChange> {
return hermesApi<WebAccessChange>({ ...profileScoped(), method: 'POST', path: '/api/webapp-access/stop' })
}
+
+/** Restart the gateway onto the saved config, and nothing else. */
+export function restartWebAccess(): Promise<WebAccessChange> {
+ return hermesApi<WebAccessChange>({ ...profileScoped(), method: 'POST', path: '/api/webapp-access/restart' })
+}
diff --git a/apps/desktop/src/app/settings/web-access-settings.test.tsx b/apps/desktop/src/app/settings/web-access-settings.test.tsx
index 337d02862d8..47796554754 100644
--- a/apps/desktop/src/app/settings/web-access-settings.test.tsx
+++ b/apps/desktop/src/app/settings/web-access-settings.test.tsx
@@ -10,13 +10,14 @@ vi.mock('@/store/profile', async (): Promise<object> => {
vi.mock('@/hermes', () => ({
getProfiles: vi.fn(async () => ({ profiles: [] })),
getWebAccessStatus: vi.fn(),
+ restartWebAccess: vi.fn(),
setApiRequestProfile: vi.fn(),
startWebAccess: vi.fn(),
stopWebAccess: vi.fn()
}))
import { QueryClientProvider } from '@tanstack/react-query'
-import { cleanup, render, screen } from '@testing-library/react'
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { WebAccessStatus } from '@/api/webapp-access'
@@ -103,4 +104,17 @@ describe('WebAccessSettings', () => {
expect(screen.queryByText(/192\.168\.1\.50/)).toBeNull()
expect(screen.getByRole('button', { name: 'Stop' })).toBeTruthy()
})
+
+ it('restarts the gateway for a saved change without starting web access again', async () => {
+ // Saved `enabled: true`, but the gateway has not restarted onto it yet (a chat refused it).
+ const pending: WebAccessStatus = { ...OFF, enabled: true, mode: 'lan' }
+ mocked.restartWebAccess.mockResolvedValue({ ...pending, restart_error: 'busy', restart_started: false })
+ renderPane(pending)
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Restart gateway' }))
+
+ await waitFor(() => expect(mocked.restartWebAccess).toHaveBeenCalledTimes(1))
+ expect(mocked.startWebAccess).not.toHaveBeenCalled()
+ expect(mocked.stopWebAccess).not.toHaveBeenCalled()
+ })
})
diff --git a/apps/desktop/src/app/settings/web-access-settings.tsx b/apps/desktop/src/app/settings/web-access-settings.tsx
index e34e277ab23..71c89162804 100644
--- a/apps/desktop/src/app/settings/web-access-settings.tsx
+++ b/apps/desktop/src/app/settings/web-access-settings.tsx
@@ -8,6 +8,7 @@ import { Input } from '@/components/ui/input'
import { SegmentedControl } from '@/components/ui/segmented-control'
import {
getWebAccessStatus,
+ restartWebAccess,
startWebAccess,
stopWebAccess,
type WebAccessChange,
@@ -34,6 +35,8 @@ const START_TIMEOUT_MS = 90_000
*/
type Phase = 'off' | 'pendingOff' | 'pendingOn' | 'serving' | 'unavailable'
+type Busy = 'restart' | 'start' | 'stop' | null
+
/** The gateway serves the configured web app: it applied this config, not an earlier one's port. */
function servesConfig(status: WebAccessStatus): boolean {
const { state, url } = status.gateway
@@ -92,7 +95,7 @@ type FormProps = { queryKey: readonly unknown[]; status: WebAccessStatus; w: Web
function WebAccessForm({ queryKey, status, w }: FormProps): ReactElement {
const queryClient = useQueryClient()
- const [busy, setBusy] = useState<'start' | 'stop' | null>(null)
+ const [busy, setBusy] = useState<Busy>(null)
const [mode, setMode] = useState<WebAccessMode>(status.mode === 'public' ? 'public' : 'lan')
const [publicUrl, setPublicUrl] = useState(status.public_url)
const phase = phaseOf(status)
@@ -109,7 +112,7 @@ function WebAccessForm({ queryKey, status, w }: FormProps): ReactElement {
}
// Saved either way; a refused restart (a chat is running) applies when the gateway next restarts.
- const run = async (kind: 'start' | 'stop', change: () => Promise<WebAccessChange>) => {
+ const run = async (kind: NonNullable<Busy>, change: () => Promise<WebAccessChange>) => {
setBusy(kind)
try {
@@ -120,7 +123,7 @@ function WebAccessForm({ queryKey, status, w }: FormProps): ReactElement {
throw new Error(w.restartRefused(result.restart_error ?? ''))
}
- if (kind === 'start') {
+ if (result.enabled && kind !== 'stop') {
apply(await waitForWebApp().catch(() => Promise.reject(new Error(w.startTimedOut))))
}
} catch (err) {
@@ -133,6 +136,8 @@ function WebAccessForm({ queryKey, status, w }: FormProps): ReactElement {
const start = () => void run('start', () => startWebAccess(mode, mode === 'public' ? publicUrl.trim() : undefined))
const stop = () => void run('stop', stopWebAccess)
+ // A saved change the gateway has not applied yet: restart it, and nothing else.
+ const restart = () => void run('restart', restartWebAccess)
return (
<SettingsContent>
@@ -156,7 +161,7 @@ function WebAccessForm({ queryKey, status, w }: FormProps): ReactElement {
action={
<Button
disabled={busy !== null || (phase === 'off' && !ready)}
- onClick={phase === 'off' || phase === 'pendingOn' ? start : stop}
+ onClick={phase === 'off' ? start : phase.startsWith('pending') ? restart : stop}
size="sm"
variant={phase === 'off' ? 'default' : 'outline'}
>
@@ -214,7 +219,7 @@ function WhereRow({ lanUrl, locked, mode, onMode, onPublicUrl, port, publicUrl,
)
}
-function pillLabel(phase: Phase, busy: 'start' | 'stop' | null, w: WebAccessTranslations): string {
+function pillLabel(phase: Phase, busy: Busy, w: WebAccessTranslations): string {
const labels: Record<Phase, string> = {
off: w.stopped,
pendingOff: w.restartNeeded,
@@ -223,7 +228,7 @@ function pillLabel(phase: Phase, busy: 'start' | 'stop' | null, w: WebAccessTran
unavailable: w.unavailable
}
- return busy === 'start' ? w.starting : labels[phase]
+ return busy === 'start' || (busy === 'restart' && phase === 'pendingOn') ? w.starting : labels[phase]
}
function describe(phase: Phase, status: WebAccessStatus, w: WebAccessTranslations): string {
diff --git a/hermes_cli/web_routers/webapp_access.py b/hermes_cli/web_routers/webapp_access.py
index c541227c1c4..fae6abd4fe0 100644
--- a/hermes_cli/web_routers/webapp_access.py
+++ b/hermes_cli/web_routers/webapp_access.py
@@ -103,3 +103,11 @@ async def stop_webapp_access(profile: Optional[str] = None):
return _restart(gateway, "turning off Web Access")
return await _scoped(profile, _stop, config_write=True)
+
+
[email protected]("/api/webapp-access/restart")
+async def restart_webapp_access(profile: Optional[str] = None):
+ """Apply the saved config to a gateway that has not restarted onto it yet: restart that gateway
+ and nothing else (no Portal registration, no build, no config write)."""
+ profile = destructive_profile(profile, "POST /api/webapp-access/restart")
+ return await _scoped(profile, lambda gateway: _restart(gateway, "applying Web Access"))
diff --git a/tests/hermes_cli/test_webapp_access.py b/tests/hermes_cli/test_webapp_access.py
index 9face66118a..e47211e960f 100644
--- a/tests/hermes_cli/test_webapp_access.py
+++ b/tests/hermes_cli/test_webapp_access.py
@@ -247,3 +247,22 @@ def test_a_failed_build_turns_nothing_on_and_says_how_to_build(client, restarts,
assert nous == []
assert restarts == []
assert not _config()["webapp"]["enabled"]
+
+
+def test_restart_applies_the_saved_config_and_does_nothing_else(client, restarts, nous, builds):
+ """The pane's "Restart gateway" (a saved change the gateway has not applied yet) restarts the
+ gateway serving the profile and nothing else: no Portal registration, no build, no config
+ write."""
+ from hermes_cli.config import read_raw_config, save_config
+
+ save_config({**_config(), "webapp": {"enabled": True, "host": "0.0.0.0"}})
+ saved = read_raw_config()
+
+ response = client.post("/api/webapp-access/restart")
+ assert response.status_code == 200, response.text
+ assert response.json()["restart_started"] is True
+ assert response.json()["mode"] == "lan"
+ assert restarts == ["applying Web Access"]
+ assert nous == []
+ assert builds == []
+ assert read_raw_config() == saved