From 024b3d969f6b15d0792cb50c2336f8983684f6cc Mon Sep 17 00:00:00 2001 From: Wesley Tanner <137104411+fireball71@users.noreply.github.com> Date: Thu, 29 Oct 2026 13:04:20 +0000 Subject: [PATCH] fix(frontend): list provider integrations in settings --- backend/src/routes/oauth.test.ts | 35 ++++++ backend/src/routes/oauth.ts | 9 ++ frontend/src/api/oauth.ts | 10 +- .../settings/ProviderSettings.test.tsx | 68 +++++++++-- .../components/settings/ProviderSettings.tsx | 114 ++++++++++++------ frontend/src/contexts/EventContext.test.tsx | 3 +- frontend/src/hooks/useProviderIntegrations.ts | 14 +++ frontend/src/lib/queryInvalidation.test.ts | 3 +- frontend/src/lib/queryInvalidation.ts | 1 + 9 files changed, 211 insertions(+), 46 deletions(-) create mode 100644 frontend/src/hooks/useProviderIntegrations.ts diff --git a/backend/src/routes/oauth.test.ts b/backend/src/routes/oauth.test.ts index ed2ceefd..78da0a07 100644 --- a/backend/src/routes/oauth.test.ts +++ b/backend/src/routes/oauth.test.ts @@ -126,6 +126,41 @@ describe('oauth routes /auth-methods', () => { }) }) +describe('oauth routes /integrations', () => { + it('returns every integration with its methods and connections', async () => { + const client = createStubOpenCodeClient() + const integrations = [ + integrationFixture({ + id: 'openrouter', + name: 'OpenRouter', + methods: [{ type: 'key' }], + }), + integrationFixture({ + id: 'anthropic', + name: 'Anthropic', + methods: [{ type: 'key' }, { type: 'env', names: ['ANTHROPIC_API_KEY'] }], + connections: [{ type: 'credential', id: 'cred_1', label: 'Anthropic', method: 'key' }], + }), + ] + vi.mocked(client.api.integration.list).mockResolvedValueOnce({ location: LOCATION, data: integrations }) + + const res = await createOAuthApp(client).request('/oauth/integrations') + + expect(res.status).toBe(200) + expect(await res.json()).toEqual({ integrations }) + }) + + it('returns 502 when the upstream is unreachable', async () => { + const client = createStubOpenCodeClient() + vi.mocked(client.api.integration.list).mockRejectedValueOnce(new ClientError('UnexpectedStatus')) + + const res = await createOAuthApp(client).request('/oauth/integrations') + + expect(res.status).toBe(502) + expect(await res.json()).toEqual({ error: 'Failed to list provider integrations', code: 'ClientError' }) + }) +}) + describe('oauth routes /:id/oauth/authorize', () => { it('starts the V2 attempt with the method and answer and returns it', async () => { const client = createStubOpenCodeClient() diff --git a/backend/src/routes/oauth.ts b/backend/src/routes/oauth.ts index 9af60b6a..6a6bf5e7 100644 --- a/backend/src/routes/oauth.ts +++ b/backend/src/routes/oauth.ts @@ -23,6 +23,15 @@ export function createOAuthRoutes(openCodeClient: OpenCodeClient) { } }) + app.get('/integrations', async (c) => { + try { + const integrations = await openCodeClient.api.integration.list() + return c.json({ integrations: integrations.data }) + } catch (error) { + return handleOpenCodeError(c, error, 'Failed to list provider integrations') + } + }) + app.post('/:id/oauth/authorize', async (c) => { try { const body = await c.req.json() diff --git a/frontend/src/api/oauth.ts b/frontend/src/api/oauth.ts index 5546b79b..a4f75306 100644 --- a/frontend/src/api/oauth.ts +++ b/frontend/src/api/oauth.ts @@ -1,5 +1,5 @@ import { API_BASE_URL } from "@/config" -import type { FormAnswer, IntegrationMethod } from "@opencode-manager/shared/opencode" +import type { FormAnswer, IntegrationInfo, IntegrationMethod } from "@opencode-manager/shared/opencode" import type { OAuthAttemptStatus, OAuthAuthorizeResponse } from "@opencode-manager/shared/schemas" import { fetchWrapper, fetchWrapperVoid } from "./fetchWrapper" @@ -7,6 +7,7 @@ export type { FormAnswer, FormField, FormValue, + IntegrationInfo, IntegrationKeyMethod, IntegrationMethod, IntegrationOAuthMethod, @@ -45,4 +46,11 @@ export const oauthApi = { ) return providers }, + + getIntegrations: async (): Promise => { + const { integrations } = await fetchWrapper<{ integrations: IntegrationInfo[] }>( + `${API_BASE_URL}/api/oauth/integrations` + ) + return integrations + }, } diff --git a/frontend/src/components/settings/ProviderSettings.test.tsx b/frontend/src/components/settings/ProviderSettings.test.tsx index a922cda9..10dae484 100644 --- a/frontend/src/components/settings/ProviderSettings.test.tsx +++ b/frontend/src/components/settings/ProviderSettings.test.tsx @@ -6,7 +6,7 @@ import { ProviderSettings } from './ProviderSettings' import { getProviders, providerCredentialsApi } from '@/api/providers' import { oauthApi } from '@/api/oauth' import type { Provider } from '@/api/providers' -import type { OAuthAuthorizeResponse } from '@/api/oauth' +import type { IntegrationInfo, IntegrationMethod, OAuthAuthorizeResponse } from '@/api/oauth' import type { ReactNode } from 'react' vi.mock('@/api/providers', () => ({ @@ -22,6 +22,7 @@ vi.mock('@/api/providers', () => ({ vi.mock('@/api/oauth', () => ({ oauthApi: { getAuthMethods: vi.fn(), + getIntegrations: vi.fn(), authorize: vi.fn(), callback: vi.fn(), }, @@ -102,6 +103,25 @@ const oauthProviderWithoutKey = providerFixture('google', 'Google', 3) const apiKeyProviderWithKey = providerFixture('openai', 'OpenAI', 1) const apiKeyProviderWithoutKey = providerFixture('together', 'Together AI', 4) +const oauthMethod: IntegrationMethod = { id: 'oauth', type: 'oauth', label: 'OAuth' } +const keyMethod: IntegrationMethod = { type: 'key', label: 'API key' } + +function integrationFixture( + id: string, + name: string, + methods: IntegrationMethod[], + connected = false, +): IntegrationInfo { + return { + id, + name, + methods, + connections: connected + ? [{ type: 'credential', id: `cred_${id}`, label: name, method: 'key' }] + : [], + } +} + function mockProviderData() { vi.mocked(getProviders).mockResolvedValue({ providers: [ @@ -112,11 +132,12 @@ function mockProviderData() { ], models: [], }) - vi.mocked(providerCredentialsApi.list).mockResolvedValue(['anthropic', 'openai']) - vi.mocked(oauthApi.getAuthMethods).mockResolvedValue({ - anthropic: [{ id: 'oauth', type: 'oauth', label: 'OAuth' }], - google: [{ id: 'oauth', type: 'oauth', label: 'OAuth' }], - }) + vi.mocked(oauthApi.getIntegrations).mockResolvedValue([ + integrationFixture('anthropic', 'Anthropic', [oauthMethod], true), + integrationFixture('google', 'Google', [oauthMethod]), + integrationFixture('openai', 'OpenAI', [keyMethod], true), + integrationFixture('together', 'Together AI', [keyMethod]), + ]) } function renderSettings() { @@ -270,11 +291,44 @@ describe('ProviderSettings', () => { }) it('shows the empty state when no OAuth-capable providers exist', async () => { - vi.mocked(oauthApi.getAuthMethods).mockResolvedValue({}) + vi.mocked(getProviders).mockResolvedValue({ providers: [], models: [] }) + vi.mocked(oauthApi.getIntegrations).mockResolvedValue([ + integrationFixture('openai', 'OpenAI', [keyMethod]), + integrationFixture('together', 'Together AI', [keyMethod]), + ]) renderSettings() await screen.findByText('No OAuth-capable providers available.') expect(screen.queryByText('Anthropic')).not.toBeInTheDocument() }) + + it('lists an unconfigured provider when the active catalog has no providers', async () => { + vi.mocked(getProviders).mockResolvedValue({ providers: [], models: [] }) + vi.mocked(oauthApi.getIntegrations).mockResolvedValue([ + integrationFixture('openrouter', 'OpenRouter', [keyMethod]), + ]) + const user = userEvent.setup() + renderSettings() + + await screen.findByText('OpenRouter') + expect(screen.getByRole('button', { name: /Available Providers/ })).toHaveTextContent('1') + + await user.type(screen.getByPlaceholderText('Search providers...'), 'openrouter') + expect(screen.getByText('OpenRouter')).toBeInTheDocument() + + await user.click(screen.getByRole('button', { name: 'Add Key' })) + expect(screen.getByTestId('api-key-dialog')).toHaveTextContent('OpenRouter') + }) + + it('lists OAuth integrations that are not in the active catalog', async () => { + vi.mocked(getProviders).mockResolvedValue({ providers: [], models: [] }) + vi.mocked(oauthApi.getIntegrations).mockResolvedValue([ + integrationFixture('github-copilot', 'GitHub Copilot', [oauthMethod]), + ]) + renderSettings() + + await screen.findByText('GitHub Copilot') + expect(screen.getByRole('button', { name: 'Connect' })).toBeInTheDocument() + }) }) diff --git a/frontend/src/components/settings/ProviderSettings.tsx b/frontend/src/components/settings/ProviderSettings.tsx index cdcabb6d..ccf6aa1a 100644 --- a/frontend/src/components/settings/ProviderSettings.tsx +++ b/frontend/src/components/settings/ProviderSettings.tsx @@ -7,14 +7,64 @@ import { DeleteDialog } from '@/components/ui/delete-dialog' import { Loader2, Check, X, Shield, ChevronDown, ChevronRight, Key, Search, Pencil, Trash2 } from 'lucide-react' import { providerCredentialsApi } from '@/api/providers' import type { Provider } from '@/api/providers' -import { type OAuthAuthorizeResponse } from '@/api/oauth' -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { type IntegrationInfo, type IntegrationMethod, type OAuthAuthorizeResponse } from '@/api/oauth' +import { useMutation, useQueryClient } from '@tanstack/react-query' import { OAuthAuthorizeDialog } from './OAuthAuthorizeDialog' import { OAuthCallbackDialog } from './OAuthCallbackDialog' import { ApiKeyDialog } from '@/components/model/ApiKeyDialog' import { invalidateProviderCaches } from '@/lib/queryInvalidation' import { useProviders } from '@/hooks/useProviders' -import { useProviderAuthMethods } from '@/hooks/useProviderAuthMethods' +import { useProviderIntegrations } from '@/hooks/useProviderIntegrations' + +interface ProviderEntry { + id: string + name: string + models: Provider['models'] + methods: IntegrationMethod[] + connected: boolean +} + +function hasCredentialConnection(integration: IntegrationInfo): boolean { + return integration.connections.some((connection) => connection.type === 'credential') +} + +function supportsOAuthMethods(methods: IntegrationMethod[]): boolean { + return methods.some((method) => method.type === 'oauth') +} + +function buildProviderEntries( + providers: Provider[] | undefined, + integrations: IntegrationInfo[] | undefined, +): ProviderEntry[] { + const integrationsByID = new Map((integrations ?? []).map((integration) => [integration.id, integration])) + const seen = new Set() + const entries: ProviderEntry[] = [] + + for (const provider of providers ?? []) { + const integration = integrationsByID.get(provider.id) + seen.add(provider.id) + entries.push({ + id: provider.id, + name: integration?.name || provider.name || provider.id, + models: provider.models, + methods: integration?.methods ?? [], + connected: integration ? hasCredentialConnection(integration) : false, + }) + } + + const integrationOnly = (integrations ?? []) + .filter((integration) => !seen.has(integration.id) && integration.methods.length > 0) + .sort((a, b) => a.name.localeCompare(b.name)) + .map((integration): ProviderEntry => ({ + id: integration.id, + name: integration.name || integration.id, + models: [], + methods: integration.methods, + connected: hasCredentialConnection(integration), + })) + + return [...entries, ...integrationOnly] +} export function ProviderSettings() { const [selectedProvider, setSelectedProvider] = useState(null) @@ -34,12 +84,12 @@ export function ProviderSettings() { const providers = providersData?.providers - const { data: credentialsList, isLoading: credentialsLoading } = useQuery({ - queryKey: ['provider-credentials'], - queryFn: () => providerCredentialsApi.list(), - }) + const { data: integrations, isLoading: integrationsLoading } = useProviderIntegrations() - const { data: authMethods } = useProviderAuthMethods() + const providerEntries = useMemo( + () => buildProviderEntries(providers, integrations), + [providers, integrations], + ) const deleteCredentialMutation = useMutation({ mutationFn: (providerId: string) => providerCredentialsApi.delete(providerId), @@ -81,32 +131,19 @@ export function ProviderSettings() { setSelectedProvider(null) } - const supportsOAuth = useCallback((providerId: string) => { - const methods = authMethods?.[providerId] || [] - return methods.some(method => method.type === 'oauth') - }, [authMethods]) - - const hasCredentials = useCallback((providerId: string) => { - return credentialsList?.includes(providerId) || false - }, [credentialsList]) - const oauthProviders = useMemo(() => { - if (!providers || !authMethods) return [] - const oauth = providers.filter(provider => supportsOAuth(provider.id)) - return oauth.slice().sort((a, b) => { - const aConnected = hasCredentials(a.id) ? 1 : 0 - const bConnected = hasCredentials(b.id) ? 1 : 0 - return bConnected - aConnected - }) - }, [providers, authMethods, supportsOAuth, hasCredentials]) + return providerEntries + .filter((provider) => supportsOAuthMethods(provider.methods)) + .sort((a, b) => Number(b.connected) - Number(a.connected)) + }, [providerEntries]) const apiKeyProviders = useMemo(() => { - if (!providers || !authMethods) return { connected: [], available: [] } - const nonOAuthProviders = providers.filter(provider => !supportsOAuth(provider.id)) - const connected = nonOAuthProviders.filter(provider => hasCredentials(provider.id)) - const available = nonOAuthProviders.filter(provider => !hasCredentials(provider.id)) - return { connected, available } - }, [providers, authMethods, supportsOAuth, hasCredentials]) + const nonOAuthProviders = providerEntries.filter((provider) => !supportsOAuthMethods(provider.methods)) + return { + connected: nonOAuthProviders.filter((provider) => provider.connected), + available: nonOAuthProviders.filter((provider) => !provider.connected), + } + }, [providerEntries]) const filteredAvailableProviders = useMemo(() => { if (!availableSearch.trim()) return apiKeyProviders.available @@ -119,8 +156,13 @@ export function ProviderSettings() { const selectedProviderName = useMemo(() => { if (!selectedProvider) return '' - return providers?.find(p => p.id === selectedProvider)?.name || selectedProvider - }, [selectedProvider, providers]) + return providerEntries.find((provider) => provider.id === selectedProvider)?.name || selectedProvider + }, [selectedProvider, providerEntries]) + + const selectedProviderMethods = useMemo(() => { + if (!selectedProvider) return [] + return providerEntries.find((provider) => provider.id === selectedProvider)?.methods ?? [] + }, [selectedProvider, providerEntries]) const handleAddApiKey = useCallback((provider: Provider) => { setApiKeyProvider(provider) @@ -147,7 +189,7 @@ export function ProviderSettings() { } }, []) - if (providersLoading || credentialsLoading) { + if (providersLoading || integrationsLoading) { return (
@@ -177,7 +219,7 @@ export function ProviderSettings() { ) : (
{oauthProviders.map((provider) => { - const hasKey = hasCredentials(provider.id) + const hasKey = provider.connected const modelCount = provider.models.length return ( @@ -236,7 +278,7 @@ export function ProviderSettings() { { for (const queryKey of [ ['provider-credentials'], ['provider-auth-methods'], + ['provider-integrations'], ['opencode', 'providers'], ]) { expect(invalidateQueries).toHaveBeenCalledWith({ queryKey }) @@ -1149,7 +1150,7 @@ describe('EventProvider permissions and forms', () => { await waitFor(() => { expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'providers'] }) }) - expect(invalidateQueries).toHaveBeenCalledTimes(3) + expect(invalidateQueries).toHaveBeenCalledTimes(4) }) it.each<[string, string[]]>([ diff --git a/frontend/src/hooks/useProviderIntegrations.ts b/frontend/src/hooks/useProviderIntegrations.ts new file mode 100644 index 00000000..668f0d90 --- /dev/null +++ b/frontend/src/hooks/useProviderIntegrations.ts @@ -0,0 +1,14 @@ +import { useQuery } from '@tanstack/react-query' +import { oauthApi } from '@/api/oauth' + +interface UseProviderIntegrationsOptions { + enabled?: boolean +} + +export function useProviderIntegrations(options: UseProviderIntegrationsOptions = {}) { + return useQuery({ + queryKey: ['provider-integrations'], + queryFn: () => oauthApi.getIntegrations(), + enabled: options.enabled ?? true, + }) +} diff --git a/frontend/src/lib/queryInvalidation.test.ts b/frontend/src/lib/queryInvalidation.test.ts index 2ef7c355..fdf78be7 100644 --- a/frontend/src/lib/queryInvalidation.test.ts +++ b/frontend/src/lib/queryInvalidation.test.ts @@ -132,6 +132,7 @@ describe('invalidateProviderCaches', () => { expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['provider-credentials'] }) expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['provider-auth-methods'] }) + expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['provider-integrations'] }) expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'providers'] }) expect(invalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['providers'] }) expect(invalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['providers-for-execution-model'] }) @@ -156,7 +157,7 @@ describe('invalidateProviderCachesDebounced', () => { vi.advanceTimersByTime(200) - expect(invalidateQueries).toHaveBeenCalledTimes(3) + expect(invalidateQueries).toHaveBeenCalledTimes(4) expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'providers'] }) }) }) diff --git a/frontend/src/lib/queryInvalidation.ts b/frontend/src/lib/queryInvalidation.ts index dbdc5146..636c1caf 100644 --- a/frontend/src/lib/queryInvalidation.ts +++ b/frontend/src/lib/queryInvalidation.ts @@ -62,6 +62,7 @@ export function invalidateChildSessionCaches(queryClient: QueryClient, sessionID export function invalidateProviderCaches(queryClient: QueryClient) { queryClient.invalidateQueries({ queryKey: ['provider-credentials'] }) queryClient.invalidateQueries({ queryKey: ['provider-auth-methods'] }) + queryClient.invalidateQueries({ queryKey: ['provider-integrations'] }) queryClient.invalidateQueries({ queryKey: ['opencode', 'providers'] }) }