The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): retain provider setup connection and profile ownership
BearHuddleston994074c789ad
diff --git a/apps/desktop/e2e/provider-setup-owner.spec.ts b/apps/desktop/e2e/provider-setup-owner.spec.tsnew file mode 100644index 00000000000..4141b840a68--- /dev/null+++ b/apps/desktop/e2e/provider-setup-owner.spec.ts@@ -0,0 +1,451 @@+/**+ * Provider setup must keep the Settings owner's gateway AND profile.+ * Two real serve backends; only OpenAI-compatible model discovery is a fixture.+ * Build dist/ separately, then run this spec with HERMES_DESKTOP_PYTHON pointing+ * at a dependency-complete interpreter. No OAuth account or inference is used.+ */+import { type ChildProcess, spawn, spawnSync } from 'node:child_process'+import * as fs from 'node:fs'+import * as http from 'node:http'+import * as net from 'node:net'+import * as path from 'node:path'++import { createSandbox, findElectron, type Sandbox } from './fixtures'+import {+ _electron,+ collectErrorBanners,+ type ElectronApplication,+ expect,+ installErrorBannerGuard,+ type Page,+ test+} from './test'++const DESKTOP_ROOT = path.resolve(import.meta.dirname, '..')+const REPO_ROOT = path.resolve(DESKTOP_ROOT, '..', '..')+const REMOTE_ID = 'athena-fixture'+const REMOTE_LABEL = 'Athena fixture'+const PROFILE = 'leverage-ai'+const REMOTE_TOKEN = 'provider-owner-fixture-token'++interface RpcReceipt {+ endpoint: string+ socketProfile: string | null+ method: string+ params: Record<string, unknown>+ result?: unknown+ error?: unknown+}++function isolatedEnv(home: string, hermesHome: string): Record<string, string> {+ // Allowlist rather than inheriting real provider keys, profile selection,+ // browser account state, live desktop overrides, or the host session bus.+ const env: Record<string, string> = {+ PATH: process.env.PATH ?? '',+ HOME: home,+ USERPROFILE: home,+ HERMES_HOME: hermesHome,+ PYTHONPATH: REPO_ROOT,+ PYTHONNOUSERSITE: '1',+ PYTHONDONTWRITEBYTECODE: '1',+ TMPDIR: process.env.TMPDIR ?? path.dirname(home),+ LANG: 'C.UTF-8',+ TZ: 'UTC',+ XDG_SESSION_TYPE: 'x11',+ ELECTRON_OZONE_PLATFORM_HINT: 'x11'+ }++ for (const key of ['DISPLAY', 'XAUTHORITY', 'TEST_WORKER_INDEX', 'SYSTEMROOT', 'WINDIR']) {+ if (process.env[key]) {+ env[key] = process.env[key]!+ }+ }++ for (const kind of ['CONFIG', 'CACHE', 'DATA', 'STATE', 'RUNTIME']) {+ const dir = path.join(home, `xdg-${kind.toLowerCase()}`)+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 })+ env[`XDG_${kind}_${kind === 'RUNTIME' ? 'DIR' : 'HOME'}`] = dir+ }++ return env+}++function pythonBinary(): string {+ const python =+ process.env.HERMES_DESKTOP_PYTHON ??+ path.join(REPO_ROOT, '.venv', process.platform === 'win32' ? 'Scripts/python.exe' : 'bin/python')++ if (!fs.existsSync(python)) {+ throw new Error('Set HERMES_DESKTOP_PYTHON to an isolated dependency-complete interpreter')+ }++ return python+}++function verifyImports(python: string, env: Record<string, string>): string {+ const probe = spawnSync(+ python,+ [+ '-c',+ [+ 'import json, pathlib, sys',+ 'import hermes_cli.main, hermes_cli.web_server, tui_gateway.server',+ 'root = pathlib.Path.cwd().resolve()',+ 'paths = {name: str(pathlib.Path(sys.modules[name].__file__).resolve()) for name in ("hermes_cli.main", "hermes_cli.web_server", "tui_gateway.server")}',+ 'assert all(pathlib.Path(p).is_relative_to(root) for p in paths.values()), paths',+ 'sys.__stdout__.write(json.dumps(paths))'+ ].join('\n')+ ],+ { cwd: REPO_ROOT, env, encoding: 'utf8', timeout: 60_000 }+ )++ expect(probe.status, probe.stderr).toBe(0)++ return probe.stdout+}++function seedConfig(home: string, endpoint: string, model: string): void {+ fs.mkdirSync(home, { recursive: true })+ // JSON is YAML, and these fixtures need no secret file at all.+ fs.writeFileSync(+ path.join(home, 'config.yaml'),+ JSON.stringify(+ {+ model: { provider: 'custom', default: model, base_url: `${endpoint}/v1` },+ auxiliary: { title_generation: { enabled: false } }+ },+ null,+ 2+ )+ )+}++function configModel(python: string, env: Record<string, string>, home: string): unknown {+ const read = spawnSync(+ python,+ [+ '-c',+ 'import json, pathlib, sys, yaml; print(json.dumps(yaml.safe_load(pathlib.Path(sys.argv[1]).read_text())["model"]))',+ path.join(home, 'config.yaml')+ ],+ { cwd: REPO_ROOT, env, encoding: 'utf8', timeout: 10_000 }+ )++ expect(read.status, read.stderr).toBe(0)++ return JSON.parse(read.stdout)+}++async function listen(server: net.Server): Promise<number> {+ return new Promise((resolve, reject) => {+ server.once('error', reject)+ server.listen(0, '127.0.0.1', () => resolve((server.address() as net.AddressInfo).port))+ })+}++async function stopChild(child: ChildProcess): Promise<void> {+ if (child.exitCode !== null || child.signalCode !== null) {+ return+ }++ await new Promise<void>(resolve => {+ const timer = setTimeout(() => child.kill('SIGKILL'), 10_000)+ child.once('exit', () => {+ clearTimeout(timer)+ resolve()+ })+ child.kill('SIGTERM')+ })+}++async function startRemote(python: string, env: Record<string, string>, logPath: string) {+ const reservation = net.createServer()+ const port = await listen(reservation)+ await new Promise<void>(resolve => reservation.close(() => resolve()))+ const url = `http://127.0.0.1:${port}`+ const log = fs.openSync(logPath, 'w')++ const child = spawn(+ python,+ ['-m', 'hermes_cli.main', 'serve', '--isolated', '--host', '127.0.0.1', '--port', String(port), '--skip-build'],+ {+ cwd: REPO_ROOT,+ env: { ...env, HERMES_DASHBOARD_SESSION_TOKEN: REMOTE_TOKEN },+ stdio: ['ignore', log, log]+ }+ )++ fs.closeSync(log)++ try {+ await expect+ .poll(+ async () => {+ if (child.exitCode !== null) {+ throw new Error(`Remote serve exited: ${child.exitCode}; see ${logPath}`)+ }++ return fetch(`${url}/api/status`, {+ headers: { 'X-Hermes-Session-Token': REMOTE_TOKEN },+ signal: AbortSignal.timeout(2_000)+ })+ .then(response => response.status)+ .catch(() => 0)+ },+ { timeout: 90_000, intervals: [200, 500, 1000] }+ )+ .toBe(200)+ } catch (error) {+ await stopChild(child)+ throw error+ }++ return { url, child }+}++function watchRpc(page: Page, receipts: RpcReceipt[]): void {+ page.on('websocket', socket => {+ const url = new URL(socket.url())+ const pending = new Map<unknown, RpcReceipt>()+ socket.on('framesent', ({ payload }) => {+ const message = JSON.parse(payload.toString())++ if (!message.method) {+ return+ }++ const receipt: RpcReceipt = {+ endpoint: url.origin,+ socketProfile: url.searchParams.get('profile'),+ method: message.method,+ params: message.params ?? {}+ }++ receipts.push(receipt)+ pending.set(message.id, receipt)+ })+ socket.on('framereceived', ({ payload }) => {+ const message = JSON.parse(payload.toString())+ const receipt = pending.get(message.id)++ if (receipt) {+ receipt.result = message.result+ receipt.error = message.error+ }+ })+ })+}++const gatewayGroup = (page: Page, id: string) =>+ page.locator(`[data-slot="profile-rail-gateway"][data-connection-id="${id}"]`)++async function selectGateway(page: Page, id: string, label: string, profile: string): Promise<void> {+ const group = gatewayGroup(page, id)+ await expect(group).toBeVisible({ timeout: 60_000 })+ await group.getByRole('button', { name: `${profile} · ${label}`, exact: true }).click()+ await expect(page.getByRole('button', { name: /^Registered gateways: / })).toHaveAttribute(+ 'aria-label',+ `Registered gateways: ${label}`,+ { timeout: 90_000 }+ )+ await expect(group).toHaveAttribute('data-active', 'true')+ await expect(group.getByRole('button', { name: profile, exact: true })).toHaveAttribute('aria-pressed', 'true')+ await expect(page.locator('[data-slot="statusbar"]').getByText('ready', { exact: true })).toBeVisible({+ timeout: 60_000+ })+}++async function openProviderKeys(page: Page): Promise<void> {+ await page.getByRole('button', { name: 'Open settings', exact: true }).click()+ await page.getByRole('button', { name: 'Providers', exact: true }).click()+ await page.getByRole('button', { name: 'API keys', exact: true }).click()+ await expect(page.getByRole('button', { name: /^Local \/ custom endpoint/ })).toBeVisible()+}++test('Settings provider setup stays on its gateway/profile across A → B → A', async () => {+ test.setTimeout(300_000)+ const original = createSandbox('provider-owner')+ const localHome = path.join(original.root, 'local')+ const remoteHome = path.join(original.root, 'remote')+ const sandbox: Sandbox = { ...original, hermesHome: path.join(localHome, '.hermes') }+ const remoteHermesHome = path.join(remoteHome, '.hermes')+ const remoteProfileHome = path.join(remoteHermesHome, 'profiles', PROFILE)+ const python = pythonBinary()+ const localEnv = isolatedEnv(localHome, sandbox.hermesHome)+ const remoteEnv = isolatedEnv(remoteHome, remoteHermesHome)+ const receipts: RpcReceipt[] = []+ const discoveryRequests: string[] = []+ let advertisedModel = 'remote-first'++ const endpoint = http.createServer((request, response) => {+ discoveryRequests.push(request.url ?? '')+ // Discovery only. An unexpected inference request must not look successful.+ response.writeHead(request.url === '/v1/models' ? 200 : 404, { 'Content-Type': 'application/json' })+ response.end(+ JSON.stringify(+ request.url === '/v1/models'+ ? { object: 'list', data: [{ id: advertisedModel, object: 'model', owned_by: 'e2e-fixture' }] }+ : { error: 'This regression fixture only serves model discovery' }+ )+ )+ })++ let app: ElectronApplication | undefined+ let page: Page | undefined+ let remote: Awaited<ReturnType<typeof startRemote>> | undefined++ try {+ const endpointUrl = `http://127.0.0.1:${await listen(endpoint)}`+ seedConfig(sandbox.hermesHome, endpointUrl, 'local-sentinel')+ seedConfig(remoteHermesHome, endpointUrl, 'remote-default-sentinel')+ seedConfig(remoteProfileHome, endpointUrl, 'remote-before-setup')+ await test+ .info()+ .attach('worktree-imports', { body: verifyImports(python, remoteEnv), contentType: 'application/json' })+ remote = await startRemote(python, remoteEnv, test.info().outputPath('remote-serve.log'))+ fs.writeFileSync(+ path.join(sandbox.userDataDir, 'connections.json'),+ JSON.stringify({+ version: 2,+ primary: 'local',+ launchMode: 'primary',+ lastUsed: 'local',+ connections: [+ { id: 'local', kind: 'local', label: 'This device' },+ {+ id: REMOTE_ID,+ kind: 'remote',+ label: REMOTE_LABEL,+ url: remote.url,+ authMode: 'token',+ token: { encoding: 'plain', value: REMOTE_TOKEN }+ }+ ]+ })+ )+ expect(fs.existsSync(path.join(DESKTOP_ROOT, 'dist/electron-main.mjs')), 'Build desktop dist before E2E').toBe(true)+ app = await _electron.launch({+ executablePath: findElectron(),+ args: [DESKTOP_ROOT, '--disable-gpu', '--no-sandbox'],+ cwd: DESKTOP_ROOT,+ ...(process.env.PROVIDER_SETUP_VIDEO === '1'+ ? {+ recordVideo: { dir: test.info().outputPath('video'), size: { width: 1220, height: 800 } }+ }+ : {}),+ env: {+ ...localEnv,+ HERMES_DESKTOP_PYTHON: python,+ HERMES_DESKTOP_USER_DATA_DIR: sandbox.userDataDir,+ HERMES_DESKTOP_IGNORE_EXISTING: '1',+ HERMES_DESKTOP_HERMES_ROOT: REPO_ROOT,+ HERMES_DESKTOP_APP_NAME: `ProviderOwnerE2E-${Date.now()}`,+ HERMES_DESKTOP_SKIP_QUIT_CONFIRM: '1'+ }+ })+ page = await app.firstWindow()+ installErrorBannerGuard(page)+ watchRpc(page, receipts)+ await expect(page.getByRole('button', { name: 'Open settings', exact: true })).toBeVisible({ timeout: 90_000 })+ await expect(page.locator('[data-slot="statusbar"]').getByText('ready', { exact: true })).toBeVisible({+ timeout: 60_000+ })+ const localConfig = fs.readFileSync(path.join(sandbox.hermesHome, 'config.yaml'), 'utf8')+ const remoteDefault = fs.readFileSync(path.join(remoteHermesHome, 'config.yaml'), 'utf8')++ const localProfiles = () =>+ fs.existsSync(path.join(sandbox.hermesHome, 'profiles'))+ ? fs.readdirSync(path.join(sandbox.hermesHome, 'profiles')).sort()+ : []++ expect(localProfiles()).toEqual([])++ // A: inspect the local default through Settings, without changing it.+ await openProviderKeys(page)+ await page.getByRole('button', { name: 'Close settings', exact: true }).click()+ await selectGateway(page, REMOTE_ID, REMOTE_LABEL, PROFILE)++ for (const model of ['remote-first', 'remote-second']) {+ advertisedModel = model+ await openProviderKeys(page)+ await expect(page.getByText(new RegExp(`Changes on this page apply to.*${PROFILE}`))).toBeVisible()+ await page.getByRole('button', { name: /^Local \/ custom endpoint/ }).click()+ const input = page.getByPlaceholder('http://127.0.0.1:8000/v1')+ await expect(input).toBeVisible()+ await input.fill(`${endpointUrl}/v1`)+ await input.scrollIntoViewIfNeeded()+ await page.screenshot({ path: test.info().outputPath(`${model}-endpoint-form.png`) })+ const start = receipts.length+ await page.getByRole('button', { name: 'Connect', exact: true }).click()+ await expect(input).toBeHidden({ timeout: 45_000 })+ await expect+ .poll(() => configModel(python, remoteEnv, remoteProfileHome))+ .toMatchObject({+ provider: expect.stringMatching(/^custom(?::.+)?$/),+ default: model,+ base_url: `${endpointUrl}/v1`+ })++ const setupCalls = receipts+ .slice(start)+ .filter(row => ['reload.env', 'setup.status', 'setup.runtime_check'].includes(row.method))++ // A scoped setup must not mutate the launch profile's process environment.+ expect(setupCalls.some(row => row.method === 'reload.env')).toBe(false)++ for (const method of ['setup.status', 'setup.runtime_check']) {+ const calls = setupCalls.filter(row => row.method === method)+ expect(calls, `wire request for ${method}`).not.toHaveLength(0)++ for (const call of calls) {+ expect(new URL(call.endpoint).host).toBe(new URL(remote.url).host)+ expect(call.params.profile).toBe(PROFILE)+ expect(call.error).toBeUndefined()+ }+ }++ expect+ .soft(+ setupCalls.find(row => row.method === 'setup.runtime_check')?.result,+ 'readiness must resolve the model just saved in the owning profile'+ )+ .toMatchObject({ ok: true, model, profile: PROFILE })+ expect(fs.readFileSync(path.join(sandbox.hermesHome, 'config.yaml'), 'utf8')).toBe(localConfig)+ expect(localProfiles()).toEqual([])+ expect(fs.readFileSync(path.join(remoteHermesHome, 'config.yaml'), 'utf8')).toBe(remoteDefault)+ await page.screenshot({ path: test.info().outputPath(`${model}-saved.png`) })+ await page.getByRole('button', { name: 'Close settings', exact: true }).click()+ await selectGateway(page, 'local', 'This device', 'default')+ await openProviderKeys(page)+ expect(configModel(python, localEnv, sandbox.hermesHome)).toMatchObject({ default: 'local-sentinel' })+ await page.screenshot({ path: test.info().outputPath(`${model}-back-on-local.png`) })+ await page.getByRole('button', { name: 'Close settings', exact: true }).click()++ if (model === 'remote-first') {+ await selectGateway(page, REMOTE_ID, REMOTE_LABEL, PROFILE)+ }+ }++ expect(discoveryRequests).toContain('/v1/models')+ expect(await collectErrorBanners(page)).toEqual([])+ } finally {+ if (page && !page.isClosed()) {+ await test.info().attach('last-ui', { body: await page.locator('body').innerText(), contentType: 'text/plain' })+ await page.screenshot({ path: test.info().outputPath('last-ui.png') })+ await collectErrorBanners(page)+ }++ fs.writeFileSync(test.info().outputPath('setup-wire.json'), JSON.stringify(receipts, null, 2))+ await test+ .info()+ .attach('setup-wire', { path: test.info().outputPath('setup-wire.json'), contentType: 'application/json' })+ await app?.close()++ if (remote) {+ await stopChild(remote.child)+ }++ await new Promise<void>(resolve => endpoint.close(() => resolve()))+ sandbox.cleanup()+ }+})diff --git a/apps/desktop/src/api/config.ts b/apps/desktop/src/api/config.tsindex f0ce96655f7..d17f4a4d2e8 100644--- a/apps/desktop/src/api/config.ts+++ b/apps/desktop/src/api/config.ts@@ -238,16 +238,21 @@ export function revealEnvVar(key: string, profile?: ProfileScope): Promise<{ keyexport function validateProviderCredential(key: string,value: string,- apiKey?: string+ apiKey?: string,+ profile?: ProfileScope): Promise<{ ok: boolean; reachable: boolean; message: string; models?: string[]; resolved_base_url?: string }> {- return hermesApi<{ ok: boolean; reachable: boolean; message: string; models?: string[]; resolved_base_url?: string }>(- {- ...profileScoped(),- path: '/api/providers/validate',- method: 'POST',- body: { key, value, api_key: apiKey ?? '' }- }- )+ return window.hermesDesktop.api<{+ ok: boolean+ reachable: boolean+ message: string+ models?: string[]+ resolved_base_url?: string+ }>({+ ...capabilityScoped(profile),+ path: '/api/providers/validate',+ method: 'POST',+ body: { key, value, api_key: apiKey ?? '' }+ })}export function getCustomEndpoints(profile?: null | string): Promise<CustomEndpointsResponse> {@@ -300,9 +305,9 @@ export function deleteCustomEndpoint(id: string, profile?: null | string): Promi})}-export function listOAuthProviders(profile?: null | string): Promise<OAuthProvidersResponse> {- return hermesApi<OAuthProvidersResponse>({- ...profileScoped(profile),+export function listOAuthProviders(profile?: ProfileScope): Promise<OAuthProvidersResponse> {+ return window.hermesDesktop.api<OAuthProvidersResponse>({+ ...capabilityScoped(profile),path: '/api/providers/oauth'})}@@ -331,10 +336,10 @@ export function submitOAuthCode(providerId: string,sessionId: string,code: string,- profile?: null | string+ profile?: ProfileScope): Promise<OAuthSubmitResponse> {- return hermesApi<OAuthSubmitResponse>({- ...profileScoped(profile),+ return window.hermesDesktop.api<OAuthSubmitResponse>({+ ...capabilityScoped(profile),path: `/api/providers/oauth/${encodeURIComponent(providerId)}/submit`,method: 'POST',body: { session_id: sessionId, code }@@ -352,9 +357,9 @@ export function pollOAuthSession(})}-export function cancelOAuthSession(sessionId: string, profile?: null | string): Promise<{ ok: boolean }> {- return hermesApi<{ ok: boolean }>({- ...profileScoped(profile),+export function cancelOAuthSession(sessionId: string, profile?: ProfileScope): Promise<{ ok: boolean }> {+ return window.hermesDesktop.api<{ ok: boolean }>({+ ...capabilityScoped(profile),path: `/api/providers/oauth/sessions/${encodeURIComponent(sessionId)}`,method: 'DELETE'})diff --git a/apps/desktop/src/api/models.ts b/apps/desktop/src/api/models.tsindex 9f3e34ecf83..6f38cfcc2d9 100644--- a/apps/desktop/src/api/models.ts+++ b/apps/desktop/src/api/models.ts@@ -32,7 +32,7 @@ export function getGlobalModelOptions(includeUnconfigured?: booleanexplicitOnly?: boolean},- profile?: null | string+ profile?: ProfileScope): Promise<ModelOptionsResult> {const params = new URLSearchParams()@@ -48,8 +48,8 @@ export function getGlobalModelOptions(params.set('explicit_only', '1')}- return hermesApi<ModelOptionsResult>({- ...profileScoped(profile),+ return window.hermesDesktop.api<ModelOptionsResult>({+ ...capabilityScoped(profile),path: params.size > 0 ? `/api/model/options?${params.toString()}` : '/api/model/options',timeoutMs: STARTUP_REQUEST_TIMEOUT_MS})@@ -65,12 +65,9 @@ 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,- profile?: null | string-): Promise<RecommendedDefaultModel> {- return hermesApi<RecommendedDefaultModel>({- ...profileScoped(profile),+export function getRecommendedDefaultModel(provider: string, profile?: ProfileScope): Promise<RecommendedDefaultModel> {+ return window.hermesDesktop.api<RecommendedDefaultModel>({+ ...capabilityScoped(profile),path: `/api/model/recommended-default?provider=${encodeURIComponent(provider)}`})}@@ -119,10 +116,10 @@ export function saveMoaModels(export function setModelAssignment(body: ModelAssignmentRequest,- profile?: null | string+ profile?: ProfileScope): Promise<ModelAssignmentResponse> {- return hermesApi<ModelAssignmentResponse>({- ...profileScoped(profile),+ return window.hermesDesktop.api<ModelAssignmentResponse>({+ ...capabilityScoped(profile),path: '/api/model/set',method: 'POST',bodydiff --git a/apps/desktop/src/app/settings/model-settings.test.tsx b/apps/desktop/src/app/settings/model-settings.test.tsxindex 653ae735853..c7a59dd32e4 100644--- a/apps/desktop/src/app/settings/model-settings.test.tsx+++ b/apps/desktop/src/app/settings/model-settings.test.tsx@@ -49,9 +49,9 @@ vi.mock('@/hermes', async () => ({}))vi.mock('@/store/onboarding', () => ({- startManualLocalEndpoint: () => startManualLocalEndpoint(),- startManualOnboarding: () => startManualOnboarding(),- startManualProviderOAuth: (slug: string) => startManualProviderOAuth(slug)+ startManualLocalEndpoint: (...args: unknown[]) => startManualLocalEndpoint(...args),+ startManualOnboarding: (...args: unknown[]) => startManualOnboarding(...args),+ startManualProviderOAuth: (...args: unknown[]) => startManualProviderOAuth(...args)}))vi.mock('../hooks/use-on-profile-switch', () => ({@@ -137,7 +137,7 @@ describe('ModelSettings', () => {getGlobalModelInfo.mockResolvedValueOnce({ provider, model: '' })getGlobalModelOptions.mockResolvedValueOnce({ providers: [] })- await renderModelSettings()+ await renderModelSettings('leverage-ai')const providerSelect = (await screen.findAllByRole('combobox'))[0]@@ -148,6 +148,7 @@ describe('ModelSettings', () => {fireEvent.click(await screen.findByRole('button', { name: 'Set up provider' }))expect(startManualLocalEndpoint).toHaveBeenCalledOnce()+ expect(startManualLocalEndpoint).toHaveBeenCalledWith(null, 'leverage-ai')expect(startManualOnboarding).not.toHaveBeenCalled()expect(startManualProviderOAuth).not.toHaveBeenCalled()}@@ -157,16 +158,17 @@ describe('ModelSettings', () => {getGlobalModelInfo.mockResolvedValueOnce({ provider: 'retired-provider', model: '' })getGlobalModelOptions.mockResolvedValueOnce({ providers: [] })- await renderModelSettings()+ await renderModelSettings('leverage-ai')fireEvent.click(await screen.findByRole('button', { name: 'Set up provider' }))expect(startManualOnboarding).toHaveBeenCalledOnce()+ expect(startManualOnboarding).toHaveBeenCalledWith(undefined, 'leverage-ai')expect(startManualLocalEndpoint).not.toHaveBeenCalled()expect(startManualProviderOAuth).not.toHaveBeenCalled()})- it('deep-links a known OAuth provider row into its setup flow', async () => {+ it('deep-links a known OAuth provider row into its scoped setup flow', async () => {getGlobalModelInfo.mockResolvedValueOnce({ provider: 'anthropic', model: '' })getGlobalModelOptions.mockResolvedValueOnce({providers: [@@ -180,11 +182,11 @@ describe('ModelSettings', () => {]})- await renderModelSettings()+ await renderModelSettings('leverage-ai')fireEvent.click(await screen.findByRole('button', { name: 'Set up Anthropic' }))- expect(startManualProviderOAuth).toHaveBeenCalledWith('anthropic')+ expect(startManualProviderOAuth).toHaveBeenCalledWith('anthropic', 'leverage-ai')expect(startManualLocalEndpoint).not.toHaveBeenCalled()expect(startManualOnboarding).not.toHaveBeenCalled()})diff --git a/apps/desktop/src/app/settings/model-settings.tsx b/apps/desktop/src/app/settings/model-settings.tsxindex c984f0a9115..9b0663b17c8 100644--- a/apps/desktop/src/app/settings/model-settings.tsx+++ b/apps/desktop/src/app/settings/model-settings.tsx@@ -658,15 +658,15 @@ export function ModelSettings({ onMainModelChanged, scopeProfile, subpage }: Modconst lower = slug.toLowerCase()if (lower === 'custom' || lower === 'local' || lower.startsWith('custom:')) {- startManualLocalEndpoint()+ startManualLocalEndpoint(null, scopeProfile)} else if (rowSlug) {- startManualProviderOAuth(rowSlug)+ startManualProviderOAuth(rowSlug, scopeProfile)} else {// An absent row has no trustworthy auth metadata. Open the generic// provider picker instead of deep-linking an unknown or stale slug.- startManualOnboarding()+ startManualOnboarding(undefined, scopeProfile)}- }, [selectedProvider, selectedProviderRow])+ }, [scopeProfile, selectedProvider, selectedProviderRow])const applyMainModel = useCallback(async () => {if (!selectedProvider || !selectedModel) {diff --git a/apps/desktop/src/components/model-picker.tsx b/apps/desktop/src/components/model-picker.tsxindex 99a65357a85..df5e0b03781 100644--- a/apps/desktop/src/components/model-picker.tsx+++ b/apps/desktop/src/components/model-picker.tsx@@ -34,7 +34,7 @@ interface ModelPickerDialogProps {currentModel: stringcurrentProvider: stringonSelect: (selection: { provider: string; model: string }) => void- ownerConnectionId?: string+ ownerConnectionId?: null | stringprofile?: stringrequest?: <T>(method: string, params?: Record<string, unknown>) => Promise<T>/**@@ -184,7 +184,10 @@ export function ModelPickerDialog({// model-confirm) instead of duplicating provider UI here. Closes the picker// so the onboarding overlay isn't rendered underneath it.const addProvider = () => {- startManualOnboarding()+ startManualOnboarding(+ undefined,+ ownerConnectionId !== undefined ? { connectionId: ownerConnectionId, profile } : profile+ )onOpenChange(false)}diff --git a/apps/desktop/src/components/onboarding/connection-owner.test.tsx b/apps/desktop/src/components/onboarding/connection-owner.test.tsxnew file mode 100644index 00000000000..d6ee3e6affe--- /dev/null+++ b/apps/desktop/src/components/onboarding/connection-owner.test.tsx@@ -0,0 +1,183 @@+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { afterEach, expect, it, vi } from 'vitest'++import { setApiRequestConnection, setApiRequestProfile } from '@/api/client'+import { startOAuthLogin } from '@/api/config'+import type { HermesApiRequest } from '@/global'+import type * as HermesApi from '@/hermes'+import {+ closeSecondaryGateways,+ configureGatewayRegistry,+ ensureGatewayForAgent,+ requestGatewayForAgent,+ setPrimaryGateway,+ setPrimaryGatewayConnection+} from '@/store/gateway'+import type * as OnboardingStore from '@/store/onboarding'+import {+ $desktopOnboarding,+ closeManualOnboarding,+ type OnboardingContext,+ startManualProviderOAuth+} from '@/store/onboarding'+import { stubMenuDomApis, stubResizeObserver } from '@/test/jsdom'+import { makeOAuthProvider } from '@/test/oauth-provider'++import { FlowPanel } from './flow'++import { DesktopOnboardingOverlay } from '.'++stubResizeObserver()+stubMenuDomApis()++// Boundary test: real overlay/API helpers/gateway router; no OAuth+// account or production backend. Intercept acquisition to inspect its context.+const mocks = vi.hoisted(() => ({+ begin: vi.fn(),+ rpc: vi.fn(async () => ({ ok: true }))+}))++vi.mock('@/store/onboarding', async importOriginal => ({+ ...(await importOriginal<typeof OnboardingStore>()),+ startProviderOAuth: mocks.begin+}))+vi.mock('@/hermes', async importOriginal => ({+ ...(await importOriginal<typeof HermesApi>()),+ HermesGateway: class {+ connectionState = 'closed'+ connect = async () => {+ this.connectionState = 'open'+ }+ request = mocks.rpc+ close = () => {+ this.connectionState = 'closed'+ }+ onEvent = () => () => {}+ onState = () => () => {}+ }+}))+vi.mock('@/store/notify-baseline', () => ({ markNativeNotifyBaseline: vi.fn() }))++const provider = { ...makeOAuthProvider('openai-codex'), flow: 'device_code' as const }++afterEach(() => {+ cleanup()+ closeManualOnboarding()+ closeSecondaryGateways()+ setApiRequestConnection(null)+ setApiRequestProfile(null)+ vi.clearAllMocks()+ delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop+})++it.each([+ { profile: 'leverage-ai', sharedRemote: true },+ { profile: 'custom', sharedRemote: true },+ { profile: 'mara', sharedRemote: false }+])('keeps Settings readiness on its owner ($profile, shared=$sharedRemote)', async ({ profile, sharedRemote }) => {+ const localRequest = vi.fn(async () => ({ ok: true }))++ const localDial = vi.fn(async () => {+ throw new Error('Diagnostic local backend has no remote-only profile')+ })++ const remoteDial = vi.fn(async ({ connectionId, profile: routeProfile }) => ({+ connectionId,+ profile: routeProfile,+ sharedRemote,+ ...(sharedRemote ? {} : { remoteKind: 'ssh', remoteProfile: 'remote-research' }),+ mode: 'remote',+ authMode: 'token',+ baseUrl: 'https://athena.invalid',+ wsUrl: 'wss://athena.invalid/api/ws',+ token: 'fixture-only'+ }))++ const api = vi.fn(async () => ({ providers: [provider] }))+ Object.defineProperty(window, 'hermesDesktop', {+ configurable: true,+ value: {+ api,+ getConnection: localDial,+ getConnectionFor: remoteDial,+ touchBackend: vi.fn(async () => undefined)+ }+ })+ configureGatewayRegistry({ onEvent: vi.fn() })+ setPrimaryGateway({ connectionState: 'open', request: localRequest } as never, 'default')+ setPrimaryGatewayConnection({ connectionId: 'local' })+ await ensureGatewayForAgent('athena', profile)+ setApiRequestConnection('athena')+ setApiRequestProfile(profile)+ localDial.mockClear()++ await act(async () => {+ startManualProviderOAuth('openai-codex', profile)+ })+ render(+ <DesktopOnboardingOverlay+ enabled={false}+ profile={profile}+ requestGateway={(method, params) => requestGatewayForAgent('athena', profile, method, params)}+ />+ )+ await waitFor(() => expect(mocks.begin).toHaveBeenCalledOnce())+ const context = mocks.begin.mock.calls[0][1] as OnboardingContext++ // Switching the foreground device must not retarget a pending setup.+ setApiRequestConnection('local')+ setApiRequestProfile('default')+ await startOAuthLogin('openai-codex', context.scope)+ expect(api).toHaveBeenLastCalledWith(+ expect.objectContaining({+ connectionId: 'athena',+ profile,+ path: '/api/providers/oauth/openai-codex/start'+ })+ )+ await context.requestGateway('setup.status')+ await context.requestGateway('setup.runtime_check', { provider: 'openai-codex' })+ await context.requestGateway('model.options', { profile, explicit_only: true })+ const params = sharedRemote ? { profile } : {}+ expect(mocks.rpc).toHaveBeenCalledWith('setup.status', params)+ expect(localDial).not.toHaveBeenCalled()+ expect(mocks.rpc).toHaveBeenCalledWith('setup.runtime_check', { provider: 'openai-codex', ...params })+ expect(mocks.rpc).toHaveBeenCalledWith('model.options', { explicit_only: true, ...params })+ expect(localRequest).not.toHaveBeenCalled()+})++it('keeps an explicitly untagged owner through Change → Add provider', async () => {+ const owner = { connectionId: null, profile: 'legacy' }+ const api = vi.fn(async (_request: HermesApiRequest) => ({ providers: [] }))+ Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: { api } })+ startManualProviderOAuth('openai-codex', owner)+ setApiRequestConnection('athena')+ setApiRequestProfile('default')+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })++ render(+ <QueryClientProvider client={client}>+ <FlowPanel+ ctx={{ scope: owner, profile: owner.profile, requestGateway: async () => ({ providers: [] }) as never }}+ flow={{+ status: 'confirming_model',+ currentModel: 'fixture-model',+ providerSlug: 'openai-codex',+ label: 'Codex',+ saving: false+ }}+ leaving={false}+ onBegin={() => undefined}+ />+ </QueryClientProvider>+ )+ fireEvent.click(screen.getByRole('button', { name: 'Change' }))+ fireEvent.click(await screen.findByRole('button', { name: 'Add provider' }))+ expect($desktopOnboarding.get().targetScope).toEqual(owner)+ await waitFor(() =>+ expect(api).toHaveBeenCalledWith(expect.objectContaining({ path: '/api/providers/oauth', profile: 'legacy' }))+ )+ expect(api.mock.calls.every(([request]) => !(request as { connectionId?: string }).connectionId)).toBe(true)+ client.clear()+})diff --git a/apps/desktop/src/components/onboarding/flow.tsx b/apps/desktop/src/components/onboarding/flow.tsxindex ed4fff038e6..01c9c190bb6 100644--- a/apps/desktop/src/components/onboarding/flow.tsx+++ b/apps/desktop/src/components/onboarding/flow.tsx@@ -6,7 +6,7 @@ import { Button } from '@/components/ui/button'import { ErrorIcon } from '@/components/ui/error-state'import { Input } from '@/components/ui/input'import { Loader } from '@/components/ui/loader'-import { getGlobalModelOptions } from '@/hermes'+import { getGlobalModelOptions, profileScopeKey } from '@/hermes'import { useI18n } from '@/i18n'import { ExternalLink, Loader2 } from '@/lib/icons'import { cn } from '@/lib/utils'@@ -54,7 +54,7 @@ export function FlowPanel({}if (flow.status === 'confirming_model') {- return <ConfirmingModelPanel flow={flow} leaving={leaving} onBegin={onBegin} profile={ctx.profile} />+ return <ConfirmingModelPanel ctx={ctx} flow={flow} leaving={leaving} onBegin={onBegin} />}if (flow.status === 'error') {@@ -79,7 +79,7 @@ export function FlowPanel({<Button onClick={cancelOnboardingFlow} variant="text">{t.onboarding.pickDifferentProvider}</Button>- <Button onClick={() => startManualOnboarding(null, ctx.profile)} variant="outline">+ <Button onClick={() => startManualOnboarding(null, ctx.scope ?? ctx.profile)} variant="outline">{t.onboarding.useApiKeyInstead}</Button>{failedProvider ? (@@ -237,12 +237,12 @@ function ConfirmingModelPanel({flow,leaving,onBegin,- profile+ ctx}: {flow: Extract<OnboardingFlow, { status: 'confirming_model' }>leaving: booleanonBegin: () => void- profile?: string+ ctx: OnboardingContext}) {const { t } = useI18n()const scrambledModel = useScramble(flow.currentModel, leaving)@@ -257,8 +257,8 @@ function ConfirmingModelPanel({// Pull pricing + tier for the just-picked default so the confirm card// shows the same $/Mtok + Free/Pro info the picker and CLI do.const options = useQuery({- queryKey: ['onboarding-model-options', flow.providerSlug],- queryFn: () => getGlobalModelOptions({ includeUnconfigured: true, explicitOnly: false })+ queryKey: ['onboarding-model-options', profileScopeKey(ctx.scope ?? ctx.profile), flow.providerSlug],+ queryFn: () => getGlobalModelOptions({ includeUnconfigured: true, explicitOnly: false }, ctx.scope ?? ctx.profile)})const providerRow = options.data?.providers?.find(@@ -352,7 +352,9 @@ function ConfirmingModelPanel({setPickerOpen(false)}}open={pickerOpen}- profile={profile}+ ownerConnectionId={ctx.scope ? (ctx.scope.connectionId ?? null) : undefined}+ profile={ctx.profile}+ request={ctx.requestGateway}/></div>)diff --git a/apps/desktop/src/components/onboarding/index.tsx b/apps/desktop/src/components/onboarding/index.tsxindex 42482347a06..742ec863657 100644--- a/apps/desktop/src/components/onboarding/index.tsx+++ b/apps/desktop/src/components/onboarding/index.tsx@@ -63,7 +63,8 @@ export {sortProviders} from './providers'-import { requestGatewayForProfile } from '@/store/gateway'+import { $gateway, activeGatewayConnectionId } from '@/store/gateway'+import { requestOnboardingGateway } from '@/store/onboarding-scope'interface DesktopOnboardingOverlayProps {enabled: boolean@@ -131,7 +132,7 @@ const API_KEY_OPTIONS: ApiKeyOption[] = [// other api_key provider is appended with a generic "paste {KEY}" affordance.// OAuth / external providers are intentionally excluded here — they go through// the OAuth picker / sign-in flow, not a pasted key.-function useApiKeyCatalog(): ApiKeyOption[] {+function useApiKeyCatalog(scope: OnboardingContext['scope']): ApiKeyOption[] {const [rows, setRows] = useState<ModelOptionProvider[]>([])useEffect(() => {@@ -141,7 +142,7 @@ function useApiKeyCatalog(): ApiKeyOption[] {// Promise.resolve().then so a synchronous throw (e.g. no desktop bridge in// tests) is funneled into the same .catch instead of escaping.void Promise.resolve()- .then(() => getGlobalModelOptions({ includeUnconfigured: true, explicitOnly: false }))+ .then(() => getGlobalModelOptions({ includeUnconfigured: true, explicitOnly: false }, scope)).then(res => {if (!cancelled) {setRows(res.providers ?? [])@@ -154,7 +155,7 @@ function useApiKeyCatalog(): ApiKeyOption[] {return () => {cancelled = true}- }, [])+ }, [scope])return useMemo(() => {const curatedByEnv = new Map(API_KEY_OPTIONS.map(o => [o.envKey, o]))@@ -210,18 +211,26 @@ export function DesktopOnboardingOverlay({useStore($onboardingSurfaces)const onCompletedRef = useRef(onCompleted)onCompletedRef.current = onCompleted- const targetProfile = onboarding.targetProfile ?? profile+ useStore($gateway)+ const connectionId = activeGatewayConnectionId()++ const scope = useMemo(+ () => onboarding.targetScope ?? { connectionId, profile },+ [onboarding.targetScope, profile, connectionId]+ )// 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,+ scope,+ profile: scope.profile ?? undefined,+ requestGateway:+ scope.profile && (onboarding.targetScope || scope.connectionId)+ ? (method, params) => requestOnboardingGateway(scope, method, params)+ : requestGateway,onCompleted: () => onCompletedRef.current?.()}),- [onboarding.targetProfile, targetProfile, requestGateway]+ [onboarding.targetScope, scope, requestGateway])// Cinematic exit on "Begin": dissolve the panel + overlay (revealing the chat@@ -606,7 +615,7 @@ export function Picker({ ctx }: { ctx: OnboardingContext }) {const ordered = useMemo(() => (providers ? sortProviders(providers) : []), [providers])const hasOauth = ordered.length > 0- const apiKeyOptions = useApiKeyCatalog()+ const apiKeyOptions = useApiKeyCatalog(ctx.scope)// localEndpoint forces the key form regardless of `mode` (which a manual// provider refresh may flip back to 'oauth'); it preselects the local optiondiff --git a/apps/desktop/src/store/model-assignment.ts b/apps/desktop/src/store/model-assignment.tsindex c044e1f7a93..6af72a8967c 100644--- a/apps/desktop/src/store/model-assignment.ts+++ b/apps/desktop/src/store/model-assignment.ts@@ -1,4 +1,4 @@-import { setModelAssignment } from '@/hermes'+import { type ProfileScope, setModelAssignment } from '@/hermes'import { translateNow } from '@/i18n'import { dismissNotification, notify } from '@/store/notifications'import type { ModelAssignmentRequest, ModelAssignmentResponse } from '@/types/hermes'@@ -41,7 +41,7 @@ function confirmModelWarning(message: string): Promise<boolean> {export async function setMainModelAssignment(request: Omit<ModelAssignmentRequest, 'scope'>,- scopeProfile?: null | string,+ scopeProfile?: ProfileScope,options?: { skipConfirmPrompt?: boolean }): Promise<ModelAssignmentResponse> {// Only pass the extra arg when a scope override exists, so unscoped callersdiff --git a/apps/desktop/src/store/onboarding-owner.test.ts b/apps/desktop/src/store/onboarding-owner.test.tsnew file mode 100644index 00000000000..015f1501572--- /dev/null+++ b/apps/desktop/src/store/onboarding-owner.test.ts@@ -0,0 +1,183 @@+import { afterEach, beforeEach, expect, it, vi } from 'vitest'++import { setApiRequestConnection, setApiRequestProfile } from '@/api/client'+import type { HermesApiRequest } from '@/global'+import { makeOAuthProvider } from '@/test/oauth-provider'++import {+ $desktopOnboarding,+ closeManualOnboarding,+ type OnboardingContext,+ saveOnboardingLocalEndpoint,+ setOnboardingCode,+ setOnboardingModel,+ startManualProviderOAuth,+ startProviderOAuth,+ submitOnboardingCode+} from './onboarding'+import { captureOnboardingScope } from './onboarding-scope'++const owner = { connectionId: 'athena', profile: 'leverage-ai' }+const requests: HermesApiRequest[] = []+let authFlow: 'device_code' | 'pkce'+let deferStart: (() => Promise<void>) | undefined++beforeEach(() => {+ vi.useFakeTimers()+ authFlow = 'device_code'+ deferStart = undefined+ requests.length = 0+ setApiRequestConnection(owner.connectionId)+ setApiRequestProfile(owner.profile)+ Object.defineProperty(window, 'hermesDesktop', {+ configurable: true,+ value: {+ openExternal: vi.fn(async () => undefined),+ api: vi.fn(async (request: HermesApiRequest) => {+ requests.push(request)+ const { path } = request++ if (path === '/api/providers/oauth') {+ return { providers: [makeOAuthProvider('openai-codex')] }+ }++ if (path.endsWith('/start')) {+ await deferStart?.()++ return {+ flow: authFlow,+ session_id: 'fixture-session',+ auth_url: 'https://example.invalid/authorize',+ verification_url: 'https://example.invalid/device',+ user_code: 'fixture-code',+ expires_in: 600+ }+ }++ if (path.includes('/poll/') || path.endsWith('/submit')) {+ return { ok: true, status: 'approved' }+ }++ if (path.startsWith('/api/model/options')) {+ return { providers: [{ slug: 'openai-codex', models: ['fixture-model'] }] }+ }++ if (path.startsWith('/api/model/recommended-default')) {+ return { model: 'fixture-model' }+ }++ if (path === '/api/providers/validate') {+ return { ok: true, reachable: true, models: ['endpoint-model'] }+ }++ return { ok: true }+ })+ }+ })+})++afterEach(() => {+ closeManualOnboarding()+ setApiRequestConnection(null)+ setApiRequestProfile(null)+ vi.useRealTimers()+ delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop+})++function beginContext(): OnboardingContext {+ startManualProviderOAuth('openai-codex', 'leverage-ai')++ return {+ scope: $desktopOnboarding.get().targetScope,+ requestGateway: vi.fn(+ async method => (method === 'setup.status' ? { provider_configured: true } : { ok: true }) as never+ )+ }+}++function switchForeground() {+ setApiRequestConnection('local')+ setApiRequestProfile('default')+}++function expectOwnerRequests() {+ expect(requests.length).toBeGreaterThan(0)++ for (const request of requests) {+ expect(request).toMatchObject(owner)+ }+}++it.each(['device_code', 'pkce'] as const)(+ 'pins %s completion and model edits after a foreground switch',+ async flow => {+ authFlow = flow+ const ctx = beginContext()+ await startProviderOAuth({ ...makeOAuthProvider('openai-codex'), flow }, ctx)+ switchForeground()++ if (flow === 'pkce') {+ setOnboardingCode('fixture-code')+ await submitOnboardingCode(ctx)+ } else {+ await vi.advanceTimersByTimeAsync(3000)+ }++ expect($desktopOnboarding.get().flow.status).toBe('confirming_model')+ expect(ctx.requestGateway).not.toHaveBeenCalledWith('reload.env')+ expect(ctx.requestGateway).toHaveBeenCalledWith('setup.runtime_check', { provider: 'openai-codex' })+ await setOnboardingModel('other-fixture-model', 'openai-codex')+ expect(requests.filter(request => request.path === '/api/model/set')).toHaveLength(2)+ expect(requests.some(request => request.path.includes(flow === 'pkce' ? '/submit' : '/poll/'))).toBe(true)+ expectOwnerRequests()+ }+)++it('cancels on the original owner after the foreground changes', async () => {+ const ctx = beginContext()+ await startProviderOAuth({ ...makeOAuthProvider('openai-codex'), flow: 'device_code' }, ctx)+ switchForeground()+ closeManualOnboarding()+ expect(requests.at(-1)).toMatchObject({ method: 'DELETE', path: '/api/providers/oauth/sessions/fixture-session' })+ expectOwnerRequests()+})++it('cancels a late OAuth start on its retired owner, not a newly opened flow', async () => {+ let release!: () => void+ deferStart = () =>+ new Promise<void>(resolve => {+ release = resolve+ })+ const ctx = beginContext()+ const pending = startProviderOAuth(makeOAuthProvider('openai-codex'), ctx)+ expect(release).toBeTypeOf('function')+ closeManualOnboarding()+ switchForeground()+ startManualProviderOAuth('openai-codex', 'default')+ release()+ await pending+ expect(requests.at(-1)).toMatchObject({ ...owner, method: 'DELETE' })+ expect($desktopOnboarding.get().targetScope).toEqual({ connectionId: 'local', profile: 'default' })+ expect($desktopOnboarding.get().flow.status).toBe('idle')+})++it('pins local-endpoint validation and persistence to the setup owner', async () => {+ const ctx = beginContext()+ switchForeground()+ await saveOnboardingLocalEndpoint('http://127.0.0.1:11434/v1', '', ctx)+ expect(requests.some(request => request.path === '/api/providers/validate')).toBe(true)+ expect(requests.some(request => request.path === '/api/model/set')).toBe(true)+ expectOwnerRequests()+})++it('preserves explicit local and untagged legacy routes instead of filling ambient halves', () => {+ expect(captureOnboardingScope({ connectionId: 'local', profile: 'default' })).toEqual({+ connectionId: 'local',+ profile: 'default'+ })+ expect(captureOnboardingScope({ profile: 'legacy' })).toEqual({ profile: 'legacy' })+ setApiRequestConnection(null)+ const legacy = captureOnboardingScope('legacy')+ setApiRequestConnection('athena')+ expect(legacy).toEqual({ connectionId: null, profile: 'legacy' })+})diff --git a/apps/desktop/src/store/onboarding-scope.ts b/apps/desktop/src/store/onboarding-scope.tsnew file mode 100644index 00000000000..f73dafa4ad1--- /dev/null+++ b/apps/desktop/src/store/onboarding-scope.ts@@ -0,0 +1,54 @@+import { getApiRequestConnection, getApiRequestProfile, type ProfileScope } from '@/hermes'+import { RECONNECT_ATTEMPT_TIMEOUT_MS, withTimeout } from '@/lib/with-timeout'+import { requestGatewayForAgent } from '@/store/gateway'++export interface OnboardingScope {+ connectionId?: null | string+ profile?: null | string+}++/** Capture both halves once. An absent connection keeps legacy per-profile+ * routing; it must not acquire a different ambient registry owner later. */+export function captureOnboardingScope(scope?: ProfileScope): OnboardingScope {+ if (scope && typeof scope === 'object') {+ return { ...scope }+ }++ return {+ connectionId: getApiRequestConnection(),+ profile: scope === undefined ? getApiRequestProfile() : scope+ }+}++/** Desktop profile keys can be SSH aliases. Only shared descriptors interpret+ * them as backend request scopes; dedicated backends already own their home. */+export async function requestOnboardingGateway<T>(+ scope: OnboardingScope,+ method: string,+ params: Record<string, unknown> = {}+): Promise<T> {+ const profile = scope.profile || 'default'+ const desktop = window.hermesDesktop++ if (scope.connectionId && !desktop.getConnectionFor) {+ throw new Error('This Desktop build cannot dial registry connections. Update Hermes Desktop.')+ }++ const connection = await withTimeout(+ scope.connectionId+ ? desktop.getConnectionFor!({ connectionId: scope.connectionId, profile })+ : desktop.getConnection(profile),+ RECONNECT_ATTEMPT_TIMEOUT_MS,+ `Timed out resolving provider setup for "${profile}"`+ )++ const routedParams = { ...params }++ delete routedParams.profile++ if (connection.sharedPrimary || connection.sharedRemote) {+ routedParams.profile = profile+ }++ return requestGatewayForAgent<T>(scope.connectionId ?? null, profile, method, routedParams)+}diff --git a/apps/desktop/src/store/onboarding.test.ts b/apps/desktop/src/store/onboarding.test.tsindex cdbb4b15841..38be4b6f1d7 100644--- a/apps/desktop/src/store/onboarding.test.ts+++ b/apps/desktop/src/store/onboarding.test.ts@@ -147,7 +147,7 @@ describe('refreshOnboarding', () => {release()await pendingexpect(requests.some(r => r.path === '/api/model/set')).toBe(false)- expect($desktopOnboarding.get()).toMatchObject({ targetProfile: 'alpha', flow: { status: 'idle' } })+ expect($desktopOnboarding.get()).toMatchObject({ targetScope: { profile: 'alpha' }, flow: { status: 'idle' } })closeManualOnboarding()delayKey = falseprofile = 'beta'diff --git a/apps/desktop/src/store/onboarding.ts b/apps/desktop/src/store/onboarding.tsindex e839e9fc618..85f82edbede 100644--- a/apps/desktop/src/store/onboarding.ts+++ b/apps/desktop/src/store/onboarding.ts@@ -7,6 +7,7 @@ import {getRecommendedDefaultModel,listOAuthProviders,pollOAuthSession,+ type ProfileScope,setEnvVar,startOAuthLogin,submitOAuthCode,@@ -19,6 +20,7 @@ import { ackFreeTierNotice, freeTierReadyPending, refreshFreeTierStatus, setFreeimport { setMainModelAssignment } from '@/store/model-assignment'import { notify, notifyError } from '@/store/notifications'import { guidedOnboardingActive } from '@/store/onboarding-gate'+import { captureOnboardingScope, type OnboardingScope } from '@/store/onboarding-scope'import type { OAuthProvider, OAuthStartResponse } from '@/types/hermes'type PkceStart = Extract<OAuthStartResponse, { flow: 'pkce' }>@@ -72,7 +74,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+ targetScope?: OnboardingScope/** 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@@ -89,6 +91,7 @@ export interface DesktopOnboardingState {export interface OnboardingContext {onCompleted?: () => voidprofile?: string+ scope?: OnboardingScoperequestGateway: <T = unknown>(method: string, params?: Record<string, unknown>) => Promise<T>}@@ -171,12 +174,16 @@ const INITIAL: DesktopOnboardingState = {export const $desktopOnboarding = atom<DesktopOnboardingState>(INITIAL)let flowGeneration = 0-let flowProfile: string | undefined+let flowScope: OnboardingScope | undefinedlet pollTimer: number | null = nulllet providersRefreshPromise: null | Promise<void> = nullconst errMessage = (e: unknown) => (e instanceof Error ? e.message : String(e))+function captureContext(ctx: OnboardingContext): OnboardingContext & { scope: OnboardingScope } {+ return { ...ctx, scope: captureOnboardingScope(ctx.scope ?? ctx.profile) }+}+// One plain sentence for every way a provider sign-in can fail (start, poll,// code exchange); the raw error text rides along as `detail` (desktop-09).function signInDidNotFinish(provider: OAuthProvider, raw: unknown): { message: string; detail?: string } {@@ -282,7 +289,7 @@ function notifyGatewayTools(tools: string[] | undefined) {// opportunistic polish, not a hard requirement for onboarding.async function fetchProviderDefaultModel(preferredSlugs: string[],- profile?: string+ profile?: ProfileScope): Promise<null | { providerSlug: string; defaultModel: string }> {let options@@ -370,13 +377,18 @@ async function completeWithModelConfirm(ignoreRuntimeGate = false) {const generation = flowGeneration- await ctx.requestGateway('reload.env').catch(() => undefined)++ // Scoped readiness reads fresh credentials; reload.env only mutates the+ // launch process environment and cannot reload another profile safely.+ if (!ctx.scope?.profile) {+ await ctx.requestGateway('reload.env').catch(() => undefined)+ }if (generation !== flowGeneration) {return}- const defaults = await fetchProviderDefaultModel(preferredSlugs, ctx.profile)+ const defaults = await fetchProviderDefaultModel(preferredSlugs, ctx.scope)if (generation !== flowGeneration) {return@@ -392,7 +404,7 @@ async function completeWithModelConfirm(provider: defaults.providerSlug,model: defaults.defaultModel},- ctx.profile,+ ctx.scope,// Headless automated flow: nothing is mounted to click a guard// prompt, so fail with the message instead of hanging.{ skipConfirmPrompt: true }@@ -470,7 +482,7 @@ async function refreshProviders() {const generation = flowGenerationprovidersRefreshPromise = (async () => {try {- const { providers } = await listOAuthProviders($desktopOnboarding.get().targetProfile)+ const { providers } = await listOAuthProviders($desktopOnboarding.get().targetScope)if (generation !== flowGeneration) {return@@ -545,12 +557,15 @@ 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, profile?: string) {+export function startManualOnboarding(+ reason: null | string = DEFAULT_MANUAL_ONBOARDING_REASON,+ profile?: ProfileScope+) {cancelOnboardingFlow()providersRefreshPromise = nullpatch({manual: true,- targetProfile: profile,+ targetScope: captureOnboardingScope(profile),providers: null,requested: true,localEndpoint: false,@@ -570,12 +585,12 @@ 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, profile?: string) {+export function startManualLocalEndpoint(reason: null | string = null, profile?: ProfileScope) {cancelOnboardingFlow()pendingProviderOAuthId = nullpatch({manual: true,- targetProfile: profile,+ targetScope: captureOnboardingScope(profile),providers: null,requested: true,localEndpoint: true,@@ -593,7 +608,7 @@ export function startManualLocalEndpoint(reason: null | string = null, profile?:// overlay render and never needs to persist or re-render anything itself.let pendingProviderOAuthId: null | string = null-export function startManualProviderOAuth(providerId: string, profile?: string) {+export function startManualProviderOAuth(providerId: string, profile?: ProfileScope) {pendingProviderOAuthId = providerIdstartManualOnboarding(null, profile)}@@ -619,7 +634,7 @@ export function closeManualOnboarding() {pendingProviderOAuthId = nullpatch({- targetProfile: undefined,+ targetScope: undefined,manual: false,requested: false,localEndpoint: false,@@ -798,9 +813,9 @@ async function openSignInUrl(url: string) {}export async function startProviderOAuth(provider: OAuthProvider, ctx: OnboardingContext) {- ctx = { ...ctx }+ ctx = captureContext(ctx)const generation = flowGeneration- flowProfile = ctx.profile+ flowScope = ctx.scopeclearPoll()if (provider.flow === 'external') {@@ -812,10 +827,10 @@ export async function startProviderOAuth(provider: OAuthProvider, ctx: OnboardinsetFlow({ status: 'starting', provider })try {- const start = await startOAuthLogin(provider.id, ctx.profile)+ const start = await startOAuthLogin(provider.id, ctx.scope)if (generation !== flowGeneration) {- void cancelOAuthSession(start.session_id, ctx.profile).catch(() => undefined)+ void cancelOAuthSession(start.session_id, ctx.scope).catch(() => undefined)return}@@ -824,7 +839,7 @@ export async function startProviderOAuth(provider: OAuthProvider, ctx: Onboardinawait openSignInUrl(browserUrl)if (generation !== flowGeneration) {- void cancelOAuthSession(start.session_id, ctx.profile).catch(() => undefined)+ void cancelOAuthSession(start.session_id, ctx.scope).catch(() => undefined)return}@@ -857,7 +872,7 @@ export async function startProviderOAuth(provider: OAuthProvider, ctx: Onboardin// Poll a session-backed device-code flow until it resolves.async function pollSession(provider: OAuthProvider, start: DeviceStart, ctx: OnboardingContext, generation: number) {try {- const { error_message, status } = await pollOAuthSession(provider.id, start.session_id, ctx.profile)+ const { error_message, status } = await pollOAuthSession(provider.id, start.session_id, ctx.scope)if (generation !== flowGeneration) {return@@ -896,9 +911,9 @@ export function setOnboardingCode(code: string) {}export async function submitOnboardingCode(ctx: OnboardingContext) {- ctx = { ...ctx }+ ctx = captureContext(ctx)const generation = flowGeneration- flowProfile = ctx.profile+ flowScope = ctx.scopeconst { flow } = $desktopOnboarding.get()if (flow.status !== 'awaiting_user' || !flow.code.trim()) {@@ -909,7 +924,7 @@ export async function submitOnboardingCode(ctx: OnboardingContext) {setFlow({ status: 'submitting', provider, start })try {- const resp = await submitOAuthCode(provider.id, start.session_id, code.trim(), ctx.profile)+ const resp = await submitOAuthCode(provider.id, start.session_id, code.trim(), ctx.scope)if (generation !== flowGeneration) {return@@ -942,9 +957,10 @@ export function cancelOnboardingFlow() {const sessionId = sessionIdFor($desktopOnboarding.get().flow)if (sessionId) {- cancelOAuthSession(sessionId, flowProfile ?? $desktopOnboarding.get().targetProfile).catch(() => undefined)+ cancelOAuthSession(sessionId, flowScope ?? $desktopOnboarding.get().targetScope).catch(() => undefined)}+ flowScope = undefinedsetFlow({ status: 'idle' })}@@ -994,8 +1010,8 @@ export async function copyExternalCommand() {}export async function recheckExternalSignin(ctx: OnboardingContext) {- ctx = { ...ctx }- flowProfile = ctx.profile+ ctx = captureContext(ctx)+ flowScope = ctx.scopeconst { flow } = $desktopOnboarding.get()if (flow.status !== 'external_pending') {@@ -1024,9 +1040,9 @@ export async function saveOnboardingApiKey(// providers (their key IS `value`).endpointApiKey?: string) {- ctx = { ...ctx }+ ctx = captureContext(ctx)const generation = flowGeneration- flowProfile = ctx.profile+ flowScope = ctx.scopeconst trimmed = value.trim()if (!trimmed) {@@ -1047,7 +1063,7 @@ 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, ctx.profile)+ await setEnvVar(envKey, trimmed, ctx.scope)if (generation !== flowGeneration) {return { ok: false }@@ -1088,9 +1104,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 }+ ctx = captureContext(ctx)const generation = flowGeneration- flowProfile = ctx.profile+ flowScope = ctx.scopeconst url = baseUrl.trim()const key = apiKey.trim()@@ -1108,7 +1124,7 @@ export async function saveOnboardingLocalEndpoint(baseUrl: string, apiKey: strinlet resolvedUrl = urltry {- const probe = await validateProviderCredential('OPENAI_BASE_URL', url, key)+ const probe = await validateProviderCredential('OPENAI_BASE_URL', url, key, ctx.scope)if (generation !== flowGeneration) {return { ok: false }@@ -1136,13 +1152,15 @@ export async function saveOnboardingLocalEndpoint(baseUrl: string, apiKey: strin}try {- await setMainModelAssignment({ provider: 'custom', model, base_url: resolvedUrl, api_key: key }, ctx.profile)+ await setMainModelAssignment({ provider: 'custom', model, base_url: resolvedUrl, api_key: key }, ctx.scope)if (generation !== flowGeneration) {return { ok: false }}- await ctx.requestGateway('reload.env').catch(() => undefined)+ if (!ctx.scope?.profile) {+ await ctx.requestGateway('reload.env').catch(() => undefined)+ }if (generation !== flowGeneration) {return { ok: false }@@ -1204,7 +1222,7 @@ export async function setOnboardingModel(model: string, providerSlug: string, laprovider: providerSlug,model},- flowProfile ?? $desktopOnboarding.get().targetProfile+ flowScope ?? $desktopOnboarding.get().targetScope)if (generation !== flowGeneration) {