mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
fix(frontend): load provider integrations through the typed OpenCode client
Fetch integrations with callOpenCode instead of a dedicated backend route, drop the unused provider credentials list query, label an existing key as "Edit API key", and keep the loaded provider list when a background refetch fails.
This commit is contained in:
1 parent
b179267376
commit
99713e15b4
13 files changed
+44
-84
No files matched your search
@@ -126,41 +126,6 @@ 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,15 +23,6 @@ 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()
|
||||
|
||||
@@ -2,6 +2,7 @@ import { API_BASE_URL } from "@/config"
|
||||
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,
|
||||
@@ -48,9 +49,7 @@ export const oauthApi = {
|
||||
},
|
||||
|
||||
getIntegrations: async (): Promise<IntegrationInfo[]> => {
|
||||
const { integrations } = await fetchWrapper<{ integrations: IntegrationInfo[] }>(
|
||||
`${API_BASE_URL}/api/oauth/integrations`
|
||||
)
|
||||
return integrations
|
||||
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?: {
|
||||
@@ -186,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`
|
||||
|
||||
@@ -12,7 +12,6 @@ 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(),
|
||||
@@ -343,8 +342,9 @@ describe('ProviderSettings', () => {
|
||||
renderSettings()
|
||||
|
||||
await screen.findByText('Anthropic Integration')
|
||||
expect(screen.getByText('2 models')).toBeInTheDocument()
|
||||
expect(screen.getByText('Connected')).toBeInTheDocument()
|
||||
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')
|
||||
@@ -395,7 +395,7 @@ describe('ProviderSettings', () => {
|
||||
expect(screen.getByTestId('api-key-dialog')).toHaveAttribute('data-mode', 'add')
|
||||
})
|
||||
|
||||
it('labels an existing API key action as Add API key without changing its handling', async () => {
|
||||
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: [],
|
||||
@@ -409,10 +409,10 @@ describe('ProviderSettings', () => {
|
||||
await screen.findByText('Anthropic')
|
||||
const row = screen.getByText('Anthropic').closest('.py-3') as HTMLElement
|
||||
|
||||
const addKeyButton = within(row).getByRole('button', { name: 'Add API key for Anthropic' })
|
||||
expect(addKeyButton).toHaveTextContent('Add API key')
|
||||
const editKeyButton = within(row).getByRole('button', { name: 'Edit API key for Anthropic' })
|
||||
expect(editKeyButton).toHaveTextContent('Edit API key')
|
||||
|
||||
await user.click(addKeyButton)
|
||||
await user.click(editKeyButton)
|
||||
expect(screen.getByTestId('api-key-dialog')).toHaveAttribute('data-mode', 'edit')
|
||||
})
|
||||
|
||||
@@ -497,4 +497,23 @@ describe('ProviderSettings', () => {
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -81,7 +81,6 @@ function buildProviderEntries(
|
||||
!seen.has(integration.id) &&
|
||||
(supportsSettingsAuthentication(integration.methods) || hasCredentialConnection(integration)),
|
||||
)
|
||||
.sort((a, b) => a.name.localeCompare(b.name))
|
||||
.map((integration): ProviderEntry => ({
|
||||
id: integration.id,
|
||||
name: integration.name || integration.id,
|
||||
@@ -90,6 +89,7 @@ function buildProviderEntries(
|
||||
connected: hasCredentialConnection(integration),
|
||||
keyConnected: hasKeyConnection(integration),
|
||||
}))
|
||||
.sort((a, b) => a.name.localeCompare(b.name))
|
||||
|
||||
return [...entries, ...integrationOnly]
|
||||
}
|
||||
@@ -117,10 +117,11 @@ export function ProviderSettings() {
|
||||
isLoading: integrationsLoading,
|
||||
isError: integrationsError,
|
||||
} = useProviderIntegrations()
|
||||
const integrationsUnavailable = integrationsError && !integrations
|
||||
|
||||
const providerEntries = useMemo(
|
||||
() => integrationsError ? [] : buildProviderEntries(providers, integrations),
|
||||
[providers, integrations, integrationsError],
|
||||
() => buildProviderEntries(providers, integrations),
|
||||
[providers, integrations],
|
||||
)
|
||||
|
||||
const deleteCredentialMutation = useMutation({
|
||||
@@ -225,7 +226,7 @@ export function ProviderSettings() {
|
||||
}
|
||||
}, [])
|
||||
|
||||
if (integrationsError) {
|
||||
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>
|
||||
@@ -310,10 +311,10 @@ export function ProviderSettings() {
|
||||
size="sm"
|
||||
variant={keyConnected ? 'outline' : 'secondary'}
|
||||
onClick={() => keyConnected ? handleEditApiKey(provider) : handleAddApiKey(provider)}
|
||||
aria-label={`Add API key for ${provider.name || provider.id}`}
|
||||
aria-label={`${keyConnected ? 'Edit' : 'Add'} API key for ${provider.name || provider.id}`}
|
||||
>
|
||||
<Key className="h-4 w-4 mr-1" />
|
||||
Add API key
|
||||
{keyConnected ? 'Edit API key' : 'Add API key'}
|
||||
</Button>
|
||||
)}
|
||||
{isConnected && (
|
||||
|
||||
@@ -1146,7 +1146,6 @@ describe('EventProvider permissions and forms', () => {
|
||||
|
||||
await waitFor(() => {
|
||||
for (const queryKey of [
|
||||
['provider-credentials'],
|
||||
['provider-auth-methods'],
|
||||
['provider-integrations'],
|
||||
['opencode', 'providers'],
|
||||
@@ -1182,7 +1181,7 @@ describe('EventProvider permissions and forms', () => {
|
||||
await waitFor(() => {
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'providers'] })
|
||||
})
|
||||
expect(invalidateQueries).toHaveBeenCalledTimes(4)
|
||||
expect(invalidateQueries).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it.each<[string, string[]]>([
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
@@ -130,7 +130,6 @@ 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'] })
|
||||
@@ -157,7 +156,7 @@ describe('invalidateProviderCachesDebounced', () => {
|
||||
|
||||
vi.advanceTimersByTime(200)
|
||||
|
||||
expect(invalidateQueries).toHaveBeenCalledTimes(4)
|
||||
expect(invalidateQueries).toHaveBeenCalledTimes(3)
|
||||
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['opencode', 'providers'] })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -62,7 +62,6 @@ 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