The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): open the rejected provider's key from Update API key
Adolan77b727551b33
diff --git a/agent/error_surface.py b/agent/error_surface.pyindex 934301a6f4a..ff977fa8526 100644--- a/agent/error_surface.py+++ b/agent/error_surface.py@@ -98,9 +98,22 @@ def _surface(layer: str, code: str, retryable: bool, provider: str = "", model:# OAuth providers are fixed by signing in again; API-key providers by# replacing the key. The client's one-click recovery needs to know which.surface["auth_kind"] = auth_kind(provider)+ if surface["auth_kind"] == "api_key" and (env_var := _api_key_env(provider)):+ surface["api_key_env"] = env_varreturn surface+def _api_key_env(provider: str) -> str:+ """The env var holding ``provider``'s API key, so the client can open that row."""+ try:+ from hermes_cli.provider_catalog import provider_catalog_by_slug++ descriptor = provider_catalog_by_slug().get(provider.strip().lower())+ return descriptor.api_key_env_vars[0] if descriptor and descriptor.api_key_env_vars else ""+ except Exception: # pragma: no cover — advisory only+ return ""++def _provider_label(provider: str) -> str:try:from hermes_cli.models import provider_labeldiff --git a/apps/desktop/src/app/settings/providers-settings.test.tsx b/apps/desktop/src/app/settings/providers-settings.test.tsxindex 8ec2e8f3fe9..f52aaa2da9d 100644--- a/apps/desktop/src/app/settings/providers-settings.test.tsx+++ b/apps/desktop/src/app/settings/providers-settings.test.tsx@@ -1,5 +1,6 @@import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'import { atom } from 'nanostores'+import { MemoryRouter } from 'react-router'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { ConfirmHost } from '@/components/confirm-host'@@ -427,6 +428,25 @@ describe('ProvidersSettings', () => {expect(await screen.findByText('No providers match your search.')).toBeTruthy()})+ it('expands and scrolls to the provider named by a ?key= deep link', async () => {+ Element.prototype.scrollIntoView = vi.fn()+ getEnvVars.mockResolvedValue({+ ACME_API_KEY: keyVar({ description: 'Acme blurb', provider: 'acme', provider_label: 'Acme' }),+ ZEBRA_API_KEY: keyVar({ description: 'Zebra blurb', provider: 'zebra', provider_label: 'Zebra' })+ })+ listOAuthProviders.mockResolvedValue({ providers: [] })++ render(+ <MemoryRouter initialEntries={['/settings?tab=providers&pview=keys&key=ZEBRA_API_KEY']}>+ <ProvidersSettings onClose={vi.fn()} onViewChange={vi.fn()} view="keys" />+ </MemoryRouter>+ )++ expect(await screen.findByText('Zebra blurb')).toBeTruthy()+ expect(screen.queryByText('Acme blurb')).toBeNull()+ await waitFor(() => expect(Element.prototype.scrollIntoView).toHaveBeenCalled())+ })+it('offers a Local / custom endpoint entry in the API-keys tab that opens the custom-endpoint flow', async () => {// Regression: the composer pill and the providers "have an API key"// affordance both dead-end on the env-var-driven key catalog, which neverdiff --git a/apps/desktop/src/app/settings/providers-settings.tsx b/apps/desktop/src/app/settings/providers-settings.tsxindex 8ee97eacf1e..47088a22534 100644--- a/apps/desktop/src/app/settings/providers-settings.tsx+++ b/apps/desktop/src/app/settings/providers-settings.tsx@@ -36,6 +36,7 @@ import { providerGroup, providerMeta, providerPriority } from './helpers'import { LocalModelsSettings } from './local-models-settings'import { SettingsContent, SettingsSkeleton } from './primitives'import { SettingsProfileScope } from './profile-scope'+import { useDeepLinkHighlight } from './use-deep-link-highlight'// The embedded terminal (and thus the "run disconnect command" path) only// exists in the Electron desktop shell, not the web dashboard.@@ -68,6 +69,8 @@ export type ProviderView = (typeof PROVIDER_VIEWS)[number]// 2. Desktop prefix match (`providerGroup`) — legacy fallback for provider// env vars that predate the backend tagging.// Only entries that resolve to neither (the "Other" bucket) are skipped.+const providerKeyElementId = (name: string) => `provider-key-${name.replace(/\W+/g, '-')}`+function buildProviderKeyGroups(vars: Record<string, EnvVarInfo>): ProviderKeyGroup[] {const buckets = new Map<string, [string, EnvVarInfo][]>()@@ -401,6 +404,32 @@ export function ProvidersSettings({// they launched from this page — otherwise the cards keep their stale status.const onboardingActive = useStore($desktopOnboarding).manual+ const keyGroupByEnv = useMemo(() => {+ const byEnv = new Map<string, string>()++ for (const group of vars ? buildProviderKeyGroups(vars) : []) {+ for (const [key] of [group.primary, ...group.advanced]) {+ byEnv.set(key, group.name)+ }+ }++ return byEnv+ }, [vars])++ const apiKeysShown = view === 'keys' || (oauthProviders.length === 0 && view !== 'custom-endpoints')++ // Deep link from a rejected-key error card (?pview=keys&key=<ENV_KEY>):+ // clear the filter, expand that provider's card and scroll to it.+ useDeepLinkHighlight({+ elementId: key => providerKeyElementId(keyGroupByEnv.get(key) ?? ''),+ onResolve: key => {+ setKeyQuery('')+ setOpenProvider(keyGroupByEnv.get(key) ?? null)+ },+ param: 'key',+ ready: key => apiKeysShown && keyGroupByEnv.has(key)+ })+const refreshOAuthProviders = useCallback(async () => {// OAuth providers are best-effort — a failure here just hides the panel.const { providers } = await listOAuthProviders(scopeProfile)@@ -538,14 +567,15 @@ export function ProvidersSettings({{visibleGroups.length > 0 ? (<div className="grid gap-2">{visibleGroups.map(group => (- <ProviderKeyRows- expanded={openProvider === group.name}- group={group}- key={group.name}- onExpand={() => setOpenProvider(group.name)}- onToggle={() => setOpenProvider(prev => (prev === group.name ? null : group.name))}- rowProps={rowProps}- />+ <div className="scroll-mt-6 rounded-[6px]" id={providerKeyElementId(group.name)} key={group.name}>+ <ProviderKeyRows+ expanded={openProvider === group.name}+ group={group}+ onExpand={() => setOpenProvider(group.name)}+ onToggle={() => setOpenProvider(prev => (prev === group.name ? null : group.name))}+ rowProps={rowProps}+ />+ </div>))}</div>) : (diff --git a/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx b/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsxindex 4dfb2cd1d97..88c17523a8a 100644--- a/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx@@ -399,7 +399,9 @@ describe('rejected API key recovery', () => {expect(screen.getByRole('button', { name: 'Retry' })).toBeTruthy()screen.getByRole('button', { name: 'Update API key' }).click()- await waitFor(() => expect(screen.getByTestId('location').textContent).toMatch(/\?tab=keys&key=OPENAI_API_KEY$/))+ await waitFor(() =>+ expect(screen.getByTestId('location').textContent).toMatch(/\?tab=providers&pview=keys&key=OPENAI_API_KEY$/)+ )})})diff --git a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsxindex 19f560e1920..da67b759bdf 100644--- a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx@@ -615,12 +615,12 @@ const SwitchProviderAction: FC<{ label: string }> = ({ label }) => {)}-// Settings → Keys deep link for a rejected API key: `?tab=keys` plus-// `&key=<ENV>` when the descriptor names the env var (keys-settings.tsx-// scrolls to and expands that row). Older backends omit `api_key_env`; the-// tab alone is still the right place.+// Settings → Providers → API keys deep link for a rejected API key, plus+// `&key=<ENV>` when the descriptor names the env var (providers-settings.tsx+// scrolls to and expands that provider). Older backends omit `api_key_env`;+// the API-keys list alone is still the right place.const updateApiKeyRoute = (surface: ErrorSurface | undefined) => {- const params = new URLSearchParams({ tab: 'keys' })+ const params = new URLSearchParams({ tab: 'providers', pview: 'keys' })if (surface?.apiKeyEnv) {params.set('key', surface.apiKeyEnv)diff --git a/tests/agent/test_error_surface.py b/tests/agent/test_error_surface.pyindex 458b8e56ab5..ca689639a9a 100644--- a/tests/agent/test_error_surface.py+++ b/tests/agent/test_error_surface.py@@ -61,6 +61,11 @@ def test_auth_surface_names_oauth_vs_api_key_recovery():key = build_error_surface_from_result(_failed_result("auth"), provider="openrouter")assert key["auth_kind"] == "api_key"+ assert key["api_key_env"] == "OPENROUTER_API_KEY"+ assert "api_key_env" not in oauth++ opencode = build_error_surface_from_result(_failed_result("auth"), provider="opencode-go")+ assert opencode["api_key_env"] == "OPENCODE_GO_API_KEY"# Non-auth layers never carry the field (clients gate the button on it).assert "auth_kind" not in build_error_surface_from_result(_failed_result("rate_limit"), provider="nous")