The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): shared 'Applies to' profile scope across settings pages and Messaging
Teknium7999ac6e3d59
diff --git a/apps/desktop/src/app/messaging/index.test.tsx b/apps/desktop/src/app/messaging/index.test.tsxindex 6005131ccdc..72d9c100443 100644--- a/apps/desktop/src/app/messaging/index.test.tsx+++ b/apps/desktop/src/app/messaging/index.test.tsx@@ -16,10 +16,23 @@ vi.mock('@/hermes', () => ({approvePairing: (platformId: string, requestId: string) => approvePairing(platformId, requestId),getMessagingPlatforms: () => getMessagingPlatforms(),getPairing: () => getPairing(),+ getProfiles: vi.fn(async () => ({ profiles: [] })),revokePairing: (platformId: string, userId: string) => revokePairing(platformId, userId),+ setApiRequestProfile: vi.fn(),updateMessagingPlatform: (id: string, body: unknown) => updateMessagingPlatform(id, body)}))+// Keep store/profile's side-effecting imports inert (pulled in via the shared+// settings scope store) — same seam as store/profile.test.ts.+vi.mock('@/store/gateway', () => ({+ $gateway: { get: () => null, subscribe: () => () => {} },+ ensureGatewayForAgent: vi.fn(async () => undefined),+ ensureGatewayForProfile: vi.fn(async () => undefined),+ openGatewayForProfile: vi.fn(async () => undefined)+}))+vi.mock('@/lib/query-client', () => ({ invalidateProfileScopedQueries: vi.fn() }))+vi.mock('@/store/starmap', () => ({ resetStarmapGraph: vi.fn() }))+vi.mock('@/lib/external-link', () => ({openExternalLink: (href: string) => openExternalLink(href)}))diff --git a/apps/desktop/src/app/messaging/index.tsx b/apps/desktop/src/app/messaging/index.tsxindex a921e8f97d3..579305dd3b5 100644--- a/apps/desktop/src/app/messaging/index.tsx+++ b/apps/desktop/src/app/messaging/index.tsx@@ -1,6 +1,6 @@import { useStore } from '@nanostores/react'import type * as React from 'react'-import { useCallback, useEffect, useMemo, useState } from 'react'+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { PageLoader } from '@/components/page-loader'import { StatusDot, type StatusTone } from '@/components/status-dot'@@ -28,6 +28,7 @@ import { normalize } from '@/lib/text'import { cn } from '@/lib/utils'import { $changeEventsAvailable, $pairingChangeTick, $platformsChangeTick } from '@/store/live-sync'import { notify, notifyError } from '@/store/notifications'+import { $settingsScopeOverride } from '@/store/settings-scope'import { runGatewayRestart } from '@/store/system-actions'import { useRefreshHotkey } from '../hooks/use-refresh-hotkey'@@ -36,6 +37,7 @@ import { DetailColumn, ListColumn, MasterDetail } from '../master-detail'import { PageSearchShell } from '../page-search-shell'import { CREDENTIAL_CONTROL_CLASS } from '../settings/credential-key-ui'import { ListRow } from '../settings/primitives'+import { SettingsProfileScope } from '../settings/profile-scope'import type { SetStatusbarItemGroup } from '../shell/statusbar-controls'import { PlatformAvatar } from './platform-icon'@@ -126,6 +128,9 @@ function fieldCopy(field: MessagingEnvVarInfo, m: Translations['messaging']) {export function MessagingView({ setStatusbarItemGroup: _setStatusbarItemGroup, ...props }: MessagingViewProps) {const { t } = useI18n()const m = t.messaging+ // Shared settings "Applies to" scope: configure another profile's gateway+ // platforms/pairing without switching the whole app (null → active profile).+ const scopeProfile = useStore($settingsScopeOverride)// Both save/toggle toasts offer the same one-click restart.const restartGatewayAction = { label: t.commandCenter.restartGateway, onClick: () => void runGatewayRestart() }const [platforms, setPlatforms] = useState<MessagingPlatformInfo[] | null>(null)@@ -151,7 +156,7 @@ export function MessagingView({ setStatusbarItemGroup: _setStatusbarItemGroup, .}try {- const result = await getMessagingPlatforms()+ const result = await getMessagingPlatforms(scopeProfile)setPlatforms(result.platforms)} catch (err) {if (!silent) {@@ -163,7 +168,7 @@ export function MessagingView({ setStatusbarItemGroup: _setStatusbarItemGroup, .}}},- [m]+ [m, scopeProfile])// Pairing has its own signal. platforms.changed tracks connect/disconnect@@ -173,12 +178,12 @@ export function MessagingView({ setStatusbarItemGroup: _setStatusbarItemGroup, .// should show no rows, not an error banner over a working page.const refreshPairing = useCallback(async () => {try {- const result = await getPairing()+ const result = await getPairing(scopeProfile)setPairing({ approved: result.approved ?? [], pending: result.pending ?? [] })} catch {// Leave the last known rows in place rather than blanking them.}- }, [])+ }, [scopeProfile])const refreshAll = useCallback(async (silent = false) => {@@ -193,6 +198,23 @@ export function MessagingView({ setStatusbarItemGroup: _setStatusbarItemGroup, .void refreshAll()}, [refreshAll])+ // Scope switch: the mounted list still shows the PREVIOUS profile's+ // platforms/pairing while the new fetch is in flight — blank it so stale+ // rows can't be toggled against the wrong backend.+ const scopeSeenRef = useRef(scopeProfile)++ // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (scope-change guard)+ useEffect(() => {+ if (scopeSeenRef.current === scopeProfile) {+ return+ }++ scopeSeenRef.current = scopeProfile+ setPlatforms(null)+ setPairing({ approved: [], pending: [] })+ setEdits({})+ }, [scopeProfile])+const changeEventsAvailable = useStore($changeEventsAvailable)const platformsChangeTick = useStore($platformsChangeTick)const pairingChangeTick = useStore($pairingChangeTick)@@ -275,7 +297,7 @@ export function MessagingView({ setStatusbarItemGroup: _setStatusbarItemGroup, .setSaving(`enabled:${platform.id}`)try {- await updateMessagingPlatform(platform.id, { enabled })+ await updateMessagingPlatform(platform.id, { enabled }, scopeProfile)setPlatforms(current =>current?.map(row =>@@ -311,7 +333,7 @@ export function MessagingView({ setStatusbarItemGroup: _setStatusbarItemGroup, .setSaving(`env:${platform.id}`)try {- await updateMessagingPlatform(platform.id, { env })+ await updateMessagingPlatform(platform.id, { env }, scopeProfile)setEdits(current => ({ ...current, [platform.id]: {} }))await refreshPlatforms()notify({@@ -331,7 +353,7 @@ export function MessagingView({ setStatusbarItemGroup: _setStatusbarItemGroup, .setSaving(`clear:${key}`)try {- await updateMessagingPlatform(platform.id, { clear_env: [key] })+ await updateMessagingPlatform(platform.id, { clear_env: [key] }, scopeProfile)setEdits(current => ({...current,[platform.id]: {@@ -365,7 +387,7 @@ export function MessagingView({ setStatusbarItemGroup: _setStatusbarItemGroup, .}))try {- await approvePairing(user.platform, user.request_id)+ await approvePairing(user.platform, user.request_id, scopeProfile)notify({ kind: 'success', title: m.approvedUser(pairingLabel(user)), message: m.approvedHint })await refreshPairing()} catch (err) {@@ -390,7 +412,7 @@ export function MessagingView({ setStatusbarItemGroup: _setStatusbarItemGroup, .}))try {- await revokePairing(user.platform, user.user_id)+ await revokePairing(user.platform, user.user_id, scopeProfile)notify({ kind: 'success', title: m.revokedUser(pairingLabel(user)), message: user.platform })await refreshPairing()} catch (err) {@@ -411,59 +433,66 @@ export function MessagingView({ setStatusbarItemGroup: _setStatusbarItemGroup, .{!platforms ? (<PageLoader label={m.loading} />) : (- <MasterDetail>- <ListColumn>- <ul className="space-y-1">- {visiblePlatforms.map(platform => (- <li key={platform.id}>- <PlatformRow- active={selected?.id === platform.id}- onSelect={() => setSelectedId(platform.id)}- pendingCount={pendingByPlatform[platform.id]?.length ?? 0}- platform={platform}- />- </li>- ))}- </ul>- </ListColumn>-- <DetailColumn- actionBar={- selected && (- <PlatformActionBar- hasEdits={Object.keys(trimEdits(edits[selected.id] || {})).length > 0}- onSave={() => void handleSave(selected)}- onToggle={enabled => void handleToggle(selected, enabled)}- platform={selected}- saving={saving}- />- )- }- >- {selected && (- <PlatformDetail- approved={approvedByPlatform[selected.id] ?? []}- approving={approving}- edits={edits[selected.id] || {}}- onApprove={user => void handleApprove(user)}- onClear={key => void handleClear(selected, key)}- onEdit={(key, value) =>- setEdits(current => ({- ...current,- [selected.id]: {- ...(current[selected.id] || {}),- [key]: value- }- }))+ <div className="flex h-full min-h-0 flex-col">+ {/* Which profile's gateway this page configures (hidden for+ single-profile users). */}+ <SettingsProfileScope className="border-b border-(--ui-stroke-secondary) px-3 py-2" />+ <div className="min-h-0 flex-1">+ <MasterDetail>+ <ListColumn>+ <ul className="space-y-1">+ {visiblePlatforms.map(platform => (+ <li key={platform.id}>+ <PlatformRow+ active={selected?.id === platform.id}+ onSelect={() => setSelectedId(platform.id)}+ pendingCount={pendingByPlatform[platform.id]?.length ?? 0}+ platform={platform}+ />+ </li>+ ))}+ </ul>+ </ListColumn>++ <DetailColumn+ actionBar={+ selected && (+ <PlatformActionBar+ hasEdits={Object.keys(trimEdits(edits[selected.id] || {})).length > 0}+ onSave={() => void handleSave(selected)}+ onToggle={enabled => void handleToggle(selected, enabled)}+ platform={selected}+ saving={saving}+ />+ )}- onRevoke={setPendingRevoke}- pending={pendingByPlatform[selected.id] ?? []}- platform={selected}- saving={saving}- />- )}- </DetailColumn>- </MasterDetail>+ >+ {selected && (+ <PlatformDetail+ approved={approvedByPlatform[selected.id] ?? []}+ approving={approving}+ edits={edits[selected.id] || {}}+ onApprove={user => void handleApprove(user)}+ onClear={key => void handleClear(selected, key)}+ onEdit={(key, value) =>+ setEdits(current => ({+ ...current,+ [selected.id]: {+ ...(current[selected.id] || {}),+ [key]: value+ }+ }))+ }+ onRevoke={setPendingRevoke}+ pending={pendingByPlatform[selected.id] ?? []}+ platform={selected}+ saving={saving}+ />+ )}+ </DetailColumn>+ </MasterDetail>+ </div>+ </div>)}<ConfirmDialogdiff --git a/apps/desktop/src/app/settings/config-settings.tsx b/apps/desktop/src/app/settings/config-settings.tsxindex a3feb4611ae..7ded49ff4b7 100644--- a/apps/desktop/src/app/settings/config-settings.tsx+++ b/apps/desktop/src/app/settings/config-settings.tsx@@ -21,10 +21,12 @@ import {import { $disableF12, setDisableF12 } from '@/store/disable-f12'import { $keepAwake, setKeepAwake } from '@/store/keep-awake'import { notify, notifyError } from '@/store/notifications'+import { normalizeProfileKey } from '@/store/profile'import { repoDiscoveryPolicyFromConfig, repoDiscoveryPolicySignature, scanAndRecordRepos } from '@/store/projects'+import { $settingsScopeOverride } from '@/store/settings-scope'import type { ConfigFieldSchema, HermesConfigRecord } from '@/types/hermes'-import { setHermesConfigCache, useHermesConfigRecord } from '../hooks/use-config-record'+import { hermesConfigCacheWriter, useHermesConfigRecord } from '../hooks/use-config-record'import { useOnProfileSwitch } from '../hooks/use-on-profile-switch'import { PanelEmpty } from '../overlays/panel'@@ -41,6 +43,7 @@ import { MemoryConnect } from './memory/connect'import { ProviderConfigPanel } from './memory/provider-config-panel'import { ModelSettings, ModelSettingsSkeleton } from './model-settings'import { EmptyState, ListRow, SettingsContent, SettingsSkeleton, ToggleRow } from './primitives'+import { SettingsProfileScope } from './profile-scope'import { QuickEntrySettings } from './quick-entry-settings'// On the Voice page, only surface the sub-fields of the *selected* TTS/STT@@ -68,12 +71,39 @@ export function ConfigSettings({onConfigSaved,onMainModelChanged,importInputRef-}: {+}: ConfigSettingsProps) {+ // Shared "Applies to" scope (null → the app's active profile). Remount the+ // inner page per scope so every draft/seed/autosave ref resets wholesale+ // when the target profile changes — the same guarantee useOnProfileSwitch+ // provides for app-wide switches, without hand-clearing each piece.+ const scopeProfile = useStore($settingsScopeOverride)++ return (+ <ConfigSettingsInner+ activeSectionId={activeSectionId}+ importInputRef={importInputRef}+ key={scopeProfile ?? '__active__'}+ onConfigSaved={onConfigSaved}+ onMainModelChanged={onMainModelChanged}+ scopeProfile={scopeProfile}+ />+ )+}++interface ConfigSettingsProps {activeSectionId: stringonConfigSaved?: () => voidonMainModelChanged?: (provider: string, model: string) => voidimportInputRef: React.RefObject<HTMLInputElement | null>-}) {+}++function ConfigSettingsInner({+ activeSectionId,+ onConfigSaved,+ onMainModelChanged,+ importInputRef,+ scopeProfile+}: ConfigSettingsProps & { scopeProfile: null | string }) {const { t } = useI18n()const c = t.settings.configconst keepAwake = useStore($keepAwake)@@ -82,15 +112,21 @@ export function ConfigSettings({// from — and saved back through — the shared config cache, so edits are visible// in the MCP/model surfaces and reopening the page doesn't reload-flash.const [config, setConfig] = useState<HermesConfigRecord | null>(null)- const { data: loadedConfig, isError: configLoadFailed, refetch: refetchConfig } = useHermesConfigRecord()+ const { data: loadedConfig, isError: configLoadFailed, refetch: refetchConfig } = useHermesConfigRecord(scopeProfile)+ // Writes land on the same cache key the query above reads (base key when+ // following the active profile, suffixed when a scope override is set).+ const writeConfigCache = useMemo(() => hermesConfigCacheWriter(scopeProfile), [scopeProfile])const {data: schemaResponse,isError: schemaFailed,refetch: refetchSchema} = useQuery({- queryKey: ['hermes-config-schema'],- queryFn: getHermesConfigSchema,+ // Base key when following the active profile (matches every pre-existing+ // consumer); suffixed only for an explicit scope override.+ queryKey:+ scopeProfile == null ? ['hermes-config-schema'] : ['hermes-config-schema', normalizeProfileKey(scopeProfile)],+ queryFn: () => getHermesConfigSchema(scopeProfile ?? undefined),staleTime: 5 * 60 * 1000})@@ -129,7 +165,7 @@ export function ConfigSettings({useEffect(() => {let cancelled = false- getElevenLabsVoices()+ getElevenLabsVoices(scopeProfile ?? undefined).then(result => {if (cancelled || !result.available) {return@@ -146,7 +182,8 @@ export function ConfigSettings({})return () => void (cancelled = true)- }, [])+ // scopeProfile is constant per mount (the inner component is keyed on it).+ }, [scopeProfile])// eslint-disable-next-line no-restricted-syntax -- autosave bookkeeping refs, not an atom mirroruseEffect(() => {@@ -159,7 +196,7 @@ export function ConfigSettings({const t = window.setTimeout(() => {void (async () => {try {- const result = await saveHermesConfig(config)+ const result = await saveHermesConfig(config, scopeProfile ?? undefined)if (!result.ok) {throw new Error(c.autosaveFailed)@@ -167,14 +204,18 @@ export function ConfigSettings({// Mirror the saved record into the shared cache so MCP/model surfaces// reflect the edit without their own refetch.- setHermesConfigCache(config)+ writeConfigCache(config)if (saveVersionRef.current === v) {- const discoverySignature = repoDiscoveryPolicySignature(repoDiscoveryPolicyFromConfig(config))-- if (savedDiscoverySignatureRef.current !== discoverySignature) {- savedDiscoverySignatureRef.current = discoverySignature- await scanAndRecordRepos(true)+ // The repo-discovery scan reads the ACTIVE profile's workspace+ // policy; skip it when this page is editing another profile.+ if (scopeProfile == null) {+ const discoverySignature = repoDiscoveryPolicySignature(repoDiscoveryPolicyFromConfig(config))++ if (savedDiscoverySignatureRef.current !== discoverySignature) {+ savedDiscoverySignatureRef.current = discoverySignature+ await scanAndRecordRepos(true)+ }}onConfigSaved?.()@@ -301,6 +342,7 @@ export function ConfigSettings({if (activeSectionId === 'model') {return (<SettingsContent>+ <SettingsProfileScope className="mb-5" /><div className="mb-6"><ModelSettingsSkeleton /></div>@@ -315,9 +357,12 @@ export function ConfigSettings({return (<SettingsContent>+ {/* Which profile's config.yaml this page edits — shared across every+ config-backed settings page (and hidden for single-profile users). */}+ <SettingsProfileScope className="mb-5" />{activeSectionId === 'model' && (<div className="mb-6">- <ModelSettings onMainModelChanged={onMainModelChanged} />+ <ModelSettings onMainModelChanged={onMainModelChanged} scopeProfile={scopeProfile} /></div>)}{/* Device-local desktop prefs (not config.yaml) — they live here since@@ -353,7 +398,7 @@ export function ConfigSettings({<ConfigFielddescriptionExtra={key === 'memory.provider' && isExternalMemoryProvider(getNested(config, key)) ? (- <MemoryConnect provider={String(getNested(config, key))} />+ <MemoryConnect profile={scopeProfile} provider={String(getNested(config, key))} />) : undefined}enumOptions={@@ -368,7 +413,11 @@ export function ConfigSettings({value={getNested(config, key)}/>{key === 'memory.provider' && isExternalMemoryProvider(getNested(config, key)) ? (- <ProviderConfigPanel key={String(getNested(config, key))} provider={String(getNested(config, key))} />+ <ProviderConfigPanel+ key={String(getNested(config, key))}+ profile={scopeProfile}+ provider={String(getNested(config, key))}+ />) : null}</div>))}diff --git a/apps/desktop/src/app/settings/env-credentials.tsx b/apps/desktop/src/app/settings/env-credentials.tsxindex 4b340ede931..1a69d39a6db 100644--- a/apps/desktop/src/app/settings/env-credentials.tsx+++ b/apps/desktop/src/app/settings/env-credentials.tsx@@ -40,8 +40,10 @@ export function SettingsCategoryHeading({ count, icon: Icon, title }: CategoryHe// Owns the env-var fetch + the edit/reveal/save/delete lifecycle so multiple// credential pages (Providers, Keys) share one source of truth and one set of-// mutation handlers instead of duplicating the plumbing.-export function useEnvCredentials(): UseEnvCredentials {+// mutation handlers instead of duplicating the plumbing. An optional `profile`+// targets another profile's env store (the shared settings "Applies to"+// scope); undefined/null keeps the app-wide active profile.+export function useEnvCredentials(profile: null | string = null): UseEnvCredentials {const { t } = useI18n()const credentials = t.settings.credentialsconst toolsets = t.settings.toolsets@@ -63,9 +65,11 @@ export function useEnvCredentials(): UseEnvCredentials {useEffect(() => {let cancelled = false+ setVars(null)+void (async () => {try {- const next = await getEnvVars()+ const next = await getEnvVars(profile)if (!cancelled) {setVars(next)@@ -76,8 +80,8 @@ export function useEnvCredentials(): UseEnvCredentials {})()return () => void (cancelled = true)- // eslint-disable-next-line react-hooks/exhaustive-deps -- load once on mount; copy is stable- }, [])+ // eslint-disable-next-line react-hooks/exhaustive-deps -- reload per target profile; copy is stable+ }, [profile])function patchVar(key: string, patch: Partial<Pick<EnvVarInfo, 'is_set' | 'redacted_value'>>) {setVars(c => (c ? { ...c, [key]: { ...c[key], ...patch } } : c))@@ -98,7 +102,7 @@ export function useEnvCredentials(): UseEnvCredentials {setSaving(key)try {- await setEnvVar(key, value)+ await setEnvVar(key, value, profile)patchVar(key, { is_set: true, redacted_value: redactedValue(value) })clearLocalState(key)notify({ kind: 'success', title: toolsets.savedTitle, message: toolsets.savedMessage(key) })@@ -122,7 +126,7 @@ export function useEnvCredentials(): UseEnvCredentials {setSaving(key)try {- await setEnvVar(key, trimmed)+ await setEnvVar(key, trimmed, profile)patchVar(key, { is_set: true, redacted_value: redactedValue(trimmed) })clearLocalState(key)notify({ kind: 'success', message: toolsets.savedMessage(key), title: toolsets.savedTitle })@@ -145,7 +149,7 @@ export function useEnvCredentials(): UseEnvCredentials {setSaving(key)try {- await deleteEnvVar(key)+ await deleteEnvVar(key, profile)patchVar(key, { is_set: false, redacted_value: null })clearLocalState(key)notify({ kind: 'success', title: toolsets.removedTitle, message: toolsets.removedMessage(key) })@@ -164,7 +168,7 @@ export function useEnvCredentials(): UseEnvCredentials {}try {- const result = await revealEnvVar(key)+ const result = await revealEnvVar(key, profile)setRevealed(c => ({ ...c, [key]: result.value }))} catch (err) {notifyError(err, toolsets.failedReveal(key))diff --git a/apps/desktop/src/app/settings/keys-settings.tsx b/apps/desktop/src/app/settings/keys-settings.tsxindex b180689a841..173b359856a 100644--- a/apps/desktop/src/app/settings/keys-settings.tsx+++ b/apps/desktop/src/app/settings/keys-settings.tsx@@ -1,12 +1,15 @@+import { useStore } from '@nanostores/react'import { useEffect, useMemo, useState } from 'react'import { useI18n } from '@/i18n'+import { $settingsScopeOverride } from '@/store/settings-scope'import type { EnvVarInfo } from '@/types/hermes'import { CredentialKeyCard, credentialPlaceholder, credentialRowLabel } from './credential-key-ui'import { useEnvCredentials } from './env-credentials'import { asText } from './helpers'import { SettingsContent, SettingsSkeleton } from './primitives'+import { SettingsProfileScope } from './profile-scope'import { useDeepLinkHighlight } from './use-deep-link-highlight'// Sub-views surfaced as sidebar subnav under Tools & Keys (see settings/index.tsx).@@ -30,12 +33,15 @@ const VIEW_CATEGORIES: Record<KeysView, readonly string[]> = {export function KeysSettings({ view }: KeysSettingsProps) {const { t } = useI18n()- const { rowProps, vars } = useEnvCredentials()+ // Shared settings "Applies to" scope: fetch + edit the selected profile's+ // env store instead of the active one (null → active, the default path).+ const scopeProfile = useStore($settingsScopeOverride)+ const { rowProps, vars } = useEnvCredentials(scopeProfile)const [openKey, setOpenKey] = useState<null | string>(null)useEffect(() => {setOpenKey(null)- }, [view])+ }, [scopeProfile, view])// Deep link from Capabilities env-var rows (?tab=keys&key=<ENV_KEY>): scroll// the credential card into view, flash it, and expand it. Same mechanism the@@ -71,6 +77,7 @@ export function KeysSettings({ view }: KeysSettingsProps) {return (<SettingsContent>+ <SettingsProfileScope className="mb-5" />{visible.map(group => (<div className="grid gap-2" key={group.category}>{group.entries.map(([key, info]: [string, EnvVarInfo]) => {diff --git a/apps/desktop/src/app/settings/memory/connect.tsx b/apps/desktop/src/app/settings/memory/connect.tsxindex 75ff9a64750..64d9cfa6fa5 100644--- a/apps/desktop/src/app/settings/memory/connect.tsx+++ b/apps/desktop/src/app/settings/memory/connect.tsx@@ -12,7 +12,7 @@ const POLL_TIMEOUT_MS = 120_000// Small connect affordance rendered under the provider dropdown. Capability is// backend-driven: the status route 404s for providers without an oauth_flow// module, so non-OAuth providers render nothing.-export function MemoryConnect({ provider }: { provider: string }) {+export function MemoryConnect({ profile = null, provider }: { profile?: null | string; provider: string }) {const [capable, setCapable] = useState<'no' | 'unknown' | 'yes'>('unknown')const [connected, setConnected] = useState(false)const [auth, setAuth] = useState<MemoryProviderOAuthStatus['auth']>(null)@@ -31,7 +31,7 @@ export function MemoryConnect({ provider }: { provider: string }) {useEffect(() => {let active = truesetCapable('unknown')- getMemoryProviderOAuthStatus(provider)+ getMemoryProviderOAuthStatus(provider, profile).then(s => {if (!active) {return@@ -51,7 +51,7 @@ export function MemoryConnect({ provider }: { provider: string }) {active = falsestop()}- }, [provider, stop])+ }, [profile, provider, stop])// An error message isn't sticky — it clears back to the steady state// (Connect link, plus the connected badge if a credential is stored).@@ -72,7 +72,7 @@ export function MemoryConnect({ provider }: { provider: string }) {setPhase('pending')try {- await startMemoryProviderOAuth(provider)+ await startMemoryProviderOAuth(provider, profile)} catch (err) {setPhase('error')setDetail('Could not start the connection.')@@ -86,7 +86,7 @@ export function MemoryConnect({ provider }: { provider: string }) {timer.current = setInterval(() => {void (async () => {try {- const next = await getMemoryProviderOAuthStatus(provider)+ const next = await getMemoryProviderOAuthStatus(provider, profile)if (next.state === 'pending') {if (Date.now() > deadline.current) {@@ -113,7 +113,7 @@ export function MemoryConnect({ provider }: { provider: string }) {}})()}, POLL_MS)- }, [provider, stop])+ }, [profile, provider, stop])const cancel = useCallback(() => {stop()diff --git a/apps/desktop/src/app/settings/memory/provider-config-modal.tsx b/apps/desktop/src/app/settings/memory/provider-config-modal.tsxindex 228e78f737c..e3327c00348 100644--- a/apps/desktop/src/app/settings/memory/provider-config-modal.tsx+++ b/apps/desktop/src/app/settings/memory/provider-config-modal.tsx@@ -46,12 +46,14 @@ function groupFields(fields: MemoryProviderField[]): [string, MemoryProviderFielexport function ProviderConfigModal({config,+ profile = null,provider,open,onOpenChange,onSaved}: {config: MemoryProviderConfig+ profile?: null | stringprovider: stringopen: booleanonOpenChange: (open: boolean) => void@@ -78,7 +80,7 @@ export function ProviderConfigModal({setSaving(true)try {- await saveMemoryProviderConfig(provider, edited)+ await saveMemoryProviderConfig(provider, edited, profile)notify({ kind: 'success', title: `${config.label} saved`, message: 'Memory provider configuration updated.' })await onSaved()onOpenChange(false)@@ -95,8 +97,8 @@ export function ProviderConfigModal({<DialogHeader><DialogTitle icon={SlidersHorizontal}>{config.label} — full configuration</DialogTitle><DialogDescription>- Every {config.label} option for the <span className="font-medium">{activeProfile}</span> profile. Blank- fields fall back to the resolved host or built-in default.+ Every {config.label} option for the <span className="font-medium">{profile ?? activeProfile}</span> profile.+ Blank fields fall back to the resolved host or built-in default.</DialogDescription>{config.docs_url && (<adiff --git a/apps/desktop/src/app/settings/memory/provider-config-panel.tsx b/apps/desktop/src/app/settings/memory/provider-config-panel.tsxindex aa0c5ffd866..2d7b6ae0c4a 100644--- a/apps/desktop/src/app/settings/memory/provider-config-panel.tsx+++ b/apps/desktop/src/app/settings/memory/provider-config-panel.tsx@@ -20,7 +20,7 @@ function seedValues(config: MemoryProviderConfig): Record<string, string> {)}-export function ProviderConfigPanel({ provider }: { provider: string }) {+export function ProviderConfigPanel({ profile = null, provider }: { profile?: null | string; provider: string }) {const [config, setConfig] = useState<MemoryProviderConfig | null>(null)const [loadError, setLoadError] = useState<null | string>(null)const [values, setValues] = useState<Record<string, string>>({})@@ -30,7 +30,7 @@ export function ProviderConfigPanel({ provider }: { provider: string }) {const refresh = useCallback(async () => {try {- const next = await getMemoryProviderConfig(provider)+ const next = await getMemoryProviderConfig(provider, profile)const seed = seedValues(next)setConfig(next)setValues(seed)@@ -40,7 +40,7 @@ export function ProviderConfigPanel({ provider }: { provider: string }) {setConfig(null)setLoadError(err instanceof Error ? err.message : 'Memory provider settings failed to load')}- }, [provider])+ }, [profile, provider])useEffect(() => {setConfig(null)@@ -56,7 +56,7 @@ export function ProviderConfigPanel({ provider }: { provider: string }) {}try {- await saveMemoryProviderConfig(provider, { [field.key]: value })+ await saveMemoryProviderConfig(provider, { [field.key]: value }, profile)if (field.kind === 'secret') {setValues(current => ({ ...current, [field.key]: '' }))@@ -74,7 +74,7 @@ export function ProviderConfigPanel({ provider }: { provider: string }) {notifyError(err, `Failed to save ${field.label}`)}},- [provider, saved]+ [profile, provider, saved])// Providers without a declared config surface (e.g. builtin) render nothing.@@ -155,6 +155,7 @@ export function ProviderConfigPanel({ provider }: { provider: string }) {onOpenChange={setShowModal}onSaved={refresh}open={showModal}+ profile={profile}provider={provider}/>)}diff --git a/apps/desktop/src/app/settings/model-settings.tsx b/apps/desktop/src/app/settings/model-settings.tsxindex b91a04f103a..28036e9e672 100644--- a/apps/desktop/src/app/settings/model-settings.tsx+++ b/apps/desktop/src/app/settings/model-settings.tsx@@ -31,7 +31,7 @@ import { setMainModelAssignment } from '@/store/cron-model-impact'import { notifyError } from '@/store/notifications'import { startManualLocalEndpoint, startManualOnboarding, startManualProviderOAuth } from '@/store/onboarding'-import { invalidateHermesConfig, setHermesConfigCache, useHermesConfigRecord } from '../hooks/use-config-record'+import { hermesConfigCacheWriter, invalidateHermesConfig, useHermesConfigRecord } from '../hooks/use-config-record'import { useOnProfileSwitch } from '../hooks/use-on-profile-switch'import { CONTROL_TEXT } from './constants'@@ -181,9 +181,12 @@ function StaleAuxWarning({ applying, onReset, slots, taskLabel }: StaleAuxWarnininterface ModelSettingsProps {/** Notified after the main model is applied, so live UI stores can sync. */onMainModelChanged?: (provider: string, model: string) => void+ /** Shared settings "Applies to" scope: a concrete profile to edit instead of+ * the app's active one, or null to follow the active profile (default). */+ scopeProfile?: null | string}-export function ModelSettings({ onMainModelChanged }: ModelSettingsProps) {+export function ModelSettings({ onMainModelChanged, scopeProfile = null }: ModelSettingsProps) {const { t } = useI18n()const m = t.settings.modelconst [loading, setLoading] = useState(true)@@ -197,9 +200,9 @@ export function ModelSettings({ onMainModelChanged }: ModelSettingsProps) {const [selectedMoaPreset, setSelectedMoaPreset] = useState('')const [newMoaPresetName, setNewMoaPresetName] = useState('')// agent.* defaults round-trip through the shared config cache (read → write- // back the whole record), so a save here shows in the MCP/config surfaces.- const { data: config } = useHermesConfigRecord()- const setConfig = setHermesConfigCache+ // back the whole record), so a save here shows in the MCP/model surfaces.+ const { data: config } = useHermesConfigRecord(scopeProfile)+ const setConfig = useMemo(() => hermesConfigCacheWriter(scopeProfile), [scopeProfile])const [applying, setApplying] = useState(false)const [editingAuxTask, setEditingAuxTask] = useState<null | string>(null)const [auxDraft, setAuxDraft] = useState<{ model: string; provider: string }>({ model: '', provider: '' })@@ -224,54 +227,57 @@ export function ModelSettings({ onMainModelChanged }: ModelSettingsProps) {// A's models/providers into profile B (or fire onMainModelChanged for A).const profileEpoch = useRef(0)- const refresh = useCallback(async ({ replaceSelection = false }: { replaceSelection?: boolean } = {}) => {- const epoch = profileEpoch.current- setLoading(true)- setError('')-- try {- const [modelInfo, modelOptions, auxiliaryModels, moaModels] = await Promise.all([- getGlobalModelInfo(),- getGlobalModelOptions(),- getAuxiliaryModels(),- getMoaModels().catch(() => null)- ])+ const refresh = useCallback(+ async ({ replaceSelection = false }: { replaceSelection?: boolean } = {}) => {+ const epoch = profileEpoch.current+ setLoading(true)+ setError('')- if (profileEpoch.current !== epoch) {- return- }+ try {+ const [modelInfo, modelOptions, auxiliaryModels, moaModels] = await Promise.all([+ getGlobalModelInfo(scopeProfile),+ getGlobalModelOptions(undefined, scopeProfile),+ getAuxiliaryModels(scopeProfile),+ getMoaModels(scopeProfile).catch(() => null)+ ])++ if (profileEpoch.current !== epoch) {+ return+ }- setMainModel({ model: modelInfo.model, provider: modelInfo.provider })- setProviders(modelOptions.providers || [])+ setMainModel({ model: modelInfo.model, provider: modelInfo.provider })+ setProviders(modelOptions.providers || [])- if (replaceSelection) {- setSelectedProvider(modelInfo.provider)- setSelectedModel(modelInfo.model)- } else {- setSelectedProvider(prev => prev || modelInfo.provider)- setSelectedModel(prev => prev || modelInfo.model)- }+ if (replaceSelection) {+ setSelectedProvider(modelInfo.provider)+ setSelectedModel(modelInfo.model)+ } else {+ setSelectedProvider(prev => prev || modelInfo.provider)+ setSelectedModel(prev => prev || modelInfo.model)+ }- setAuxiliary(auxiliaryModels)- setMoa(moaModels)+ setAuxiliary(auxiliaryModels)+ setMoa(moaModels)- if (moaModels) {- setSelectedMoaPreset(prev => (prev && moaModels.presets[prev] ? prev : moaModels.default_preset))- }+ if (moaModels) {+ setSelectedMoaPreset(prev => (prev && moaModels.presets[prev] ? prev : moaModels.default_preset))+ }- // The config record loads via its own shared query; a model switch can- // change it server-side (aux slots), so nudge that cache to refetch.- void invalidateHermesConfig()- } catch (err) {- if (profileEpoch.current === epoch) {- setError(err instanceof Error ? err.message : String(err))- }- } finally {- if (profileEpoch.current === epoch) {- setLoading(false)+ // The config record loads via its own shared query; a model switch can+ // change it server-side (aux slots), so nudge that cache to refetch.+ void invalidateHermesConfig(scopeProfile)+ } catch (err) {+ if (profileEpoch.current === epoch) {+ setError(err instanceof Error ? err.message : String(err))+ }+ } finally {+ if (profileEpoch.current === epoch) {+ setLoading(false)+ }}- }- }, [])+ },+ [scopeProfile]+ )useEffect(() => {void refresh()@@ -377,33 +383,36 @@ export function ModelSettings({ onMainModelChanged }: ModelSettingsProps) {// edit that completes the slot flushes the whole preset. Every edit bumps// the generation so an in-flight response from an older save can never// repaint over the user's mid-edit state.- const scheduleMoaSave = useCallback((next: MoaConfigResponse) => {- if (moaSaveTimer.current) {- window.clearTimeout(moaSaveTimer.current)- moaSaveTimer.current = null- }+ const scheduleMoaSave = useCallback(+ (next: MoaConfigResponse) => {+ if (moaSaveTimer.current) {+ window.clearTimeout(moaSaveTimer.current)+ moaSaveTimer.current = null+ }- const generation = moaSaveGeneration.current + 1- moaSaveGeneration.current = generation+ const generation = moaSaveGeneration.current + 1+ moaSaveGeneration.current = generation- if (!moaConfigComplete(next)) {- return- }+ if (!moaConfigComplete(next)) {+ return+ }- moaSaveTimer.current = window.setTimeout(() => {- void saveMoaModels(next)- .then(saved => {- if (moaSaveGeneration.current === generation) {- setMoa(saved)- }- })- .catch(err => {- if (moaSaveGeneration.current === generation) {- setError(err instanceof Error ? err.message : String(err))- }- })- }, 600)- }, [])+ moaSaveTimer.current = window.setTimeout(() => {+ void saveMoaModels(next, scopeProfile)+ .then(saved => {+ if (moaSaveGeneration.current === generation) {+ setMoa(saved)+ }+ })+ .catch(err => {+ if (moaSaveGeneration.current === generation) {+ setError(err instanceof Error ? err.message : String(err))+ }+ })+ }, 600)+ },+ [scopeProfile]+ )const updateMoaPreset = useCallback((updater: (preset: NonNullable<typeof currentMoaPreset>) => NonNullable<typeof currentMoaPreset>) => {@@ -441,35 +450,38 @@ export function ModelSettings({ onMainModelChanged }: ModelSettingsProps) {return next}, [])- const saveMoa = useCallback(async (next: MoaConfigResponse) => {- const epoch = profileEpoch.current+ const saveMoa = useCallback(+ async (next: MoaConfigResponse) => {+ const epoch = profileEpoch.current- // Explicit preset ops (set default / add / delete) supersede any pending- // debounced slot autosave — cancel it and invalidate in-flight responses- // so the two writers can't race each other's state.- if (moaSaveTimer.current) {- window.clearTimeout(moaSaveTimer.current)- moaSaveTimer.current = null- }+ // Explicit preset ops (set default / add / delete) supersede any pending+ // debounced slot autosave — cancel it and invalidate in-flight responses+ // so the two writers can't race each other's state.+ if (moaSaveTimer.current) {+ window.clearTimeout(moaSaveTimer.current)+ moaSaveTimer.current = null+ }- moaSaveGeneration.current += 1- setApplying(true)- setError('')+ moaSaveGeneration.current += 1+ setApplying(true)+ setError('')- try {- const saved = await saveMoaModels(next)+ try {+ const saved = await saveMoaModels(next, scopeProfile)- if (profileEpoch.current !== epoch) {- return- }+ if (profileEpoch.current !== epoch) {+ return+ }- setMoa(saved)- } catch (err) {- setError(err instanceof Error ? err.message : String(err))- } finally {- setApplying(false)- }- }, [])+ setMoa(saved)+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err))+ } finally {+ setApplying(false)+ }+ },+ [scopeProfile]+ )const auxiliaryTaskLabel = useCallback((key: string) => m.tasks[key]?.label ?? key, [m.tasks])@@ -527,13 +539,13 @@ export function ModelSettings({ onMainModelChanged }: ModelSettingsProps) {setConfig(next)try {- await saveHermesConfig(next)+ await saveHermesConfig(next, scopeProfile ?? undefined)} catch (err) {setConfig(prev)notifyError(err, m.defaultsFailed)}},- [config, m.defaultsFailed, setConfig]+ [config, m.defaultsFailed, scopeProfile, setConfig])// Paste an API key for the selected `api_key` provider, persist it, then@@ -552,7 +564,7 @@ export function ModelSettings({ onMainModelChanged }: ModelSettingsProps) {setError('')try {- await setEnvVar(keyEnv, apiKeyDraft.trim())+ await setEnvVar(keyEnv, apiKeyDraft.trim(), scopeProfile)setApiKeyDraft('')// Pick a sensible default for the freshly-activated provider (mirrors@@ -561,13 +573,13 @@ export function ModelSettings({ onMainModelChanged }: ModelSettingsProps) {let nextModel = ''try {- const rec = await getRecommendedDefaultModel(slug)+ const rec = await getRecommendedDefaultModel(slug, scopeProfile)nextModel = rec.model || ''} catch {nextModel = ''}- const options = await getGlobalModelOptions()+ const options = await getGlobalModelOptions(undefined, scopeProfile)if (profileEpoch.current !== epoch) {return@@ -582,7 +594,7 @@ export function ModelSettings({ onMainModelChanged }: ModelSettingsProps) {} finally {setActivating(false)}- }, [apiKeyDraft, selectedProviderRow])+ }, [apiKeyDraft, scopeProfile, selectedProviderRow])// OAuth / external providers can't be activated with a pasted key — hand off// to the shared onboarding flow scoped to this provider's real sign-in. The@@ -620,11 +632,14 @@ export function ModelSettings({ onMainModelChanged }: ModelSettingsProps) {setError('')try {- const result = await setMainModelAssignment({- model: selectedModel,- provider: selectedProvider,- ...(selectedProviderRow?.api_url ? { base_url: selectedProviderRow.api_url } : {})- })+ const result = await setMainModelAssignment(+ {+ model: selectedModel,+ provider: selectedProvider,+ ...(selectedProviderRow?.api_url ? { base_url: selectedProviderRow.api_url } : {})+ },+ scopeProfile+ )if (profileEpoch.current !== epoch) {return@@ -634,14 +649,20 @@ export function ModelSettings({ onMainModelChanged }: ModelSettingsProps) {const model = result.model || selectedModelsetMainModel({ provider, model })setSwitchStaleAux(result.stale_aux ?? [])- onMainModelChanged?.(provider, model)++ // Live UI stores mirror the ACTIVE profile's model; a scoped apply+ // changed a different profile and must not repaint them.+ if (scopeProfile == null) {+ onMainModelChanged?.(provider, model)+ }+await refresh()} catch (err) {setError(err instanceof Error ? err.message : String(err))} finally {setApplying(false)}- }, [onMainModelChanged, refresh, selectedModel, selectedProvider, selectedProviderRow])+ }, [onMainModelChanged, refresh, scopeProfile, selectedModel, selectedProvider, selectedProviderRow])// Sibling of the applyMainModel endpoint passthrough (#65254): auxiliary// assignments targeting a user-defined provider must carry that provider's@@ -667,13 +688,16 @@ export function ModelSettings({ onMainModelChanged }: ModelSettingsProps) {setError('')try {- await setModelAssignment({- model: mainModel.model,- provider: mainModel.provider,- scope: 'auxiliary',- task,- ...endpointForProvider(mainModel.provider)- })+ await setModelAssignment(+ {+ model: mainModel.model,+ provider: mainModel.provider,+ scope: 'auxiliary',+ task,+ ...endpointForProvider(mainModel.provider)+ },+ scopeProfile+ )await refresh()} catch (err) {setError(err instanceof Error ? err.message : String(err))@@ -681,7 +705,7 @@ export function ModelSettings({ onMainModelChanged }: ModelSettingsProps) {setApplying(false)}},- [endpointForProvider, mainModel, refresh]+ [endpointForProvider, mainModel, refresh, scopeProfile])const applyAuxiliaryDraft = useCallback(@@ -694,13 +718,16 @@ export function ModelSettings({ onMainModelChanged }: ModelSettingsProps) {setError('')try {- await setModelAssignment({- model: auxDraft.model,- provider: auxDraft.provider,- scope: 'auxiliary',- task,- ...endpointForProvider(auxDraft.provider)- })+ await setModelAssignment(+ {+ model: auxDraft.model,+ provider: auxDraft.provider,+ scope: 'auxiliary',+ task,+ ...endpointForProvider(auxDraft.provider)+ },+ scopeProfile+ )setEditingAuxTask(null)await refresh()} catch (err) {@@ -709,7 +736,7 @@ export function ModelSettings({ onMainModelChanged }: ModelSettingsProps) {setApplying(false)}},- [auxDraft, endpointForProvider, refresh]+ [auxDraft, endpointForProvider, refresh, scopeProfile])const beginAuxiliaryEdit = useCallback(@@ -735,12 +762,15 @@ export function ModelSettings({ onMainModelChanged }: ModelSettingsProps) {setError('')try {- await setModelAssignment({- model: mainModel.model,- provider: mainModel.provider,- scope: 'auxiliary',- task: '__reset__'- })+ await setModelAssignment(+ {+ model: mainModel.model,+ provider: mainModel.provider,+ scope: 'auxiliary',+ task: '__reset__'+ },+ scopeProfile+ )setSwitchStaleAux([])await refresh()} catch (err) {@@ -748,7 +778,7 @@ export function ModelSettings({ onMainModelChanged }: ModelSettingsProps) {} finally {setApplying(false)}- }, [mainModel, refresh])+ }, [mainModel, refresh, scopeProfile])if (loading && !mainModel) {return <ModelSettingsSkeleton />diff --git a/apps/desktop/src/app/settings/profile-scope.test.tsx b/apps/desktop/src/app/settings/profile-scope.test.tsxnew file mode 100644index 00000000000..664cdc260cc--- /dev/null+++ b/apps/desktop/src/app/settings/profile-scope.test.tsx@@ -0,0 +1,68 @@+// @vitest-environment jsdom+import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { atom } from 'nanostores'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import type { ProfileInfo } from '@/types/hermes'++// Keep store/profile's side-effecting imports inert — same seam as+// store/profile.test.ts / profile-tag.test.tsx.+vi.mock('@/store/gateway', () => ({+ $gateway: atom<unknown>(null),+ ensureGatewayForAgent: vi.fn(async () => undefined),+ ensureGatewayForProfile: vi.fn(async () => undefined),+ openGatewayForProfile: vi.fn(async () => undefined)+}))+vi.mock('@/hermes', () => ({+ getProfiles: vi.fn(async () => ({ profiles: [] })),+ setApiRequestProfile: vi.fn()+}))+vi.mock('@/lib/query-client', () => ({ invalidateProfileScopedQueries: vi.fn() }))+vi.mock('@/store/starmap', () => ({ resetStarmapGraph: vi.fn() }))++const { $activeGatewayProfile, $profiles } = await import('@/store/profile')+const { $settingsScopeOverride } = await import('@/store/settings-scope')+const { SettingsProfileScope } = await import('./profile-scope')++const profile = (name: string, isDefault = false): ProfileInfo =>+ ({ has_env: false, is_default: isDefault, model: null, name }) as unknown as ProfileInfo++beforeEach(() => {+ $activeGatewayProfile.set('default')+ $settingsScopeOverride.set(null)+ $profiles.set([])+})++afterEach(cleanup)++describe('SettingsProfileScope', () => {+ it('renders nothing with fewer than two profiles', () => {+ $profiles.set([profile('default', true)])++ const { container } = render(<SettingsProfileScope />)+ expect(container.textContent).toBe('')+ })++ it('shows one chip per profile with the active profile selected by default', () => {+ $profiles.set([profile('default', true), profile('coder')])++ render(<SettingsProfileScope />)++ expect(screen.getByRole('button', { name: 'default' })).toBeTruthy()+ expect(screen.getByRole('button', { name: 'coder' })).toBeTruthy()+ // Following the active profile → no override, no "applies to X" note.+ expect($settingsScopeOverride.get()).toBeNull()+ })++ it('selecting another profile sets the shared override; re-selecting the active clears it', () => {+ $profiles.set([profile('default', true), profile('coder')])++ render(<SettingsProfileScope />)++ fireEvent.click(screen.getByRole('button', { name: 'coder' }))+ expect($settingsScopeOverride.get()).toBe('coder')++ fireEvent.click(screen.getByRole('button', { name: 'default' }))+ expect($settingsScopeOverride.get()).toBeNull()+ })+})diff --git a/apps/desktop/src/app/settings/profile-scope.tsx b/apps/desktop/src/app/settings/profile-scope.tsxnew file mode 100644index 00000000000..a256096e22e--- /dev/null+++ b/apps/desktop/src/app/settings/profile-scope.tsx@@ -0,0 +1,77 @@+import { useStore } from '@nanostores/react'+import { useEffect } from 'react'++import { useI18n } from '@/i18n'+import { cn } from '@/lib/utils'+import { $activeGatewayProfile, $profiles, normalizeProfileKey, refreshProfiles } from '@/store/profile'+import { $settingsScopeOverride, setSettingsScope } from '@/store/settings-scope'++// The same chip affordance the Gateway page uses for its per-profile+// connection overrides (gateway-settings ScopeChip). That one stays local to+// gateway-settings — its `null` chip means "all profiles", while here every+// chip is a concrete profile whose config the page edits.+export 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>+ )+}++/** Shared "Applies to" profile selector for the config-backed settings pages+ * (Model, Workspace, Safety, Memory & Context, Voice, Tools & Keys) and the+ * Messaging overlay. Backed by one nanostore ($settingsScopeOverride) so the+ * selection persists across pages. Hidden with fewer than two profiles, so+ * single-profile users never see it and every request keeps its unscoped+ * default shape. */+export function SettingsProfileScope({ className }: { className?: string }) {+ const { t } = useI18n()+ const scope = t.settings.profileScope+ const override = useStore($settingsScopeOverride)+ const active = useStore($activeGatewayProfile)+ const profiles = useStore($profiles)++ // Refresh lazily so a profile created elsewhere shows up; the cached list+ // paints immediately. Best-effort — a failure keeps the cached roster.+ useEffect(() => {+ void refreshProfiles().catch(() => undefined)+ }, [])++ if (profiles.length < 2) {+ return null+ }++ const selected = normalizeProfileKey(override ?? active)++ return (+ <div className={cn('grid gap-2', className)}>+ <div className="text-[length:var(--conversation-caption-font-size)] font-medium text-(--ui-text-secondary)">+ {scope.appliesTo}+ </div>+ <div className="flex flex-wrap gap-1.5">+ {profiles.map(profile => (+ <ScopeChip+ active={normalizeProfileKey(profile.name) === selected}+ key={profile.name}+ label={profile.name}+ onSelect={() => setSettingsScope(profile.name)}+ />+ ))}+ </div>+ {override !== null ? (+ <p className="text-[length:var(--conversation-caption-font-size)] leading-(--conversation-caption-line-height) text-(--ui-text-tertiary)">+ {scope.editsProfile(selected)}+ </p>+ ) : null}+ </div>+ )+}diff --git a/apps/desktop/src/app/settings/voice-provider-fields.tsx b/apps/desktop/src/app/settings/voice-provider-fields.tsxindex 9b3a2cdd1f5..62b422016a7 100644--- a/apps/desktop/src/app/settings/voice-provider-fields.tsx+++ b/apps/desktop/src/app/settings/voice-provider-fields.tsx@@ -37,7 +37,7 @@ export function VoiceProviderFields({ section, providerKey }: { section: 'tts' |const { data: schemaResponse } = useQuery({queryKey: ['hermes-config-schema'],- queryFn: getHermesConfigSchema,+ queryFn: () => getHermesConfigSchema(),staleTime: 5 * 60 * 1000})diff --git a/apps/desktop/src/hermes.ts b/apps/desktop/src/hermes.tsindex cf44f0e4781..2defd9e732a 100644--- a/apps/desktop/src/hermes.ts+++ b/apps/desktop/src/hermes.ts@@ -891,9 +891,9 @@ export function renameSession(})}-export function getGlobalModelInfo(): Promise<ModelInfoResponse> {+export function getGlobalModelInfo(profile?: null | string): Promise<ModelInfoResponse> {return window.hermesDesktop.api<ModelInfoResponse>({- ...profileScoped(),+ ...profileScoped(profile),path: '/api/model/info',timeoutMs: STARTUP_REQUEST_TIMEOUT_MS})@@ -966,16 +966,16 @@ export function getHermesConfigDefaults(): Promise<HermesConfigRecord> {})}-export function getHermesConfigSchema(): Promise<ConfigSchemaResponse> {+export function getHermesConfigSchema(profile?: null | string): Promise<ConfigSchemaResponse> {return window.hermesDesktop.api<ConfigSchemaResponse>({- ...profileScoped(),+ ...profileScoped(profile),path: '/api/config/schema'})}-export function saveHermesConfig(config: HermesConfigRecord): Promise<{ ok: boolean }> {+export function saveHermesConfig(config: HermesConfigRecord, profile?: null | string): Promise<{ ok: boolean }> {return window.hermesDesktop.api<{ ok: boolean }>({- ...profileScoped(),+ ...profileScoped(profile),path: '/api/config',method: 'PUT',body: { config }@@ -983,25 +983,29 @@ export function saveHermesConfig(config: HermesConfigRecord): Promise<{ ok: bool}// surface=declared serves the curated desktop schema; the dashboard consumes the raw plugin schema.-export function getMemoryProviderConfig(provider: string): Promise<MemoryProviderConfig> {+export function getMemoryProviderConfig(provider: string, profile?: null | string): Promise<MemoryProviderConfig> {return window.hermesDesktop.api<MemoryProviderConfig>({- ...profileScoped(),+ ...profileScoped(profile),path: `/api/memory/providers/${encodeURIComponent(provider)}/config?surface=declared`})}-export function saveMemoryProviderConfig(provider: string, values: Record<string, string>): Promise<{ ok: boolean }> {+export function saveMemoryProviderConfig(+ provider: string,+ values: Record<string, string>,+ profile?: null | string+): Promise<{ ok: boolean }> {return window.hermesDesktop.api<{ ok: boolean }>({- ...profileScoped(),+ ...profileScoped(profile),path: `/api/memory/providers/${encodeURIComponent(provider)}/config?surface=declared`,method: 'PUT',body: { values }})}-export function getEnvVars(): Promise<Record<string, EnvVarInfo>> {+export function getEnvVars(profile?: null | string): Promise<Record<string, EnvVarInfo>> {return window.hermesDesktop.api<Record<string, EnvVarInfo>>({- ...profileScoped(),+ ...profileScoped(profile),path: '/api/env'})}@@ -1140,17 +1144,23 @@ export function cancelOAuthSession(sessionId: string): Promise<{ ok: boolean }>// Memory-provider OAuth connect (provider-keyed; 404s for providers without an// OAuth flow). Profile-scoped: the grant lands in the active profile's config.-export function startMemoryProviderOAuth(provider: string): Promise<MemoryProviderOAuthStatus> {+export function startMemoryProviderOAuth(+ provider: string,+ profile?: null | string+): Promise<MemoryProviderOAuthStatus> {return window.hermesDesktop.api<MemoryProviderOAuthStatus>({- ...profileScoped(),+ ...profileScoped(profile),path: `/api/memory/providers/${encodeURIComponent(provider)}/oauth/start`,method: 'POST'})}-export function getMemoryProviderOAuthStatus(provider: string): Promise<MemoryProviderOAuthStatus> {+export function getMemoryProviderOAuthStatus(+ provider: string,+ profile?: null | string+): Promise<MemoryProviderOAuthStatus> {return window.hermesDesktop.api<MemoryProviderOAuthStatus>({- ...profileScoped(),+ ...profileScoped(profile),path: `/api/memory/providers/${encodeURIComponent(provider)}/oauth/status`})}@@ -1436,25 +1446,32 @@ export function grantComputerUsePermissions(): Promise<ActionResponse> {})}-export function getMessagingPlatforms(): Promise<MessagingPlatformsResponse> {+export function getMessagingPlatforms(profile?: null | string): Promise<MessagingPlatformsResponse> {return window.hermesDesktop.api<MessagingPlatformsResponse>({+ ...profileScoped(profile),path: '/api/messaging/platforms'})}export function updateMessagingPlatform(platformId: string,- body: MessagingPlatformUpdate+ body: MessagingPlatformUpdate,+ profile?: null | string): Promise<{ ok: boolean; platform: string }> {return window.hermesDesktop.api<{ ok: boolean; platform: string }>({+ ...profileScoped(profile),path: `/api/messaging/platforms/${encodeURIComponent(platformId)}`,method: 'PUT',body})}-export function testMessagingPlatform(platformId: string): Promise<MessagingPlatformTestResponse> {+export function testMessagingPlatform(+ platformId: string,+ profile?: null | string+): Promise<MessagingPlatformTestResponse> {return window.hermesDesktop.api<MessagingPlatformTestResponse>({+ ...profileScoped(profile),path: `/api/messaging/platforms/${encodeURIComponent(platformId)}/test`,method: 'POST'})@@ -1467,30 +1484,34 @@ export function testMessagingPlatform(platformId: string): Promise<MessagingPlat// returned by the API, while an authenticated admin is only ever identifying// a row they can already see.-export function getPairing(): Promise<PairingResponse> {+export function getPairing(profile?: null | string): Promise<PairingResponse> {return window.hermesDesktop.api<PairingResponse>({- ...profileScoped(),+ ...profileScoped(profile),path: '/api/pairing'})}-export function approvePairing(platform: string, requestId: string): Promise<{ ok: boolean; user: PairingUser }> {+export function approvePairing(+ platform: string,+ requestId: string,+ profile?: null | string+): Promise<{ ok: boolean; user: PairingUser }> {return window.hermesDesktop.api<{ ok: boolean; user: PairingUser }>({- ...profileScoped(),+ ...profileScoped(profile),path: '/api/pairing/approve',method: 'POST',// These endpoints read the profile off the body, not the query string —// `profileScoped()` alone would approve into the wrong profile's store.- body: { platform, request_id: requestId, ...profileScoped() }+ body: { platform, request_id: requestId, ...profileScoped(profile) }})}-export function revokePairing(platform: string, userId: string): Promise<{ ok: boolean }> {+export function revokePairing(platform: string, userId: string, profile?: null | string): Promise<{ ok: boolean }> {return window.hermesDesktop.api<{ ok: boolean }>({- ...profileScoped(),+ ...profileScoped(profile),path: '/api/pairing/revoke',method: 'POST',- body: { platform, user_id: userId, ...profileScoped() }+ body: { platform, user_id: userId, ...profileScoped(profile) }})}@@ -1767,11 +1788,14 @@ export function getUsageAnalytics(days = 30, profile?: null | string): Promise<A})}-export function getGlobalModelOptions(opts?: {- refresh?: boolean- includeUnconfigured?: boolean- explicitOnly?: boolean-}): Promise<ModelOptionsResponse> {+export function getGlobalModelOptions(+ opts?: {+ refresh?: boolean+ includeUnconfigured?: boolean+ explicitOnly?: boolean+ },+ profile?: null | string+): Promise<ModelOptionsResponse> {const params = new URLSearchParams()if (opts?.refresh) {@@ -1787,7 +1811,7 @@ export function getGlobalModelOptions(opts?: {}return window.hermesDesktop.api<ModelOptionsResponse>({- ...profileScoped(),+ ...profileScoped(profile),path: params.size > 0 ? `/api/model/options?${params.toString()}` : '/api/model/options',timeoutMs: STARTUP_REQUEST_TIMEOUT_MS})@@ -1803,9 +1827,12 @@ export interface RecommendedDefaultModel {// Recommended default model for a freshly-authenticated provider. Mirrors the// curation `hermes model` does — for Nous it honors the free/paid tier so a// free user gets a free model instead of a paid default.-export function getRecommendedDefaultModel(provider: string): Promise<RecommendedDefaultModel> {+export function getRecommendedDefaultModel(+ provider: string,+ profile?: null | string+): Promise<RecommendedDefaultModel> {return window.hermesDesktop.api<RecommendedDefaultModel>({- ...profileScoped(),+ ...profileScoped(profile),path: `/api/model/recommended-default?provider=${encodeURIComponent(provider)}`})}@@ -1826,32 +1853,38 @@ export function setGlobalModel(})}-export function getAuxiliaryModels(): Promise<AuxiliaryModelsResponse> {+export function getAuxiliaryModels(profile?: null | string): Promise<AuxiliaryModelsResponse> {return window.hermesDesktop.api<AuxiliaryModelsResponse>({- ...profileScoped(),+ ...profileScoped(profile),path: '/api/model/auxiliary'})}-export function getMoaModels(): Promise<MoaConfigResponse> {+export function getMoaModels(profile?: null | string): Promise<MoaConfigResponse> {return window.hermesDesktop.api<MoaConfigResponse>({- ...profileScoped(),+ ...profileScoped(profile),path: '/api/model/moa'})}-export function saveMoaModels(body: MoaConfigResponse): Promise<MoaConfigResponse & { ok: boolean }> {+export function saveMoaModels(+ body: MoaConfigResponse,+ profile?: null | string+): Promise<MoaConfigResponse & { ok: boolean }> {return window.hermesDesktop.api<MoaConfigResponse & { ok: boolean }>({- ...profileScoped(),+ ...profileScoped(profile),path: '/api/model/moa',method: 'PUT',body})}-export function setModelAssignment(body: ModelAssignmentRequest): Promise<ModelAssignmentResponse> {+export function setModelAssignment(+ body: ModelAssignmentRequest,+ profile?: null | string+): Promise<ModelAssignmentResponse> {return window.hermesDesktop.api<ModelAssignmentResponse>({- ...profileScoped(),+ ...profileScoped(profile),path: '/api/model/set',method: 'POST',body@@ -1920,10 +1953,10 @@ export function speakText(text: string): Promise<AudioSpeakResponse> {})}-export function getElevenLabsVoices(): Promise<ElevenLabsVoicesResponse> {+export function getElevenLabsVoices(profile?: null | string): Promise<ElevenLabsVoicesResponse> {return window.hermesDesktop.api<ElevenLabsVoicesResponse>({path: '/api/audio/elevenlabs/voices',- ...profileScoped()+ ...profileScoped(profile)})}diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex 02da8ff3b7a..36a4cc98b47 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -753,6 +753,10 @@ export const ar = defineLocale({failedLoad: 'فشل تحميل مفاتيح API',empty: 'لا يوجد شيء مضبوط في هذه الفئة بعد.'},+ profileScope: {+ appliesTo: 'ينطبق على',+ editsProfile: profile => `تنطبق التغييرات في هذه الصفحة على الملف الشخصي «${profile}».`+ },mcp: {loading: 'جار تحميل خوادم MCP...',failedLoad: 'فشل تحميل إعدادات MCP',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 0076cdc8a59..70ef7e6d393 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -864,6 +864,10 @@ export const en: Translations = {failedLoad: 'API keys failed to load',empty: 'Nothing configured in this category yet.'},+ profileScope: {+ appliesTo: 'Applies to',+ editsProfile: profile => `Changes on this page apply to the “${profile}” profile.`+ },mcp: {loading: 'Loading MCP servers...',failedLoad: 'MCP config failed to load',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex eb77073033c..149a3edadbe 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -853,6 +853,10 @@ export const ja = defineLocale({failedLoad: 'API キーの読み込みに失敗しました',empty: 'このカテゴリーにはまだ設定がありません。'},+ profileScope: {+ appliesTo: '適用対象',+ editsProfile: profile => `このページの変更は「${profile}」プロファイルに適用されます。`+ },mcp: {loading: 'MCP サーバーを読み込み中...',failedLoad: 'MCP 設定の読み込みに失敗しました',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 32a7595161a..cf025edf906 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -734,6 +734,10 @@ export interface Translations {failedLoad: stringempty: string}+ profileScope: {+ appliesTo: string+ editsProfile: (profile: string) => string+ }mcp: {loading: stringfailedLoad: stringdiff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex c4e95d1c3ff..257fd14036c 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -827,6 +827,10 @@ export const zhHant = defineLocale({failedLoad: 'API 金鑰載入失敗',empty: '此類別尚未有任何設定。'},+ profileScope: {+ appliesTo: '套用至',+ editsProfile: profile => `此頁面的變更將套用至「${profile}」設定檔。`+ },mcp: {loading: '正在載入 MCP 伺服器...',failedLoad: 'MCP 設定載入失敗',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 8fc390973cb..d567c129139 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -1061,6 +1061,10 @@ export const zh: Translations = {failedLoad: 'API 密钥加载失败',empty: '此类别暂时没有配置项。'},+ profileScope: {+ appliesTo: '应用于',+ editsProfile: profile => `此页面的更改将应用于“${profile}”配置文件。`+ },mcp: {loading: '正在加载 MCP 服务器...',failedLoad: 'MCP 配置加载失败',diff --git a/apps/desktop/src/store/cron-model-impact.ts b/apps/desktop/src/store/cron-model-impact.tsindex 88d7467edfc..67ef8696415 100644--- a/apps/desktop/src/store/cron-model-impact.ts+++ b/apps/desktop/src/store/cron-model-impact.ts@@ -145,16 +145,29 @@ function publishImpact(impact: CronModelImpact, profile: string, connection: str}export async function setMainModelAssignment(- request: Omit<ModelAssignmentRequest, 'scope'>+ request: Omit<ModelAssignmentRequest, 'scope'>,+ scopeProfile?: null | string): Promise<ModelAssignmentResponse> {const { connection, generation } = beginCronModelImpactAssignment()const profile = profileIdentity()- const result = await setModelAssignment({ ...request, scope: 'main' })+ // Only pass the extra arg when a scope override exists, so unscoped callers+ // keep the exact legacy call shape.+ const result =+ scopeProfile == null+ ? await setModelAssignment({ ...request, scope: 'main' })+ : await setModelAssignment({ ...request, scope: 'main' }, scopeProfile)if (result.ok !== true) {throw new Error(result.confirm_message?.trim() || translateNow('cron.modelImpact.saveFailed'))}+ // A scoped assignment targets ANOTHER profile's backend: its cron impact+ // belongs to that profile, and the review action would open the ACTIVE+ // profile's cron view — skip the warning rather than mis-route it.+ if (scopeProfile != null) {+ return result+ }+if (!currentResponseScope(profile, connection, generation)) {return result}diff --git a/apps/desktop/src/store/settings-scope.test.ts b/apps/desktop/src/store/settings-scope.test.tsnew file mode 100644index 00000000000..85824a91c27--- /dev/null+++ b/apps/desktop/src/store/settings-scope.test.ts@@ -0,0 +1,72 @@+import { atom } from 'nanostores'+import { beforeEach, describe, expect, it, vi } from 'vitest'++// Keep store/profile's side-effecting imports inert — same seam as+// store/profile.test.ts.+vi.mock('@/store/gateway', () => ({+ $gateway: atom<unknown>(null),+ ensureGatewayForAgent: vi.fn(async () => undefined),+ ensureGatewayForProfile: vi.fn(async () => undefined),+ openGatewayForProfile: vi.fn(async () => undefined)+}))+vi.mock('@/hermes', () => ({+ getProfiles: vi.fn(async () => ({ profiles: [] })),+ setApiRequestProfile: vi.fn()+}))+vi.mock('@/lib/query-client', () => ({ invalidateProfileScopedQueries: vi.fn() }))+vi.mock('@/store/starmap', () => ({ resetStarmapGraph: vi.fn() }))++const { $activeGatewayProfile } = await import('./profile')+const { $settingsScopeOverride, $settingsScopeProfile, setSettingsScope } = await import('./settings-scope')++beforeEach(() => {+ $activeGatewayProfile.set('default')+ $settingsScopeOverride.set(null)+})++describe('settings scope store', () => {+ it('defaults to following the active gateway profile (no override)', () => {+ expect($settingsScopeOverride.get()).toBeNull()+ expect($settingsScopeProfile.get()).toBe('default')++ $activeGatewayProfile.set('coder')+ expect($settingsScopeProfile.get()).toBe('coder')+ })++ it('stores a concrete override when a non-active profile is selected', () => {+ setSettingsScope('research')++ expect($settingsScopeOverride.get()).toBe('research')+ expect($settingsScopeProfile.get()).toBe('research')+ })++ it('selecting the active profile clears the override instead of pinning it', () => {+ setSettingsScope('research')+ setSettingsScope('default')++ // No override → requests keep their unscoped shape and the scope keeps+ // following the app on future profile switches.+ expect($settingsScopeOverride.get()).toBeNull()+ expect($settingsScopeProfile.get()).toBe('default')+ })++ it('normalizes empty/blank names to the default profile key', () => {+ $activeGatewayProfile.set('coder')+ setSettingsScope('')++ expect($settingsScopeOverride.get()).toBe('default')+ expect($settingsScopeProfile.get()).toBe('default')+ })++ it('drops the override on an app-wide profile switch', () => {+ setSettingsScope('research')+ expect($settingsScopeOverride.get()).toBe('research')++ // The app re-homes to another profile: a surviving override would keep+ // settings edits silently pointed at the previous target.+ $activeGatewayProfile.set('coder')++ expect($settingsScopeOverride.get()).toBeNull()+ expect($settingsScopeProfile.get()).toBe('coder')+ })+})diff --git a/apps/desktop/src/store/settings-scope.ts b/apps/desktop/src/store/settings-scope.tsnew file mode 100644index 00000000000..0c079bb7ff9--- /dev/null+++ b/apps/desktop/src/store/settings-scope.ts@@ -0,0 +1,41 @@+import { atom, computed } from 'nanostores'++import { $activeGatewayProfile, normalizeProfileKey } from '@/store/profile'++// ── Shared settings "Applies to" scope ──────────────────────────────────────+// One selection shared by every config-backed settings page (Model, Workspace,+// Safety, Memory & Context, Voice, Tools & Keys) and the Messaging overlay, so+// picking a profile on one page carries to the next instead of resetting per+// page. `null` means "follow the app's active profile" — the default, which+// keeps single-profile users on the exact pre-existing code path (requests+// fall back to the app-wide active profile in hermes.ts `profileScoped`).+export const $settingsScopeOverride = atom<null | string>(null)++// The profile the settings pages are currently editing (a concrete key).+export const $settingsScopeProfile = computed([$settingsScopeOverride, $activeGatewayProfile], (override, active) =>+ normalizeProfileKey(override ?? active)+)++// Select the profile the settings pages should edit. Picking the app's active+// profile stores `null` (no override) so the scope keeps following the app on+// profile switches — and requests keep their unscoped default shape.+export function setSettingsScope(name: string): void {+ const key = normalizeProfileKey(name)++ $settingsScopeOverride.set(key === normalizeProfileKey($activeGatewayProfile.get()) ? null : key)+}++// An app-wide profile switch re-homes every settings surface to the new+// backend; a surviving override would silently keep edits pointed at the+// previous target. Same drop-the-override contract as the Capabilities+// selector (app/skills useOnProfileSwitch).+let lastActiveProfile = normalizeProfileKey($activeGatewayProfile.get())++$activeGatewayProfile.subscribe(value => {+ const key = normalizeProfileKey(value)++ if (key !== lastActiveProfile) {+ lastActiveProfile = key+ $settingsScopeOverride.set(null)+ }+})