mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
fix(frontend): list provider integrations in settings
This commit is contained in:
1 parent
c8647c1eec
commit
024b3d969f
9 files changed
+211
-46
No files matched your search
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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<IntegrationInfo[]> => {
|
||||
const { integrations } = await fetchWrapper<{ integrations: IntegrationInfo[] }>(
|
||||
`${API_BASE_URL}/api/oauth/integrations`
|
||||
)
|
||||
return integrations
|
||||
},
|
||||
}
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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<string>()
|
||||
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<string | null>(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 (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
|
||||
@@ -177,7 +219,7 @@ export function ProviderSettings() {
|
||||
) : (
|
||||
<div className="divide-y divide-border">
|
||||
{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() {
|
||||
<OAuthAuthorizeDialog
|
||||
providerId={selectedProvider}
|
||||
providerName={selectedProviderName}
|
||||
methods={authMethods?.[selectedProvider] || []}
|
||||
methods={selectedProviderMethods}
|
||||
open={oauthDialogOpen}
|
||||
onOpenChange={handleOAuthDialogClose}
|
||||
onSuccess={handleOAuthAuthorize}
|
||||
|
||||
@@ -1116,6 +1116,7 @@ describe('EventProvider permissions and forms', () => {
|
||||
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[]]>([
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
@@ -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'] })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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'] })
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user