Skip to content

The agent that grows with you

fix: keep desktop provider setup within its selected profile

Teknium0b3391322ca2
diff --git a/apps/desktop/src/api/config.ts b/apps/desktop/src/api/config.ts
index 2906c34d871..88c63ada611 100644
--- a/apps/desktop/src/api/config.ts
+++ b/apps/desktop/src/api/config.ts
@@ -198,16 +198,16 @@ export function deleteCustomEndpoint(id: string): Promise<CustomEndpointsRespons
})
}
-export function listOAuthProviders(): Promise<OAuthProvidersResponse> {
+export function listOAuthProviders(profile?: null | string): Promise<OAuthProvidersResponse> {
return hermesApi<OAuthProvidersResponse>({
- ...profileScoped(),
+ ...profileScoped(profile),
path: '/api/providers/oauth'
})
}
-export function disconnectOAuthProvider(providerId: string): Promise<{ ok: boolean; provider: string }> {
+export function disconnectOAuthProvider(providerId: string, profile?: null | string): Promise<{ ok: boolean; provider: string }> {
return hermesApi<{ ok: boolean; provider: string }>({
- ...profileScoped(),
+ ...profileScoped(profile),
path: `/api/providers/oauth/${encodeURIComponent(providerId)}`,
method: 'DELETE'
})
@@ -222,9 +222,9 @@ export function startOAuthLogin(providerId: string, profile?: ProfileScope): Pro
})
}
-export function submitOAuthCode(providerId: string, sessionId: string, code: string): Promise<OAuthSubmitResponse> {
+export function submitOAuthCode(providerId: string, sessionId: string, code: string, profile?: null | string): Promise<OAuthSubmitResponse> {
return hermesApi<OAuthSubmitResponse>({
- ...profileScoped(),
+ ...profileScoped(profile),
path: `/api/providers/oauth/${encodeURIComponent(providerId)}/submit`,
method: 'POST',
body: { session_id: sessionId, code }
@@ -242,9 +242,9 @@ export function pollOAuthSession(
})
}
-export function cancelOAuthSession(sessionId: string): Promise<{ ok: boolean }> {
+export function cancelOAuthSession(sessionId: string, profile?: null | string): Promise<{ ok: boolean }> {
return hermesApi<{ ok: boolean }>({
- ...profileScoped(),
+ ...profileScoped(profile),
path: `/api/providers/oauth/sessions/${encodeURIComponent(sessionId)}`,
method: 'DELETE'
})
diff --git a/apps/desktop/src/app/settings/index.tsx b/apps/desktop/src/app/settings/index.tsx
index 38a6bf0e377..c019f82b433 100644
--- a/apps/desktop/src/app/settings/index.tsx
+++ b/apps/desktop/src/app/settings/index.tsx
@@ -34,6 +34,7 @@ import { confirm } from '@/store/confirm'
import { bindingsFor } from '@/store/keybinds'
import { $localModelsEnabled } from '@/store/local-models-flag'
import { notifyError } from '@/store/notifications'
+import { $settingsScopeProfile } from '@/store/settings-scope'
import { useRouteEnumParam } from '../hooks/use-route-enum-param'
import { OverlayIconButton } from '../overlays/overlay-chrome'
@@ -72,6 +73,7 @@ const SETTINGS_VIEWS: readonly SettingsViewId[] = [
]
export function SettingsView({ onClose, onConfigSaved, onMainModelChanged }: SettingsPageProps) {
+ const scopeProfile = useStore($settingsScopeProfile)
const { t } = useI18n()
const navigate = useNavigate()
const { hash, pathname, search } = useLocation()
@@ -407,6 +409,7 @@ export function SettingsView({ onClose, onConfigSaved, onMainModelChanged }: Set
/>
) : activeView === 'providers' ? (
<ProvidersSettings
+ key={scopeProfile}
onClose={onClose}
onConfigSaved={onConfigSaved}
onMainModelChanged={onMainModelChanged}
diff --git a/apps/desktop/src/app/settings/providers-settings.test.tsx b/apps/desktop/src/app/settings/providers-settings.test.tsx
index d7587f69b2d..e3c8f5947e7 100644
--- a/apps/desktop/src/app/settings/providers-settings.test.tsx
+++ b/apps/desktop/src/app/settings/providers-settings.test.tsx
@@ -14,18 +14,25 @@ const startManualProviderOAuth = vi.fn()
const startManualLocalEndpoint = vi.fn()
const onboarding = atom({ manual: false })
+vi.mock('@/store/profile', () => ({
+ $activeGatewayProfile: atom('alpha'),
+ $profiles: atom([]),
+ refreshProfiles: async () => {},
+ normalizeProfileKey: (p: string | null) => p || 'default'
+}))
+
vi.mock('@/hermes', () => ({
setApiRequestProfile: vi.fn(),
getProfiles: async () => ({ profiles: (await import('@/store/profile')).$profiles.get() }),
- disconnectOAuthProvider: (providerId: string) => disconnectOAuthProvider(providerId),
- getEnvVars: (profile?: string) => getEnvVars(profile),
setEnvVar: (key: string, value: string, profile?: string) => setEnvVar(key, value, profile),
- listOAuthProviders: () => listOAuthProviders()
+ disconnectOAuthProvider: (...args: unknown[]) => disconnectOAuthProvider(...args),
+ getEnvVars: (...args: unknown[]) => getEnvVars(...args),
+ listOAuthProviders: (...args: unknown[]) => listOAuthProviders(...args)
}))
vi.mock('@/store/onboarding', () => ({
$desktopOnboarding: onboarding,
- startManualProviderOAuth: (providerId: string) => startManualProviderOAuth(providerId),
+ startManualProviderOAuth: (...args: unknown[]) => startManualProviderOAuth(...args),
startManualLocalEndpoint: (reason: null | string) => startManualLocalEndpoint(reason)
}))
@@ -135,6 +142,25 @@ describe('ProvidersSettings', () => {
$profiles.set([])
}
})
+
+ it('uses the settings target for account reads, removal and sign-in', async () => {
+ const { $settingsScopeOverride } = await import('@/store/settings-scope')
+ $settingsScopeOverride.set('beta')
+
+ try {
+ await renderProvidersSettings()
+ expect(getEnvVars).toHaveBeenCalledWith('beta')
+ expect(listOAuthProviders).toHaveBeenCalledWith('beta')
+ fireEvent.click(await screen.findByText('Nous Portal'))
+ expect(startManualProviderOAuth).toHaveBeenCalledWith('nous', 'beta')
+ fireEvent.click(await screen.findByRole('button', { name: 'Remove Nous Portal' }))
+ fireEvent.click(await screen.findByRole('button', { name: 'Disconnect' }))
+ await waitFor(() => expect(disconnectOAuthProvider).toHaveBeenCalledWith('nous', 'beta'))
+ } finally {
+ $settingsScopeOverride.set(null)
+ }
+ })
+
it('disconnects a connected provider account and refreshes the accounts list', async () => {
await renderProvidersSettings()
@@ -151,7 +177,7 @@ describe('ProvidersSettings', () => {
fireEvent.click(screen.getByRole('button', { name: 'Disconnect' }))
})
- await waitFor(() => expect(disconnectOAuthProvider).toHaveBeenCalledWith('nous'))
+ await waitFor(() => expect(disconnectOAuthProvider).toHaveBeenCalledWith('nous', undefined))
expect(listOAuthProviders).toHaveBeenCalledTimes(2)
})
@@ -176,7 +202,7 @@ describe('ProvidersSettings', () => {
fireEvent.click(await screen.findByText('Nous Portal'))
})
- expect(startManualProviderOAuth).toHaveBeenCalledWith('nous')
+ expect(startManualProviderOAuth).toHaveBeenCalledWith('nous', undefined)
expect(disconnectOAuthProvider).not.toHaveBeenCalled()
})
diff --git a/apps/desktop/src/app/settings/providers-settings.tsx b/apps/desktop/src/app/settings/providers-settings.tsx
index 0417431898d..86562e26cb2 100644
--- a/apps/desktop/src/app/settings/providers-settings.tsx
+++ b/apps/desktop/src/app/settings/providers-settings.tsx
@@ -135,7 +135,8 @@ function OAuthPicker({
onTerminalDisconnect,
onWantApiKey,
onWantLocalModels,
- providers
+ providers,
+ profile
}: {
disconnecting: null | string
onDisconnect: (provider: OAuthProvider) => void
@@ -143,6 +144,7 @@ function OAuthPicker({
onWantApiKey: () => void
onWantLocalModels: () => void
providers: OAuthProvider[]
+ profile?: string
}) {
const { t } = useI18n()
const p = t.settings.providers
@@ -153,7 +155,7 @@ function OAuthPicker({
return null
}
- const select = (p: OAuthProvider) => startManualProviderOAuth(p.id)
+ const select = (p: OAuthProvider) => startManualProviderOAuth(p.id, profile)
const featured = ordered.find(p => p.id === FEATURED_ID && !p.status?.logged_in) ?? null
const rest = featured ? ordered.filter(p => p.id !== FEATURED_ID) : ordered
@@ -349,7 +351,6 @@ export function ProvidersSettings({
view
}: ProvidersSettingsProps) {
const { t } = useI18n()
- // Match the shared Settings target for credential reads and writes.
const scopeProfile = useStore($settingsRequestProfile)
const { rowProps, vars } = useEnvCredentials(scopeProfile)
const [oauthProviders, setOauthProviders] = useState<OAuthProvider[]>([])
@@ -364,9 +365,9 @@ export function ProvidersSettings({
const refreshOAuthProviders = useCallback(async () => {
// OAuth providers are best-effort — a failure here just hides the panel.
- const { providers } = await listOAuthProviders()
+ const { providers } = await listOAuthProviders(scopeProfile)
setOauthProviders(providers)
- }, [])
+ }, [scopeProfile])
useEffect(() => {
let cancelled = false
@@ -377,7 +378,7 @@ export function ProvidersSettings({
}
try {
- const { providers } = await listOAuthProviders()
+ const { providers } = await listOAuthProviders(scopeProfile)
if (!cancelled) {
setOauthProviders(providers)
@@ -388,7 +389,7 @@ export function ProvidersSettings({
})()
return () => void (cancelled = true)
- }, [onboardingActive])
+ }, [onboardingActive, scopeProfile])
// External (CLI-managed) providers can't be cleared via the API by design —
// Hermes never deletes creds another tool owns behind a silent API call.
@@ -439,7 +440,7 @@ export function ProvidersSettings({
setDisconnecting(provider.id)
try {
- await disconnectOAuthProvider(provider.id)
+ await disconnectOAuthProvider(provider.id, scopeProfile)
notify({
durationMs: 3_000,
kind: 'success',
@@ -479,7 +480,7 @@ export function ProvidersSettings({
return (
<SettingsContent>
<SettingsProfileScope className="mb-5" />
- <LocalEndpointRow onOpen={startManualLocalEndpoint} />
+ <LocalEndpointRow onOpen={reason => startManualLocalEndpoint(reason, scopeProfile)} />
{keyGroups.length > 0 ? (
<div className="grid gap-3">
<SearchField
@@ -528,12 +529,14 @@ export function ProvidersSettings({
return (
<SettingsContent>
+ <SettingsProfileScope className="mb-5" />
<OAuthPicker
disconnecting={disconnecting}
onDisconnect={provider => void handleDisconnect(provider)}
onTerminalDisconnect={provider => void handleTerminalDisconnect(provider)}
onWantApiKey={() => onViewChange('keys')}
onWantLocalModels={() => onViewChange('local')}
+ profile={scopeProfile}
providers={oauthProviders}
/>
</SettingsContent>
diff --git a/apps/desktop/src/components/onboarding/index.tsx b/apps/desktop/src/components/onboarding/index.tsx
index def3899a8cf..64ccd7f4c65 100644
--- a/apps/desktop/src/components/onboarding/index.tsx
+++ b/apps/desktop/src/components/onboarding/index.tsx
@@ -50,6 +50,8 @@ export {
sortProviders
} from './providers'
+import { requestGatewayForProfile } from '@/store/gateway'
+
interface DesktopOnboardingOverlayProps {
enabled: boolean
onCompleted?: () => void
@@ -191,19 +193,18 @@ export function DesktopOnboardingOverlay({
const { t } = useI18n()
const onboarding = useStore($desktopOnboarding)
const boot = useStore($desktopBoot)
- const ctxRef = useRef<OnboardingContext>({ requestGateway, onCompleted, profile })
- ctxRef.current = { requestGateway, onCompleted, profile }
-
- const ctx = useMemo<OnboardingContext>(
- () => ({
- requestGateway: (...args) => ctxRef.current.requestGateway(...args),
- onCompleted: () => ctxRef.current.onCompleted?.(),
- get profile() {
- return ctxRef.current.profile
- }
- }),
- []
- )
+ const onCompletedRef = useRef(onCompleted)
+ onCompletedRef.current = onCompleted
+ const targetProfile = onboarding.targetProfile ?? profile
+
+ // Async flows retain the initiating route even after the overlay closes.
+ const ctx = useMemo<OnboardingContext>(() => ({
+ profile: targetProfile,
+ requestGateway: onboarding.targetProfile
+ ? (method, params) => requestGatewayForProfile(targetProfile, method, params)
+ : requestGateway,
+ onCompleted: () => onCompletedRef.current?.()
+ }), [onboarding.targetProfile, targetProfile, requestGateway])
// Cinematic exit on "Begin": dissolve the panel + overlay (revealing the chat
// behind), THEN finalize so the unmount lands after the fade — mirrors the
diff --git a/apps/desktop/src/store/onboarding.test.ts b/apps/desktop/src/store/onboarding.test.ts
index d836020cb94..740a1659be2 100644
--- a/apps/desktop/src/store/onboarding.test.ts
+++ b/apps/desktop/src/store/onboarding.test.ts
@@ -80,6 +80,66 @@ function fallbackTimeoutGateway(): OnboardingContext['requestGateway'] {
}
describe('refreshOnboarding', () => {
+ it('keeps onboarding work in its initiating lifetime and profile', async () => {
+ const { startManualOnboarding, startProviderOAuth, saveOnboardingApiKey, closeManualOnboarding } = await import('./onboarding')
+ const requests: { path: string; profile?: string }[] = []
+ let release!: () => void
+ let delayKey = true
+ installApiMock(async request => {
+ requests.push(request)
+
+ if (request.path === '/api/providers/oauth') { return { providers: [] } }
+
+ if (request.path.endsWith('/start')) {
+ return { flow: 'device_code', session_id: 'local-fixture', user_code: 'FAKE', verification_url: 'http://localhost/fixture', expires_in: 600 }
+ }
+
+ if (request.path.includes('/poll/')) { return { status: 'approved' } }
+
+ if (request.path === '/api/env' && delayKey) { await new Promise<void>(resolve => { release = resolve }) }
+
+ if (request.path.startsWith('/api/model/options')) {
+ return { providers: [{ slug: 'fixture', name: 'Fixture', models: ['fixture-model'] }] }
+ }
+
+ if (request.path.startsWith('/api/model/recommended-default')) { return { model: 'fixture-model' } }
+
+ return { ok: true }
+ })
+ vi.spyOn(window, 'open').mockReturnValue(null)
+ let profile = 'beta'
+
+ const ctx: OnboardingContext = {
+ get profile() { return profile },
+ requestGateway: async method => (method === 'setup.status' ? { provider_configured: true } : { ok: true }) as never
+ }
+
+ try {
+ startManualOnboarding(null, 'beta')
+ const pending = saveOnboardingApiKey('FIREWORKS_API_KEY', 'fake-key', 'Fireworks', ctx)
+ await vi.waitFor(() => expect(release).toBeTypeOf('function'))
+ closeManualOnboarding()
+ profile = 'alpha'
+ startManualOnboarding(null, 'alpha')
+ release()
+ await pending
+ expect(requests.some(r => r.path === '/api/model/set')).toBe(false)
+ expect($desktopOnboarding.get()).toMatchObject({ targetProfile: 'alpha', flow: { status: 'idle' } })
+ closeManualOnboarding()
+ delayKey = false
+ profile = 'beta'
+ startManualOnboarding(null, 'beta')
+ const startAt = requests.length
+ await startProviderOAuth(makeOAuthProvider('fixture'), ctx)
+ await vi.waitFor(() => expect($desktopOnboarding.get().flow.status).toBe('confirming_model'), { timeout: 5000 })
+ expect(requests.slice(startAt).some(r => r.path.includes('/poll/'))).toBe(true)
+ expect(requests.slice(startAt).some(r => r.path === '/api/model/set')).toBe(true)
+ expect(requests.slice(startAt).every(r => r.profile === 'beta')).toBe(true)
+ } finally {
+ closeManualOnboarding()
+ }
+ })
+
beforeEach(() => {
window.localStorage.clear()
$desktopOnboarding.set(baseState())
diff --git a/apps/desktop/src/store/onboarding.ts b/apps/desktop/src/store/onboarding.ts
index 9108041503a..ae58ba58f6d 100644
--- a/apps/desktop/src/store/onboarding.ts
+++ b/apps/desktop/src/store/onboarding.ts
@@ -69,6 +69,7 @@ export interface DesktopOnboardingState {
* picker's "Add provider" button). Forces the overlay to show the picker
* even when configured === true, and adds a close affordance. */
manual: boolean
+ targetProfile?: string
/** True when the overlay was opened specifically to configure a local /
* custom OpenAI-compatible endpoint (e.g. from Settings → Model's "Set up
* custom endpoint"). Forces the API-key form with the local option
@@ -159,6 +160,8 @@ const INITIAL: DesktopOnboardingState = {
export const $desktopOnboarding = atom<DesktopOnboardingState>(INITIAL)
+let flowGeneration = 0
+let flowProfile: string | undefined
let pollTimer: number | null = null
let providersRefreshPromise: null | Promise<void> = null
@@ -260,12 +263,13 @@ function notifyGatewayTools(tools: string[] | undefined) {
// we had before, which works but is surprising. The confirm step is
// opportunistic polish, not a hard requirement for onboarding.
async function fetchProviderDefaultModel(
- preferredSlugs: string[]
+ preferredSlugs: string[],
+ profile?: string
): Promise<null | { providerSlug: string; defaultModel: string }> {
let options
try {
- options = await getGlobalModelOptions({ includeUnconfigured: true, explicitOnly: false })
+ options = await getGlobalModelOptions({ includeUnconfigured: true, explicitOnly: false }, profile)
} catch {
return null
}
@@ -297,7 +301,7 @@ async function fetchProviderDefaultModel(
let defaultModel = String(models[0])
try {
- const recommended = await getRecommendedDefaultModel(String(matched.slug))
+ const recommended = await getRecommendedDefaultModel(String(matched.slug), profile)
if (recommended.model && models.map(String).includes(recommended.model)) {
defaultModel = recommended.model
@@ -334,9 +338,13 @@ async function completeWithModelConfirm(
// where we intentionally don't validate the key (it blocked too many users).
ignoreRuntimeGate = false
) {
+ const generation = flowGeneration
await ctx.requestGateway('reload.env').catch(() => undefined)
- const defaults = await fetchProviderDefaultModel(preferredSlugs)
+ if (generation !== flowGeneration) { return }
+ const defaults = await fetchProviderDefaultModel(preferredSlugs, ctx.profile)
+
+ if (generation !== flowGeneration) { return }
if (defaults) {
// Persist the chosen provider/model before the runtime gate so a stale
@@ -348,14 +356,16 @@ async function completeWithModelConfirm(
provider: defaults.providerSlug,
model: defaults.defaultModel
},
- undefined,
+ ctx.profile,
// Headless automated flow: nothing is mounted to click a guard
// prompt, so fail with the message instead of hanging.
{ skipConfirmPrompt: true }
)
+ if (generation !== flowGeneration) { return }
notifyGatewayTools(res.gateway_tools)
} catch (error) {
+ if (generation !== flowGeneration) { return }
onFail(error instanceof Error ? error.message : 'Hermes could not save the selected model.')
return
@@ -364,6 +374,8 @@ async function completeWithModelConfirm(
const runtime = await checkRuntime(ctx, preferredSlugs[0])
+ if (generation !== flowGeneration) { return }
+
if (!runtime.ready && !ignoreRuntimeGate) {
onFail(runtime.reason)
@@ -403,14 +415,18 @@ async function refreshProviders() {
return
}
+ const generation = flowGeneration
providersRefreshPromise = (async () => {
try {
- const { providers } = await listOAuthProviders()
+ const { providers } = await listOAuthProviders($desktopOnboarding.get().targetProfile)
+
+ if (generation !== flowGeneration) { return }
patch({ mode: providers.length > 0 ? 'oauth' : 'apikey', providers })
} catch {
+ if (generation !== flowGeneration) { return }
patch({ mode: 'apikey', providers: [] })
} finally {
- providersRefreshPromise = null
+ if (generation === flowGeneration) { providersRefreshPromise = null }
}
})()
@@ -460,9 +476,13 @@ export function consumePendingCredentialWarning(): null | string {
// onboarding flow (OAuth rows, API-key form, model-confirm) instead of
// duplicating provider UI. Sets manual=true so the overlay shows the picker
// even though configured===true, and refreshes the provider list.
-export function startManualOnboarding(reason: null | string = DEFAULT_MANUAL_ONBOARDING_REASON) {
+export function startManualOnboarding(reason: null | string = DEFAULT_MANUAL_ONBOARDING_REASON, profile?: string) {
+ cancelOnboardingFlow()
+ providersRefreshPromise = null
patch({
manual: true,
+ targetProfile: profile,
+ providers: null,
requested: true,
localEndpoint: false,
// `null` opts out of the prompt banner entirely (e.g. when the user already
@@ -479,10 +499,13 @@ export function startManualOnboarding(reason: null | string = DEFAULT_MANUAL_ONB
// configure the endpoint instead of dead-ending on the OAuth provider list
// (`custom` is not an OAuth provider, so the generic manual flow would just
// re-show the picker — the original "booted back to the first screen" loop).
-export function startManualLocalEndpoint(reason: null | string = null) {
+export function startManualLocalEndpoint(reason: null | string = null, profile?: string) {
+ cancelOnboardingFlow()
pendingProviderOAuthId = null
patch({
manual: true,
+ targetProfile: profile,
+ providers: null,
requested: true,
localEndpoint: true,
mode: 'apikey',
@@ -499,9 +522,9 @@ export function startManualLocalEndpoint(reason: null | string = null) {
// overlay render and never needs to persist or re-render anything itself.
let pendingProviderOAuthId: null | string = null
-export function startManualProviderOAuth(providerId: string, reason: null | string = null) {
+export function startManualProviderOAuth(providerId: string, profile?: string) {
pendingProviderOAuthId = providerId
- startManualOnboarding(reason)
+ startManualOnboarding(null, profile)
}
// Read the pending provider id without clearing it. The overlay only clears it
@@ -520,9 +543,11 @@ export function clearPendingProviderOAuth() {
// (working) configuration. Only valid in the manual path — the unconfigured
// first-run flow has no close affordance because the app can't run yet.
export function closeManualOnboarding() {
+ cancelOnboardingFlow()
+ providersRefreshPromise = null
pendingProviderOAuthId = null
- patch({ manual: false, requested: false, localEndpoint: false, flow: { status: 'idle' } })
+ patch({ targetProfile: undefined, manual: false, requested: false, localEndpoint: false, flow: { status: 'idle' } })
}
export function completeDesktopOnboarding() {
@@ -633,6 +658,9 @@ async function openSignInUrl(url: string) {
}
export async function startProviderOAuth(provider: OAuthProvider, ctx: OnboardingContext) {
+ ctx = { ...ctx }
+ const generation = flowGeneration
+ flowProfile = ctx.profile
clearPoll()
if (provider.flow === 'external') {
@@ -644,10 +672,23 @@ export async function startProviderOAuth(provider: OAuthProvider, ctx: Onboardin
setFlow({ status: 'starting', provider })
try {
- const start = await startOAuthLogin(provider.id)
+ const start = await startOAuthLogin(provider.id, ctx.profile)
+
+ if (generation !== flowGeneration) {
+ void cancelOAuthSession(start.session_id, ctx.profile).catch(() => undefined)
+
+ return
+ }
+
const browserUrl = start.flow === 'device_code' ? start.verification_url : start.auth_url
await openSignInUrl(browserUrl)
+ if (generation !== flowGeneration) {
+ void cancelOAuthSession(start.session_id, ctx.profile).catch(() => undefined)
+
+ return
+ }
+
if (start.flow === 'pkce') {
setFlow({ status: 'awaiting_user', provider, start, code: '' })
@@ -663,16 +704,19 @@ export async function startProviderOAuth(provider: OAuthProvider, ctx: Onboardin
message: translateNow('onboarding.signInExpired')
})
)
- pollTimer = window.setInterval(() => void pollSession(provider, start, ctx), POLL_MS)
+ pollTimer = window.setInterval(() => void pollSession(provider, start, ctx, generation), POLL_MS)
} catch (error) {
+ if (generation !== flowGeneration) { return }
setFlow({ status: 'error', provider, message: `Could not start sign-in: ${errMessage(error)}` })
}
}
// Poll a session-backed device-code flow until it resolves.
-async function pollSession(provider: OAuthProvider, start: DeviceStart, ctx: OnboardingContext) {
+async function pollSession(provider: OAuthProvider, start: DeviceStart, ctx: OnboardingContext, generation: number) {
try {
- const { error_message, status } = await pollOAuthSession(provider.id, start.session_id)
+ const { error_message, status } = await pollOAuthSession(provider.id, start.session_id, ctx.profile)
+
+ if (generation !== flowGeneration) { return }
if (status === 'approved') {
clearPoll()
@@ -689,6 +733,7 @@ async function pollSession(provider: OAuthProvider, start: DeviceStart, ctx: Onb
setFlow({ status: 'error', provider, start, message: error_message || `Sign-in ${status}.` })
}
} catch (error) {
+ if (generation !== flowGeneration) { return }
clearPoll()
setFlow({ status: 'error', provider, start, message: `Polling failed: ${errMessage(error)}` })
}
@@ -703,6 +748,9 @@ export function setOnboardingCode(code: string) {
}
export async function submitOnboardingCode(ctx: OnboardingContext) {
+ ctx = { ...ctx }
+ const generation = flowGeneration
+ flowProfile = ctx.profile
const { flow } = $desktopOnboarding.get()
if (flow.status !== 'awaiting_user' || !flow.code.trim()) {
@@ -713,7 +761,9 @@ export async function submitOnboardingCode(ctx: OnboardingContext) {
setFlow({ status: 'submitting', provider, start })
try {
- const resp = await submitOAuthCode(provider.id, start.session_id, code.trim())
+ const resp = await submitOAuthCode(provider.id, start.session_id, code.trim(), ctx.profile)
+
+ if (generation !== flowGeneration) { return }
if (resp.ok && resp.status === 'approved') {
setFlow({ status: 'success', provider })
@@ -728,16 +778,18 @@ export async function submitOnboardingCode(ctx: OnboardingContext) {
setFlow({ status: 'error', provider, start, message: resp.message || 'Token exchange failed.' })
}
} catch (error) {
+ if (generation !== flowGeneration) { return }
setFlow({ status: 'error', provider, start, message: errMessage(error) })
}
}
export function cancelOnboardingFlow() {
+ flowGeneration++
clearPoll()
const sessionId = sessionIdFor($desktopOnboarding.get().flow)
if (sessionId) {
- cancelOAuthSession(sessionId).catch(() => undefined)
+ cancelOAuthSession(sessionId, flowProfile ?? $desktopOnboarding.get().targetProfile).catch(() => undefined)
}
setFlow({ status: 'idle' })
@@ -789,6 +841,8 @@ export async function copyExternalCommand() {
}
export async function recheckExternalSignin(ctx: OnboardingContext) {
+ ctx = { ...ctx }
+ flowProfile = ctx.profile
const { flow } = $desktopOnboarding.get()
if (flow.status !== 'external_pending') {
@@ -817,6 +871,9 @@ export async function saveOnboardingApiKey(
// providers (their key IS `value`).
endpointApiKey?: string
) {
+ ctx = { ...ctx }
+ const generation = flowGeneration
+ flowProfile = ctx.profile
const trimmed = value.trim()
if (!trimmed) {
@@ -837,7 +894,9 @@ export async function saveOnboardingApiKey(
// provider probes, self-hosted endpoints). We now save the value as-is and
// let the user proceed; an actually-bad key surfaces later at chat time.
try {
- await setEnvVar(envKey, trimmed)
+ await setEnvVar(envKey, trimmed, ctx.profile)
+
+ if (generation !== flowGeneration) { return { ok: false } }
// For API-key flows we don't have a definitive provider id (the
// user picked which API key they're entering, but the corresponding
// backend slug — e.g. OPENROUTER_API_KEY → "openrouter" — is the
@@ -873,6 +932,9 @@ export async function saveOnboardingApiKey(
// wipe the base_url we just wrote. We have a concrete model already, so we
// verify the runtime directly and finish.
export async function saveOnboardingLocalEndpoint(baseUrl: string, apiKey: string, ctx: OnboardingContext) {
+ ctx = { ...ctx }
+ const generation = flowGeneration
+ flowProfile = ctx.profile
const url = baseUrl.trim()
const key = apiKey.trim()
@@ -888,6 +950,8 @@ export async function saveOnboardingLocalEndpoint(baseUrl: string, apiKey: strin
try {
const probe = await validateProviderCredential('OPENAI_BASE_URL', url, key)
+ if (generation !== flowGeneration) { return { ok: false } }
+
if (!probe.ok && probe.reachable) {
return { ok: false, message: probe.message || 'Could not reach that endpoint.' }
}
@@ -909,11 +973,17 @@ export async function saveOnboardingLocalEndpoint(baseUrl: string, apiKey: strin
}
try {
- await setMainModelAssignment({ provider: 'custom', model, base_url: url, api_key: key })
+ await setMainModelAssignment({ provider: 'custom', model, base_url: url, api_key: key }, ctx.profile)
+
+ if (generation !== flowGeneration) { return { ok: false } }
await ctx.requestGateway('reload.env').catch(() => undefined)
+ if (generation !== flowGeneration) { return { ok: false } }
+
const runtime = await checkRuntime(ctx)
+ if (generation !== flowGeneration) { return { ok: false } }
+
if (!runtime.ready) {
const detail = (runtime.reason ?? '').trim()
@@ -935,6 +1005,7 @@ export async function saveOnboardingLocalEndpoint(baseUrl: string, apiKey: strin
// User picked a different model from the dropdown on the confirm card.
// Persists immediately so the displayed value is always what's on disk.
export async function setOnboardingModel(model: string) {
+ const generation = flowGeneration
const { flow } = $desktopOnboarding.get()
if (flow.status !== 'confirming_model') {
@@ -949,13 +1020,16 @@ export async function setOnboardingModel(model: string) {
await setMainModelAssignment({
provider: flow.providerSlug,
model
- })
+ }, flowProfile ?? $desktopOnboarding.get().targetProfile)
+
+ if (generation !== flowGeneration) { return }
const current = $desktopOnboarding.get().flow
if (current.status === 'confirming_model') {
setFlow({ ...current, currentModel: model, saving: false })
}
} catch (error) {
+ if (generation !== flowGeneration) { return }
notifyError(error, 'Could not change model')
const current = $desktopOnboarding.get().flow
diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.md
index 61d35230d1b..0ab8acd2618 100644
--- a/website/docs/user-guide/desktop.md
+++ b/website/docs/user-guide/desktop.md
@@ -165,7 +165,7 @@ That bridges to `ELECTRON_OZONE_PLATFORM_HINT` at launch (an explicit env var st
Manage providers, models, tools, and credentials from a real UI instead of editing YAML. First-run onboarding gets you to your first message in seconds. The settings panes cover providers/keys, model selection, toolset configuration, MCP servers, the gateway, and session management.
-- **Providers settings pane** — a dedicated place to manage inference providers, with an Accounts / API-keys UX for signing in and storing credentials per provider. Its **Local Models** view installs and manages an on-device llama.cpp runtime — see [Local Models](/user-guide/local-models).
+- **Providers settings pane** — a dedicated place to manage inference providers, with an Accounts / API-keys UX for signing in and storing credentials per provider. Accounts and API keys share the Settings **Applies to** selection: credential reads and edits, OAuth account removal, and sign-in launched here target the selected profile, not the active chat profile. The sign-in flow keeps that target through credential saving and model selection. Changing **Applies to** discards unsaved credential drafts. Closing sign-in cancels polling and ignores late results; a credential write already sent may still finish in its original profile. Externally managed CLI credentials use their own CLI and are not covered by this profile selector. Its **Local Models** view installs and manages an on-device llama.cpp runtime — see [Local Models](/user-guide/local-models).
- **Every provider and model in the menus** — the GUI surfaces the full provider list and every model that `hermes model` knows about, so you pick from the same catalog the CLI sees rather than a curated subset.
- **xAI Grok OAuth** — Grok is a first-class OAuth provider in the launcher; sign in through the browser flow like the other OAuth providers.
- **Tool-backend installs from the GUI** — run a tool backend's post-setup install steps directly from the app instead of dropping to a terminal.