diff --git a/apps/desktop/electron/connection-registry.test.ts b/apps/desktop/electron/connection-registry.test.ts index f5aa64a722..e594157312 100644 --- a/apps/desktop/electron/connection-registry.test.ts +++ b/apps/desktop/electron/connection-registry.test.ts @@ -417,6 +417,54 @@ test('editing an entry does not collide with its own label', () => { assert.equal(edited.url, 'http://10.0.0.6:9119') }) +test('duplicate gateway URLs are rejected across remote and cloud kinds', () => { + let registry = emptyRegistry() + registry = upsertConnection( + registry, + normalizeConnectionInput({ kind: 'remote', label: 'Homelab', url: 'http://10.0.0.5:9119' }, registry) + ) + + // Same URL modulo trailing slash → dupe, even as a different kind. + assert.throws( + () => normalizeConnectionInput({ kind: 'remote', label: 'Twin', url: 'http://10.0.0.5:9119/' }, registry), + /already exists/ + ) + assert.throws( + () => normalizeConnectionInput({ kind: 'cloud', label: 'Cloud twin', url: 'http://10.0.0.5:9119' }, registry), + /already exists/ + ) + // Editing the entry itself keeps its own URL without self-colliding. + const existing = registry.connections.find(c => c.kind === 'remote')! + + const edited = normalizeConnectionInput( + { id: existing.id, kind: 'remote', label: 'Homelab', url: 'http://10.0.0.5:9119' }, + registry + ) + + assert.equal(edited.id, existing.id) +}) + +test('duplicate ssh targets are rejected on user@host:port + remote profile', () => { + let registry = emptyRegistry() + registry = upsertConnection( + registry, + normalizeConnectionInput({ kind: 'ssh', label: 'Box', host: 'alice@box:22', remoteProfile: 'work' }, registry) + ) + + assert.throws( + () => normalizeConnectionInput({ kind: 'ssh', label: 'Box twin', host: 'alice@box:22', remoteProfile: 'work' }, registry), + /already exists/ + ) + + // A different remote profile on the same host is a distinct agent source. + const otherProfile = normalizeConnectionInput( + { kind: 'ssh', label: 'Box other', host: 'alice@box:22', remoteProfile: 'other' }, + registry + ) + + assert.equal(otherProfile.kind, 'ssh') +}) + test('remote input normalizes URL and auth mode; cloud keeps org', () => { const registry = emptyRegistry() diff --git a/apps/desktop/electron/connection-registry.ts b/apps/desktop/electron/connection-registry.ts index b888e85ef6..eae226578b 100644 --- a/apps/desktop/electron/connection-registry.ts +++ b/apps/desktop/electron/connection-registry.ts @@ -495,12 +495,38 @@ export function normalizeConnectionInput(input: ConnectionInput, registry: Conne const { mode: _mode, ...sshFields } = ssh + // Duplicate prevention (enforced here so a crafted IPC payload can't slip + // past the editor's check): two ssh entries collide on the same + // user@host:port + remote profile. + const sshKey = (c: { host?: string; port?: number; remoteProfile?: string; user?: string }) => + `${(c.user || '').toLowerCase()}@${(c.host || '').toLowerCase()}:${c.port ?? 22}::${(c.remoteProfile || '').trim()}` + + const sshDupe = registry.connections.find(c => c.kind === 'ssh' && c.id !== id && sshKey(c) === sshKey(sshFields)) + + if (sshDupe) { + throw new Error(`A connection to this SSH host already exists ("${sshDupe.label}").`) + } + return { id, kind: 'ssh', label, ...sshFields } } if (kind === 'remote' || kind === 'cloud') { // normalizeRemoteBaseUrl throws its own user-facing message on bad input. const url = normalizeRemoteBaseUrl(input.url) + + // Duplicate prevention: remote/cloud entries collide on the normalized URL + // (trimmed, trailing slashes stripped, lowercased) regardless of kind — a + // cloud entry and a remote entry pointing at the same gateway are dupes. + const urlKey = (value: string) => value.trim().replace(/\/+$/, '').toLowerCase() + + const urlDupe = registry.connections.find( + c => (c.kind === 'remote' || c.kind === 'cloud') && c.id !== id && urlKey(c.url || '') === urlKey(url) + ) + + if (urlDupe) { + throw new Error(`A connection to this gateway URL already exists ("${urlDupe.label}").`) + } + const authMode = normAuthMode(input.authMode) const entry: RegistryConnection = { id, kind, label, url, authMode } diff --git a/apps/desktop/src/app/chat/sidebar/profile-rail-connect.test.tsx b/apps/desktop/src/app/chat/sidebar/profile-rail-connect.test.tsx index 75f8b9eb3b..c16cc7dec6 100644 --- a/apps/desktop/src/app/chat/sidebar/profile-rail-connect.test.tsx +++ b/apps/desktop/src/app/chat/sidebar/profile-rail-connect.test.tsx @@ -77,13 +77,13 @@ vi.mock('../../profiles/delete-profile-dialog', () => ({ DeleteProfileDialog: () vi.mock('../../profiles/rename-profile-dialog', () => ({ RenameProfileDialog: () => null })) describe('ProfileRail multi-gateway entry point', () => { - it('deep-links to Settings → Connections from the rail', () => { + it('deep-links to the unified Settings → Gateways page from the rail', () => { render() const pill = screen.getByRole('button', { name: 'Connect another Hermes gateway…' }) fireEvent.click(pill) - expect(navigate).toHaveBeenCalledWith('/settings?tab=connections') + expect(navigate).toHaveBeenCalledWith('/settings?tab=gateway') }) it('keeps the entry point visible for single-profile users', () => { diff --git a/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx b/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx index 5074df3ce5..95f73cebc0 100644 --- a/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx +++ b/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx @@ -319,15 +319,16 @@ export function ProfileRail() { navigate(PROFILES_ROUTE)} /> {/* Multi-gateway discoverability: a plug pinned beside Manage deep-links - to Settings → Connections. The registry (local runtime + remote - gateways + Hermes Cloud + SSH) is otherwise buried three levels into - Settings, and the rail is exactly where a user looks when they wonder - "how do I get my other machine's agents in here". */} + to Settings → Gateways (the connections registry lives on the unified + Gateways page now). The registry (local runtime + remote gateways + + Hermes Cloud + SSH) is otherwise buried three levels into Settings, + and the rail is exactly where a user looks when they wonder "how do I + get my other machine's agents in here". */} navigate(`${SETTINGS_ROUTE}?tab=connections`)} + onSelect={() => navigate(`${SETTINGS_ROUTE}?tab=gateway`)} /> {/* Land in the new profile on a fresh chat (selectProfile triggers the diff --git a/apps/desktop/src/app/command-palette/index.tsx b/apps/desktop/src/app/command-palette/index.tsx index 6f8287fcb9..2b65e440b0 100644 --- a/apps/desktop/src/app/command-palette/index.tsx +++ b/apps/desktop/src/app/command-palette/index.tsx @@ -41,7 +41,6 @@ import { MessageCircle, Monitor, Moon, - Network, Package, Palette, PawPrint, @@ -386,7 +385,6 @@ const toSessionEntry = (session: SessionRow): SessionEntry => ({ type NonConfigSettingsLabel = | 'about' | 'archivedChats' - | 'connections' | 'gateway' | 'keysSettings' | 'keysTools' @@ -413,12 +411,12 @@ const NON_CONFIG_SETTINGS: ReadonlyArray<{ labelKey: 'providerApiKeys', tab: 'providers&pview=keys' }, - { icon: Globe, keywords: ['connection', 'messaging'], labelKey: 'gateway', tab: 'gateway' }, { - icon: Network, - keywords: ['connections', 'gateway', 'remote', 'multi', 'instances', 'ssh', 'cloud', 'add gateway', 'registry'], - labelKey: 'connections', - tab: 'connections' + icon: Globe, + // The Connections registry merged into the unified Gateways page. + keywords: ['connection', 'connections', 'messaging', 'remote', 'multi', 'instances', 'ssh', 'cloud', 'add gateway', 'registry'], + labelKey: 'gateway', + tab: 'gateway' }, { icon: KeyRound, diff --git a/apps/desktop/src/app/settings/connections-registry.test.tsx b/apps/desktop/src/app/settings/connections-registry.test.tsx new file mode 100644 index 0000000000..c2823aed7a --- /dev/null +++ b/apps/desktop/src/app/settings/connections-registry.test.tsx @@ -0,0 +1,213 @@ +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import type { DesktopConnectionsRegistry } from '@/global' + +import { ConnectionsRegistrySection, findDuplicateConnection, normalizeGatewayUrl, sshCompositeKey } from './connections-registry' + +const list = vi.fn() +const save = vi.fn() +const remove = vi.fn() +const setPrimary = vi.fn() +const test = vi.fn() + +const registry: DesktopConnectionsRegistry = { + connections: [ + { id: 'local', kind: 'local', label: 'This device', tokenPreview: null, tokenSet: false }, + { + authMode: 'token', + id: 'homelab', + kind: 'remote', + label: 'Homelab', + tokenPreview: '...abc123', + tokenSet: true, + url: 'http://homelab.lan:9119' + } + ], + primary: 'local', + secureTokenStorage: true, + version: 2 +} + +beforeEach(() => { + list.mockResolvedValue(registry) + save.mockResolvedValue({ connection: registry.connections[1], ok: true, registry }) + remove.mockResolvedValue({ ok: true, registry: { ...registry, connections: [registry.connections[0]] } }) + setPrimary.mockResolvedValue({ ok: true, registry: { ...registry, primary: 'homelab' } }) + test.mockResolvedValue({ ok: true, reachable: true }) + Object.defineProperty(window, 'hermesDesktop', { + configurable: true, + value: { connections: { list, remove, save, setPrimary, test } } + }) +}) + +afterEach(() => { + cleanup() + vi.clearAllMocks() +}) + +describe('ConnectionsRegistrySection', () => { + it('lists registered connections with primary + local pills', async () => { + render() + + await waitFor(() => expect(screen.getByText('Homelab')).toBeTruthy()) + // Label and the managed pill share the copy, so expect both instances. + expect(screen.getAllByText('This device').length).toBeGreaterThan(0) + expect(screen.getByText('Primary')).toBeTruthy() + expect(list).toHaveBeenCalledTimes(1) + }) + + it('opens the add-connection editor and saves with a required label', async () => { + render() + + await waitFor(() => expect(screen.getByText('Homelab')).toBeTruthy()) + fireEvent.click(screen.getByText('Add connection')) + + // Save is disabled until a label is present. + const saveButton = screen.getByText('Save connection').closest('button')! + expect(saveButton.disabled).toBe(true) + + fireEvent.change(screen.getByPlaceholderText('Homelab'), { target: { value: 'Spark box' } }) + fireEvent.change(screen.getByPlaceholderText('http://homelab.lan:9119'), { + target: { value: 'http://spark.lan:9119' } + }) + expect(saveButton.disabled).toBe(false) + fireEvent.click(saveButton) + + await waitFor(() => expect(save).toHaveBeenCalledTimes(1)) + expect(save.mock.calls[0][0]).toMatchObject({ + kind: 'remote', + label: 'Spark box', + url: 'http://spark.lan:9119' + }) + }) + + it('offers every kind on create and disables Local while the managed entry exists', async () => { + render() + + await waitFor(() => expect(screen.getByText('Homelab')).toBeTruthy()) + fireEvent.click(screen.getByText('Add connection')) + + const localKind = screen.getByRole('button', { name: 'Local' }) as HTMLButtonElement + expect(localKind.disabled).toBe(true) + expect(screen.getByRole('button', { name: 'Hermes Cloud' })).toBeTruthy() + expect(screen.getByRole('button', { name: 'Remote gateway' })).toBeTruthy() + expect(screen.getByRole('button', { name: 'SSH' })).toBeTruthy() + }) + + it('rejects a duplicate gateway URL in the save path with an inline error', async () => { + render() + + await waitFor(() => expect(screen.getByText('Homelab')).toBeTruthy()) + fireEvent.click(screen.getByText('Add connection')) + + fireEvent.change(screen.getByPlaceholderText('Homelab'), { target: { value: 'Homelab twin' } }) + // Same URL modulo case + trailing slash: normalized-dupe of the existing entry. + fireEvent.change(screen.getByPlaceholderText('http://homelab.lan:9119'), { + target: { value: 'HTTP://HOMELAB.LAN:9119/' } + }) + fireEvent.click(screen.getByText('Save connection').closest('button')!) + + await waitFor(() => + expect(screen.getByText('A connection to this gateway URL already exists (“Homelab”).')).toBeTruthy() + ) + expect(save).not.toHaveBeenCalled() + }) + + it('makes a non-primary connection primary', async () => { + render() + + await waitFor(() => expect(screen.getByText('Homelab')).toBeTruthy()) + fireEvent.click(screen.getByText('Make primary')) + + await waitFor(() => expect(setPrimary).toHaveBeenCalledWith('homelab')) + }) + + it('tests a connection through the bridge', async () => { + render() + + await waitFor(() => expect(screen.getByText('Homelab')).toBeTruthy()) + fireEvent.click(screen.getAllByText('Test')[0]) + + await waitFor(() => expect(test).toHaveBeenCalled()) + }) +}) + +describe('dedupe helpers', () => { + it('normalizes gateway URLs (trim, trailing slashes, lowercase)', () => { + expect(normalizeGatewayUrl(' HTTP://Homelab.LAN:9119// ')).toBe('http://homelab.lan:9119') + }) + + it('normalizes ssh composites and defaults the port', () => { + expect(sshCompositeKey('alice@Box')).toBe('alice@box:22') + expect(sshCompositeKey('alice@box:22')).toBe('alice@box:22') + expect(sshCompositeKey('box:2222')).toBe('@box:2222') + expect(sshCompositeKey(' ')).toBe('') + }) + + it('finds at most one local entry', () => { + expect( + findDuplicateConnection({ host: '', id: null, kind: 'local', remoteProfile: '', url: '' }, registry.connections) + ).toMatchObject({ id: 'local' }) + // Editing the local entry itself is not a self-collision. + expect( + findDuplicateConnection( + { host: '', id: 'local', kind: 'local', remoteProfile: '', url: '' }, + registry.connections + ) + ).toBeNull() + }) + + it('keys remote/cloud dupes on the normalized URL across both kinds', () => { + expect( + findDuplicateConnection( + { host: '', id: null, kind: 'cloud', remoteProfile: '', url: 'http://HOMELAB.lan:9119/' }, + registry.connections + ) + ).toMatchObject({ id: 'homelab' }) + expect( + findDuplicateConnection( + { host: '', id: null, kind: 'remote', remoteProfile: '', url: 'http://other.lan:9119' }, + registry.connections + ) + ).toBeNull() + // Editing the entry itself is not a self-collision. + expect( + findDuplicateConnection( + { host: '', id: 'homelab', kind: 'remote', remoteProfile: '', url: 'http://homelab.lan:9119' }, + registry.connections + ) + ).toBeNull() + }) + + it('keys ssh dupes on user@host:port + remote profile', () => { + const connections = [ + ...registry.connections, + { + host: 'box', + id: 'box', + kind: 'ssh' as const, + label: 'Box', + port: 22, + remoteProfile: 'work', + tokenPreview: null, + tokenSet: false, + user: 'alice' + } + ] + + expect( + findDuplicateConnection( + { host: 'alice@box:22', id: null, kind: 'ssh', remoteProfile: 'work', url: '' }, + connections + ) + ).toMatchObject({ id: 'box' }) + // Different profile on the same host is a distinct agent source. + expect( + findDuplicateConnection( + { host: 'alice@box:22', id: null, kind: 'ssh', remoteProfile: 'other', url: '' }, + connections + ) + ).toBeNull() + }) +}) diff --git a/apps/desktop/src/app/settings/connections-settings.tsx b/apps/desktop/src/app/settings/connections-registry.tsx similarity index 74% rename from apps/desktop/src/app/settings/connections-settings.tsx rename to apps/desktop/src/app/settings/connections-registry.tsx index 8941b3bf12..aa6d62d477 100644 --- a/apps/desktop/src/app/settings/connections-settings.tsx +++ b/apps/desktop/src/app/settings/connections-registry.tsx @@ -14,7 +14,7 @@ import { triggerHaptic } from '@/lib/haptics' import { Cloud, Globe, Loader2, Monitor, Pencil, Plus, RefreshCw, Terminal, Trash2 } from '@/lib/icons' import { notify, notifyError } from '@/store/notifications' -import { EmptyState, ListRow, Pill, SectionHeading, SettingsContent, SettingsSkeleton } from './primitives' +import { EmptyState, ListRow, Pill, SectionHeading } from './primitives' const KIND_ICONS: Record = { cloud: Cloud, @@ -33,6 +33,9 @@ interface EditorState { token: string host: string keyPath: string + // ssh remote profile, hydrated on edit so the duplicate key matches the + // main-process one (user@host:port + profile); the editor doesn't expose it. + remoteProfile: string // Extra gateway headers (access proxies such as Cloudflare Access). // `value: ''` on a row that came from storage means "keep the saved // secret" (sent as null); a typed value replaces it; a removed row clears @@ -56,21 +59,113 @@ function editorFromConnection(conn: DesktopRegistryConnection): EditorState { // would silently resurrect the old values. host: conn.host ? `${conn.user ? `${conn.user}@` : ''}${conn.host}${conn.port ? `:${conn.port}` : ''}` : '', keyPath: conn.keyPath || '', + remoteProfile: conn.remoteProfile || '', headers: (conn.headerNames || []).map(name => ({ name, stored: true, value: '' })) } } function emptyEditor(kind: DesktopConnectionKind): EditorState { - return { id: null, kind, label: '', url: '', authMode: 'token', token: '', host: '', keyPath: '', headers: [] } + return { + id: null, + kind, + label: '', + url: '', + authMode: 'token', + token: '', + host: '', + keyPath: '', + remoteProfile: '', + headers: [] + } +} + +/** Dedupe key for a remote/cloud gateway URL: trim, drop trailing slashes, lowercase. */ +export function normalizeGatewayUrl(url: string): string { + return url.trim().replace(/\/+$/, '').toLowerCase() } /** - * Settings → Connections: manage the registry of named agent sources (local - * runtime + any number of remote gateways / Hermes Cloud instances / SSH - * hosts). Storage-level management only — the active/primary switchover UX - * stays in Settings → Gateway until the routing generalization lands. + * Dedupe key for the composite ssh host string the editor shows + * (`user@host:port`, user/port optional): normalized to `user@host:port` with + * the default port made explicit so `box` and `box:22` collide. */ -export function ConnectionsSettings() { +export function sshCompositeKey(composite: string): string { + const raw = composite.trim().toLowerCase() + + if (!raw) { + return '' + } + + const at = raw.lastIndexOf('@') + const user = at > 0 ? raw.slice(0, at) : '' + const rest = at >= 0 ? raw.slice(at + 1) : raw + const portMatch = rest.match(/^(.*?):(\d+)$/) + const host = portMatch ? portMatch[1] : rest + const port = portMatch ? portMatch[2] : '22' + + if (!host) { + return '' + } + + return `${user}@${host}:${port}` +} + +/** + * The renderer-side duplicate rule, mirrored by the main process + * (normalizeConnectionInput enforces the same keys in the save path): + * - at most ONE local entry, ever; + * - remote/cloud entries are duplicates when their normalized URLs match; + * - ssh entries are duplicates on user@host:port + remote profile. + * Returns the existing entry the candidate collides with, or null. + */ +export function findDuplicateConnection( + editor: Pick, + connections: DesktopRegistryConnection[] +): DesktopRegistryConnection | null { + if (editor.kind === 'local') { + return connections.find(c => c.kind === 'local' && c.id !== editor.id) ?? null + } + + if (editor.kind === 'remote' || editor.kind === 'cloud') { + const key = normalizeGatewayUrl(editor.url) + + if (!key) { + return null + } + + return ( + connections.find( + c => (c.kind === 'remote' || c.kind === 'cloud') && c.id !== editor.id && normalizeGatewayUrl(c.url || '') === key + ) ?? null + ) + } + + const key = sshCompositeKey(editor.host) + + if (!key) { + return null + } + + const profile = editor.remoteProfile.trim() + + return ( + connections.find( + c => + c.kind === 'ssh' && + c.id !== editor.id && + sshCompositeKey(`${c.user ? `${c.user}@` : ''}${c.host ?? ''}${c.port ? `:${c.port}` : ''}`) === key && + (c.remoteProfile || '').trim() === profile + ) ?? null + ) +} + +/** + * The connections registry section of Settings → Gateways: manage the named + * agent sources (local runtime + any number of remote gateways / Hermes Cloud + * instances / SSH hosts). Storage-level management — the active/primary + * switchover UX is the connection-mode controls above this section. + */ +export function ConnectionsRegistrySection() { const { t } = useI18n() const s = t.settings.connections const [registry, setRegistry] = useState(null) @@ -82,9 +177,14 @@ export function ConnectionsSettings() { const [removeTarget, setRemoveTarget] = useState(null) const [plainTextConfirm, setPlainTextConfirm] = useState(false) const [updatingAll, setUpdatingAll] = useState(false) + // Inline duplicate rejection from the save path (dedupe is also enforced in + // the main process, so a crafted payload can't slip past the UI check). + const [dupeError, setDupeError] = useState(null) const bridge = window.hermesDesktop?.connections + const hasLocal = Boolean(registry?.connections.some(c => c.kind === 'local')) + const load = useCallback(async () => { if (!bridge) { setLoading(false) @@ -107,12 +207,35 @@ export function ConnectionsSettings() { void load() }, [load]) + const openEditor = (next: EditorState | null) => { + setDupeError(null) + setEditor(next) + } + const save = useCallback( async (allowPlainTextToken = false) => { if (!bridge || !editor) { return } + // Duplicate prevention lives in the save path (not just a disabled + // button): reject a candidate that collides with an existing entry with + // an inline error before anything crosses the IPC boundary. + const dupe = findDuplicateConnection(editor, registry?.connections ?? []) + + if (dupe) { + setDupeError( + editor.kind === 'local' + ? s.duplicateLocal + : editor.kind === 'ssh' + ? s.duplicateSsh(dupe.label) + : s.duplicateUrl(dupe.label) + ) + + return + } + + setDupeError(null) setSaving(true) try { @@ -162,8 +285,8 @@ export function ConnectionsSettings() { setPlainTextConfirm(false) } catch (err) { // Keyring-less machine and the user hasn't consented to plain-text - // storage yet: raise the same opt-in dialog Settings → Gateway uses - // instead of dead-ending the save. + // storage yet: raise the same opt-in dialog the connection-mode form + // uses instead of dead-ending the save. if ( !allowPlainTextToken && registry?.secureTokenStorage === false && @@ -181,7 +304,7 @@ export function ConnectionsSettings() { setSaving(false) } }, - [bridge, editor, registry?.secureTokenStorage, s.saveFailed] + [bridge, editor, registry?.connections, registry?.secureTokenStorage, s] ) const remove = useCallback(async () => { @@ -283,12 +406,12 @@ export function ConnectionsSettings() { ssh: { desc: s.kindSshDesc, label: s.kindSsh } } - if (loading) { - return + if (!bridge) { + return null } return ( - +

{s.intro}

{/* Storage-only slice: be explicit that routing consumption is staged so @@ -297,7 +420,11 @@ export function ConnectionsSettings() { {s.stagedNote}

- {!registry || registry.connections.length === 0 ? ( + {loading ? ( +
+ +
+ ) : !registry || registry.connections.length === 0 ? ( ) : ( registry.connections.map(conn => { @@ -329,7 +456,7 @@ export function ConnectionsSettings() { <>

{kindMeta[editor.kind].desc}

+ {!editor.id && hasLocal ?

{s.localAddHint}

: null} + {!editor.id && editor.kind === 'cloud' ? ( +

{s.cloudAddHint}

+ ) : null} setEditor({ ...editor, url: e.target.value })} + onChange={e => { + setDupeError(null) + setEditor({ ...editor, url: e.target.value }) + }} placeholder="http://homelab.lan:9119" value={editor.url} /> @@ -509,7 +645,10 @@ export function ConnectionsSettings() { setEditor({ ...editor, host: e.target.value })} + onChange={e => { + setDupeError(null) + setEditor({ ...editor, host: e.target.value }) + }} placeholder="user@host:22" value={editor.host} /> @@ -518,8 +657,10 @@ export function ConnectionsSettings() { /> )} + {dupeError ?

{dupeError}

: null} +
-
) } diff --git a/apps/desktop/src/app/settings/connections-settings.test.tsx b/apps/desktop/src/app/settings/connections-settings.test.tsx deleted file mode 100644 index a5c4ba2006..0000000000 --- a/apps/desktop/src/app/settings/connections-settings.test.tsx +++ /dev/null @@ -1,102 +0,0 @@ -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' - -import type { DesktopConnectionsRegistry } from '@/global' - -import { ConnectionsSettings } from './connections-settings' - -const list = vi.fn() -const save = vi.fn() -const remove = vi.fn() -const setPrimary = vi.fn() -const test = vi.fn() - -const registry: DesktopConnectionsRegistry = { - connections: [ - { id: 'local', kind: 'local', label: 'This device', tokenPreview: null, tokenSet: false }, - { - authMode: 'token', - id: 'homelab', - kind: 'remote', - label: 'Homelab', - tokenPreview: '...abc123', - tokenSet: true, - url: 'http://homelab.lan:9119' - } - ], - primary: 'local', - secureTokenStorage: true, - version: 2 -} - -beforeEach(() => { - list.mockResolvedValue(registry) - save.mockResolvedValue({ connection: registry.connections[1], ok: true, registry }) - remove.mockResolvedValue({ ok: true, registry: { ...registry, connections: [registry.connections[0]] } }) - setPrimary.mockResolvedValue({ ok: true, registry: { ...registry, primary: 'homelab' } }) - test.mockResolvedValue({ ok: true, reachable: true }) - Object.defineProperty(window, 'hermesDesktop', { - configurable: true, - value: { connections: { list, remove, save, setPrimary, test } } - }) -}) - -afterEach(() => { - cleanup() - vi.clearAllMocks() -}) - -describe('ConnectionsSettings', () => { - it('lists registered connections with primary + local pills', async () => { - render() - - await waitFor(() => expect(screen.getByText('Homelab')).toBeTruthy()) - // Label and the managed pill share the copy, so expect both instances. - expect(screen.getAllByText('This device').length).toBeGreaterThan(0) - expect(screen.getByText('Primary')).toBeTruthy() - expect(list).toHaveBeenCalledTimes(1) - }) - - it('opens the add-connection editor and saves with a required label', async () => { - render() - - await waitFor(() => expect(screen.getByText('Homelab')).toBeTruthy()) - fireEvent.click(screen.getByText('Add connection')) - - // Save is disabled until a label is present. - const saveButton = screen.getByText('Save connection').closest('button')! - expect(saveButton.disabled).toBe(true) - - fireEvent.change(screen.getByPlaceholderText('Homelab'), { target: { value: 'Spark box' } }) - fireEvent.change(screen.getByPlaceholderText('http://homelab.lan:9119'), { - target: { value: 'http://spark.lan:9119' } - }) - expect(saveButton.disabled).toBe(false) - fireEvent.click(saveButton) - - await waitFor(() => expect(save).toHaveBeenCalledTimes(1)) - expect(save.mock.calls[0][0]).toMatchObject({ - kind: 'remote', - label: 'Spark box', - url: 'http://spark.lan:9119' - }) - }) - - it('makes a non-primary connection primary', async () => { - render() - - await waitFor(() => expect(screen.getByText('Homelab')).toBeTruthy()) - fireEvent.click(screen.getByText('Make primary')) - - await waitFor(() => expect(setPrimary).toHaveBeenCalledWith('homelab')) - }) - - it('tests a connection through the bridge', async () => { - render() - - await waitFor(() => expect(screen.getByText('Homelab')).toBeTruthy()) - fireEvent.click(screen.getAllByText('Test')[0]) - - await waitFor(() => expect(test).toHaveBeenCalled()) - }) -}) diff --git a/apps/desktop/src/app/settings/gateway-settings.tsx b/apps/desktop/src/app/settings/gateway-settings.tsx index 14aeb1aa71..d578637ca4 100644 --- a/apps/desktop/src/app/settings/gateway-settings.tsx +++ b/apps/desktop/src/app/settings/gateway-settings.tsx @@ -28,6 +28,7 @@ import { cn } from '@/lib/utils' import { notify, notifyError, readableError } from '@/store/notifications' import { $profiles, refreshActiveProfile } from '@/store/profile' +import { ConnectionsRegistrySection } from './connections-registry' import { CONTROL_TEXT } from './constants' import { EmptyState, ListRow, Pill, SettingsContent, SettingsSkeleton } from './primitives' import { enrichSelectedSshHost, selectSshHost } from './ssh-host-selection' @@ -135,23 +136,6 @@ function ModeCard({ ) } -function ScopeChip({ active, label, onSelect }: { active: boolean; label: string; onSelect: () => void }) { - return ( - - ) -} - // `embedded` trims the page chrome for reuse inside the boot-failure recovery // card: the outer title/intro, the "Save for next restart" action, and the // Diagnostics row are redundant there (the card owns its header + a single @@ -1072,25 +1056,46 @@ export function GatewaySettings({ embedded = false }: { embedded?: boolean } = { )} + {/* Per-profile gateway overrides: an explicit subsection (not an ambient + page-scope chip row) — pick which target the connection controls + below edit: the default connection or one named profile's override. */} {namedProfiles.length > 0 ? ( -
+
- {g.appliesTo} -
-
- setScope(null)} /> - {namedProfiles.map(profile => ( - setScope(profile.name)} - /> - ))} + {g.profileOverridesTitle}

- {scope === null ? g.defaultConnection : g.profileConnection(scope)} + {g.profileOverridesDesc}

+ {g.overrideEditing} + ) : ( + + ) + } + description={g.defaultConnection} + title={g.allProfiles} + /> + {namedProfiles.map(profile => ( + {g.overrideEditing} + ) : ( + + ) + } + description={scope === profile.name ? g.profileConnection(profile.name) : g.overrideSelectHint} + key={profile.name} + title={profile.name} + /> + ))}
) : null} @@ -1573,6 +1578,11 @@ export function GatewaySettings({ embedded = false }: { embedded?: boolean } = {
)} + {/* Unified Gateways page: the full connections registry (add/edit/delete + named agent sources) lives on this page now, below the window + connection controls. Hidden in the embedded (boot-recovery) form. */} + {embedded ? null : } + {/* Plain-text token opt-in: gated when secure storage is unavailable and a new token would be persisted. Confirm resumes the remembered save/apply. */} `config:${s.id}` as SettingsViewId), 'providers', 'gateway', + // Legacy alias: the Connections page merged into Gateways. Kept in the enum + // so saved `?tab=connections` deep links still resolve (redirected below). 'connections', 'keybinds', 'keys', @@ -80,6 +80,14 @@ export function SettingsView({ onClose, onConfigSaved, onMainModelChanged }: Set }, [navigate, search]) const [activeView, setActiveView] = useRouteEnumParam('tab', SETTINGS_VIEWS, 'config:model' as SettingsViewId) + + // Connections merged into the unified Gateways page: land old + // `?tab=connections` routes/bookmarks there instead of a dead entry. + useEffect(() => { + if (activeView === 'connections') { + setActiveView('gateway') + } + }, [activeView, setActiveView]) // Providers subnav (Accounts vs API keys) lives in its own param so each // sub-view is deep-linkable and survives a refresh. const [providerView, setProviderView] = useRouteEnumParam('pview', PROVIDER_VIEWS, 'accounts') @@ -209,13 +217,6 @@ export function SettingsView({ onClose, onConfigSaved, onMainModelChanged }: Set label: t.settings.nav.gateway, onSelect: () => setActiveView('gateway') }, - { - active: activeView === 'connections', - icon: Network, - id: 'connections', - label: t.settings.nav.connections, - onSelect: () => setActiveView('connections') - }, { active: activeView === 'keybinds', icon: Keyboard, @@ -313,10 +314,10 @@ export function SettingsView({ onClose, onConfigSaved, onMainModelChanged }: Set ) : activeView === 'about' ? ( - ) : activeView === 'gateway' ? ( + ) : activeView === 'gateway' || activeView === 'connections' ? ( + // 'connections' renders the unified page too so the frame before + // the alias redirect lands doesn't flash the fallback view. - ) : activeView === 'connections' ? ( - ) : activeView === 'keybinds' ? ( ) : activeView.startsWith('config:') ? ( diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.ts index edd29adea9..02da8ff3b7 100644 --- a/apps/desktop/src/i18n/ar.ts +++ b/apps/desktop/src/i18n/ar.ts @@ -684,11 +684,16 @@ export const ar = defineLocale({ envOverride: 'تجاوز من البيئة', intro: 'يشغّل Hermes Desktop بوابة محلية خاصة افتراضياً. استخدم بوابة بعيدة عندما تريد أن يتحكم هذا التطبيق بخلفية Hermes تعمل مسبقاً على جهاز آخر أو خلف وكيل موثوق.', - appliesTo: 'ينطبق على', allProfiles: 'كل الملفات الشخصية', defaultConnection: 'الاتصال الافتراضي لكل ملف شخصي لا يملك تجاوزاً خاصاً.', profileConnection: profile => `الاتصال المستخدم فقط عندما يكون "${profile}" هو الملف الشخصي النشط. اختر "استخدام البوابة الافتراضية" لإزالة التجاوز الخاص به.`, + profileOverridesTitle: 'تجاوزات لكل ملف شخصي', + profileOverridesDesc: + 'يمكن لكل ملف شخصي أن يشير إلى بوابته الخاصة. عناصر التحكم بالاتصال أدناه تحرر الهدف المحدد؛ بقية هذه الصفحة تنطبق على التطبيق بأكمله.', + overrideEdit: 'تحرير', + overrideEditing: 'قيد التحرير', + overrideSelectHint: 'اختر لعرض أو تغيير البوابة التي يستخدمها هذا الملف الشخصي.', envOverrideTitle: 'متغيرات البيئة تتحكم في جلسة سطح المكتب هذه.', envOverrideDesc: 'أزل HERMES_DESKTOP_REMOTE_URL و HERMES_DESKTOP_REMOTE_TOKEN لاستخدام الإعداد المحفوظ أدناه.', localTitle: 'بوابة محلية', diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index 6c6b93236b..f5d6a830bd 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -354,8 +354,7 @@ export const en: Translations = { providerAccounts: 'Accounts', providerApiKeys: 'API keys', providerCustomEndpoints: 'Custom Endpoints', - gateway: 'Gateway', - connections: 'Connections', + gateway: 'Gateways', apiKeys: 'Tools & Keys', keybinds: 'Keyboard Shortcuts', keysTools: 'Tools', @@ -696,6 +695,12 @@ export const en: Translations = { headerValueSaved: 'Saved — leave blank to keep', headerAdd: 'Add header', headerRemove: 'Remove', + duplicateLocal: 'This app already manages a local connection — there can only be one.', + duplicateUrl: (label: string) => `A connection to this gateway URL already exists (“${label}”).`, + duplicateSsh: (label: string) => `A connection to this SSH host already exists (“${label}”).`, + localAddHint: 'Local is unavailable: the managed local connection already exists (there is only ever one).', + cloudAddHint: + 'Tip: signing in under Hermes Cloud above discovers your agents automatically — use this form only to register a known instance URL by hand.', save: 'Save connection', saving: 'Saving…', cancel: 'Cancel', @@ -709,11 +714,16 @@ export const en: Translations = { envOverride: 'env override', intro: 'Local by default. Use remote when this app should drive a Hermes backend elsewhere. Per-profile overrides below.', - appliesTo: 'Applies to', allProfiles: 'All profiles', defaultConnection: 'Default connection for every profile that has no override of its own.', profileConnection: profile => `Connection used only when “${profile}” is the active profile. Choose Use default gateway to remove its override.`, + profileOverridesTitle: 'Per-profile overrides', + profileOverridesDesc: + 'Each profile can point at its own gateway. The connection controls below edit the selected target; everything else on this page is app-wide.', + overrideEdit: 'Edit', + overrideEditing: 'Editing', + overrideSelectHint: 'Select to view or change the gateway this profile uses.', envOverrideTitle: 'Environment variables are controlling this desktop session.', envOverrideDesc: 'Unset HERMES_DESKTOP_REMOTE_URL and HERMES_DESKTOP_REMOTE_TOKEN to use the saved setting below.', diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts index 8e91598dad..eb77073033 100644 --- a/apps/desktop/src/i18n/ja.ts +++ b/apps/desktop/src/i18n/ja.ts @@ -730,11 +730,16 @@ export const ja = defineLocale({ envOverride: 'env オーバーライド', intro: 'Hermes Desktop はデフォルトで独自のローカルゲートウェイを起動します。別のマシンや信頼できるプロキシの背後で既に動作している Hermes バックエンドをこのアプリで制御する場合は、リモートゲートウェイを使用してください。以下でプロファイルを選択して、それぞれのリモートホストを設定します。', - appliesTo: '適用対象', allProfiles: 'すべてのプロファイル', defaultConnection: '独自のオーバーライドがないすべてのプロファイルのデフォルト接続。', profileConnection: profile => `"${profile}" がアクティブプロファイルのときのみ使用される接続。「デフォルトゲートウェイを使用」を選ぶとオーバーライドが削除されます。`, + profileOverridesTitle: 'プロファイルごとのオーバーライド', + profileOverridesDesc: + '各プロファイルは独自のゲートウェイを指定できます。下の接続コントロールは選択した対象を編集します。このページのその他の設定はアプリ全体に適用されます。', + overrideEdit: '編集', + overrideEditing: '編集中', + overrideSelectHint: '選択すると、このプロファイルが使用するゲートウェイを表示・変更できます。', envOverrideTitle: '環境変数がこのデスクトップセッションを制御しています。', envOverrideDesc: '保存された設定を使用するには HERMES_DESKTOP_REMOTE_URL と HERMES_DESKTOP_REMOTE_TOKEN の設定を解除してください。', diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts index 2cbe444dee..63ebc2b0eb 100644 --- a/apps/desktop/src/i18n/types.ts +++ b/apps/desktop/src/i18n/types.ts @@ -304,7 +304,6 @@ export interface Translations { providerApiKeys: string providerCustomEndpoints: string gateway: string - connections: string apiKeys: string keybinds: string keysTools: string @@ -583,6 +582,11 @@ export interface Translations { headerValueSaved: string headerAdd: string headerRemove: string + duplicateLocal: string + duplicateUrl: (label: string) => string + duplicateSsh: (label: string) => string + localAddHint: string + cloudAddHint: string save: string saving: string cancel: string @@ -595,10 +599,14 @@ export interface Translations { title: string envOverride: string intro: string - appliesTo: string allProfiles: string defaultConnection: string profileConnection: (profile: string) => string + profileOverridesTitle: string + profileOverridesDesc: string + overrideEdit: string + overrideEditing: string + overrideSelectHint: string envOverrideTitle: string envOverrideDesc: string modeTitle: string diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.ts index 872828d3a1..7a4d506e7f 100644 --- a/apps/desktop/src/i18n/zh-hant.ts +++ b/apps/desktop/src/i18n/zh-hant.ts @@ -715,10 +715,14 @@ export const zhHant = defineLocale({ envOverride: '環境變數覆寫', intro: 'Hermes Desktop 預設會啟動自己的本機閘道。如果您希望此應用程式控制另一台機器或可信代理後面已執行的 Hermes 後端,請使用遠端閘道。在下方按設定檔指定各自的遠端主機。', - appliesTo: '套用至', allProfiles: '全部設定檔', defaultConnection: '預設連線適用於所有沒有自訂覆寫的設定檔。', profileConnection: profile => `僅當「${profile}」為作用中設定檔時使用此連線。選擇「使用預設閘道」可移除其覆寫。`, + profileOverridesTitle: '依設定檔覆寫', + profileOverridesDesc: '每個設定檔都可以指向自己的閘道。下方的連線控制項會編輯所選目標;此頁其餘設定為整個應用程式範圍。', + overrideEdit: '編輯', + overrideEditing: '編輯中', + overrideSelectHint: '選取即可檢視或變更此設定檔使用的閘道。', envOverrideTitle: '環境變數正在控制此桌面工作階段。', envOverrideDesc: '取消設定 HERMES_DESKTOP_REMOTE_URL 和 HERMES_DESKTOP_REMOTE_TOKEN 後才會使用下方儲存的設定。', localTitle: '本機閘道', diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts index 389ab99799..9c44590a7a 100644 --- a/apps/desktop/src/i18n/zh.ts +++ b/apps/desktop/src/i18n/zh.ts @@ -344,7 +344,6 @@ export const zh: Translations = { providerApiKeys: 'API 密钥', providerCustomEndpoints: '自定义端点', gateway: '网关', - connections: '连接', apiKeys: '工具与密钥', keybinds: '键盘快捷键', keysTools: '工具', @@ -900,6 +899,11 @@ export const zh: Translations = { headerValueSaved: '已保存——留空以保留', headerAdd: '添加请求头', headerRemove: '移除', + duplicateLocal: '本应用已管理一个本地连接——只能有一个。', + duplicateUrl: (label: string) => `已存在指向此网关 URL 的连接(“${label}”)。`, + duplicateSsh: (label: string) => `已存在指向此 SSH 主机的连接(“${label}”)。`, + localAddHint: '“本地”不可用:应用管理的本地连接已存在(永远只有一个)。', + cloudAddHint: '提示:在上方登录 Hermes Cloud 可自动发现你的智能体——此表单仅用于手动注册已知的实例 URL。', save: '保存连接', saving: '保存中…', cancel: '取消', @@ -913,10 +917,14 @@ export const zh: Translations = { envOverride: '环境变量覆盖', intro: 'Hermes Desktop 默认会启动自己的本地网关。当你希望此应用控制另一台机器上或可信代理后的现有 Hermes 后端时,可以使用远程网关。下面可按 profile 指定各自的远程主机。', - appliesTo: '应用于', allProfiles: '所有 profile', defaultConnection: '默认连接会用于所有没有自定义覆盖的 profile。', profileConnection: profile => `仅当“${profile}”是当前 profile 时使用此连接。选择“使用默认网关”可移除其覆盖。`, + profileOverridesTitle: '按 profile 覆盖', + profileOverridesDesc: '每个 profile 都可以指向自己的网关。下面的连接控件编辑所选目标;此页其余设置为全应用范围。', + overrideEdit: '编辑', + overrideEditing: '正在编辑', + overrideSelectHint: '选择以查看或更改此 profile 使用的网关。', envOverrideTitle: '环境变量正在控制此桌面会话。', envOverrideDesc: '取消设置 HERMES_DESKTOP_REMOTE_URL 和 HERMES_DESKTOP_REMOTE_TOKEN 后才会使用下面保存的设置。', modeTitle: '连接模式',