The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): configure per-profile remote overrides from the profile rail
Teknium1ad4733343af
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.tsxindex 5a0d2b0a938..a559609564a 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@@ -27,6 +27,10 @@ vi.mock('@/i18n', () => ({importProfile: 'Import profile…',manageProfiles: 'Manage profiles…',newProfile: 'New profile',+ remoteOverride: {+ badge: (host: string) => `Runs on ${host}`,+ menuItem: 'Connect to a remote host…'+ },saveSoul: 'Save',saving: 'Saving…',showAllProfiles: 'Show all profiles',diff --git a/apps/desktop/src/app/chat/sidebar/profile-remote-override-dialog.test.tsx b/apps/desktop/src/app/chat/sidebar/profile-remote-override-dialog.test.tsxnew file mode 100644index 00000000000..b597f2424df--- /dev/null+++ b/apps/desktop/src/app/chat/sidebar/profile-remote-override-dialog.test.tsx@@ -0,0 +1,167 @@+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { $remoteOverrideDialogProfile, openRemoteOverrideDialog } from '@/store/profile-remote-override'++import { ProfileRemoteOverrideDialog } from './profile-remote-override-dialog'++// The rail affordance that writes connection.json `profiles.<name>` through+// the typed Electron bridge (#91349): the renderer must never touch the file+// itself, the token must ride the safeStorage path (applyConnectionConfig),+// a first-time connect shows the risk confirmation, keyring-less machines+// require the plain-text opt-in, and a registry name collision warns.++const getConnectionConfig = vi.fn()+const applyConnectionConfig = vi.fn()+const list = vi.fn()++const localScope = {+ cloudOrg: '',+ envOverride: false,+ mode: 'local',+ profile: 'work',+ remoteAuthMode: 'token',+ remoteOauthConnected: false,+ remoteTokenPlainText: false,+ remoteTokenPreview: null,+ remoteTokenSet: false,+ remoteUrl: '',+ secureTokenStorage: true+}++const emptyRegistry = { connections: [], primary: 'local', secureTokenStorage: true, version: 2 }++beforeEach(() => {+ getConnectionConfig.mockResolvedValue(localScope)+ applyConnectionConfig.mockResolvedValue({ ...localScope, mode: 'remote', remoteUrl: 'https://box.example.com' })+ list.mockResolvedValue(emptyRegistry)+ Object.defineProperty(window, 'hermesDesktop', {+ configurable: true,+ value: { applyConnectionConfig, connections: { list }, getConnectionConfig }+ })+ $remoteOverrideDialogProfile.set(null)+})++afterEach(() => {+ cleanup()+ vi.clearAllMocks()+})++async function openDialog(profile = 'work') {+ render(<ProfileRemoteOverrideDialog profileNames={[profile]} />)+ openRemoteOverrideDialog(profile)+ await waitFor(() => expect(getConnectionConfig).toHaveBeenCalledWith(profile))+ await screen.findByLabelText(/Remote address/)+}++describe('ProfileRemoteOverrideDialog', () => {+ it('walks the first-time connect through the risk confirmation before writing', async () => {+ await openDialog()++ fireEvent.change(screen.getByLabelText(/Remote address/), { target: { value: 'https://box.example.com' } })+ fireEvent.change(screen.getByLabelText(/Access token/), { target: { value: 'tok-123' } })+ fireEvent.click(screen.getByRole('button', { name: 'Connect' }))++ // No write yet — the risk note comes first.+ expect(applyConnectionConfig).not.toHaveBeenCalled()+ expect(screen.getByText('Connect this profile to a remote host?')).toBeTruthy()+ expect(screen.getByText(/Only connect to a host you trust/)).toBeTruthy()++ fireEvent.click(screen.getByRole('button', { name: 'Connect' }))++ await waitFor(() =>+ expect(applyConnectionConfig).toHaveBeenCalledWith({+ mode: 'remote',+ profile: 'work',+ remoteAuthMode: 'token',+ remoteToken: 'tok-123',+ remoteUrl: 'https://box.example.com'+ })+ )+ await waitFor(() => expect($remoteOverrideDialogProfile.get()).toBeNull())+ })++ it('skips the confirmation when editing an existing override (token rotation)', async () => {+ getConnectionConfig.mockResolvedValue({+ ...localScope,+ mode: 'remote',+ remoteTokenSet: true,+ remoteUrl: 'https://box.example.com'+ })+ await openDialog()++ fireEvent.change(screen.getByLabelText(/Access token/), { target: { value: 'rotated-tok' } })+ fireEvent.click(screen.getByRole('button', { name: 'Connect' }))++ await waitFor(() =>+ expect(applyConnectionConfig).toHaveBeenCalledWith(+ expect.objectContaining({ profile: 'work', remoteToken: 'rotated-tok' })+ )+ )+ })++ it('offers removal for an overridden profile and clears via mode local', async () => {+ getConnectionConfig.mockResolvedValue({+ ...localScope,+ mode: 'remote',+ remoteTokenSet: true,+ remoteUrl: 'https://box.example.com'+ })+ applyConnectionConfig.mockResolvedValue(localScope)+ await openDialog()++ fireEvent.click(screen.getByRole('button', { name: 'Remove remote connection' }))++ await waitFor(() => expect(applyConnectionConfig).toHaveBeenCalledWith({ mode: 'local', profile: 'work' }))+ await waitFor(() => expect($remoteOverrideDialogProfile.get()).toBeNull())+ })++ it('requires the explicit unencrypted-token opt-in on keyring-less machines', async () => {+ getConnectionConfig.mockResolvedValue({ ...localScope, secureTokenStorage: false })+ await openDialog()++ fireEvent.change(screen.getByLabelText(/Remote address/), { target: { value: 'https://box.example.com' } })+ fireEvent.change(screen.getByLabelText(/Access token/), { target: { value: 'tok-123' } })++ const connect = screen.getByRole('button', { name: 'Connect' })+ expect((connect as HTMLButtonElement).disabled).toBe(true)+ expect(screen.getByText(/saved unencrypted on disk/)).toBeTruthy()++ fireEvent.click(screen.getByRole('checkbox'))+ expect((screen.getByRole('button', { name: 'Connect' }) as HTMLButtonElement).disabled).toBe(false)++ fireEvent.click(screen.getByRole('button', { name: 'Connect' }))+ fireEvent.click(screen.getByRole('button', { name: 'Connect' }))++ await waitFor(() =>+ expect(applyConnectionConfig).toHaveBeenCalledWith(expect.objectContaining({ allowPlainTextToken: true }))+ )+ })++ it('warns when the profile name collides with a registered gateway', async () => {+ list.mockResolvedValue({+ ...emptyRegistry,+ connections: [{ id: 'abc123', kind: 'remote', label: 'Work', tokenPreview: null, tokenSet: true }]+ })+ await openDialog('work')++ await screen.findByText(/A gateway named “Work” already exists in Settings/)+ })++ it('keeps the dialog open and shows the error when the write fails', async () => {+ getConnectionConfig.mockResolvedValue({+ ...localScope,+ mode: 'remote',+ remoteTokenSet: true,+ remoteUrl: 'https://box.example.com'+ })+ applyConnectionConfig.mockRejectedValue(new Error('Remote gateway session token is required.'))+ await openDialog()++ fireEvent.change(screen.getByLabelText(/Access token/), { target: { value: 'bad' } })+ fireEvent.click(screen.getByRole('button', { name: 'Connect' }))++ await screen.findByText('Remote gateway session token is required.')+ expect($remoteOverrideDialogProfile.get()).toBe('work')+ })+})diff --git a/apps/desktop/src/app/chat/sidebar/profile-remote-override-dialog.tsx b/apps/desktop/src/app/chat/sidebar/profile-remote-override-dialog.tsxnew file mode 100644index 00000000000..acf71926fd9--- /dev/null+++ b/apps/desktop/src/app/chat/sidebar/profile-remote-override-dialog.tsx@@ -0,0 +1,305 @@+import { useStore } from '@nanostores/react'+import { useEffect, useRef, useState } from 'react'++import { Button } from '@/components/ui/button'+import { Checkbox } from '@/components/ui/checkbox'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle+} from '@/components/ui/dialog'+import { Input } from '@/components/ui/input'+import { useI18n } from '@/i18n'+import { notify, notifyError } from '@/store/notifications'+import {+ $remoteOverrideDialogProfile,+ closeRemoteOverrideDialog,+ refreshProfileRemoteOverrides,+ remoteHostLabel+} from '@/store/profile-remote-override'++// "Connect this profile to a remote host…" — the profile-rail affordance for+// the per-profile override the Electron main already honors+// (connection.json `profiles.<name>` → profileRemoteOverride). The renderer+// never touches connection.json: everything goes through the existing typed+// getConnectionConfig / applyConnectionConfig bridge with a `profile` scope,+// which encrypts the token via safeStorage (or the explicit plain-text opt-in+// on machines without an OS keychain).+//+// Safety beats requested in #91349:+// - first-time connect shows a confirmation with a plain-language risk note;+// - saving warns when the profile name collides with a v2 registry gateway+// (two different stores keyed by the same name is how routing surprises+// start);+// - a keyring-less machine requires the explicit unencrypted-token opt-in.++interface LoadedScope {+ authMode: 'oauth' | 'token'+ hasOverride: boolean+ secureTokenStorage: boolean+ tokenPlainText: boolean+ tokenSet: boolean+ url: string+}++export function ProfileRemoteOverrideDialog({ profileNames }: { profileNames: string[] }) {+ const { t } = useI18n()+ const p = t.profiles.remoteOverride+ const profile = useStore($remoteOverrideDialogProfile)+ const open = profile !== null++ const [loaded, setLoaded] = useState<LoadedScope | null>(null)+ const [url, setUrl] = useState('')+ const [token, setToken] = useState('')+ const [allowPlainText, setAllowPlainText] = useState(false)+ const [confirming, setConfirming] = useState(false)+ const [saving, setSaving] = useState(false)+ const [error, setError] = useState<null | string>(null)+ const [collision, setCollision] = useState<null | string>(null)+ const urlRef = useRef<HTMLInputElement>(null)++ // Load this profile's saved scope + the registry (for the name-collision+ // warning) each time the dialog opens. The registry read goes straight to+ // the bridge instead of the connections store so this dialog stays a leaf.+ useEffect(() => {+ if (!profile) {+ return+ }++ let cancelled = false+ setLoaded(null)+ setUrl('')+ setToken('')+ setAllowPlainText(false)+ setConfirming(false)+ setSaving(false)+ setError(null)+ setCollision(null)++ window.hermesDesktop+ ?.getConnectionConfig?.(profile)+ .then(config => {+ if (cancelled) {+ return+ }++ const hasOverride = (config.mode === 'remote' || config.mode === 'cloud') && Boolean(config.remoteUrl)+ setLoaded({+ authMode: config.remoteAuthMode === 'oauth' ? 'oauth' : 'token',+ hasOverride,+ secureTokenStorage: config.secureTokenStorage !== false,+ tokenPlainText: config.remoteTokenPlainText === true,+ tokenSet: config.remoteTokenSet === true,+ url: hasOverride ? config.remoteUrl : ''+ })+ setUrl(hasOverride ? config.remoteUrl : '')+ window.setTimeout(() => urlRef.current?.focus(), 0)+ })+ .catch(err => !cancelled && setError(err instanceof Error ? err.message : String(err)))++ window.hermesDesktop?.connections+ ?.list()+ .then(registry => {+ if (cancelled) {+ return+ }++ const lowered = profile.trim().toLowerCase()++ const match = registry.connections.find(+ connection => connection.id.toLowerCase() === lowered || connection.label.trim().toLowerCase() === lowered+ )++ setCollision(match ? match.label : null)+ })+ .catch(() => undefined)++ return () => void (cancelled = true)+ }, [profile])++ const close = () => {+ if (!saving) {+ closeRemoteOverrideDialog()+ }+ }++ const trimmedUrl = url.trim()+ const urlValid = /^https?:\/\/\S+$/i.test(trimmedUrl)+ const tokenReady = Boolean(token.trim()) || (loaded?.tokenSet === true && trimmedUrl === loaded.url)+ const canSubmit = Boolean(loaded) && urlValid && tokenReady && !saving+ // Writing a NEW token on a machine without an OS keychain stores it as+ // plain text on disk — that needs the explicit opt-in checked first.+ const needsPlainTextOptIn = Boolean(loaded && loaded.secureTokenStorage === false && token.trim() && !allowPlainText)++ const performSave = async () => {+ if (!profile) {+ return+ }++ setSaving(true)+ setError(null)++ try {+ await window.hermesDesktop.applyConnectionConfig({+ mode: 'remote',+ profile,+ remoteAuthMode: 'token',+ remoteToken: token.trim() || undefined,+ remoteUrl: trimmedUrl,+ ...(allowPlainText ? { allowPlainTextToken: true } : {})+ })++ notify({ kind: 'success', title: p.savedTitle, message: p.savedMessage(profile, remoteHostLabel(trimmedUrl) || trimmedUrl) })+ await refreshProfileRemoteOverrides(profileNames)+ closeRemoteOverrideDialog()+ } catch (err) {+ setConfirming(false)+ setError(err instanceof Error ? err.message : String(err))+ } finally {+ setSaving(false)+ }+ }++ const submit = () => {+ if (!canSubmit || needsPlainTextOptIn) {+ return+ }++ // First-time connect gets the one-time risk confirmation; editing an+ // existing override (token rotation, URL fix) skips straight to the save.+ if (!loaded?.hasOverride && !confirming) {+ setConfirming(true)++ return+ }++ void performSave()+ }++ const removeOverride = async () => {+ if (!profile) {+ return+ }++ setSaving(true)+ setError(null)++ try {+ await window.hermesDesktop.applyConnectionConfig({ mode: 'local', profile })+ notify({ kind: 'success', title: p.removedTitle, message: p.removedMessage(profile) })+ await refreshProfileRemoteOverrides(profileNames)+ closeRemoteOverrideDialog()+ } catch (err) {+ notifyError(err, p.removeFailed)+ setSaving(false)+ }+ }++ const host = remoteHostLabel(trimmedUrl) || trimmedUrl++ // Mounted permanently in the rail; render nothing until a profile's dialog+ // is actually requested (also keeps the closed tree from touching i18n).+ if (!open) {+ return null+ }++ return (+ <Dialog onOpenChange={next => !next && close()} open={open}>+ <DialogContent className="max-w-md">+ {confirming ? (+ <>+ <DialogHeader>+ <DialogTitle>{p.confirmTitle}</DialogTitle>+ <DialogDescription>{p.confirmNote(profile ?? '', host)}</DialogDescription>+ </DialogHeader>+ {error && <p className="text-xs text-destructive">{error}</p>}+ <DialogFooter>+ <Button disabled={saving} onClick={() => setConfirming(false)} type="button" variant="ghost">+ {p.confirmBack}+ </Button>+ <Button disabled={saving} onClick={() => void performSave()} type="button">+ {saving ? p.connecting : p.connect}+ </Button>+ </DialogFooter>+ </>+ ) : (+ <>+ <DialogHeader>+ <DialogTitle>{p.title(profile ?? '')}</DialogTitle>+ <DialogDescription>{p.description}</DialogDescription>+ </DialogHeader>++ <div className="flex flex-col gap-3">+ <label className="flex flex-col gap-1 text-xs">+ <span className="text-(--ui-text-secondary)">{p.urlLabel}</span>+ <Input+ autoCorrect="off"+ onChange={event => setUrl(event.target.value)}+ onKeyDown={event => event.key === 'Enter' && submit()}+ placeholder={p.urlPlaceholder}+ ref={urlRef}+ spellCheck={false}+ type="url"+ value={url}+ />+ {trimmedUrl && !urlValid && <span className="text-destructive">{p.urlInvalid}</span>}+ </label>++ <label className="flex flex-col gap-1 text-xs">+ <span className="text-(--ui-text-secondary)">{p.tokenLabel}</span>+ <Input+ autoComplete="off"+ onChange={event => setToken(event.target.value)}+ onKeyDown={event => event.key === 'Enter' && submit()}+ placeholder={p.tokenPlaceholder}+ type="password"+ value={token}+ />+ {loaded?.tokenSet && !token.trim() && (+ <span className="text-(--ui-text-tertiary)">{p.tokenSavedHint}</span>+ )}+ </label>++ {loaded && loaded.secureTokenStorage === false && Boolean(token.trim()) && (+ <label className="flex items-start gap-2 text-xs text-(--ui-text-secondary)">+ <Checkbox+ checked={allowPlainText}+ className="mt-0.5"+ onCheckedChange={checked => setAllowPlainText(checked === true)}+ />+ <span>{p.plainTextOptIn}</span>+ </label>+ )}++ {collision && <p className="text-xs text-(--ui-text-secondary)">{p.collisionWarning(collision)}</p>}+ {error && <p className="text-xs text-destructive">{error}</p>}+ </div>++ <DialogFooter>+ {loaded?.hasOverride && (+ <Button+ className="mr-auto"+ disabled={saving}+ onClick={() => void removeOverride()}+ type="button"+ variant="ghost"+ >+ {p.disconnect}+ </Button>+ )}+ <Button disabled={saving} onClick={close} type="button" variant="ghost">+ {t.common.cancel}+ </Button>+ <Button disabled={!canSubmit || needsPlainTextOptIn} onClick={submit} type="button">+ {saving ? p.connecting : p.connect}+ </Button>+ </DialogFooter>+ </>+ )}+ </DialogContent>+ </Dialog>+ )+}diff --git a/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx b/apps/desktop/src/app/chat/sidebar/profile-switcher.tsxindex 5b86c788f5c..a29e75453aa 100644--- a/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx+++ b/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx@@ -70,6 +70,11 @@ import {setShowAllProfiles,sortByProfileOrder} from '@/store/profile'+import {+ $profileRemoteOverrides,+ openRemoteOverrideDialog,+ refreshProfileRemoteOverrides+} from '@/store/profile-remote-override'import { runExportProfileFlow, runImportProfileFlow } from '@/store/profile-share'import type { ProfileInfo } from '@/types/hermes'@@ -78,6 +83,7 @@ import { DeleteProfileDialog } from '../../profiles/delete-profile-dialog'import { RenameProfileDialog } from '../../profiles/rename-profile-dialog'import { PROFILES_ROUTE, SETTINGS_ROUTE } from '../../routes'+import { ProfileRemoteOverrideDialog } from './profile-remote-override-dialog'import { useProfilePrewarm } from './use-profile-prewarm'import { useProfileRailRefreshOnActive } from './use-profile-rail-refresh-on-active'@@ -124,6 +130,7 @@ export function ProfileRail() {const gatewayProfile = useStore($activeGatewayProfile)const order = useStore($profileOrder)const colors = useStore($profileColors)+ const remoteOverrides = useStore($profileRemoteOverrides)const multipleConnections = useStore($hasMultipleConnections)const navigate = useNavigate()@@ -223,6 +230,16 @@ export function ProfileRail() {// wiring.useProfileRailRefreshOnActive()+ // Which profiles carry a per-profile remote override (connection.json+ // profiles.<name>) — refreshed whenever the profile list changes so the+ // rail's "remote" badge tracks create/rename/override edits.+ const profileNames = profiles.map(profile => profile.name)+ const profileNamesKey = profileNames.join('\u0000')++ useEffect(() => {+ void refreshProfileRemoteOverrides(profileNamesKey ? profileNamesKey.split('\u0000') : [])+ }, [profileNamesKey])+// Open the create dialog when the `profile.create` hotkey fires (the dialog// state lives here, so the global keybind bumps a request atom we watch).const createRequest = useStore($profileCreateRequest)@@ -305,11 +322,13 @@ export function ProfileRail() {color={resolveProfileColor(profile.name, colors)}key={profile.name}label={profileLabel(profile)}+ onConnectRemote={() => openRemoteOverrideDialog(profile.name)}onDelete={() => setPendingDelete(profile)}onEditSoul={() => setPendingSoul(profile.name)}onRecolor={color => setProfileColor(profile.name, color)}onRename={() => setPendingRename(profile)}onSelect={() => selectProfile(profile.name)}+ remoteHost={remoteOverrides[normalizeProfileKey(profile.name)]?.host ?? null}/>))}</div>@@ -368,6 +387,8 @@ export function ProfileRail() {/><EditSoulDialog onClose={() => setPendingSoul(null)} profileName={pendingSoul} />++ <ProfileRemoteOverrideDialog profileNames={profileNames} /></div>)}@@ -618,7 +639,11 @@ interface ProfileSquareProps {onRecolor: (color: null | string) => voidonRename: () => voidonEditSoul: () => void+ onConnectRemote: () => voidonDelete: () => void+ // hostname[:port] of this profile's remote override, or null when the+ // profile runs locally. Drives the "remote" badge on the square.+ remoteHost: null | string}// Hold this long without moving (a drag would have started first) to open the@@ -636,11 +661,13 @@ function ProfileSquare({active,color,label,+ onConnectRemote,onDelete,onEditSoul,onRecolor,onRename,- onSelect+ onSelect,+ remoteHost}: ProfileSquareProps) {const { t } = useI18n()const p = t.profiles@@ -693,7 +720,7 @@ function ProfileSquare({<TooltipTrigger asChild><buttonclassName={cn(- 'grid size-5 shrink-0 cursor-grab touch-none select-none place-items-center rounded-[3px] text-[0.5625rem] font-semibold uppercase leading-none transition-opacity hover:opacity-100',+ 'relative grid size-5 shrink-0 cursor-grab touch-none select-none place-items-center rounded-[3px] text-[0.5625rem] font-semibold uppercase leading-none transition-opacity hover:opacity-100',active ? 'opacity-100' : 'opacity-55',isDragging && 'z-10 cursor-grabbing opacity-100')}@@ -710,7 +737,7 @@ function ProfileSquare({type="button"{...attributes}{...listeners}- aria-label={label}+ aria-label={remoteHost ? `${label} — ${p.remoteOverride.badge(remoteHost)}` : label}aria-pressed={active}// Hold-to-recolor rides alongside the dnd pointer listener (call// it first so drag tracking still arms), then a timer opens the@@ -748,11 +775,23 @@ function ProfileSquare({onPointerUp={clearPress}>{label.replace(/[^a-z0-9]/gi, '').charAt(0) || '?'}+ {/* The "remote" badge: a tiny globe pinned to the corner of an+ overridden profile's square, so which profiles leave this+ machine is visible at a glance (#91349). */}+ {remoteHost && (+ <span+ aria-hidden="true"+ className="absolute -right-0.5 -top-0.5 grid size-2 place-items-center rounded-full bg-(--ui-panel-background)"+ data-slot="profile-remote-badge"+ >+ <Codicon name="globe" size="0.5rem" />+ </span>+ )}</button></TooltipTrigger></ContextMenuTrigger></PopoverAnchor>- <TooltipContent>{label}</TooltipContent>+ <TooltipContent>{remoteHost ? `${label} · ${p.remoteOverride.badge(remoteHost)}` : label}</TooltipContent></Tooltip></TooltipProvider>@@ -783,6 +822,10 @@ function ProfileSquare({<Codicon name="package" size="0.875rem" /><span>{p.exportProfile}</span></ContextMenuItem>+ <ContextMenuItem onSelect={onConnectRemote}>+ <Codicon name="globe" size="0.875rem" />+ <span>{remoteHost ? p.remoteOverride.badge(remoteHost) : p.remoteOverride.menuItem}</span>+ </ContextMenuItem><ContextMenuItemclassName="text-destructive focus:text-destructive"onSelect={onDelete}diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex 887ec354a65..9328dfddb14 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -1390,6 +1390,38 @@ export const ar = defineLocale({switchToConnection: name => `التبديل إلى ${name}`,switchConnectionFailed: name => `تعذّر الاتصال بـ ${name}`,manageProfiles: 'إدارة الملفات الشخصية',+ remoteOverride: {+ menuItem: 'الاتصال بمضيف بعيد…',+ badge: (host: string) => `يعمل على ${host}`,+ title: (profile: string) => `ربط ${profile} بمضيف بعيد`,+ description: 'ستعمل جلسات هذا الملف الشخصي على خادم Hermes البعيد الذي تحدده، بدلاً من هذا الجهاز.',+ urlLabel: 'العنوان البعيد',+ urlPlaceholder: 'https://hermes.example.com',+ urlInvalid: 'أدخل عنواناً كاملاً يبدأ بـ http:// أو https://',+ tokenLabel: 'رمز الوصول',+ tokenPlaceholder: 'الصق رمز الجلسة البعيد',+ tokenSavedHint: 'يوجد رمز محفوظ بالفعل. اتركه فارغاً للاحتفاظ به.',+ plainTextOptIn:+ 'لا يتوفر تخزين مفاتيح آمن على هذا الجهاز، لذا سيُحفظ الرمز على القرص دون تشفير. احفظه على أي حال.',+ collisionWarning: (label: string) =>+ `توجد بوابة باسم «${label}» في الإعدادات بالفعل. اتصال هذا الملف الشخصي منفصل ولن يغيّرها.`,+ confirmTitle: 'ربط هذا الملف الشخصي بمضيف بعيد؟',+ confirmNote: (profile: string, host: string) =>+ `ستعمل المحادثات الجديدة في ${profile} على ${host}. سيقوم ذلك الجهاز بتنفيذ الأوامر وقراءة الملفات هناك، وليس هنا. اتصل فقط بمضيف تثق به.`,+ confirmBack: 'رجوع',+ connect: 'اتصال',+ connecting: 'جارٍ الاتصال…',+ disconnect: 'إزالة الاتصال البعيد',+ savedTitle: 'تم ربط الملف الشخصي',+ savedMessage: (profile: string, host: string) => `${profile} يعمل الآن على ${host}`,+ removedTitle: 'تمت إزالة الاتصال البعيد',+ removedMessage: (profile: string) => `${profile} يعمل الآن على هذا الجهاز`,+ removeFailed: 'تعذّرت إزالة الاتصال البعيد',+ authFailedTitle: 'رفض المضيف البعيد الرمز المحفوظ',+ authFailedMessage: (profile: string, host: string) =>+ `رفض ${host} الرمز المحفوظ لـ ${profile}. ربما تم تغييره على الجانب البعيد.`,+ updateToken: 'أدخل رمزاً جديداً…'+ },actions: 'إجراءات',color: 'اللون',colorFor: 'اللون',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 26c50a4200a..e4a112700e3 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -1815,6 +1815,39 @@ export const en: Translations = {switchConnectionFailed: name => `Could not connect to ${name}`,manageProfiles: 'Manage profiles…',connectGateway: 'Manage gateways…',+ remoteOverride: {+ menuItem: 'Connect to a remote host…',+ badge: (host: string) => `Runs on ${host}`,+ title: (profile: string) => `Connect ${profile} to a remote host`,+ description:+ 'Sessions in this profile will run on the remote Hermes you point it at, instead of this computer.',+ urlLabel: 'Remote address',+ urlPlaceholder: 'https://hermes.example.com',+ urlInvalid: 'Enter a full address starting with http:// or https://',+ tokenLabel: 'Access token',+ tokenPlaceholder: 'Paste the remote session token',+ tokenSavedHint: 'A token is already saved. Leave blank to keep it.',+ plainTextOptIn:+ 'This computer has no secure key storage, so the token would be saved unencrypted on disk. Save it anyway.',+ collisionWarning: (label: string) =>+ `A gateway named “${label}” already exists in Settings. This profile connection is separate and will not change it.`,+ confirmTitle: 'Connect this profile to a remote host?',+ confirmNote: (profile: string, host: string) =>+ `New chats in ${profile} will run on ${host}. That computer will run commands and read files there, not on this one. Only connect to a host you trust.`,+ confirmBack: 'Back',+ connect: 'Connect',+ connecting: 'Connecting…',+ disconnect: 'Remove remote connection',+ savedTitle: 'Profile connected',+ savedMessage: (profile: string, host: string) => `${profile} now runs on ${host}`,+ removedTitle: 'Remote connection removed',+ removedMessage: (profile: string) => `${profile} now runs on this computer`,+ removeFailed: 'Could not remove the remote connection',+ authFailedTitle: 'Remote host rejected the saved token',+ authFailedMessage: (profile: string, host: string) =>+ `${host} refused the token saved for ${profile}. It may have been changed on the remote side.`,+ updateToken: 'Enter new token…'+ },actions: 'Actions',color: 'Color…',colorFor: 'Color',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex cf8015972a9..0607f2260d8 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -1527,6 +1527,38 @@ export const ja = defineLocale({switchToConnection: name => `${name} に切り替え`,switchConnectionFailed: name => `${name} に接続できませんでした`,manageProfiles: 'プロファイルを管理…',+ remoteOverride: {+ menuItem: 'リモートホストに接続…',+ badge: (host: string) => `${host} で実行中`,+ title: (profile: string) => `${profile} をリモートホストに接続`,+ description: 'このプロファイルのセッションは、このパソコンではなく指定したリモートの Hermes で実行されます。',+ urlLabel: 'リモートアドレス',+ urlPlaceholder: 'https://hermes.example.com',+ urlInvalid: 'http:// または https:// で始まる完全なアドレスを入力してください',+ tokenLabel: 'アクセストークン',+ tokenPlaceholder: 'リモートのセッショントークンを貼り付け',+ tokenSavedHint: 'トークンは保存済みです。空欄のままにすると保持されます。',+ plainTextOptIn:+ 'このパソコンには安全な鍵ストレージがないため、トークンは暗号化されずにディスクへ保存されます。それでも保存する。',+ collisionWarning: (label: string) =>+ `「${label}」という名前のゲートウェイが設定に既に存在します。このプロファイル接続は別物であり、それを変更しません。`,+ confirmTitle: 'このプロファイルをリモートホストに接続しますか?',+ confirmNote: (profile: string, host: string) =>+ `${profile} の新しいチャットは ${host} で実行されます。コマンドの実行やファイルの読み取りはこのパソコンではなくそのコンピュータで行われます。信頼できるホストにのみ接続してください。`,+ confirmBack: '戻る',+ connect: '接続',+ connecting: '接続中…',+ disconnect: 'リモート接続を解除',+ savedTitle: 'プロファイルを接続しました',+ savedMessage: (profile: string, host: string) => `${profile} は ${host} で実行されます`,+ removedTitle: 'リモート接続を解除しました',+ removedMessage: (profile: string) => `${profile} はこのパソコンで実行されます`,+ removeFailed: 'リモート接続を解除できませんでした',+ authFailedTitle: 'リモートホストが保存済みトークンを拒否しました',+ authFailedMessage: (profile: string, host: string) =>+ `${host} が ${profile} 用に保存されたトークンを拒否しました。リモート側で変更された可能性があります。`,+ updateToken: '新しいトークンを入力…'+ },actions: 'アクション',color: 'カラー…',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 5c51c20fdf3..ec1bd531440 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -1535,6 +1535,34 @@ export interface Translations {switchConnectionFailed: (name: string) => stringmanageProfiles: stringconnectGateway: string+ remoteOverride: {+ menuItem: string+ badge: (host: string) => string+ title: (profile: string) => string+ description: string+ urlLabel: string+ urlPlaceholder: string+ urlInvalid: string+ tokenLabel: string+ tokenPlaceholder: string+ tokenSavedHint: string+ plainTextOptIn: string+ collisionWarning: (label: string) => string+ confirmTitle: string+ confirmNote: (profile: string, host: string) => string+ confirmBack: string+ connect: string+ connecting: string+ disconnect: string+ savedTitle: string+ savedMessage: (profile: string, host: string) => string+ removedTitle: string+ removedMessage: (profile: string) => string+ removeFailed: string+ authFailedTitle: string+ authFailedMessage: (profile: string, host: string) => string+ updateToken: string+ }actions: stringcolor: stringcolorFor: stringdiff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex 4be98f606bb..7edaa7c6e63 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -1471,6 +1471,37 @@ export const zhHant = defineLocale({switchToConnection: name => `切換至 ${name}`,switchConnectionFailed: name => `無法連線至 ${name}`,manageProfiles: '管理設定檔…',+ remoteOverride: {+ menuItem: '連線至遠端主機…',+ badge: (host: string) => `執行於 ${host}`,+ title: (profile: string) => `將 ${profile} 連線至遠端主機`,+ description: '此設定檔中的工作階段將在你指定的遠端 Hermes 上執行,而不是這台電腦。',+ urlLabel: '遠端位址',+ urlPlaceholder: 'https://hermes.example.com',+ urlInvalid: '請輸入以 http:// 或 https:// 開頭的完整位址',+ tokenLabel: '存取權杖',+ tokenPlaceholder: '貼上遠端工作階段權杖',+ tokenSavedHint: '已儲存權杖。留空以保留現有權杖。',+ plainTextOptIn: '這台電腦沒有安全金鑰儲存空間,權杖將以未加密方式儲存到磁碟。仍要儲存。',+ collisionWarning: (label: string) =>+ `設定中已存在名為「${label}」的閘道。此設定檔連線是獨立的,不會變更它。`,+ confirmTitle: '將此設定檔連線至遠端主機?',+ confirmNote: (profile: string, host: string) =>+ `${profile} 中的新對話將在 ${host} 上執行。指令執行與檔案讀取都會發生在那台電腦上,而不是這台。請只連線你信任的主機。`,+ confirmBack: '返回',+ connect: '連線',+ connecting: '連線中…',+ disconnect: '移除遠端連線',+ savedTitle: '設定檔已連線',+ savedMessage: (profile: string, host: string) => `${profile} 現在執行於 ${host}`,+ removedTitle: '已移除遠端連線',+ removedMessage: (profile: string) => `${profile} 現在在這台電腦上執行`,+ removeFailed: '無法移除遠端連線',+ authFailedTitle: '遠端主機拒絕了已儲存的權杖',+ authFailedMessage: (profile: string, host: string) =>+ `${host} 拒絕了為 ${profile} 儲存的權杖。它可能已在遠端被變更。`,+ updateToken: '輸入新權杖…'+ },actions: '動作',color: '顏色…',colorFor: '顏色',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 3d8f0fdfe28..c6393e6c1f3 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -2001,6 +2001,37 @@ export const zh: Translations = {switchConnectionFailed: name => `无法连接到 ${name}`,manageProfiles: '管理配置档案…',connectGateway: '管理网关…',+ remoteOverride: {+ menuItem: '连接到远程主机…',+ badge: (host: string) => `运行于 ${host}`,+ title: (profile: string) => `将 ${profile} 连接到远程主机`,+ description: '此配置档案中的会话将在你指定的远程 Hermes 上运行,而不是这台电脑。',+ urlLabel: '远程地址',+ urlPlaceholder: 'https://hermes.example.com',+ urlInvalid: '请输入以 http:// 或 https:// 开头的完整地址',+ tokenLabel: '访问令牌',+ tokenPlaceholder: '粘贴远程会话令牌',+ tokenSavedHint: '已保存令牌。留空以保留现有令牌。',+ plainTextOptIn: '这台电脑没有安全密钥存储,令牌将以未加密方式保存到磁盘。仍然保存。',+ collisionWarning: (label: string) =>+ `设置中已存在名为“${label}”的网关。此配置档案连接是独立的,不会更改它。`,+ confirmTitle: '将此配置档案连接到远程主机?',+ confirmNote: (profile: string, host: string) =>+ `${profile} 中的新对话将在 ${host} 上运行。命令和文件读取都发生在那台电脑上,而不是这台。请只连接你信任的主机。`,+ confirmBack: '返回',+ connect: '连接',+ connecting: '连接中…',+ disconnect: '移除远程连接',+ savedTitle: '配置档案已连接',+ savedMessage: (profile: string, host: string) => `${profile} 现在运行于 ${host}`,+ removedTitle: '已移除远程连接',+ removedMessage: (profile: string) => `${profile} 现在在这台电脑上运行`,+ removeFailed: '无法移除远程连接',+ authFailedTitle: '远程主机拒绝了已保存的令牌',+ authFailedMessage: (profile: string, host: string) =>+ `${host} 拒绝了为 ${profile} 保存的令牌。它可能已在远程端被更改。`,+ updateToken: '输入新令牌…'+ },actions: '操作',color: '颜色…',colorFor: '颜色',diff --git a/apps/desktop/src/store/profile-remote-override.test.ts b/apps/desktop/src/store/profile-remote-override.test.tsnew file mode 100644index 00000000000..a3f300a2880--- /dev/null+++ b/apps/desktop/src/store/profile-remote-override.test.ts@@ -0,0 +1,125 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { $notifications } from './notifications'+import {+ $profileRemoteOverrides,+ $remoteOverrideDialogProfile,+ closeRemoteOverrideDialog,+ notifyRemoteOverrideAuthFailure,+ openRemoteOverrideDialog,+ refreshProfileRemoteOverrides,+ remoteHostLabel+} from './profile-remote-override'++const getConnectionConfig = vi.fn()++beforeEach(() => {+ Object.defineProperty(window, 'hermesDesktop', {+ configurable: true,+ value: { getConnectionConfig }+ })+ $profileRemoteOverrides.set({})+ $remoteOverrideDialogProfile.set(null)+ $notifications.set([])+})++afterEach(() => {+ vi.clearAllMocks()+})++describe('remoteHostLabel', () => {+ it('keeps a non-default port and drops default ones', () => {+ expect(remoteHostLabel('https://hermes.example.com:8443/x')).toBe('hermes.example.com:8443')+ expect(remoteHostLabel('https://hermes.example.com:443')).toBe('hermes.example.com')+ expect(remoteHostLabel('http://hermes.example.com:80')).toBe('hermes.example.com')+ })++ it('returns empty for unparseable input', () => {+ expect(remoteHostLabel('not a url')).toBe('')+ expect(remoteHostLabel('')).toBe('')+ })+})++describe('refreshProfileRemoteOverrides', () => {+ it('publishes only profiles whose scope resolves to a remote override', async () => {+ getConnectionConfig.mockImplementation(async (profile: string) => {+ if (profile === 'work') {+ return { mode: 'remote', remoteUrl: 'https://work.example.com' }+ }++ if (profile === 'cloudy') {+ return { mode: 'cloud', remoteUrl: 'https://cloud.example.com:8443' }+ }++ return { mode: 'local', remoteUrl: '' }+ })++ await refreshProfileRemoteOverrides(['work', 'cloudy', 'home'])++ expect($profileRemoteOverrides.get()).toEqual({+ work: { host: 'work.example.com', url: 'https://work.example.com' },+ cloudy: { host: 'cloud.example.com:8443', url: 'https://cloud.example.com:8443' }+ })+ })++ it('drops a stale override entry when the profile went back to local', async () => {+ $profileRemoteOverrides.set({ work: { host: 'old.example.com', url: 'https://old.example.com' } })+ getConnectionConfig.mockResolvedValue({ mode: 'local', remoteUrl: '' })++ await refreshProfileRemoteOverrides(['work'])++ expect($profileRemoteOverrides.get()).toEqual({})+ })++ it('leaves a profile unbadged when its scope read fails, without failing the rest', async () => {+ getConnectionConfig.mockImplementation(async (profile: string) => {+ if (profile === 'broken') {+ throw new Error('bridge unavailable')+ }++ return { mode: 'remote', remoteUrl: 'https://ok.example.com' }+ })++ await refreshProfileRemoteOverrides(['broken', 'work'])++ expect(Object.keys($profileRemoteOverrides.get())).toEqual(['work'])+ })+})++describe('notifyRemoteOverrideAuthFailure', () => {+ beforeEach(() => {+ $profileRemoteOverrides.set({ work: { host: 'work.example.com', url: 'https://work.example.com' } })+ })++ it('surfaces a re-enter-token toast whose action reopens the dialog on a 401', () => {+ const handled = notifyRemoteOverrideAuthFailure('work', new Error('WebSocket handshake failed: 401 Unauthorized'))++ expect(handled).toBe(true)+ const toast = $notifications.get()[0]+ expect(toast.kind).toBe('error')+ expect(toast.action).toBeTruthy()++ toast.action?.onClick()+ expect($remoteOverrideDialogProfile.get()).toBe('work')+ })++ it('ignores connectivity failures — a down host is not a rotated token', () => {+ expect(notifyRemoteOverrideAuthFailure('work', new Error('connect ECONNREFUSED 10.0.0.5:8000'))).toBe(false)+ expect(notifyRemoteOverrideAuthFailure('work', new Error('timeout waiting for backend'))).toBe(false)+ expect($notifications.get()).toEqual([])+ })++ it('ignores profiles without an override entirely', () => {+ expect(notifyRemoteOverrideAuthFailure('home', new Error('401 Unauthorized'))).toBe(false)+ expect($notifications.get()).toEqual([])+ })+})++describe('dialog open/close atoms', () => {+ it('opens for a profile and closes back to null', () => {+ openRemoteOverrideDialog('work')+ expect($remoteOverrideDialogProfile.get()).toBe('work')+ closeRemoteOverrideDialog()+ expect($remoteOverrideDialogProfile.get()).toBeNull()+ })+})diff --git a/apps/desktop/src/store/profile-remote-override.ts b/apps/desktop/src/store/profile-remote-override.tsnew file mode 100644index 00000000000..14a39175e42--- /dev/null+++ b/apps/desktop/src/store/profile-remote-override.ts@@ -0,0 +1,132 @@+import { atom } from 'nanostores'++import { translateNow } from '@/i18n'+import { notify } from '@/store/notifications'++// ── Per-profile remote overrides (connection.json `profiles.<name>`) ────────+// The Electron main already routes a profile with a remote entry to its own+// pooled backend (profileRemoteOverride → resolveProfileBackendRoute case 2);+// until now the only way to WRITE that entry was hand-editing connection.json+// (#91349). This store is the renderer-side cache of which profiles carry an+// override, so the rail can badge them and the dialog can be opened from+// anywhere (context menu, auth-failure toast) without threading callbacks.+//+// Deliberately no import from store/profile: profile.ts imports THIS module+// for the auth-failure toast, so the dependency must stay one-way.++export interface ProfileRemoteOverride {+ /** hostname[:port] parsed from the override URL — the display label. */+ host: string+ url: string+}++/** profile key → its remote override, refreshed from Electron on demand. */+export const $profileRemoteOverrides = atom<Record<string, ProfileRemoteOverride>>({})++// The profile whose "Connect to a remote host" dialog is open, or null. An+// atom (not component state) so the rail's context menu AND the re-enter-token+// toast action can both open the same dialog.+export const $remoteOverrideDialogProfile = atom<null | string>(null)++export function openRemoteOverrideDialog(profile: string): void {+ $remoteOverrideDialogProfile.set(profile)+}++export function closeRemoteOverrideDialog(): void {+ $remoteOverrideDialogProfile.set(null)+}++/** hostname[:port] for a gateway URL, or '' when it does not parse. */+export function remoteHostLabel(url: string): string {+ try {+ const parsed = new URL(String(url || ''))++ if (!parsed.hostname) {+ return ''+ }++ return parsed.port && parsed.port !== '80' && parsed.port !== '443'+ ? `${parsed.hostname}:${parsed.port}`+ : parsed.hostname+ } catch {+ return ''+ }+}++/**+ * Re-pull each named profile's connection scope from Electron and publish the+ * ones that resolve to a remote/cloud override. Best-effort per profile: a+ * single failed read keeps that profile unbadged rather than failing the lot.+ */+export async function refreshProfileRemoteOverrides(names: string[]): Promise<void> {+ const getConnectionConfig = window.hermesDesktop?.getConnectionConfig++ if (!getConnectionConfig) {+ return+ }++ const next: Record<string, ProfileRemoteOverride> = {}++ await Promise.all(+ names.map(async name => {+ const key = String(name || '').trim()++ if (!key) {+ return+ }++ try {+ const config = await getConnectionConfig(key)++ if ((config.mode === 'remote' || config.mode === 'cloud') && config.remoteUrl) {+ next[key] = { host: remoteHostLabel(config.remoteUrl) || config.remoteUrl, url: config.remoteUrl }+ }+ } catch {+ // Backend bridge hiccup — leave this profile unbadged until the next refresh.+ }+ })+ )++ $profileRemoteOverrides.set(next)+}++// The token-rotation failure shape: the remote host answered but refused the+// credentials. Mirrors the auth-vocabulary used by suggestion-providers/repair+// — connectivity failures (timeout, refused, DNS) stay generic so a down host+// doesn't misread as a revoked token.+const AUTH_FAILURE_RE =+ /\b(401|403|unauthorized|forbidden)\b|invalid[_ ]?token|token .*(expired|invalid|rejected)|authenticat\w+ (failed|required|expired)/i++/**+ * When switching to a profile with a remote override fails because the host+ * rejected the saved token (rotated/revoked), surface a re-enter-token toast+ * whose action reopens the override dialog — never a silently dead profile.+ * Returns true when the toast was shown (callers keep their generic handling+ * for everything else).+ */+export function notifyRemoteOverrideAuthFailure(profile: string, error: unknown): boolean {+ const key = String(profile || '').trim()+ const override = key ? $profileRemoteOverrides.get()[key] : undefined++ if (!override) {+ return false+ }++ const message = error instanceof Error ? error.message : String(error ?? '')++ if (!AUTH_FAILURE_RE.test(message)) {+ return false+ }++ notify({+ kind: 'error',+ title: translateNow('profiles.remoteOverride.authFailedTitle'),+ message: translateNow('profiles.remoteOverride.authFailedMessage', key, override.host),+ action: {+ label: translateNow('profiles.remoteOverride.updateToken'),+ onClick: () => openRemoteOverrideDialog(key)+ }+ })++ return true+}diff --git a/apps/desktop/src/store/profile.ts b/apps/desktop/src/store/profile.tsindex f2dc71e502d..c0cbb262a0a 100644--- a/apps/desktop/src/store/profile.ts+++ b/apps/desktop/src/store/profile.ts@@ -14,6 +14,7 @@ import {} from '@/lib/storage'import { invalidateCronModelImpactScopeState } from '@/store/cron-model-impact-scope'import { $gateway, ensureGatewayForAgent, ensureGatewayForProfile, openGatewayForProfile } from '@/store/gateway'+import { notifyRemoteOverrideAuthFailure } from '@/store/profile-remote-override'import { setConnection } from '@/store/session'import { resetStarmapGraph } from '@/store/starmap'import type { ProfileInfo } from '@/types/hermes'@@ -516,7 +517,10 @@ export function selectProfile(name: string): void {requestFreshSession()}- void ensureGatewayProfile(target)+ // A profile with a remote override can fail to activate because the remote+ // host rejected its saved token (rotated/revoked). That must surface as a+ // "re-enter token" affordance, never a silently dead profile (#91349).+ void ensureGatewayProfile(target).catch(error => notifyRemoteOverrideAuthFailure(target, error))}// Start a fresh session in `name` WITHOUT collapsing the "All profiles" browse@@ -530,7 +534,7 @@ export function newSessionInProfile(name: string): void {$newChatProfile.set(target)$newChatRoute.set(null)requestFreshSession()- void ensureGatewayProfile(target)+ void ensureGatewayProfile(target).catch(error => notifyRemoteOverrideAuthFailure(target, error))}/** Start a draft owned by a specific registry agent. Foreground activation is