From ac92143dbe9b191aaa1b4bb90f95e88c4fda0544 Mon Sep 17 00:00:00 2001 From: Ethan <39577870+ethanndickson@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:16:34 +1100 Subject: [PATCH] refactor!: remove the AI Gateway provider list route (#32651) Relates to AIGOV-824 Stacked on #32650. `GET /api/v2/ai-gateway/providers` was added in #28966, in September, and first shipped in v2.38.0. It was a fix for the provider filter on the AI Gateway sessions page. That filter called `GET /api/v2/ai/providers`, which only owners could read, so the dropdown was empty for auditors. Rather than open up the provider config, #28966 added a second route that returns just the `name`, `type`, `display_name` and `icon` of every provider, deleted ones included, to anyone who can read sessions, i.e. owners and auditors. Now that `GET /api/v2/ai/providers` answers every signed-in user with those same fields (#32650), the second route has no caller that it alone can serve. Jake, who added it, and I agree that we should remove it rather than keep two routes that list providers, so this PR does that. The one thing only the old route did was return deleted providers, so that sessions and spend recorded under a provider that has since been deleted keep their label. So, `GET /api/v2/ai/providers` gains an `include_deleted` query parameter. A deleted provider can share its name with a live one, so each name appears once, as its live provider if there is one, otherwise the most recently updated deleted one. Unlike the old route, any caller can pass it, so members can now see the names of deleted providers. A deleted provider comes back without its configuration, for owners too. The sessions provider filter and the Spend page now call `GET /api/v2/ai/providers?include_deleted=true`, and show the same thing as before. `codersdk.AIBridgeProvider`, `Client.AIBridgeListProviders` and the `GetAIProviderFilterOptions` query go with the route. ## For changelog - `GET /api/v2/ai-gateway/providers` has been removed (#32651) > `GET /api/v2/ai-gateway/providers` has been removed, along with `codersdk.AIBridgeProvider` and `Client.AIBridgeListProviders` in the Go SDK. It listed providers only for users who can read AI Gateway sessions, i.e. owners and auditors. `GET /api/v2/ai/providers` replaces it, and now answers every signed-in user. Owners still get each provider's full configuration from it, and everyone else gets the same list with an empty `base_url`, an empty `api_keys` array, `null` `settings` and no `status`. > > Migration: Call `GET /api/v2/ai/providers?include_deleted=true` instead. Each provider keeps its `name`, `type`, `display_name` and `icon` fields, and `display_name` now holds the provider name when no display name is set. In the Go SDK, `Client.AIProviders` now takes a `codersdk.AIProvidersFilter`. Set its `IncludeDeleted` field to list deleted providers too. An API token with an allow list needs `ai_provider` in that list to call `GET /api/v2/ai/providers`, where the removed route needed `aibridge_interception`. --- coderd/ai_providers.go | 13 +- coderd/ai_providers_bedrock_test.go | 2 +- coderd/ai_providers_test.go | 56 +++++- coderd/apidoc/docs.go | 56 ++---- coderd/apidoc/swagger.json | 52 ++---- coderd/database/db2sdk/db2sdk.go | 2 + coderd/database/dbauthz/dbauthz.go | 16 +- coderd/database/dbauthz/dbauthz_test.go | 11 +- coderd/database/dbmetrics/querymetrics.go | 12 +- coderd/database/dbmock/dbmock.go | 23 +-- coderd/database/querier.go | 7 +- coderd/database/queries.sql.go | 68 ++------ coderd/database/queries/ai_providers.sql | 20 +-- coderd/exp_chats.go | 5 +- coderd/exp_chats_test.go | 2 +- codersdk/aibridge.go | 26 --- codersdk/aiproviders.go | 14 +- docs/reference/api/aigateway.md | 54 ------ docs/reference/api/aiproviders.md | 11 ++ docs/reference/api/schemas.md | 22 +-- enterprise/coderd/aibridge.go | 42 ----- enterprise/coderd/aibridge_test.go | 160 ------------------ enterprise/coderd/coderd.go | 10 -- site/src/api/api.ts | 13 +- site/src/api/queries/aiBridge.ts | 8 - site/src/api/queries/aiProviders.ts | 12 ++ site/src/api/typesGenerated.ts | 19 +-- .../ListSessionsFilter.stories.tsx | 24 +-- .../ListSessionsFilter.test.tsx | 18 +- .../ListSessionsPage/categoryOptions.tsx | 11 +- .../src/pages/AIBridgePage/ProvidersBadge.tsx | 4 +- .../DetailedReportFilter.stories.tsx | 2 +- .../AISpendPage/DetailedReportFilter.tsx | 4 +- site/src/testHelpers/entities.ts | 5 + 34 files changed, 194 insertions(+), 610 deletions(-) diff --git a/coderd/ai_providers.go b/coderd/ai_providers.go index 6f38a587f0f..35c01cc8552 100644 --- a/coderd/ai_providers.go +++ b/coderd/ai_providers.go @@ -51,12 +51,23 @@ func aiProvidersHandler(api *API, middlewares ...func(http.Handler) http.Handler // @Security CoderSessionToken // @Produce json // @Tags AI Providers +// @Param include_deleted query bool false "Include deleted providers, which are returned without configuration. Each name appears once: its live provider if one exists, otherwise the most recently updated deleted one." // @Success 200 {array} codersdk.AIProvider // @Router /api/v2/ai/providers [get] func (api *API) aiProvidersList(rw http.ResponseWriter, r *http.Request) { ctx := r.Context() - summaries, err := api.Database.GetAIProviderSummaries(ctx) + parser := httpapi.NewQueryParamParser() + includeDeleted := parser.Boolean(r.URL.Query(), false, "include_deleted") + if len(parser.Errors) > 0 { + httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{ + Message: "Invalid query parameters.", + Validations: parser.Errors, + }) + return + } + + summaries, err := api.Database.GetAIProviderSummaries(ctx, includeDeleted) if dbauthz.IsNotAuthorizedError(err) { httpapi.Forbidden(rw) return diff --git a/coderd/ai_providers_bedrock_test.go b/coderd/ai_providers_bedrock_test.go index 7beb168a3ca..d4158ba149d 100644 --- a/coderd/ai_providers_bedrock_test.go +++ b/coderd/ai_providers_bedrock_test.go @@ -180,7 +180,7 @@ func TestAIProvidersBedrockProfileResolution(t *testing.T) { // The write is rejected: a stored ARN with no resolution would be // served as its own identity. //nolint:gocritic // Owner role is the audience for this endpoint. - providers, err := client.AIProviders(ctx) + providers, err := client.AIProviders(ctx, codersdk.AIProvidersFilter{}) require.NoError(t, err) require.Empty(t, providers) }) diff --git a/coderd/ai_providers_test.go b/coderd/ai_providers_test.go index 7012a8a18b5..fb8fca2f4d1 100644 --- a/coderd/ai_providers_test.go +++ b/coderd/ai_providers_test.go @@ -15,6 +15,7 @@ import ( "github.com/coder/coder/v2/coderd/database" "github.com/coder/coder/v2/coderd/database/db2sdk" "github.com/coder/coder/v2/coderd/database/dbauthz" + "github.com/coder/coder/v2/coderd/rbac" "github.com/coder/coder/v2/codersdk" "github.com/coder/coder/v2/testutil" "github.com/coder/serpent" @@ -40,10 +41,10 @@ func TestAIProvidersCRUD(t *testing.T) { memberClient, _ := coderdtest.CreateAnotherUser(t, client, firstUser.OrganizationID) ctx := testutil.Context(t, testutil.WaitLong) //nolint:gocritic // Owners get the full view, which is built separately. - got, err := client.AIProviders(ctx) + got, err := client.AIProviders(ctx, codersdk.AIProvidersFilter{}) require.NoError(t, err) require.Equal(t, []codersdk.AIProvider{}, got) - got, err = memberClient.AIProviders(ctx) + got, err = memberClient.AIProviders(ctx, codersdk.AIProvidersFilter{}) require.NoError(t, err) require.Equal(t, []codersdk.AIProvider{}, got) }) @@ -129,7 +130,7 @@ func TestAIProvidersCRUD(t *testing.T) { require.Equal(t, created.ID, gotByName.ID) // List. - list, err := client.AIProviders(ctx) + list, err := client.AIProviders(ctx, codersdk.AIProvidersFilter{}) require.NoError(t, err) require.Len(t, list, 1) require.Equal(t, created.ID, list[0].ID) @@ -162,7 +163,7 @@ func TestAIProvidersCRUD(t *testing.T) { require.Equal(t, "anthropic.claude-3-5-sonnet", updated.Settings.Bedrock.Model) memberClient, _ := coderdtest.CreateAnotherUser(t, client, firstUser.OrganizationID) - memberList, err := memberClient.AIProviders(ctx) + memberList, err := memberClient.AIProviders(ctx, codersdk.AIProvidersFilter{}) require.NoError(t, err) withoutConfig := updated withoutConfig.BaseURL = "" @@ -181,7 +182,7 @@ func TestAIProvidersCRUD(t *testing.T) { require.Contains(t, sdkErr.Message, "Resource not found") // List excludes the deleted provider. - list, err = client.AIProviders(ctx) + list, err = client.AIProviders(ctx, codersdk.AIProvidersFilter{}) require.NoError(t, err) require.Empty(t, list) @@ -509,7 +510,7 @@ func TestAIProvidersCRUD(t *testing.T) { }) require.NoError(t, err) - list, err := client.AIProviders(ctx) + list, err := client.AIProviders(ctx, codersdk.AIProvidersFilter{}) require.NoError(t, err) require.Len(t, list, 1) require.Equal(t, live.ID, list[0].ID) @@ -517,6 +518,43 @@ func TestAIProvidersCRUD(t *testing.T) { require.Equal(t, live.APIKeys[0].ID, list[0].APIKeys[0].ID) }) + t.Run("ListIncludeDeleted", func(t *testing.T) { + t.Parallel() + ownerClient := coderdtest.New(t, nil) + firstUser := coderdtest.CreateFirstUser(t, ownerClient) + ctx := testutil.Context(t, testutil.WaitLong) + + create := func(name string) codersdk.AIProvider { + //nolint:gocritic // Only owners can create providers. + provider, err := ownerClient.CreateAIProvider(ctx, codersdk.CreateAIProviderRequest{ + Type: codersdk.AIProviderTypeOpenAI, + Name: name, + Enabled: true, + BaseURL: "https://api.openai.com/v1", + }) + require.NoError(t, err) + return provider + } + gone := create("list-gone") + require.NoError(t, ownerClient.DeleteAIProvider(ctx, gone.ID.String())) + reusedBefore := create("list-reused") + require.NoError(t, ownerClient.DeleteAIProvider(ctx, reusedBefore.ID.String())) + reused := create("list-reused") + + auditorClient, _ := coderdtest.CreateAnotherUser(t, ownerClient, firstUser.OrganizationID, rbac.RoleAuditor()) + for _, client := range []*codersdk.Client{ownerClient, auditorClient} { + got, err := client.AIProviders(ctx, codersdk.AIProvidersFilter{IncludeDeleted: true}) + require.NoError(t, err) + + require.Len(t, got, 2) + require.Equal(t, gone.ID, got[0].ID) + require.True(t, got[0].Deleted) + require.Empty(t, got[0].BaseURL) + require.Equal(t, reused.ID, got[1].ID) + require.False(t, got[1].Deleted) + } + }) + t.Run("LookupInvalidName", func(t *testing.T) { t.Parallel() client := coderdtest.New(t, nil) @@ -547,7 +585,7 @@ func TestAIProvidersCRUD(t *testing.T) { ctx := testutil.Context(t, testutil.WaitLong) anon := codersdk.New(ownerClient.URL) - _, err := anon.AIProviders(ctx) + _, err := anon.AIProviders(ctx, codersdk.AIProvidersFilter{}) require.Error(t, err) var sdkErr *codersdk.Error require.ErrorAs(t, err, &sdkErr) @@ -2233,7 +2271,7 @@ func TestAIProviderHostnameCollisionWarnings(t *testing.T) { require.Nil(t, winner.Status, "first provider in database order should not get a warning on get") //nolint:gocritic // Owner role is the audience for this endpoint. - providers, err := client.AIProviders(ctx) + providers, err := client.AIProviders(ctx, codersdk.AIProvidersFilter{}) require.NoError(t, err) require.Len(t, providers, 2) var firstListed, secondListed codersdk.AIProvider @@ -2349,7 +2387,7 @@ func TestAIProviderHostnameCollisionWarnings(t *testing.T) { require.Nil(t, second.Status) //nolint:gocritic // Owner role is the audience for this endpoint. - providers, err := client.AIProviders(ctx) + providers, err := client.AIProviders(ctx, codersdk.AIProvidersFilter{}) require.NoError(t, err) for _, provider := range providers { require.Nil(t, provider.Status) diff --git a/coderd/apidoc/docs.go b/coderd/apidoc/docs.go index a521a194b65..50f005f9fec 100644 --- a/coderd/apidoc/docs.go +++ b/coderd/apidoc/docs.go @@ -2722,34 +2722,6 @@ const docTemplate = `{ ] } }, - "/api/v2/ai-gateway/providers": { - "get": { - "produces": [ - "application/json" - ], - "tags": [ - "AI Gateway" - ], - "summary": "List AI Gateway providers", - "operationId": "list-ai-gateway-providers", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/codersdk.AIBridgeProvider" - } - } - } - }, - "security": [ - { - "CoderSessionToken": [] - } - ] - } - }, "/api/v2/ai-gateway/serve": { "get": { "tags": [ @@ -2885,6 +2857,14 @@ const docTemplate = `{ ], "summary": "List AI providers", "operationId": "list-ai-providers", + "parameters": [ + { + "type": "boolean", + "description": "Include deleted providers, which are returned without configuration. Each name appears once: its live provider if one exists, otherwise the most recently updated deleted one.", + "name": "include_deleted", + "in": "query" + } + ], "responses": { "200": { "description": "OK", @@ -20167,23 +20147,6 @@ const docTemplate = `{ } } }, - "codersdk.AIBridgeProvider": { - "type": "object", - "properties": { - "display_name": { - "type": "string" - }, - "icon": { - "type": "string" - }, - "name": { - "type": "string" - }, - "type": { - "$ref": "#/definitions/codersdk.AIProviderType" - } - } - }, "codersdk.AIBridgeProxyConfig": { "type": "object", "properties": { @@ -20749,6 +20712,9 @@ const docTemplate = `{ "type": "string", "format": "date-time" }, + "deleted": { + "type": "boolean" + }, "display_name": { "type": "string" }, diff --git a/coderd/apidoc/swagger.json b/coderd/apidoc/swagger.json index f921fc7a896..606644689af 100644 --- a/coderd/apidoc/swagger.json +++ b/coderd/apidoc/swagger.json @@ -2461,30 +2461,6 @@ ] } }, - "/api/v2/ai-gateway/providers": { - "get": { - "produces": ["application/json"], - "tags": ["AI Gateway"], - "summary": "List AI Gateway providers", - "operationId": "list-ai-gateway-providers", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/codersdk.AIBridgeProvider" - } - } - } - }, - "security": [ - { - "CoderSessionToken": [] - } - ] - } - }, "/api/v2/ai-gateway/serve": { "get": { "tags": ["Enterprise"], @@ -2606,6 +2582,14 @@ "tags": ["AI Providers"], "summary": "List AI providers", "operationId": "list-ai-providers", + "parameters": [ + { + "type": "boolean", + "description": "Include deleted providers, which are returned without configuration. Each name appears once: its live provider if one exists, otherwise the most recently updated deleted one.", + "name": "include_deleted", + "in": "query" + } + ], "responses": { "200": { "description": "OK", @@ -18025,23 +18009,6 @@ } } }, - "codersdk.AIBridgeProvider": { - "type": "object", - "properties": { - "display_name": { - "type": "string" - }, - "icon": { - "type": "string" - }, - "name": { - "type": "string" - }, - "type": { - "$ref": "#/definitions/codersdk.AIProviderType" - } - } - }, "codersdk.AIBridgeProxyConfig": { "type": "object", "properties": { @@ -18599,6 +18566,9 @@ "type": "string", "format": "date-time" }, + "deleted": { + "type": "boolean" + }, "display_name": { "type": "string" }, diff --git a/coderd/database/db2sdk/db2sdk.go b/coderd/database/db2sdk/db2sdk.go index ee6986d313d..caaa963f5ef 100644 --- a/coderd/database/db2sdk/db2sdk.go +++ b/coderd/database/db2sdk/db2sdk.go @@ -58,6 +58,7 @@ func AIProvider(row database.AIProvider, keys []database.AIProviderKey) (codersd DisplayName: aiProviderDisplayName(row.Name, row.DisplayName), Icon: row.Icon, Enabled: row.Enabled, + Deleted: row.Deleted, BaseURL: row.BaseUrl, APIKeys: maskAIProviderKeys(keys), CreatedAt: row.CreatedAt, @@ -81,6 +82,7 @@ func AIProviderFromSummary(row database.GetAIProviderSummariesRow) codersdk.AIPr DisplayName: aiProviderDisplayName(row.Name, row.DisplayName), Icon: row.Icon, Enabled: row.Enabled, + Deleted: row.Deleted, APIKeys: []codersdk.AIProviderKey{}, CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt, diff --git a/coderd/database/dbauthz/dbauthz.go b/coderd/database/dbauthz/dbauthz.go index 03fea29a8cb..66d2f6ffd3a 100644 --- a/coderd/database/dbauthz/dbauthz.go +++ b/coderd/database/dbauthz/dbauthz.go @@ -3114,18 +3114,6 @@ func (q *querier) GetAIProviderByName(ctx context.Context, name string) (databas return q.db.GetAIProviderByName(ctx, name) } -func (q *querier) GetAIProviderFilterOptions(ctx context.Context) ([]database.GetAIProviderFilterOptionsRow, error) { - // This query returns display metadata only (name, type, display name, - // icon), never configuration or secrets. It exists so callers who can - // read AI Gateway interceptions deployment-wide (owners and auditors) - // can label the provider_name values they already see on those - // interceptions, so it is gated on interception read, not AIProvider read. - if err := q.authorizeContext(ctx, policy.ActionRead, rbac.ResourceAibridgeInterception); err != nil { - return nil, err - } - return q.db.GetAIProviderFilterOptions(ctx) -} - func (q *querier) GetAIProviderKeyByID(ctx context.Context, id uuid.UUID) (database.AIProviderKey, error) { if err := q.authorizeContext(ctx, policy.ActionReadSecret, rbac.ResourceAIProvider); err != nil { return database.AIProviderKey{}, err @@ -3165,11 +3153,11 @@ func (q *querier) GetAIProviderKeysByProviderIDs(ctx context.Context, providerID return q.db.GetAIProviderKeysByProviderIDs(ctx, providerIDs) } -func (q *querier) GetAIProviderSummaries(ctx context.Context) ([]database.GetAIProviderSummariesRow, error) { +func (q *querier) GetAIProviderSummaries(ctx context.Context, includeDeleted bool) ([]database.GetAIProviderSummariesRow, error) { if err := q.authorizeContext(ctx, policy.ActionRead, rbac.ResourceAIProvider); err != nil { return nil, err } - return q.db.GetAIProviderSummaries(ctx) + return q.db.GetAIProviderSummaries(ctx, includeDeleted) } func (q *querier) GetAIProviders(ctx context.Context, arg database.GetAIProvidersParams) ([]database.AIProvider, error) { diff --git a/coderd/database/dbauthz/dbauthz_test.go b/coderd/database/dbauthz/dbauthz_test.go index 94e576f42cc..a60e7d8d912 100644 --- a/coderd/database/dbauthz/dbauthz_test.go +++ b/coderd/database/dbauthz/dbauthz_test.go @@ -7985,15 +7985,8 @@ func (s *MethodTestSuite) TestAIBridge() { s.Run("GetAIProviderSummaries", s.Mocked(func(dbm *dbmock.MockStore, faker *gofakeit.Faker, check *expects) { summaryA := testutil.Fake(s.T(), faker, database.GetAIProviderSummariesRow{}) summaryB := testutil.Fake(s.T(), faker, database.GetAIProviderSummariesRow{}) - dbm.EXPECT().GetAIProviderSummaries(gomock.Any()).Return([]database.GetAIProviderSummariesRow{summaryA, summaryB}, nil).AnyTimes() - check.Args().Asserts(rbac.ResourceAIProvider, policy.ActionRead).Returns([]database.GetAIProviderSummariesRow{summaryA, summaryB}) - })) - s.Run("GetAIProviderFilterOptions", s.Mocked(func(dbm *dbmock.MockStore, faker *gofakeit.Faker, check *expects) { - options := []database.GetAIProviderFilterOptionsRow{ - testutil.Fake(s.T(), faker, database.GetAIProviderFilterOptionsRow{}), - } - dbm.EXPECT().GetAIProviderFilterOptions(gomock.Any()).Return(options, nil).AnyTimes() - check.Args().Asserts(rbac.ResourceAibridgeInterception, policy.ActionRead).Returns(options) + dbm.EXPECT().GetAIProviderSummaries(gomock.Any(), false).Return([]database.GetAIProviderSummariesRow{summaryA, summaryB}, nil).AnyTimes() + check.Args(false).Asserts(rbac.ResourceAIProvider, policy.ActionRead).Returns([]database.GetAIProviderSummariesRow{summaryA, summaryB}) })) s.Run("GetAIProviders", s.Mocked(func(dbm *dbmock.MockStore, faker *gofakeit.Faker, check *expects) { providerA := testutil.Fake(s.T(), faker, database.AIProvider{}) diff --git a/coderd/database/dbmetrics/querymetrics.go b/coderd/database/dbmetrics/querymetrics.go index 5307055ca0d..6efff5cedeb 100644 --- a/coderd/database/dbmetrics/querymetrics.go +++ b/coderd/database/dbmetrics/querymetrics.go @@ -1280,14 +1280,6 @@ func (m queryMetricsStore) GetAIProviderByName(ctx context.Context, name string) return r0, r1 } -func (m queryMetricsStore) GetAIProviderFilterOptions(ctx context.Context) ([]database.GetAIProviderFilterOptionsRow, error) { - start := time.Now() - r0, r1 := m.s.GetAIProviderFilterOptions(ctx) - m.queryLatencies.WithLabelValues("GetAIProviderFilterOptions").Observe(time.Since(start).Seconds()) - m.queryCounts.WithLabelValues(httpmw.ExtractHTTPRoute(ctx), httpmw.ExtractHTTPMethod(ctx), "GetAIProviderFilterOptions").Inc() - return r0, r1 -} - func (m queryMetricsStore) GetAIProviderKeyByID(ctx context.Context, id uuid.UUID) (database.AIProviderKey, error) { start := time.Now() r0, r1 := m.s.GetAIProviderKeyByID(ctx, id) @@ -1328,9 +1320,9 @@ func (m queryMetricsStore) GetAIProviderKeysByProviderIDs(ctx context.Context, p return r0, r1 } -func (m queryMetricsStore) GetAIProviderSummaries(ctx context.Context) ([]database.GetAIProviderSummariesRow, error) { +func (m queryMetricsStore) GetAIProviderSummaries(ctx context.Context, includeDeleted bool) ([]database.GetAIProviderSummariesRow, error) { start := time.Now() - r0, r1 := m.s.GetAIProviderSummaries(ctx) + r0, r1 := m.s.GetAIProviderSummaries(ctx, includeDeleted) m.queryLatencies.WithLabelValues("GetAIProviderSummaries").Observe(time.Since(start).Seconds()) m.queryCounts.WithLabelValues(httpmw.ExtractHTTPRoute(ctx), httpmw.ExtractHTTPMethod(ctx), "GetAIProviderSummaries").Inc() return r0, r1 diff --git a/coderd/database/dbmock/dbmock.go b/coderd/database/dbmock/dbmock.go index 70e429b2183..7e266affa17 100644 --- a/coderd/database/dbmock/dbmock.go +++ b/coderd/database/dbmock/dbmock.go @@ -2245,21 +2245,6 @@ func (mr *MockStoreMockRecorder) GetAIProviderByName(ctx, name any) *gomock.Call return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAIProviderByName", reflect.TypeOf((*MockStore)(nil).GetAIProviderByName), ctx, name) } -// GetAIProviderFilterOptions mocks base method. -func (m *MockStore) GetAIProviderFilterOptions(ctx context.Context) ([]database.GetAIProviderFilterOptionsRow, error) { - m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAIProviderFilterOptions", ctx) - ret0, _ := ret[0].([]database.GetAIProviderFilterOptionsRow) - ret1, _ := ret[1].(error) - return ret0, ret1 -} - -// GetAIProviderFilterOptions indicates an expected call of GetAIProviderFilterOptions. -func (mr *MockStoreMockRecorder) GetAIProviderFilterOptions(ctx any) *gomock.Call { - mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAIProviderFilterOptions", reflect.TypeOf((*MockStore)(nil).GetAIProviderFilterOptions), ctx) -} - // GetAIProviderKeyByID mocks base method. func (m *MockStore) GetAIProviderKeyByID(ctx context.Context, id uuid.UUID) (database.AIProviderKey, error) { m.ctrl.T.Helper() @@ -2336,18 +2321,18 @@ func (mr *MockStoreMockRecorder) GetAIProviderKeysByProviderIDs(ctx, providerIds } // GetAIProviderSummaries mocks base method. -func (m *MockStore) GetAIProviderSummaries(ctx context.Context) ([]database.GetAIProviderSummariesRow, error) { +func (m *MockStore) GetAIProviderSummaries(ctx context.Context, includeDeleted bool) ([]database.GetAIProviderSummariesRow, error) { m.ctrl.T.Helper() - ret := m.ctrl.Call(m, "GetAIProviderSummaries", ctx) + ret := m.ctrl.Call(m, "GetAIProviderSummaries", ctx, includeDeleted) ret0, _ := ret[0].([]database.GetAIProviderSummariesRow) ret1, _ := ret[1].(error) return ret0, ret1 } // GetAIProviderSummaries indicates an expected call of GetAIProviderSummaries. -func (mr *MockStoreMockRecorder) GetAIProviderSummaries(ctx any) *gomock.Call { +func (mr *MockStoreMockRecorder) GetAIProviderSummaries(ctx, includeDeleted any) *gomock.Call { mr.mock.ctrl.T.Helper() - return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAIProviderSummaries", reflect.TypeOf((*MockStore)(nil).GetAIProviderSummaries), ctx) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAIProviderSummaries", reflect.TypeOf((*MockStore)(nil).GetAIProviderSummaries), ctx, includeDeleted) } // GetAIProviders mocks base method. diff --git a/coderd/database/querier.go b/coderd/database/querier.go index f6e7249e46f..154523e0cfd 100644 --- a/coderd/database/querier.go +++ b/coderd/database/querier.go @@ -376,11 +376,6 @@ type sqlcQuerier interface { // between validation and writing the model config reference. GetAIProviderByIDForReferenceLock(ctx context.Context, id uuid.UUID) (AIProvider, error) GetAIProviderByName(ctx context.Context, name string) (AIProvider, error) - // Returns the display metadata AI Gateway session viewers need to filter - // interceptions by provider_name. Soft-deleted and disabled rows are - // included because interceptions keep referencing them. When a name has - // been reused, the live row wins so current metadata is shown. - GetAIProviderFilterOptions(ctx context.Context) ([]GetAIProviderFilterOptionsRow, error) GetAIProviderKeyByID(ctx context.Context, id uuid.UUID) (AIProviderKey, error) // Returns the provider IDs that have at least one provider-scoped key. GetAIProviderKeyPresence(ctx context.Context, providerIds []uuid.UUID) ([]uuid.UUID, error) @@ -398,7 +393,7 @@ type sqlcQuerier interface { // Returns all keys for the requested providers, ordered by provider then created_at ASC // so callers can select the oldest non-empty key per provider without issuing N queries. GetAIProviderKeysByProviderIDs(ctx context.Context, providerIds []uuid.UUID) ([]AIProviderKey, error) - GetAIProviderSummaries(ctx context.Context) ([]GetAIProviderSummariesRow, error) + GetAIProviderSummaries(ctx context.Context, includeDeleted bool) ([]GetAIProviderSummariesRow, error) // Returns AI provider rows. Soft-deleted and disabled rows are excluded // unless include_deleted or include_disabled is set. GetAIProviders(ctx context.Context, arg GetAIProvidersParams) ([]AIProvider, error) diff --git a/coderd/database/queries.sql.go b/coderd/database/queries.sql.go index 0e7159129bb..d11d0a90394 100644 --- a/coderd/database/queries.sql.go +++ b/coderd/database/queries.sql.go @@ -660,75 +660,25 @@ func (q *sqlQuerier) GetAIProviderByName(ctx context.Context, name string) (AIPr return i, err } -const getAIProviderFilterOptions = `-- name: GetAIProviderFilterOptions :many -SELECT DISTINCT ON (name) - name, - type, - display_name, - icon -FROM - ai_providers -ORDER BY - name ASC, - deleted ASC, - updated_at DESC -` - -type GetAIProviderFilterOptionsRow struct { - Name string `db:"name" json:"name"` - Type AIProviderType `db:"type" json:"type"` - DisplayName sql.NullString `db:"display_name" json:"display_name"` - Icon string `db:"icon" json:"icon"` -} - -// Returns the display metadata AI Gateway session viewers need to filter -// interceptions by provider_name. Soft-deleted and disabled rows are -// included because interceptions keep referencing them. When a name has -// been reused, the live row wins so current metadata is shown. -func (q *sqlQuerier) GetAIProviderFilterOptions(ctx context.Context) ([]GetAIProviderFilterOptionsRow, error) { - rows, err := q.db.QueryContext(ctx, getAIProviderFilterOptions) - if err != nil { - return nil, err - } - defer rows.Close() - var items []GetAIProviderFilterOptionsRow - for rows.Next() { - var i GetAIProviderFilterOptionsRow - if err := rows.Scan( - &i.Name, - &i.Type, - &i.DisplayName, - &i.Icon, - ); err != nil { - return nil, err - } - items = append(items, i) - } - if err := rows.Close(); err != nil { - return nil, err - } - if err := rows.Err(); err != nil { - return nil, err - } - return items, nil -} - const getAIProviderSummaries = `-- name: GetAIProviderSummaries :many -SELECT +SELECT DISTINCT ON (name) id, type, name, display_name, icon, enabled, + deleted, created_at, updated_at FROM ai_providers WHERE - NOT deleted + $1::boolean OR NOT deleted ORDER BY - name ASC + name ASC, + deleted ASC, + updated_at DESC ` type GetAIProviderSummariesRow struct { @@ -738,12 +688,13 @@ type GetAIProviderSummariesRow struct { DisplayName sql.NullString `db:"display_name" json:"display_name"` Icon string `db:"icon" json:"icon"` Enabled bool `db:"enabled" json:"enabled"` + Deleted bool `db:"deleted" json:"deleted"` CreatedAt time.Time `db:"created_at" json:"created_at"` UpdatedAt time.Time `db:"updated_at" json:"updated_at"` } -func (q *sqlQuerier) GetAIProviderSummaries(ctx context.Context) ([]GetAIProviderSummariesRow, error) { - rows, err := q.db.QueryContext(ctx, getAIProviderSummaries) +func (q *sqlQuerier) GetAIProviderSummaries(ctx context.Context, includeDeleted bool) ([]GetAIProviderSummariesRow, error) { + rows, err := q.db.QueryContext(ctx, getAIProviderSummaries, includeDeleted) if err != nil { return nil, err } @@ -758,6 +709,7 @@ func (q *sqlQuerier) GetAIProviderSummaries(ctx context.Context) ([]GetAIProvide &i.DisplayName, &i.Icon, &i.Enabled, + &i.Deleted, &i.CreatedAt, &i.UpdatedAt, ); err != nil { diff --git a/coderd/database/queries/ai_providers.sql b/coderd/database/queries/ai_providers.sql index 014bbd9b5ef..1d8d137cd04 100644 --- a/coderd/database/queries/ai_providers.sql +++ b/coderd/database/queries/ai_providers.sql @@ -40,34 +40,20 @@ ORDER BY name ASC; -- name: GetAIProviderSummaries :many -SELECT +SELECT DISTINCT ON (name) id, type, name, display_name, icon, enabled, + deleted, created_at, updated_at FROM ai_providers WHERE - NOT deleted -ORDER BY - name ASC; - --- name: GetAIProviderFilterOptions :many --- Returns the display metadata AI Gateway session viewers need to filter --- interceptions by provider_name. Soft-deleted and disabled rows are --- included because interceptions keep referencing them. When a name has --- been reused, the live row wins so current metadata is shown. -SELECT DISTINCT ON (name) - name, - type, - display_name, - icon -FROM - ai_providers + @include_deleted::boolean OR NOT deleted ORDER BY name ASC, deleted ASC, diff --git a/coderd/exp_chats.go b/coderd/exp_chats.go index d3d74a19452..0ee1c2f83ec 100644 --- a/coderd/exp_chats.go +++ b/coderd/exp_chats.go @@ -8214,6 +8214,7 @@ func convertAIProviderSummary(provider database.GetAIProviderSummariesRow) coder DisplayName: displayName, Icon: provider.Icon, Enabled: provider.Enabled, + Deleted: provider.Deleted, } } @@ -8230,7 +8231,7 @@ func (api *API) listUserAIProviderKeyConfigs(rw http.ResponseWriter, r *http.Req targetUser := httpmw.UserParam(r) //nolint:gocritic // Users can list limited provider metadata to manage their own AI provider keys. metadataCtx := dbauthz.AsAIProviderMetadataReader(ctx) - providers, err := api.Database.GetAIProviderSummaries(metadataCtx) + providers, err := api.Database.GetAIProviderSummaries(metadataCtx, false) if err != nil { api.Logger.Error(ctx, "failed to list user AI provider configs", slog.Error(err), slog.F("user_id", targetUser.ID)) httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{Message: "Failed to list AI providers."}) @@ -8312,7 +8313,7 @@ func (api *API) upsertUserAIProviderKey(rw http.ResponseWriter, r *http.Request) } //nolint:gocritic // Users can attach their own key to an enabled provider without AI provider admin permissions. metadataCtx := dbauthz.AsAIProviderMetadataReader(ctx) - providers, err := api.Database.GetAIProviderSummaries(metadataCtx) + providers, err := api.Database.GetAIProviderSummaries(metadataCtx, false) if err != nil { api.Logger.Error(ctx, "failed to get AI provider", slog.Error(err), slog.F("ai_provider_id", providerID)) httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{Message: "Failed to get AI provider."}) diff --git a/coderd/exp_chats_test.go b/coderd/exp_chats_test.go index 0e670c47e2e..864979dbe7b 100644 --- a/coderd/exp_chats_test.go +++ b/coderd/exp_chats_test.go @@ -15374,7 +15374,7 @@ func enableUserChatProviderKey( t.Helper() ctx := testutil.Context(t, testutil.WaitLong) - providers, err := adminClient.AIProviders(ctx) + providers, err := adminClient.AIProviders(ctx, codersdk.AIProvidersFilter{}) require.NoError(t, err) var provider codersdk.AIProvider diff --git a/codersdk/aibridge.go b/codersdk/aibridge.go index febbcfaf8b4..95ff7bb5ab5 100644 --- a/codersdk/aibridge.go +++ b/codersdk/aibridge.go @@ -580,32 +580,6 @@ func (c *Client) AIBridgeListClients(ctx context.Context) ([]string, error) { return clients, ReadBodyAsJSON(res, &clients) } -// AIBridgeProvider is the display metadata for a configured AI provider, -// used to filter AI Gateway sessions by provider_name. It carries no -// configuration so it can be served to anyone who can read sessions. -type AIBridgeProvider struct { - Name string `json:"name"` - Type AIProviderType `json:"type"` - DisplayName string `json:"display_name"` - Icon string `json:"icon"` -} - -// AIBridgeListProviders returns the providers available for filtering AI -// Gateway sessions, including disabled and deleted ones that past sessions -// may still reference. -func (c *Client) AIBridgeListProviders(ctx context.Context) ([]AIBridgeProvider, error) { - res, err := c.Request(ctx, http.MethodGet, "/api/v2/ai-gateway/providers", nil) - if err != nil { - return nil, err - } - defer res.Body.Close() - if res.StatusCode != http.StatusOK { - return nil, ReadBodyAsError(res) - } - var providers []AIBridgeProvider - return providers, ReadBodyAsJSON(res, &providers) -} - // AIGatewayRetention is how long AI Gateway data, such as interceptions and // token usage, is kept before it is purged. type AIGatewayRetention struct { diff --git a/codersdk/aiproviders.go b/codersdk/aiproviders.go index 0d8774fd42a..cac34ddd486 100644 --- a/codersdk/aiproviders.go +++ b/codersdk/aiproviders.go @@ -8,6 +8,7 @@ import ( "net/http" "net/url" "regexp" + "strconv" "strings" "time" @@ -245,6 +246,7 @@ type AIProvider struct { DisplayName string `json:"display_name"` Icon string `json:"icon"` Enabled bool `json:"enabled"` + Deleted bool `json:"deleted"` BaseURL string `json:"base_url"` APIKeys []AIProviderKey `json:"api_keys"` Settings AIProviderSettings `json:"settings"` @@ -674,10 +676,14 @@ func validateAIProviderKeyMutations(muts []AIProviderKeyMutation) []ValidationEr return validations } -// AIProviders lists all (non-deleted) AI providers. Callers who cannot -// read provider configuration get rows without base URL, keys or settings. -func (c *Client) AIProviders(ctx context.Context) ([]AIProvider, error) { - res, err := c.Request(ctx, http.MethodGet, "/api/v2/ai/providers", nil) +type AIProvidersFilter struct { + IncludeDeleted bool `json:"include_deleted,omitempty"` +} + +// AIProviders lists providers, omitting configuration the caller cannot read. +func (c *Client) AIProviders(ctx context.Context, filter AIProvidersFilter) ([]AIProvider, error) { + res, err := c.Request(ctx, http.MethodGet, "/api/v2/ai/providers", nil, + WithQueryParam("include_deleted", strconv.FormatBool(filter.IncludeDeleted))) if err != nil { return nil, err } diff --git a/docs/reference/api/aigateway.md b/docs/reference/api/aigateway.md index 7a9d500c50e..a978486e5b9 100644 --- a/docs/reference/api/aigateway.md +++ b/docs/reference/api/aigateway.md @@ -82,60 +82,6 @@ Alias: also available at /api/v2/aibridge/models for backward compatibility. To perform this operation, you must be authenticated. [Learn more](authentication.md). -## List AI Gateway providers - -### Code samples - -```sh -# Example request using curl -curl -X GET http://coder-server:8080/api/v2/ai-gateway/providers \ - -H 'Accept: application/json' \ - -H 'Coder-Session-Token: API_KEY' -``` - -`GET /api/v2/ai-gateway/providers` - -### Example responses - -> 200 Response - -```json -[ - { - "display_name": "string", - "icon": "string", - "name": "string", - "type": "openai" - } -] -``` - -### Responses - -| Status | Meaning | Description | Schema | -|--------|---------------------------------------------------------|-------------|---------------------------------------------------------------------------| -| 200 | [OK](https://tools.ietf.org/html/rfc7231#section-6.3.1) | OK | array of [codersdk.AIBridgeProvider](schemas.md#codersdkaibridgeprovider) | - -