mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Merge pull request #473 from fireball71/Fix-0-Providers
fix(frontend): show provider integrations missing from the active catalog
This commit is contained in:
13 files changed
+459
-83
No files matched your search
@@ -1,12 +1,14 @@
|
||||
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"
|
||||
import { callOpenCode } from "./opencodeApi"
|
||||
|
||||
export type {
|
||||
FormAnswer,
|
||||
FormField,
|
||||
FormValue,
|
||||
IntegrationInfo,
|
||||
IntegrationKeyMethod,
|
||||
IntegrationMethod,
|
||||
IntegrationOAuthMethod,
|
||||
@@ -45,4 +47,9 @@ export const oauthApi = {
|
||||
)
|
||||
return providers
|
||||
},
|
||||
|
||||
getIntegrations: async (): Promise<IntegrationInfo[]> => {
|
||||
const { data } = await callOpenCode((api) => api.integration.list())
|
||||
return data
|
||||
},
|
||||
}
|
||||
@@ -304,13 +304,6 @@ describe('providerCredentialsApi', () => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('lists provider ids with credentials from the Manager response', async () => {
|
||||
mockFetchWrapper.mockResolvedValue({ providers: ['anthropic', 'openai'] })
|
||||
|
||||
await expect(providerCredentialsApi.list()).resolves.toEqual(['anthropic', 'openai'])
|
||||
expect(mockFetchWrapper).toHaveBeenCalledWith(`${API_BASE_URL}/api/providers/credentials`)
|
||||
})
|
||||
|
||||
it('reports credential status from the Manager response', async () => {
|
||||
mockFetchWrapper.mockResolvedValue({ hasCredentials: true })
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
type ModelPreferenceModel,
|
||||
type ModelRef,
|
||||
} from "@opencode-manager/shared/opencode";
|
||||
import type { CredentialListResponse, CredentialStatusResponse } from "@opencode-manager/shared/schemas";
|
||||
import type { CredentialStatusResponse } from "@opencode-manager/shared/schemas";
|
||||
|
||||
export type Model = Pick<ModelInfo, 'id' | 'modelID' | 'name'> & {
|
||||
limit?: {
|
||||
@@ -29,6 +29,7 @@ export type Model = Pick<ModelInfo, 'id' | 'modelID' | 'name'> & {
|
||||
|
||||
export interface Provider {
|
||||
id: string;
|
||||
integrationID?: string;
|
||||
name: string;
|
||||
models: Model[];
|
||||
}
|
||||
@@ -80,6 +81,7 @@ export async function getProviders(directory?: string, serverId?: string): Promi
|
||||
|
||||
return {
|
||||
id: provider.id,
|
||||
integrationID: provider.integrationID,
|
||||
name: provider.name,
|
||||
models,
|
||||
};
|
||||
@@ -184,11 +186,6 @@ export function formatProviderName(provider: Provider): string {
|
||||
}
|
||||
|
||||
export const providerCredentialsApi = {
|
||||
list: async (): Promise<string[]> => {
|
||||
const { providers } = await fetchWrapper<CredentialListResponse>(`${API_BASE_URL}/api/providers/credentials`);
|
||||
return providers;
|
||||
},
|
||||
|
||||
getStatus: async (providerId: string): Promise<boolean> => {
|
||||
const { hasCredentials } = await fetchWrapper<CredentialStatusResponse>(
|
||||
`${API_BASE_URL}/api/providers/${providerId}/credentials/status`
|
||||
|
||||
@@ -6,13 +6,12 @@ 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', () => ({
|
||||
getProviders: vi.fn(),
|
||||
providerCredentialsApi: {
|
||||
list: vi.fn(),
|
||||
getStatus: vi.fn(),
|
||||
set: vi.fn(),
|
||||
delete: vi.fn(),
|
||||
@@ -22,6 +21,7 @@ vi.mock('@/api/providers', () => ({
|
||||
vi.mock('@/api/oauth', () => ({
|
||||
oauthApi: {
|
||||
getAuthMethods: vi.fn(),
|
||||
getIntegrations: vi.fn(),
|
||||
authorize: vi.fn(),
|
||||
callback: vi.fn(),
|
||||
},
|
||||
@@ -84,9 +84,10 @@ vi.mock('@/components/ui/delete-dialog', () => ({
|
||||
}) => (open ? <button onClick={onConfirm}>Confirm delete</button> : null),
|
||||
}))
|
||||
|
||||
function providerFixture(id: string, name: string, modelCount: number): Provider {
|
||||
function providerFixture(id: string, name: string, modelCount: number, integrationID?: string): Provider {
|
||||
return {
|
||||
id,
|
||||
integrationID,
|
||||
name,
|
||||
models: Array.from({ length: modelCount }, (_, index) => ({
|
||||
id: `model-${index}`,
|
||||
@@ -103,6 +104,33 @@ 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' }
|
||||
const commandMethod: IntegrationMethod = {
|
||||
id: 'command',
|
||||
type: 'command',
|
||||
label: 'Command',
|
||||
command: ['example-command'],
|
||||
}
|
||||
const envMethod: IntegrationMethod = { type: 'env', names: ['ENV_ONLY_API_KEY'] }
|
||||
|
||||
function integrationFixture(
|
||||
id: string,
|
||||
name: string,
|
||||
methods: IntegrationMethod[],
|
||||
connected = false,
|
||||
connectionMethod: 'key' | 'oauth' = 'key',
|
||||
): IntegrationInfo {
|
||||
return {
|
||||
id,
|
||||
name,
|
||||
methods,
|
||||
connections: connected
|
||||
? [{ type: 'credential', id: `cred_${id}`, label: name, method: connectionMethod }]
|
||||
: [],
|
||||
}
|
||||
}
|
||||
|
||||
function mockProviderData() {
|
||||
vi.mocked(getProviders).mockResolvedValue({
|
||||
providers: [
|
||||
@@ -113,11 +141,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() {
|
||||
@@ -271,11 +300,231 @@ 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('uses integration IDs for provider entries when catalog IDs differ', async () => {
|
||||
vi.mocked(getProviders).mockResolvedValue({
|
||||
providers: [providerFixture('catalog-anthropic', 'Anthropic Catalog', 2, 'anthropic')],
|
||||
models: [],
|
||||
})
|
||||
vi.mocked(oauthApi.getIntegrations).mockResolvedValue([
|
||||
integrationFixture('anthropic', 'Anthropic Integration', [oauthMethod], true),
|
||||
])
|
||||
const user = userEvent.setup()
|
||||
renderSettings()
|
||||
|
||||
await screen.findByText('Anthropic Integration')
|
||||
const row = screen.getByText('Anthropic Integration').closest('.py-3') as HTMLElement
|
||||
expect(within(row).getByText('2 models')).toBeInTheDocument()
|
||||
expect(within(row).getByText('Connected')).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Reconnect' }))
|
||||
expect(screen.getByTestId('oauth-authorize-dialog')).toHaveTextContent('anthropic')
|
||||
expect(screen.queryByText('catalog-anthropic')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('groups catalog providers that share an integration and combines their models', async () => {
|
||||
vi.mocked(getProviders).mockResolvedValue({
|
||||
providers: [
|
||||
providerFixture('catalog-one', 'Catalog One', 2, 'shared-integration'),
|
||||
providerFixture('catalog-two', 'Catalog Two', 3, 'shared-integration'),
|
||||
],
|
||||
models: [],
|
||||
})
|
||||
vi.mocked(oauthApi.getIntegrations).mockResolvedValue([
|
||||
integrationFixture('shared-integration', 'Shared Integration', [oauthMethod]),
|
||||
])
|
||||
const user = userEvent.setup()
|
||||
renderSettings()
|
||||
|
||||
await screen.findByText('Shared Integration')
|
||||
|
||||
expect(screen.getAllByText('Shared Integration')).toHaveLength(1)
|
||||
expect(screen.getByText('5 models')).toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Connect' }))
|
||||
expect(screen.getByTestId('oauth-authorize-dialog')).toHaveTextContent('shared-integration')
|
||||
})
|
||||
|
||||
it('offers an API-key action for mixed-method integrations even when connected with OAuth', async () => {
|
||||
vi.mocked(getProviders).mockResolvedValue({
|
||||
providers: [providerFixture('anthropic', 'Anthropic', 2)],
|
||||
models: [],
|
||||
})
|
||||
vi.mocked(oauthApi.getIntegrations).mockResolvedValue([
|
||||
integrationFixture('anthropic', 'Anthropic', [oauthMethod, keyMethod], true, 'oauth'),
|
||||
])
|
||||
const user = userEvent.setup()
|
||||
renderSettings()
|
||||
|
||||
await screen.findByText('Anthropic')
|
||||
const row = screen.getByText('Anthropic').closest('.py-3') as HTMLElement
|
||||
|
||||
expect(within(row).getByRole('button', { name: 'Reconnect' })).toBeInTheDocument()
|
||||
expect(within(row).getByRole('button', { name: 'Add API key for Anthropic' })).toBeInTheDocument()
|
||||
|
||||
await user.click(within(row).getByRole('button', { name: 'Add API key for Anthropic' }))
|
||||
expect(screen.getByTestId('api-key-dialog')).toHaveAttribute('data-mode', 'add')
|
||||
})
|
||||
|
||||
it('labels an existing API key action as Edit API key and opens the dialog in edit mode', async () => {
|
||||
vi.mocked(getProviders).mockResolvedValue({
|
||||
providers: [providerFixture('anthropic', 'Anthropic', 2)],
|
||||
models: [],
|
||||
})
|
||||
vi.mocked(oauthApi.getIntegrations).mockResolvedValue([
|
||||
integrationFixture('anthropic', 'Anthropic', [oauthMethod, keyMethod], true, 'key'),
|
||||
])
|
||||
const user = userEvent.setup()
|
||||
renderSettings()
|
||||
|
||||
await screen.findByText('Anthropic')
|
||||
const row = screen.getByText('Anthropic').closest('.py-3') as HTMLElement
|
||||
|
||||
const editKeyButton = within(row).getByRole('button', { name: 'Edit API key for Anthropic' })
|
||||
expect(editKeyButton).toHaveTextContent('Edit API key')
|
||||
|
||||
await user.click(editKeyButton)
|
||||
expect(screen.getByTestId('api-key-dialog')).toHaveAttribute('data-mode', 'edit')
|
||||
})
|
||||
|
||||
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()
|
||||
})
|
||||
|
||||
it('does not list integration-only entries without OAuth or API-key methods', async () => {
|
||||
vi.mocked(getProviders).mockResolvedValue({ providers: [], models: [] })
|
||||
vi.mocked(oauthApi.getIntegrations).mockResolvedValue([
|
||||
integrationFixture('command-only', 'Command Only', [commandMethod]),
|
||||
integrationFixture('env-only', 'Environment Only', [envMethod]),
|
||||
])
|
||||
renderSettings()
|
||||
|
||||
await screen.findByText('No OAuth-capable providers available.')
|
||||
|
||||
expect(screen.queryByText('Command Only')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Environment Only')).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: /Available Providers/ })).toHaveTextContent('0')
|
||||
})
|
||||
|
||||
it('includes connected integration-only providers without key or OAuth methods', async () => {
|
||||
vi.mocked(getProviders).mockResolvedValue({ providers: [], models: [] })
|
||||
vi.mocked(oauthApi.getIntegrations).mockResolvedValue([
|
||||
integrationFixture('connected-command', 'Connected Command', [commandMethod], true),
|
||||
])
|
||||
const user = userEvent.setup()
|
||||
renderSettings()
|
||||
|
||||
await screen.findByText('No OAuth-capable providers available.')
|
||||
expect(screen.getByRole('button', { name: /Connected/ })).toHaveTextContent('1')
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Connected/ }))
|
||||
const connectedCard = screen.getByText('Connected Command').closest('.bg-card') as HTMLElement
|
||||
expect(connectedCard).toBeInTheDocument()
|
||||
expect(within(connectedCard).getByRole('button', { name: 'Remove credentials for Connected Command' })).toBeInTheDocument()
|
||||
expect(within(connectedCard).queryByRole('button', { name: 'Edit API key for Connected Command' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps connected non-key providers visible without exposing API-key edit actions', async () => {
|
||||
vi.mocked(getProviders).mockResolvedValue({
|
||||
providers: [
|
||||
providerFixture('command-only', 'Command Only', 1),
|
||||
providerFixture('command-connected', 'Connected Command Only', 1),
|
||||
providerFixture('env-only', 'Environment Only', 1),
|
||||
providerFixture('empty-methods', 'No Auth Methods', 1),
|
||||
],
|
||||
models: [],
|
||||
})
|
||||
vi.mocked(oauthApi.getIntegrations).mockResolvedValue([
|
||||
integrationFixture('command-only', 'Command Only', [commandMethod]),
|
||||
integrationFixture('command-connected', 'Connected Command Only', [commandMethod], true),
|
||||
integrationFixture('env-only', 'Environment Only', [envMethod]),
|
||||
integrationFixture('empty-methods', 'No Auth Methods', []),
|
||||
])
|
||||
const user = userEvent.setup()
|
||||
renderSettings()
|
||||
|
||||
expect(await screen.findByRole('button', { name: /Available Providers/ })).toHaveTextContent('0')
|
||||
expect(screen.getByText('No available providers.')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Add Key' })).not.toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /Connected/ }))
|
||||
const connectedCard = screen.getByText('Connected Command Only').closest('.bg-card') as HTMLElement
|
||||
expect(within(connectedCard).getByRole('button', { name: 'Remove credentials for Connected Command Only' })).toBeInTheDocument()
|
||||
expect(within(connectedCard).queryByRole('button', { name: 'Edit API key for Connected Command Only' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('leaves MCP server integrations out of the provider lists', async () => {
|
||||
vi.mocked(oauthApi.getIntegrations).mockResolvedValue([
|
||||
integrationFixture('anthropic', 'Anthropic', [oauthMethod], true),
|
||||
{ ...integrationFixture('mcp_figma', 'figma', [oauthMethod]), metadata: { source: 'mcp' } },
|
||||
])
|
||||
renderSettings()
|
||||
|
||||
await screen.findByText('Anthropic')
|
||||
expect(screen.queryByText('figma')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows an integration-list error instead of guessing connection status', async () => {
|
||||
vi.mocked(oauthApi.getIntegrations).mockRejectedValue(new Error('Server unavailable'))
|
||||
renderSettings()
|
||||
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('Unable to load provider integrations.')
|
||||
expect(screen.queryByText('Anthropic')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('No OAuth-capable providers available.')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps the loaded providers when an integration refetch fails', async () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
})
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ProviderSettings />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
await screen.findByText('Anthropic')
|
||||
|
||||
vi.mocked(oauthApi.getIntegrations).mockRejectedValue(new Error('Server unavailable'))
|
||||
await queryClient.refetchQueries({ queryKey: ['provider-integrations'] })
|
||||
|
||||
await waitFor(() => expect(queryClient.getQueryState(['provider-integrations'])?.status).toBe('error'))
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('Anthropic')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -7,14 +7,97 @@ 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
|
||||
keyConnected: boolean
|
||||
}
|
||||
|
||||
function hasCredentialConnection(integration: IntegrationInfo): boolean {
|
||||
return integration.connections.some((connection) => connection.type === 'credential')
|
||||
}
|
||||
|
||||
function hasKeyConnection(integration: IntegrationInfo): boolean {
|
||||
return integration.connections.some(
|
||||
(connection) => connection.type === 'credential' && connection.method === 'key',
|
||||
)
|
||||
}
|
||||
|
||||
function isMcpIntegration(integration: IntegrationInfo): boolean {
|
||||
return integration.metadata?.source === 'mcp'
|
||||
}
|
||||
|
||||
function supportsOAuthMethods(methods: IntegrationMethod[]): boolean {
|
||||
return methods.some((method) => method.type === 'oauth')
|
||||
}
|
||||
|
||||
function supportsSettingsAuthentication(methods: IntegrationMethod[]): boolean {
|
||||
return methods.some((method) => method.type === 'oauth' || method.type === 'key')
|
||||
}
|
||||
|
||||
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 entriesByID = new Map<string, ProviderEntry>()
|
||||
const entries: ProviderEntry[] = []
|
||||
|
||||
for (const provider of providers ?? []) {
|
||||
const integrationID = provider.integrationID ?? provider.id
|
||||
const integration = integrationsByID.get(integrationID)
|
||||
seen.add(integrationID)
|
||||
|
||||
const existingEntry = entriesByID.get(integrationID)
|
||||
if (existingEntry) {
|
||||
existingEntry.models.push(...provider.models)
|
||||
continue
|
||||
}
|
||||
|
||||
const entry: ProviderEntry = {
|
||||
id: integrationID,
|
||||
name: integration?.name || provider.name || provider.id,
|
||||
models: [...provider.models],
|
||||
methods: integration?.methods ?? [],
|
||||
connected: integration ? hasCredentialConnection(integration) : false,
|
||||
keyConnected: integration ? hasKeyConnection(integration) : false,
|
||||
}
|
||||
entriesByID.set(integrationID, entry)
|
||||
entries.push(entry)
|
||||
}
|
||||
|
||||
const integrationOnly = (integrations ?? [])
|
||||
.filter(
|
||||
(integration) =>
|
||||
!seen.has(integration.id) &&
|
||||
!isMcpIntegration(integration) &&
|
||||
(supportsSettingsAuthentication(integration.methods) || hasCredentialConnection(integration)),
|
||||
)
|
||||
.map((integration): ProviderEntry => ({
|
||||
id: integration.id,
|
||||
name: integration.name || integration.id,
|
||||
models: [],
|
||||
methods: integration.methods,
|
||||
connected: hasCredentialConnection(integration),
|
||||
keyConnected: hasKeyConnection(integration),
|
||||
}))
|
||||
.sort((a, b) => a.name.localeCompare(b.name))
|
||||
|
||||
return [...entries, ...integrationOnly]
|
||||
}
|
||||
|
||||
export function ProviderSettings() {
|
||||
const [selectedProvider, setSelectedProvider] = useState<string | null>(null)
|
||||
@@ -34,12 +117,17 @@ export function ProviderSettings() {
|
||||
|
||||
const providers = providersData?.providers
|
||||
|
||||
const { data: credentialsList, isLoading: credentialsLoading } = useQuery({
|
||||
queryKey: ['provider-credentials'],
|
||||
queryFn: () => providerCredentialsApi.list(),
|
||||
})
|
||||
const {
|
||||
data: integrations,
|
||||
isLoading: integrationsLoading,
|
||||
isError: integrationsError,
|
||||
} = useProviderIntegrations()
|
||||
const integrationsUnavailable = integrationsError && !integrations
|
||||
|
||||
const { data: authMethods } = useProviderAuthMethods()
|
||||
const providerEntries = useMemo(
|
||||
() => buildProviderEntries(providers, integrations),
|
||||
[providers, integrations],
|
||||
)
|
||||
|
||||
const deleteCredentialMutation = useMutation({
|
||||
mutationFn: (providerId: string) => providerCredentialsApi.delete(providerId),
|
||||
@@ -81,32 +169,23 @@ 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) &&
|
||||
(provider.connected || provider.methods.some((method) => method.type === 'key')),
|
||||
)
|
||||
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 +198,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 +231,18 @@ export function ProviderSettings() {
|
||||
}
|
||||
}, [])
|
||||
|
||||
if (providersLoading || credentialsLoading) {
|
||||
if (integrationsUnavailable) {
|
||||
return (
|
||||
<div role="alert" className="rounded-md border border-destructive/50 bg-card p-4">
|
||||
<p className="text-sm font-medium text-foreground">Unable to load provider integrations.</p>
|
||||
<p className="mt-1 text-sm text-muted-foreground">
|
||||
Provider connection status and available authentication methods could not be verified. Reload the settings page to try again.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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 +272,8 @@ export function ProviderSettings() {
|
||||
) : (
|
||||
<div className="divide-y divide-border">
|
||||
{oauthProviders.map((provider) => {
|
||||
const hasKey = hasCredentials(provider.id)
|
||||
const isConnected = provider.connected
|
||||
const keyConnected = provider.keyConnected
|
||||
const modelCount = provider.models.length
|
||||
|
||||
return (
|
||||
@@ -193,7 +289,7 @@ export function ProviderSettings() {
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{hasKey ? (
|
||||
{isConnected ? (
|
||||
<Badge variant="default" className="bg-success text-success-foreground hover:bg-success/90 shrink-0">
|
||||
<Check className="h-3 w-3 mr-1" />
|
||||
Connected
|
||||
@@ -206,16 +302,27 @@ export function ProviderSettings() {
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant={hasKey ? 'outline' : 'default'}
|
||||
variant={isConnected ? 'outline' : 'default'}
|
||||
onClick={() => {
|
||||
setSelectedProvider(provider.id)
|
||||
setOauthDialogOpen(true)
|
||||
}}
|
||||
>
|
||||
<Shield className="h-4 w-4 mr-1" />
|
||||
{hasKey ? 'Reconnect' : 'Connect'}
|
||||
{isConnected ? 'Reconnect' : 'Connect'}
|
||||
</Button>
|
||||
{hasKey && (
|
||||
{provider.methods.some((method) => method.type === 'key') && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant={keyConnected ? 'outline' : 'secondary'}
|
||||
onClick={() => keyConnected ? handleEditApiKey(provider) : handleAddApiKey(provider)}
|
||||
aria-label={`${keyConnected ? 'Edit' : 'Add'} API key for ${provider.name || provider.id}`}
|
||||
>
|
||||
<Key className="h-4 w-4 mr-1" />
|
||||
{keyConnected ? 'Edit API key' : 'Add API key'}
|
||||
</Button>
|
||||
)}
|
||||
{isConnected && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="destructive"
|
||||
@@ -236,7 +343,7 @@ export function ProviderSettings() {
|
||||
<OAuthAuthorizeDialog
|
||||
providerId={selectedProvider}
|
||||
providerName={selectedProviderName}
|
||||
methods={authMethods?.[selectedProvider] || []}
|
||||
methods={selectedProviderMethods}
|
||||
open={oauthDialogOpen}
|
||||
onOpenChange={handleOAuthDialogClose}
|
||||
onSuccess={handleOAuthAuthorize}
|
||||
@@ -308,15 +415,17 @@ export function ProviderSettings() {
|
||||
<Check className="h-3 w-3 mr-1" />
|
||||
Connected
|
||||
</Badge>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleEditApiKey(provider)}
|
||||
aria-label={`Edit API key for ${provider.name || provider.id}`}
|
||||
className="h-8 w-8 p-0"
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
{provider.methods.some((method) => method.type === 'key') && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => handleEditApiKey(provider)}
|
||||
aria-label={`Edit API key for ${provider.name || provider.id}`}
|
||||
className="h-8 w-8 p-0"
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
|
||||
@@ -1146,8 +1146,8 @@ describe('EventProvider permissions and forms', () => {
|
||||
|
||||
await waitFor(() => {
|
||||
for (const queryKey of [
|
||||
['provider-credentials'],
|
||||
['provider-auth-methods'],
|
||||
['provider-integrations'],
|
||||
['opencode', 'providers'],
|
||||
]) {
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey })
|
||||
@@ -1209,7 +1209,7 @@ describe('EventProvider permissions and forms', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('invalidates the location catalog caches on an upstream resync', async () => {
|
||||
it('invalidates the location catalog and provider integration caches on an upstream resync', async () => {
|
||||
const queryClient = createTestQueryClient()
|
||||
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
|
||||
|
||||
@@ -1230,11 +1230,12 @@ describe('EventProvider permissions and forms', () => {
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'agents'] })
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'skills'] })
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'providers'] })
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['provider-integrations'] })
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode-config', 'managed'] })
|
||||
})
|
||||
})
|
||||
|
||||
it('invalidates the location catalog caches when the browser stream reconnects', async () => {
|
||||
it('invalidates the location catalog and provider integration caches when the browser stream reconnects', async () => {
|
||||
const queryClient = createTestQueryClient()
|
||||
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
|
||||
|
||||
@@ -1256,10 +1257,11 @@ describe('EventProvider permissions and forms', () => {
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'agents'] })
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'skills'] })
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'providers'] })
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['provider-integrations'] })
|
||||
})
|
||||
})
|
||||
|
||||
it('invalidates both config caches on config.updated', async () => {
|
||||
it('invalidates config and provider integration caches on config.updated', async () => {
|
||||
const queryClient = createTestQueryClient()
|
||||
const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries')
|
||||
|
||||
@@ -1278,6 +1280,7 @@ describe('EventProvider permissions and forms', () => {
|
||||
await waitFor(() => {
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'config'] })
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode-config'] })
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['provider-integrations'] })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -3108,6 +3111,7 @@ describe('EventProvider permissions and forms', () => {
|
||||
await waitFor(() => {
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'commands', 'srv_remote'] })
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'agents', 'srv_remote'] })
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['provider-integrations'] })
|
||||
})
|
||||
expect(invalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['opencode', 'commands'] })
|
||||
expect(invalidateQueries).not.toHaveBeenCalledWith({ queryKey: ['opencode-config', 'managed'] })
|
||||
|
||||
@@ -1217,6 +1217,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
break
|
||||
case 'config.updated':
|
||||
invalidateQueryKeysDebounced(queryClient, [['opencode', 'config'], ['opencode-config']])
|
||||
invalidateProviderCachesDebounced(queryClient)
|
||||
break
|
||||
case 'ssh.host-key-request':
|
||||
setSSHHostKeyRequest(event.properties)
|
||||
@@ -1257,6 +1258,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
void syncRunningShells(collectTrackedDirectories())
|
||||
invalidateChildSessionCaches(queryClient)
|
||||
invalidateQueryKeysDebounced(queryClient, LOCATION_CATALOG_QUERY_KEYS)
|
||||
invalidateProviderCachesDebounced(queryClient)
|
||||
queryClient.invalidateQueries({ queryKey: [SESSION_GOAL_QUERY_ROOT] })
|
||||
startStatusPoll()
|
||||
} else {
|
||||
@@ -1275,6 +1277,7 @@ export function EventProvider({ children }: { children: React.ReactNode }) {
|
||||
*/
|
||||
const handleResync = (subscribedDirectories: string[], serverId?: string) => {
|
||||
queryClient.invalidateQueries({ queryKey: [SESSION_GOAL_QUERY_ROOT] })
|
||||
invalidateProviderCachesDebounced(queryClient)
|
||||
if (serverId && !isLocalOpenCodeServer(serverId)) {
|
||||
void reconcileRemoteDirectoryActivity(serverId, subscribedDirectories)
|
||||
invalidateSessionListCachesDebounced(queryClient, undefined, serverId)
|
||||
|
||||
@@ -183,7 +183,7 @@ describe('QueryCachePersistenceProvider', () => {
|
||||
client.setQueryData(['opencode', 'sessions', '/work/repo'], [{ id: 'ses_1' }])
|
||||
client.setQueryData(['settings', 'user-1'], { opencodeServerAuth: 'secret' })
|
||||
client.setQueryData(['opencode', 'transcript', 'ses_1'], [{ text: 'streamed' }])
|
||||
client.setQueryData(['provider-credentials'], [{ apiKey: 'secret' }])
|
||||
client.setQueryData(['provider-integrations'], [{ apiKey: 'secret' }])
|
||||
})
|
||||
await settle()
|
||||
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
@@ -130,8 +130,8 @@ describe('invalidateProviderCaches', () => {
|
||||
|
||||
invalidateProviderCaches(queryClient)
|
||||
|
||||
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'] })
|
||||
|
||||
@@ -62,8 +62,8 @@ 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'] })
|
||||
}
|
||||
|
||||
|
||||
@@ -118,7 +118,7 @@ describe('isPersistedQueryKey', () => {
|
||||
it.each([
|
||||
['repo git status', ['reposGitStatus', [1, 2]]],
|
||||
['settings', ['settings', 'user-1']],
|
||||
['provider credentials', ['provider-credentials']],
|
||||
['provider integrations', ['provider-integrations']],
|
||||
['provider auth methods', ['provider-auth-methods']],
|
||||
['passkeys', ['passkeys']],
|
||||
['schedules', ['schedules', '/work/repo']],
|
||||
@@ -165,7 +165,7 @@ describe('shouldPersistQuery', () => {
|
||||
const queryClient = createClient()
|
||||
|
||||
expect(shouldPersistQuery(buildQuery(queryClient, ['settings', 'user-1']))).toBe(false)
|
||||
expect(shouldPersistQuery(buildQuery(queryClient, ['provider-credentials']))).toBe(false)
|
||||
expect(shouldPersistQuery(buildQuery(queryClient, ['provider-integrations']))).toBe(false)
|
||||
expect(shouldPersistQuery(buildQuery(queryClient, ['passkeys']))).toBe(false)
|
||||
})
|
||||
|
||||
@@ -201,7 +201,7 @@ describe('PERSISTED_QUERY_RULES', () => {
|
||||
const roots = PERSISTED_QUERY_RULES.map((rule) => rule.prefix.join('.'))
|
||||
const excluded = [
|
||||
'settings',
|
||||
'provider-credentials',
|
||||
'provider-integrations',
|
||||
'provider-auth-methods',
|
||||
'passkeys',
|
||||
'schedules',
|
||||
|
||||
@@ -39,7 +39,7 @@ export interface QueryCachePersister extends Persister {
|
||||
*
|
||||
* Every rule is a list or roster key whose shape is stable across reloads of the same account.
|
||||
* Excluded on purpose: `settings` (contains the OpenCode server auth token and API keys),
|
||||
* `provider-credentials`, `passkeys`, `provider-auth-methods`, the `opencode` transcript kinds
|
||||
* `provider-integrations`, `passkeys`, `provider-auth-methods`, the `opencode` transcript kinds
|
||||
* (large, and rewritten on every streamed token), `schedules` and `all-schedules` (a schedule or
|
||||
* MCP config can carry `client_secret`), `reposGitStatus` (a `Map` that JSON turns into `{}`), and
|
||||
* every root not listed here.
|
||||
|
||||
Reference in new issue
Block a user