feat(desktop): unify Gateway + Connections into one Gateways settings page

Merge Settings → Connections into Settings → Gateway as a single
"Gateways" page:

- One nav entry ("Gateways"); the Connections nav entry is removed. The
  legacy `?tab=connections` deep link stays in the route enum and
  redirects to the unified page, and renders it in the interim frame so
  saved routes/bookmarks don't break or flash.
- The connections registry UI (list, add, edit, delete, test, make
  primary, update-all) moves into its own component
  (connections-registry.tsx) composed at the bottom of the Gateways
  page; connections-settings.tsx is deleted (nothing else imported it).
- The Add flow now offers ALL kinds: Local, Hermes Cloud, Remote
  gateway, and SSH (previously only remote/ssh). The Local kind button
  is disabled while the managed local entry exists; a hint points cloud
  adds at the sign-in/discovery flow above.
- Duplicate prevention, enforced in the save path on both sides of the
  IPC boundary (renderer inline error + main-process
  normalizeConnectionInput throw): only one 'local' entry ever;
  remote/cloud dupes keyed on the normalized URL (trim, strip trailing
  slashes, lowercase) across both kinds; ssh dupes keyed on normalized
  user@host:port + remote profile.
- The page-level "Applies to" ScopeChip row is gone. Per-profile
  gateway overrides are now an explicit "Per-profile overrides"
  subsection listing the default connection and each named profile,
  with an Edit affordance that drives the same scope state machinery.
- Command palette and profile-rail deep links retarget the unified
  page; i18n nav rename + new strings across types, en, ja, zh,
  zh-hant, ar.

Tests: new connections-registry.test.tsx (registry UI + dedupe helper
units, including the inline duplicate rejection), electron
connection-registry.test.ts dedupe cases, and updated
profile-rail-connect test.
This commit is contained in:
Teknium
2026-08-17 16:07:40 -07:00
parent 91878fb3c1
commit 9a85769fc3
16 changed files with 573 additions and 197 deletions
@@ -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()
@@ -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 }
@@ -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(<ProfileRail />)
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', () => {
@@ -319,15 +319,16 @@ export function ProfileRail() {
<ProfilePill active={false} glyph="ellipsis" label={p.manageProfiles} onSelect={() => 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". */}
<ProfilePill
active={false}
glyph="plug"
label={p.connectGateway}
onSelect={() => navigate(`${SETTINGS_ROUTE}?tab=connections`)}
onSelect={() => navigate(`${SETTINGS_ROUTE}?tab=gateway`)}
/>
{/* Land in the new profile on a fresh chat (selectProfile triggers the
@@ -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,
@@ -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(<ConnectionsRegistrySection />)
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(<ConnectionsRegistrySection />)
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(<ConnectionsRegistrySection />)
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(<ConnectionsRegistrySection />)
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(<ConnectionsRegistrySection />)
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(<ConnectionsRegistrySection />)
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()
})
})
@@ -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<DesktopConnectionKind, typeof Globe> = {
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<EditorState, 'host' | 'id' | 'kind' | 'remoteProfile' | 'url'>,
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<DesktopConnectionsRegistry | null>(null)
@@ -82,9 +177,14 @@ export function ConnectionsSettings() {
const [removeTarget, setRemoveTarget] = useState<DesktopRegistryConnection | null>(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 | string>(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 <SettingsSkeleton />
if (!bridge) {
return null
}
return (
<SettingsContent>
<div className="mt-8 border-t border-border/60 pt-6">
<SectionHeading icon={Globe} title={s.title} />
<p className="mb-1 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">{s.intro}</p>
{/* Storage-only slice: be explicit that routing consumption is staged so
@@ -297,7 +420,11 @@ export function ConnectionsSettings() {
{s.stagedNote}
</p>
{!registry || registry.connections.length === 0 ? (
{loading ? (
<div className="flex items-center gap-2 py-3 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">
<Loader2 className="size-4 animate-spin" />
</div>
) : !registry || registry.connections.length === 0 ? (
<EmptyState title={s.empty} />
) : (
registry.connections.map(conn => {
@@ -329,7 +456,7 @@ export function ConnectionsSettings() {
<>
<Button
aria-label={s.editConnection}
onClick={() => setEditor(editorFromConnection(conn))}
onClick={() => openEditor(editorFromConnection(conn))}
size="icon-sm"
variant="ghost"
>
@@ -372,15 +499,17 @@ export function ConnectionsSettings() {
{editor ? (
<div className="mt-4 space-y-3 rounded-lg border border-border/60 p-4">
<div className="grid grid-cols-2 gap-2 @2xl:grid-cols-4">
{/* Cloud creation is deliberately absent: a dialable cloud entry
comes from the Hermes Cloud sign-in/discovery flow (Settings →
Gateway), not a hand-typed URL. Migrated/discovered cloud
entries remain editable (kind buttons are disabled on edit). */}
{(editor.kind === 'cloud' ? (['cloud'] as const) : (['remote', 'ssh'] as const)).map(kind => (
{/* Kind is fixed once created (buttons disable on edit). On create
every kind is offered; Local is disabled while the managed
local entry exists (the registry holds at most one). */}
{(editor.id ? ([editor.kind] as const) : (['local', 'cloud', 'remote', 'ssh'] as const)).map(kind => (
<Button
disabled={Boolean(editor.id)}
disabled={Boolean(editor.id) || (kind === 'local' && hasLocal)}
key={kind}
onClick={() => setEditor({ ...editor, kind })}
onClick={() => {
setDupeError(null)
setEditor({ ...editor, kind })
}}
size="sm"
variant={editor.kind === kind ? 'default' : 'outline'}
>
@@ -389,6 +518,10 @@ export function ConnectionsSettings() {
))}
</div>
<p className="text-xs text-muted-foreground">{kindMeta[editor.kind].desc}</p>
{!editor.id && hasLocal ? <p className="text-xs text-muted-foreground">{s.localAddHint}</p> : null}
{!editor.id && editor.kind === 'cloud' ? (
<p className="text-xs text-muted-foreground">{s.cloudAddHint}</p>
) : null}
<ListRow
action={
@@ -406,7 +539,10 @@ export function ConnectionsSettings() {
<ListRow
action={
<Input
onChange={e => 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() {
<ListRow
action={
<Input
onChange={e => 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 ? <p className="text-xs text-destructive">{dupeError}</p> : null}
<div className="flex justify-end gap-2">
<Button disabled={saving} onClick={() => setEditor(null)} size="sm" variant="ghost">
<Button disabled={saving} onClick={() => openEditor(null)} size="sm" variant="ghost">
{s.cancel}
</Button>
<Button disabled={saving || !editor.label.trim()} onClick={() => void save()} size="sm">
@@ -532,7 +673,7 @@ export function ConnectionsSettings() {
<Button
onClick={() => {
triggerHaptic('selection')
setEditor(emptyEditor('remote'))
openEditor(emptyEditor('remote'))
}}
size="sm"
variant="outline"
@@ -573,7 +714,7 @@ export function ConnectionsSettings() {
title={s.removeConfirmTitle}
/>
{/* Keyring-less opt-in: same consent flow as Settings → Gateway. */}
{/* Keyring-less opt-in: same consent flow as the connection-mode form. */}
<ConfirmDialog
confirmLabel={t.settings.gateway.plainTextConfirmAction}
description={t.settings.gateway.plainTextConfirmDesc}
@@ -583,6 +724,6 @@ export function ConnectionsSettings() {
open={plainTextConfirm}
title={t.settings.gateway.plainTextConfirmTitle}
/>
</SettingsContent>
</div>
)
}
@@ -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(<ConnectionsSettings />)
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(<ConnectionsSettings />)
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(<ConnectionsSettings />)
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(<ConnectionsSettings />)
await waitFor(() => expect(screen.getByText('Homelab')).toBeTruthy())
fireEvent.click(screen.getAllByText('Test')[0])
await waitFor(() => expect(test).toHaveBeenCalled())
})
})
@@ -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 (
<button
className={cn(
'rounded-full border px-3 py-1 text-[length:var(--conversation-caption-font-size)] transition',
active
? 'border-(--ui-stroke-secondary) bg-(--ui-bg-tertiary) text-(--ui-text-primary)'
: 'border-(--ui-stroke-tertiary) bg-(--ui-bg-quinary) text-(--ui-text-tertiary) hover:bg-(--chrome-action-hover)'
)}
onClick={onSelect}
type="button"
>
{label}
</button>
)
}
// `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 } = {
</div>
)}
{/* 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 ? (
<div className="mb-5 grid gap-2">
<div className="mb-5 grid gap-1">
<div className="text-[length:var(--conversation-caption-font-size)] font-medium text-(--ui-text-secondary)">
{g.appliesTo}
</div>
<div className="flex flex-wrap gap-1.5">
<ScopeChip active={scope === null} label={g.allProfiles} onSelect={() => setScope(null)} />
{namedProfiles.map(profile => (
<ScopeChip
active={scope === profile.name}
key={profile.name}
label={profile.name}
onSelect={() => setScope(profile.name)}
/>
))}
{g.profileOverridesTitle}
</div>
<p className="text-[length:var(--conversation-caption-font-size)] leading-(--conversation-caption-line-height) text-(--ui-text-tertiary)">
{scope === null ? g.defaultConnection : g.profileConnection(scope)}
{g.profileOverridesDesc}
</p>
<ListRow
action={
scope === null ? (
<Pill tone="primary">{g.overrideEditing}</Pill>
) : (
<Button aria-label={g.allProfiles} onClick={() => setScope(null)} size="sm" variant="outline">
{g.overrideEdit}
</Button>
)
}
description={g.defaultConnection}
title={g.allProfiles}
/>
{namedProfiles.map(profile => (
<ListRow
action={
scope === profile.name ? (
<Pill tone="primary">{g.overrideEditing}</Pill>
) : (
<Button aria-label={profile.name} onClick={() => setScope(profile.name)} size="sm" variant="outline">
{g.overrideEdit}
</Button>
)
}
description={scope === profile.name ? g.profileConnection(profile.name) : g.overrideSelectHint}
key={profile.name}
title={profile.name}
/>
))}
</div>
) : null}
@@ -1573,6 +1578,11 @@ export function GatewaySettings({ embedded = false }: { embedded?: boolean } = {
</div>
)}
{/* 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 : <ConnectionsRegistrySection />}
{/* Plain-text token opt-in: gated when secure storage is unavailable and a
new token would be persisted. Confirm resumes the remembered save/apply. */}
<ConfirmDialog
+13 -12
View File
@@ -15,7 +15,6 @@ import {
Info,
Keyboard,
KeyRound,
Network,
Package,
RefreshCw,
Settings2,
@@ -35,7 +34,6 @@ import { AboutSettings } from './about-settings'
import { AppearanceSettings } from './appearance-settings'
import { BillingSettings } from './billing'
import { ConfigSettings } from './config-settings'
import { ConnectionsSettings } from './connections-settings'
import { SECTIONS } from './constants'
import { GatewaySettings } from './gateway-settings'
import { KeybindSettings } from './keybind-settings'
@@ -50,6 +48,8 @@ const SETTINGS_VIEWS: readonly SettingsViewId[] = [
...SECTIONS.map(s => `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<ProviderView>('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
<AppearanceSettings />
) : activeView === 'about' ? (
<AboutSettings />
) : 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.
<GatewaySettings />
) : activeView === 'connections' ? (
<ConnectionsSettings />
) : activeView === 'keybinds' ? (
<KeybindSettings />
) : activeView.startsWith('config:') ? (
+6 -1
View File
@@ -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: 'بوابة محلية',
+13 -3
View File
@@ -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.',
+6 -1
View File
@@ -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 の設定を解除してください。',
+10 -2
View File
@@ -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
+5 -1
View File
@@ -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: '本機閘道',
+10 -2
View File
@@ -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: '连接模式',