diff --git a/coderd/ai_providers.go b/coderd/ai_providers.go index 35c01cc8552..fa6b630502b 100644 --- a/coderd/ai_providers.go +++ b/coderd/ai_providers.go @@ -576,7 +576,7 @@ func (api *API) aiProvidersDelete(rw http.ResponseWriter, r *http.Request) { } // publishAIProvidersChanged notifies subscribers (aibridged, -// aibridgeproxyd, chatd) that the live provider set changed and they +// aibridgeproxyd) that the live provider set changed and they // should refetch from the database. Pubsub failures are logged but not // propagated: subscribers refresh authoritatively from the DB, so a // dropped notification only delays convergence. diff --git a/coderd/pubsub/aiproviderschangedevent.go b/coderd/pubsub/aiproviderschangedevent.go index 5d61b3b7fa7..a0ff20f9606 100644 --- a/coderd/pubsub/aiproviderschangedevent.go +++ b/coderd/pubsub/aiproviderschangedevent.go @@ -2,8 +2,8 @@ package pubsub // AIProvidersChangedChannel is the pubsub channel that carries AI // provider lifecycle events: provider create / update / soft-delete -// and key insert / delete. Subscribers (aibridged, aibridgeproxyd, -// chatd) reload their in-memory provider snapshot on receipt. +// and key insert / delete. Subscribers (aibridged, aibridgeproxyd) +// reload their in-memory provider snapshot on receipt. // // The payload is an empty invalidation hint; subscribers refetch the // authoritative state from the database, so dropped messages only diff --git a/coderd/x/chatd/chatd.go b/coderd/x/chatd/chatd.go index 4c135fdcf97..f718058ed2e 100644 --- a/coderd/x/chatd/chatd.go +++ b/coderd/x/chatd/chatd.go @@ -175,7 +175,6 @@ type Server struct { pubsub pubsub.Pubsub webpushDispatcher webpush.Dispatcher hooks *chathooks.Trigger - providerAPIKeys chatprovider.ProviderAPIKeys allowBYOK bool disableCallerSuppliedTools bool oidcTokenSource mcpclient.UserOIDCTokenSource @@ -187,7 +186,6 @@ type Server struct { debugSvcInit sync.Once configCache *chatConfigCache configCacheUnsubscribe func() - providerCacheUnsubscribe func() usageTracker *workspacestats.UsageTracker clock quartz.Clock @@ -1232,7 +1230,6 @@ type Config struct { CreateWorkspace chattool.CreateWorkspaceFn BuildWorkspace chattool.BuildWorkspaceFn RenderTemplateParameters chattool.RenderTemplateParametersFn - ProviderAPIKeys chatprovider.ProviderAPIKeys AllowBYOK bool AllowBYOKSet bool AlwaysEnableDebugLogs bool @@ -1348,7 +1345,6 @@ func New(ps pubsub.Pubsub, cfg Config) (*Server, error) { pubsub: ps, webpushDispatcher: cfg.WebpushDispatcher, hooks: chathooks.NewTrigger(hookDispatcher), - providerAPIKeys: cfg.ProviderAPIKeys, allowBYOK: allowBYOK, disableCallerSuppliedTools: cfg.DisableCallerSuppliedTools, oidcTokenSource: cfg.OIDCTokenSource, @@ -1451,22 +1447,6 @@ func New(ps pubsub.Pubsub, cfg Config) (*Server, error) { p.configCacheUnsubscribe = cancelConfigSub } - cancelProviderSub, err := p.pubsub.SubscribeWithErr( - coderdpubsub.AIProvidersChangedChannel, - func(cbCtx context.Context, _ []byte, err error) { - if err != nil { - p.logger.Warn(cbCtx, "ai providers changed event error", slog.Error(err)) - return - } - p.configCache.InvalidateProviders() - }, - ) - if err != nil { - p.logger.Error(ctx, "subscribe to ai providers changed events", slog.Error(err)) - } else { - p.providerCacheUnsubscribe = cancelProviderSub - } - p.ctx = ctx // Spawn background goroutines that all servers need. @@ -1748,48 +1728,6 @@ func (p *Server) aiProviderConfigFromKeys(provider database.AIProvider, keys []d }, nil } -func (p *Server) aiProviderConfigs(ctx context.Context, providers []database.AIProvider) ([]chatprovider.ConfiguredProvider, error) { - if len(providers) == 0 { - return nil, nil - } - providerIDs := make([]uuid.UUID, 0, len(providers)) - for _, provider := range providers { - providerIDs = append(providerIDs, provider.ID) - } - keys, err := p.db.GetAIProviderKeysByProviderIDs(ctx, providerIDs) - if err != nil { - return nil, xerrors.Errorf("get AI provider keys: %w", err) - } - keysByProviderID := make(map[uuid.UUID][]database.AIProviderKey, len(providers)) - for _, key := range keys { - keysByProviderID[key.ProviderID] = append(keysByProviderID[key.ProviderID], key) - } - configuredProviders := make([]chatprovider.ConfiguredProvider, 0, len(providers)) - for _, provider := range providers { - configuredProvider, err := p.aiProviderConfigFromKeys(provider, keysByProviderID[provider.ID]) - if err != nil { - return nil, err - } - configuredProviders = append(configuredProviders, configuredProvider) - } - return configuredProviders, nil -} - -func ensureUniqueConfiguredProviderTypes(providers []chatprovider.ConfiguredProvider) error { - seen := make(map[string]uuid.UUID, len(providers)) - for _, provider := range providers { - normalizedProvider := chatprovider.NormalizeProvider(provider.Provider) - if normalizedProvider == "" { - continue - } - if existingProviderID, ok := seen[normalizedProvider]; ok && existingProviderID != provider.ProviderID { - return xerrors.Errorf("multiple enabled AI providers use provider type %q; select an AI provider by ID", normalizedProvider) - } - seen[normalizedProvider] = provider.ProviderID - } - return nil -} - func (p *Server) resolveUserProviderAPIKeysForProvider( ctx context.Context, ownerID uuid.UUID, @@ -1828,62 +1766,11 @@ func (p *Server) resolveUserProviderAPIKeys( ownerID uuid.UUID, selectedAIProviderID uuid.UUID, ) (chatprovider.ProviderAPIKeys, error) { - if selectedAIProviderID != uuid.Nil { - provider, err := p.db.GetAIProviderByID(ctx, selectedAIProviderID) - if err != nil { - return chatprovider.ProviderAPIKeys{}, xerrors.Errorf("get AI provider: %w", err) - } - return p.resolveUserProviderAPIKeysForProvider(ctx, ownerID, provider) - } - - providers, err := p.configCache.EnabledProviders(ctx) + provider, err := p.db.GetAIProviderByID(ctx, selectedAIProviderID) if err != nil { - return chatprovider.ProviderAPIKeys{}, xerrors.Errorf( - "get enabled AI providers: %w", - err, - ) + return chatprovider.ProviderAPIKeys{}, xerrors.Errorf("get AI provider: %w", err) } - configuredProviders, err := p.aiProviderConfigs(ctx, providers) - if err != nil { - return chatprovider.ProviderAPIKeys{}, err - } - if err := ensureUniqueConfiguredProviderTypes(configuredProviders); err != nil { - return chatprovider.ProviderAPIKeys{}, err - } - - userKeys := []chatprovider.UserProviderKey{} - if p.allowBYOK { - userKeyRows, err := p.db.GetUserAIProviderKeysByUserID(ctx, ownerID) - if err != nil { - return chatprovider.ProviderAPIKeys{}, xerrors.Errorf( - "get user AI provider keys: %w", - err, - ) - } - userKeys = make([]chatprovider.UserProviderKey, 0, len(userKeyRows)) - for _, userKey := range userKeyRows { - userKeys = append(userKeys, chatprovider.UserProviderKey{ - ChatProviderID: userKey.AIProviderID, - APIKey: userKey.APIKey, - }) - } - } - - keys, _ := chatprovider.ResolveUserProviderKeys( - p.providerAPIKeys, - configuredProviders, - userKeys, - ) - enabledProviders := make(map[string]struct{}, len(configuredProviders)) - for _, provider := range configuredProviders { - normalizedProvider := chatprovider.NormalizeProvider(provider.Provider) - if normalizedProvider == "" { - continue - } - enabledProviders[normalizedProvider] = struct{}{} - } - chatprovider.PruneDisabledProviderKeys(&keys, enabledProviders) - return keys, nil + return p.resolveUserProviderAPIKeysForProvider(ctx, ownerID, provider) } var errModelConfigOutsideOrganization = xerrors.Errorf("%w: model config belongs to another organization", sql.ErrNoRows) @@ -2663,10 +2550,6 @@ func (p *Server) Close() error { p.configCacheUnsubscribe = nil unsub() } - if unsub := p.providerCacheUnsubscribe; unsub != nil { - p.providerCacheUnsubscribe = nil - unsub() - } if p.chatWorker != nil { if err := p.chatWorker.Close(); err != nil { p.logger.Warn(context.Background(), "failed to close chat worker", slog.Error(err)) diff --git a/coderd/x/chatd/chatd_internal_test.go b/coderd/x/chatd/chatd_internal_test.go index f9d3e028d61..6351be557fb 100644 --- a/coderd/x/chatd/chatd_internal_test.go +++ b/coderd/x/chatd/chatd_internal_test.go @@ -35,7 +35,6 @@ import ( "github.com/coder/coder/v2/coderd/x/chatd/agentselect" "github.com/coder/coder/v2/coderd/x/chatd/chatloop" "github.com/coder/coder/v2/coderd/x/chatd/chatprompt" - "github.com/coder/coder/v2/coderd/x/chatd/chatprovider" "github.com/coder/coder/v2/coderd/x/chatd/chatstate" "github.com/coder/coder/v2/coderd/x/chatd/chattest" "github.com/coder/coder/v2/coderd/x/chatd/chattool" @@ -413,7 +412,7 @@ func TestGenerateAndStoreChatSummary_UsesTitleGenerationModel(t *testing.T) { require.NoError(t, err) server := newInternalTestServer( - t, db, ps, chatprovider.ProviderAPIKeys{}, + t, db, ps, withInternalTestServerTransportFactory(chattest.NewMockAIBridgeTransport(t, openAIURL)), ) logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true}) @@ -958,126 +957,6 @@ func TestRenameChatTitle(t *testing.T) { } } -func TestResolveUserProviderAPIKeys_StripsDisabledFallbackKeys(t *testing.T) { - t.Parallel() - - ctx := testutil.Context(t, testutil.WaitShort) - ctrl := gomock.NewController(t) - db := dbmock.NewMockStore(ctrl) - ownerID := uuid.New() - - server := &Server{ - db: db, - configCache: newChatConfigCache( - context.Background(), - db, - quartz.NewReal(), - ), - providerAPIKeys: chatprovider.ProviderAPIKeys{ - OpenAI: "openai-deployment-key", - Anthropic: "anthropic-deployment-key", - ByProvider: map[string]string{ - "openai": "openai-deployment-key", - "anthropic": "anthropic-deployment-key", - }, - BaseURLByProvider: map[string]string{ - "openai": "https://openai.example.com", - "anthropic": "https://anthropic.example.com", - }, - }, - } - - providerID := uuid.New() - db.EXPECT().GetAIProviders(gomock.Any(), gomock.Any()).Return([]database.AIProvider{{ - ID: providerID, - Type: database.AIProviderTypeAnthropic, - Enabled: true, - }}, nil) - db.EXPECT().GetAIProviderKeysByProviderIDs(gomock.Any(), []uuid.UUID{providerID}).Return(nil, nil) - - keys, err := server.resolveUserProviderAPIKeys(ctx, ownerID, uuid.Nil) - require.NoError(t, err) - require.Empty(t, keys.OpenAI) - require.Empty(t, keys.APIKey("openai")) - require.Empty(t, keys.BaseURL("openai")) - require.Equal(t, "anthropic-deployment-key", keys.Anthropic) - require.Equal(t, "anthropic-deployment-key", keys.APIKey("anthropic")) - require.Equal(t, "https://anthropic.example.com", keys.BaseURL("anthropic")) - require.Equal(t, map[string]string{"anthropic": "anthropic-deployment-key"}, keys.ByProvider) - require.Equal(t, map[string]string{"anthropic": "https://anthropic.example.com"}, keys.BaseURLByProvider) -} - -func TestResolveUserProviderAPIKeys_SelectedAIProviderDoesNotUseDeploymentFallback(t *testing.T) { - t.Parallel() - - ctx := testutil.Context(t, testutil.WaitShort) - ctrl := gomock.NewController(t) - db := dbmock.NewMockStore(ctrl) - ownerID := uuid.New() - providerID := uuid.New() - - server := &Server{ - db: db, - providerAPIKeys: chatprovider.ProviderAPIKeys{ - OpenAI: "openai-deployment-key", - ByProvider: map[string]string{ - "openai": "openai-deployment-key", - }, - }, - } - - db.EXPECT().GetAIProviderByID(gomock.Any(), providerID).Return(database.AIProvider{ - ID: providerID, - Type: database.AIProviderTypeOpenai, - Name: "agents-openai", - Enabled: true, - }, nil) - db.EXPECT().GetAIProviderKeysByProviderID(gomock.Any(), providerID).Return(nil, nil) - - keys, err := server.resolveUserProviderAPIKeys(ctx, ownerID, providerID) - require.NoError(t, err) - require.Empty(t, keys.OpenAI) - require.Empty(t, keys.APIKey("openai")) - require.False(t, keys.HasProvider("openai")) -} - -func TestResolveUserProviderAPIKeys_SkipsUserKeyLookupWhenNoProviderAllowsUserKeys(t *testing.T) { - t.Parallel() - - ctx := testutil.Context(t, testutil.WaitShort) - ctrl := gomock.NewController(t) - db := dbmock.NewMockStore(ctrl) - ownerID := uuid.New() - - server := &Server{ - db: db, - configCache: newChatConfigCache( - context.Background(), - db, - quartz.NewReal(), - ), - providerAPIKeys: chatprovider.ProviderAPIKeys{ - OpenAI: "openai-deployment-key", - ByProvider: map[string]string{ - "openai": "openai-deployment-key", - }, - }, - } - - providerID := uuid.New() - db.EXPECT().GetAIProviders(gomock.Any(), gomock.Any()).Return([]database.AIProvider{{ - ID: providerID, - Type: database.AIProviderTypeOpenai, - Enabled: true, - }}, nil) - db.EXPECT().GetAIProviderKeysByProviderIDs(gomock.Any(), []uuid.UUID{providerID}).Return(nil, nil) - - keys, err := server.resolveUserProviderAPIKeys(ctx, ownerID, uuid.Nil) - require.NoError(t, err) - require.Equal(t, "openai-deployment-key", keys.OpenAI) - require.Equal(t, "openai-deployment-key", keys.APIKey("openai")) -} - func TestRefreshChatWorkspaceSnapshot_NoReloadWhenWorkspacePresent(t *testing.T) { t.Parallel() @@ -4098,7 +3977,7 @@ func TestResolveFallbackModelConfigID(t *testing.T) { owner := dbgen.User(t, db, database.User{}) disabledProvider := newProvider(t, db, false) model := newModelConfig(t, db, newModelConfigOrg(t, db), disabledProvider.ID, false) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) _, err := server.CreateChat(ctx, CreateOptions{ OrganizationID: uuid.New(), diff --git a/coderd/x/chatd/chatprovider/chatprovider.go b/coderd/x/chatd/chatprovider/chatprovider.go index 142b40c4ea1..15e25ed02bc 100644 --- a/coderd/x/chatd/chatprovider/chatprovider.go +++ b/coderd/x/chatd/chatprovider/chatprovider.go @@ -424,29 +424,6 @@ func setResolvedProviderAPIKey(keys *ProviderAPIKeys, provider string, apiKey st } } -// PruneDisabledProviderKeys removes keys and base URLs for disabled providers, -// including the legacy OpenAI and Anthropic key fields. -func PruneDisabledProviderKeys(keys *ProviderAPIKeys, enabledProviders map[string]struct{}) { - for provider := range keys.ByProvider { - if _, ok := enabledProviders[provider]; ok { - continue - } - delete(keys.ByProvider, provider) - } - for provider := range keys.BaseURLByProvider { - if _, ok := enabledProviders[provider]; ok { - continue - } - delete(keys.BaseURLByProvider, provider) - } - if _, ok := enabledProviders[NormalizeProvider("openai")]; !ok { - keys.OpenAI = "" - } - if _, ok := enabledProviders[NormalizeProvider("anthropic")]; !ok { - keys.Anthropic = "" - } -} - // NormalizeProvider canonicalizes a provider name. func NormalizeProvider(provider string) string { switch strings.ToLower(strings.TrimSpace(provider)) { diff --git a/coderd/x/chatd/chatprovider/chatprovider_test.go b/coderd/x/chatd/chatprovider/chatprovider_test.go index b183047cfbc..8a89d7e111e 100644 --- a/coderd/x/chatd/chatprovider/chatprovider_test.go +++ b/coderd/x/chatd/chatprovider/chatprovider_test.go @@ -473,136 +473,6 @@ func TestResolveUserProviderKeys_UnavailableReason(t *testing.T) { } } -func TestPruneDisabledProviderKeys(t *testing.T) { - t.Parallel() - - enabledProviders := func(providers ...string) map[string]struct{} { - result := make(map[string]struct{}, len(providers)) - for _, provider := range providers { - result[chatprovider.NormalizeProvider(provider)] = struct{}{} - } - return result - } - - tests := []struct { - name string - keys chatprovider.ProviderAPIKeys - enabledProviders map[string]struct{} - want chatprovider.ProviderAPIKeys - }{ - { - name: "DisabledProviderEntriesRemoved", - keys: chatprovider.ProviderAPIKeys{ - ByProvider: map[string]string{ - fantasyanthropic.Name: "sk-anthropic", - fantasyopenai.Name: "sk-openai", - }, - BaseURLByProvider: map[string]string{ - fantasyanthropic.Name: "https://anthropic.example.com", - fantasyopenai.Name: "https://openai.example.com", - }, - }, - enabledProviders: enabledProviders(fantasyopenai.Name), - want: chatprovider.ProviderAPIKeys{ - ByProvider: map[string]string{ - fantasyopenai.Name: "sk-openai", - }, - BaseURLByProvider: map[string]string{ - fantasyopenai.Name: "https://openai.example.com", - }, - }, - }, - { - name: "OpenAIDisabledClearsLegacyField", - keys: chatprovider.ProviderAPIKeys{ - OpenAI: "sk-openai", - Anthropic: "sk-anthropic", - ByProvider: map[string]string{ - fantasyopenai.Name: "sk-openai", - fantasyanthropic.Name: "sk-anthropic", - }, - BaseURLByProvider: map[string]string{ - fantasyopenai.Name: "https://openai.example.com", - fantasyanthropic.Name: "https://anthropic.example.com", - }, - }, - enabledProviders: enabledProviders(fantasyanthropic.Name), - want: chatprovider.ProviderAPIKeys{ - Anthropic: "sk-anthropic", - ByProvider: map[string]string{ - fantasyanthropic.Name: "sk-anthropic", - }, - BaseURLByProvider: map[string]string{ - fantasyanthropic.Name: "https://anthropic.example.com", - }, - }, - }, - { - name: "AnthropicDisabledClearsLegacyField", - keys: chatprovider.ProviderAPIKeys{ - OpenAI: "sk-openai", - Anthropic: "sk-anthropic", - ByProvider: map[string]string{ - fantasyopenai.Name: "sk-openai", - fantasyanthropic.Name: "sk-anthropic", - }, - BaseURLByProvider: map[string]string{ - fantasyopenai.Name: "https://openai.example.com", - fantasyanthropic.Name: "https://anthropic.example.com", - }, - }, - enabledProviders: enabledProviders(fantasyopenai.Name), - want: chatprovider.ProviderAPIKeys{ - OpenAI: "sk-openai", - ByProvider: map[string]string{ - fantasyopenai.Name: "sk-openai", - }, - BaseURLByProvider: map[string]string{ - fantasyopenai.Name: "https://openai.example.com", - }, - }, - }, - { - name: "AllEnabledLeavesKeysUnchanged", - keys: chatprovider.ProviderAPIKeys{ - OpenAI: "sk-openai", - Anthropic: "sk-anthropic", - ByProvider: map[string]string{ - fantasyopenai.Name: "sk-openai", - fantasyanthropic.Name: "sk-anthropic", - }, - BaseURLByProvider: map[string]string{ - fantasyopenai.Name: "https://openai.example.com", - fantasyanthropic.Name: "https://anthropic.example.com", - }, - }, - enabledProviders: enabledProviders(fantasyopenai.Name, fantasyanthropic.Name), - want: chatprovider.ProviderAPIKeys{ - OpenAI: "sk-openai", - Anthropic: "sk-anthropic", - ByProvider: map[string]string{ - fantasyopenai.Name: "sk-openai", - fantasyanthropic.Name: "sk-anthropic", - }, - BaseURLByProvider: map[string]string{ - fantasyopenai.Name: "https://openai.example.com", - fantasyanthropic.Name: "https://anthropic.example.com", - }, - }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - t.Parallel() - - keys := tt.keys - chatprovider.PruneDisabledProviderKeys(&keys, tt.enabledProviders) - require.Equal(t, tt.want, keys) - }) - } -} - func TestCoderHeaders(t *testing.T) { t.Parallel() diff --git a/coderd/x/chatd/configcache.go b/coderd/x/chatd/configcache.go index 60b2edcdef3..57c8e53bc44 100644 --- a/coderd/x/chatd/configcache.go +++ b/coderd/x/chatd/configcache.go @@ -6,7 +6,6 @@ import ( "encoding/json" "errors" "fmt" - "slices" "sync" "time" @@ -19,7 +18,6 @@ import ( ) const ( - chatConfigProvidersTTL = 10 * time.Second chatConfigUserPromptTTL = 5 * time.Second chatConfigAdvisorConfigTTL = 10 * time.Second // Bound user-prompt cache cardinality so one-shot users do not @@ -27,11 +25,6 @@ const ( chatConfigUserPromptEntryLimit = 64 * 1024 ) -type cachedProviders struct { - providers []database.AIProvider - expiresAt time.Time -} - type advisorRuntimeConfig struct { MaxUsesPerRun int `json:"max_uses_per_run"` MaxOutputTokens int64 `json:"max_output_tokens"` @@ -57,11 +50,6 @@ type chatConfigCache struct { mu sync.RWMutex - // Providers (singleton). - providers *cachedProviders - providerGeneration uint64 - providerFetches singleflight.Group[string, []database.AIProvider] - // User custom prompts (keyed by user ID). userPromptEpoch uint64 userPrompts *tlru.Cache[uuid.UUID, string] @@ -106,84 +94,6 @@ func singleflightDoChan[K comparable, V any]( } } -func (c *chatConfigCache) EnabledProviders(ctx context.Context) ([]database.AIProvider, error) { - if providers, ok := c.cachedProviders(); ok { - return providers, nil - } - - generation := c.providersGeneration() - providers, err := singleflightDoChan( - ctx, - &c.providerFetches, - fmt.Sprintf("%d:providers", generation), - func() ([]database.AIProvider, error) { - if cached, ok := c.cachedProviders(); ok { - return cached, nil - } - - fetched, err := c.db.GetAIProviders(c.ctx, database.GetAIProvidersParams{}) - if err != nil { - return nil, err - } - c.storeProviders(generation, fetched) - return slices.Clone(fetched), nil - }, - ) - if err != nil { - return nil, err - } - - return slices.Clone(providers), nil -} - -func (c *chatConfigCache) cachedProviders() ([]database.AIProvider, bool) { - c.mu.RLock() - entry := c.providers - c.mu.RUnlock() - if entry == nil { - return nil, false - } - if c.clock.Now().Before(entry.expiresAt) { - return slices.Clone(entry.providers), true - } - - c.mu.Lock() - if current := c.providers; current != nil && !c.clock.Now().Before(current.expiresAt) { - c.providers = nil - } - c.mu.Unlock() - - return nil, false -} - -func (c *chatConfigCache) providersGeneration() uint64 { - c.mu.RLock() - generation := c.providerGeneration - c.mu.RUnlock() - return generation -} - -func (c *chatConfigCache) storeProviders(generation uint64, providers []database.AIProvider) { - c.mu.Lock() - defer c.mu.Unlock() - - if c.providerGeneration != generation { - return - } - - c.providers = &cachedProviders{ - providers: slices.Clone(providers), - expiresAt: c.clock.Now().Add(chatConfigProvidersTTL), - } -} - -func (c *chatConfigCache) InvalidateProviders() { - c.mu.Lock() - c.providers = nil - c.providerGeneration++ - c.mu.Unlock() -} - func (c *chatConfigCache) UserPrompt(ctx context.Context, userID uuid.UUID) (string, error) { if prompt, ok := c.cachedUserPrompt(userID); ok { return prompt, nil diff --git a/coderd/x/chatd/configcache_internal_test.go b/coderd/x/chatd/configcache_internal_test.go index 85246bc2d0b..78cd531b197 100644 --- a/coderd/x/chatd/configcache_internal_test.go +++ b/coderd/x/chatd/configcache_internal_test.go @@ -14,9 +14,6 @@ import ( "golang.org/x/xerrors" "github.com/coder/coder/v2/coderd/database" - "github.com/coder/coder/v2/coderd/database/dbtestutil" - coderdpubsub "github.com/coder/coder/v2/coderd/pubsub" - "github.com/coder/coder/v2/coderd/x/chatd/chatprovider" "github.com/coder/coder/v2/testutil" "github.com/coder/quartz" ) @@ -24,21 +21,11 @@ import ( type stubChatConfigStore struct { database.Store - getAIProviders func(context.Context) ([]database.AIProvider, error) getUserChatCustomPrompt func(context.Context, uuid.UUID) (string, error) getChatAdvisorConfig func(context.Context) (string, error) - enabledProvidersCalls atomic.Int32 - userPromptCalls atomic.Int32 - advisorConfigCalls atomic.Int32 -} - -func (s *stubChatConfigStore) GetAIProviders(ctx context.Context, _ database.GetAIProvidersParams) ([]database.AIProvider, error) { - s.enabledProvidersCalls.Add(1) - if s.getAIProviders == nil { - panic("unexpected GetAIProviders call") - } - return s.getAIProviders(ctx) + userPromptCalls atomic.Int32 + advisorConfigCalls atomic.Int32 } func (s *stubChatConfigStore) GetUserChatCustomPrompt(ctx context.Context, userID uuid.UUID) (string, error) { @@ -57,73 +44,6 @@ func (s *stubChatConfigStore) GetChatAdvisorConfig(ctx context.Context) (string, return s.getChatAdvisorConfig(ctx) } -func TestConfigCache_EnabledProviders_CacheHit(t *testing.T) { - t.Parallel() - - ctx := testutil.Context(t, testutil.WaitShort) - clock := quartz.NewMock(t) - providers := []database.AIProvider{testAIProvider("provider-a")} - store := &stubChatConfigStore{ - getAIProviders: func(context.Context) ([]database.AIProvider, error) { - return providers, nil - }, - } - cache := newChatConfigCache(ctx, store, clock) - - first, err := cache.EnabledProviders(ctx) - require.NoError(t, err) - second, err := cache.EnabledProviders(ctx) - require.NoError(t, err) - - require.Equal(t, providers, first) - require.Equal(t, providers, second) - require.Equal(t, int32(1), store.enabledProvidersCalls.Load()) -} - -func TestConfigCache_EnabledProviders_TTLExpiry(t *testing.T) { - t.Parallel() - - ctx := testutil.Context(t, testutil.WaitShort) - clock := quartz.NewMock(t) - store := &stubChatConfigStore{} - store.getAIProviders = func(context.Context) ([]database.AIProvider, error) { - call := store.enabledProvidersCalls.Load() - return []database.AIProvider{testAIProvider(fmt.Sprintf("provider-%d", call))}, nil - } - cache := newChatConfigCache(ctx, store, clock) - - first, err := cache.EnabledProviders(ctx) - require.NoError(t, err) - clock.Advance(chatConfigProvidersTTL).MustWait(ctx) - second, err := cache.EnabledProviders(ctx) - require.NoError(t, err) - - require.NotEqual(t, first, second) - require.Equal(t, int32(2), store.enabledProvidersCalls.Load()) -} - -func TestConfigCache_EnabledProviders_Invalidation(t *testing.T) { - t.Parallel() - - ctx := testutil.Context(t, testutil.WaitShort) - clock := quartz.NewMock(t) - store := &stubChatConfigStore{} - store.getAIProviders = func(context.Context) ([]database.AIProvider, error) { - call := store.enabledProvidersCalls.Load() - return []database.AIProvider{testAIProvider(fmt.Sprintf("provider-%d", call))}, nil - } - cache := newChatConfigCache(ctx, store, clock) - - first, err := cache.EnabledProviders(ctx) - require.NoError(t, err) - cache.InvalidateProviders() - second, err := cache.EnabledProviders(ctx) - require.NoError(t, err) - - require.NotEqual(t, first, second) - require.Equal(t, int32(2), store.enabledProvidersCalls.Load()) -} - func TestConfigCache_UserPrompt_NegativeCaching(t *testing.T) { t.Parallel() @@ -268,27 +188,28 @@ func TestConfigCache_Singleflight(t *testing.T) { ctx := testutil.Context(t, testutil.WaitMedium) clock := quartz.NewMock(t) - providers := []database.AIProvider{testAIProvider("provider-a")} + userID := uuid.New() + const prompt = "custom prompt" fetchStarted := make(chan struct{}) releaseFetch := make(chan struct{}) var startedOnce sync.Once store := &stubChatConfigStore{} - store.getAIProviders = func(context.Context) ([]database.AIProvider, error) { + store.getUserChatCustomPrompt = func(context.Context, uuid.UUID) (string, error) { startedOnce.Do(func() { close(fetchStarted) }) <-releaseFetch - return providers, nil + return prompt, nil } cache := newChatConfigCache(ctx, store, clock) const callers = 8 - results := make([][]database.AIProvider, callers) + results := make([]string, callers) errs := make([]error, callers) var wg sync.WaitGroup start := make(chan struct{}) for i := 0; i < callers; i++ { wg.Go(func() { <-start - results[i], errs[i] = cache.EnabledProviders(ctx) + results[i], errs[i] = cache.UserPrompt(ctx, userID) }) } @@ -299,141 +220,9 @@ func TestConfigCache_Singleflight(t *testing.T) { for i := 0; i < callers; i++ { require.NoError(t, errs[i]) - require.Equal(t, providers, results[i]) - } - require.Equal(t, int32(1), store.enabledProvidersCalls.Load()) -} - -func TestConfigCache_GenerationPreventsStaleWrite(t *testing.T) { - t.Parallel() - - ctx := testutil.Context(t, testutil.WaitMedium) - clock := quartz.NewMock(t) - firstProviders := []database.AIProvider{testAIProvider("provider-a")} - secondProviders := []database.AIProvider{testAIProvider("provider-b")} - fetchStarted := make(chan struct{}) - releaseFetch := make(chan struct{}) - var startedOnce sync.Once - store := &stubChatConfigStore{} - store.getAIProviders = func(context.Context) ([]database.AIProvider, error) { - call := store.enabledProvidersCalls.Load() - if call == 1 { - startedOnce.Do(func() { close(fetchStarted) }) - <-releaseFetch - return firstProviders, nil - } - return secondProviders, nil - } - cache := newChatConfigCache(ctx, store, clock) - - resultCh := make(chan []database.AIProvider, 1) - errCh := make(chan error, 1) - go func() { - providers, err := cache.EnabledProviders(ctx) - if err != nil { - errCh <- err - return - } - resultCh <- providers - }() - - waitForSignal(t, fetchStarted) - cache.InvalidateProviders() - close(releaseFetch) - - select { - case err := <-errCh: - require.NoError(t, err) - case providers := <-resultCh: - require.Equal(t, firstProviders, providers) - case <-time.After(testutil.WaitShort): - t.Fatal("timed out waiting for in-flight fetch") - } - - require.Nil(t, cache.providers) - second, err := cache.EnabledProviders(ctx) - require.NoError(t, err) - require.Equal(t, secondProviders, second) - require.Equal(t, int32(2), store.enabledProvidersCalls.Load()) -} - -func TestConfigCache_InvalidateProviders_BlocksStaleInFlightProviders(t *testing.T) { - t.Parallel() - - ctx := testutil.Context(t, testutil.WaitMedium) - clock := quartz.NewMock(t) - staleProviders := []database.AIProvider{testAIProvider("provider-stale")} - freshProviders := []database.AIProvider{testAIProvider("provider-fresh")} - firstStarted := make(chan struct{}) - secondStarted := make(chan struct{}) - releaseFirst := make(chan struct{}) - releaseSecond := make(chan struct{}) - store := &stubChatConfigStore{} - store.getAIProviders = func(context.Context) ([]database.AIProvider, error) { - switch call := store.enabledProvidersCalls.Load(); call { - case 1: - close(firstStarted) - <-releaseFirst - return staleProviders, nil - case 2: - close(secondStarted) - <-releaseSecond - return freshProviders, nil - default: - return nil, xerrors.Errorf("unexpected provider call %d", call) - } - } - cache := newChatConfigCache(ctx, store, clock) - - type result struct { - providers []database.AIProvider - err error - } - - firstResult := make(chan result, 1) - go func() { - providers, err := cache.EnabledProviders(ctx) - firstResult <- result{providers: providers, err: err} - }() - - waitForSignal(t, firstStarted) - cache.InvalidateProviders() - - secondResult := make(chan result, 1) - go func() { - providers, err := cache.EnabledProviders(ctx) - secondResult <- result{providers: providers, err: err} - }() - - waitForSignal(t, secondStarted) - close(releaseFirst) - first := <-firstResult - require.NoError(t, first.err) - require.Equal(t, staleProviders, first.providers) - require.Nil(t, cache.providers) - - close(releaseSecond) - second := <-secondResult - require.NoError(t, second.err) - require.Equal(t, freshProviders, second.providers) - require.Equal(t, int32(2), store.enabledProvidersCalls.Load()) - - third, err := cache.EnabledProviders(ctx) - require.NoError(t, err) - require.Equal(t, freshProviders, third) - require.Equal(t, int32(2), store.enabledProvidersCalls.Load()) -} - -func testAIProvider(name string) database.AIProvider { - return database.AIProvider{ - ID: uuid.New(), - Type: database.AIProviderType(name), - Name: name, - DisplayName: sql.NullString{String: name, Valid: true}, - Enabled: true, - CreatedAt: time.Unix(0, 0).UTC(), - UpdatedAt: time.Unix(0, 0).UTC(), + require.Equal(t, prompt, results[i]) } + require.Equal(t, int32(1), store.userPromptCalls.Load()) } func waitForSignal(t *testing.T, ch <-chan struct{}) { @@ -472,36 +261,6 @@ func TestConfigCache_CallerCancellation(t *testing.T) { userID := uuid.New() methods := []cacheMethod{ - { - name: "EnabledProviders", - setupBlocked: func(store *stubChatConfigStore, started, release chan struct{}) { - var once sync.Once - store.getAIProviders = func(ctx context.Context) ([]database.AIProvider, error) { - once.Do(func() { close(started) }) - select { - case <-ctx.Done(): - return nil, ctx.Err() - case <-release: - return []database.AIProvider{testAIProvider("p")}, nil - } - } - }, - setupCtxSensitive: func(store *stubChatConfigStore, started chan struct{}) { - var once sync.Once - store.getAIProviders = func(ctx context.Context) ([]database.AIProvider, error) { - once.Do(func() { close(started) }) - <-ctx.Done() - return nil, ctx.Err() - } - }, - call: func(ctx context.Context, cache *chatConfigCache) error { - _, err := cache.EnabledProviders(ctx) - return err - }, - storeCalls: func(store *stubChatConfigStore) int32 { - return store.enabledProvidersCalls.Load() - }, - }, { name: "UserPrompt", setupBlocked: func(store *stubChatConfigStore, started, release chan struct{}) { @@ -878,19 +637,3 @@ func TestConfigCache_InvalidateAdvisorConfig_BlocksStaleInFlight(t *testing.T) { require.EqualValues(t, 2, third.MaxUsesPerRun) require.Equal(t, int32(2), store.advisorConfigCalls.Load()) } - -func TestConfigCache_InvalidatesProvidersOnAIProvidersChangedEvent(t *testing.T) { - t.Parallel() - - db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) - - // The generation counter only advances through InvalidateProviders, - // so this cannot false-pass via TTL expiry. - gen := server.configCache.providersGeneration() - require.NoError(t, ps.Publish(coderdpubsub.AIProvidersChangedChannel, nil)) - - require.Eventually(t, func() bool { - return server.configCache.providersGeneration() > gen - }, testutil.WaitShort, testutil.IntervalFast) -} diff --git a/coderd/x/chatd/quickgen_internal_test.go b/coderd/x/chatd/quickgen_internal_test.go index 1ba292249dd..52c22b431d4 100644 --- a/coderd/x/chatd/quickgen_internal_test.go +++ b/coderd/x/chatd/quickgen_internal_test.go @@ -764,7 +764,7 @@ func TestQuickgenFollowsConfiguredRetries(t *testing.T) { }, } logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true}) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}, + server := newInternalTestServer(t, db, ps, withInternalTestServerLimits(limits)) ctx := testutil.Context(t, testutil.WaitMedium) @@ -812,7 +812,7 @@ func TestQuickgenFollowsConfiguredRetries(t *testing.T) { }, nil })} logger := slogtest.Make(t, &slogtest.Options{IgnoreErrors: true}) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}, + server := newInternalTestServer(t, db, ps, withInternalTestServerTransportFactory(factory), withInternalTestServerLimits(limits), ) diff --git a/coderd/x/chatd/recording_internal_test.go b/coderd/x/chatd/recording_internal_test.go index ba30bd27c8d..79a501e3647 100644 --- a/coderd/x/chatd/recording_internal_test.go +++ b/coderd/x/chatd/recording_internal_test.go @@ -25,7 +25,6 @@ import ( "github.com/coder/coder/v2/coderd/database" "github.com/coder/coder/v2/coderd/database/dbgen" "github.com/coder/coder/v2/coderd/database/dbtestutil" - "github.com/coder/coder/v2/coderd/x/chatd/chatprovider" "github.com/coder/coder/v2/codersdk" "github.com/coder/coder/v2/codersdk/workspacesdk" "github.com/coder/coder/v2/codersdk/workspacesdk/agentconnmock" @@ -183,7 +182,7 @@ func TestWaitAgentComputerUseRecording(t *testing.T) { // Create the server WITHOUT agentConnFn so the background // processing of the parent chat doesn't use the mock. - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) parent, child := createComputerUseParentChild( t, server, user, org, model, workspace, agent, @@ -271,7 +270,7 @@ func TestWaitAgentComputerUseRecordingWithThumbnail(t *testing.T) { user, org, model := seedInternalChatDeps(t, db) workspace, _, agent := seedWorkspaceBinding(t, db, user.ID) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) parent, child := createComputerUseParentChild( t, server, user, org, model, workspace, agent, @@ -362,7 +361,7 @@ func TestWaitAgentNonComputerUseNoRecording(t *testing.T) { user, org, model := seedInternalChatDeps(t, db) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) // Create parent and regular (non-computer_use) child. parent, child := createParentChildChats(ctx, t, server, user, org, model) @@ -416,7 +415,7 @@ func TestWaitAgentRecordingStartFails(t *testing.T) { // Create the server WITHOUT agentConnFn so the background // processing of the parent chat doesn't use the mock. - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) // Create parent + computer_use child. parent, child := createComputerUseParentChild( @@ -470,7 +469,7 @@ func TestWaitAgentRecordingStopFails(t *testing.T) { // Create the server WITHOUT agentConnFn so the background // processing of the parent chat doesn't use the mock. - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) // Create parent + computer_use child. parent, child := createComputerUseParentChild( @@ -524,7 +523,7 @@ func TestWaitAgentTimeoutLeavesRecordingRunning(t *testing.T) { mockConn := agentconnmock.NewMockAgentConn(ctrl) // Use the mock clock server; don't set agentConnFn yet. - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}, withInternalTestServerClock(mClock)) + server := newInternalTestServer(t, db, ps, withInternalTestServerClock(mClock)) user, org, model := seedInternalChatDeps(t, db) workspace, _, agent := seedWorkspaceBinding(t, db, user.ID) @@ -628,7 +627,7 @@ func TestStopAndStoreRecording_EvictsOldestAtCap(t *testing.T) { mockConn := agentconnmock.NewMockAgentConn(ctrl) user, org, model := seedInternalChatDeps(t, db) workspace, _, _ := seedWorkspaceBinding(t, db, user.ID) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}, + server := newInternalTestServer(t, db, ps, withInternalTestServerLimits(tt.limits)) ctx := chatdTestContext(t) @@ -707,7 +706,7 @@ func TestStopAndStoreRecording_LimitsConcurrentUploads(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}, + server := newInternalTestServer(t, db, ps, withInternalTestServerLimits(tt.limits)) calls := tt.maxInFlight + 1 entered := make(chan struct{}, calls) @@ -758,7 +757,7 @@ func TestStopAndStoreRecording_CanceledWhileWaitingForUpload(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}, + server := newInternalTestServer(t, db, ps, withInternalTestServerLimits(Limits{MaxConcurrentRecordingUploads: 1})) entered := make(chan struct{}, 1) release := make(chan struct{}) @@ -805,7 +804,7 @@ func TestStopAndStoreRecording_WithThumbnail(t *testing.T) { user, org, model := seedInternalChatDeps(t, db) workspace, _, _ := seedWorkspaceBinding(t, db, user.ID) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) parent, _ := createParentChildChats(ctx, t, server, user, org, model) videoData := validRecordingMP4(1000, 0xDE) @@ -859,7 +858,7 @@ func TestStopAndStoreRecording_VideoOnly(t *testing.T) { user, org, model := seedInternalChatDeps(t, db) workspace, _, _ := seedWorkspaceBinding(t, db, user.ID) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) parent, _ := createParentChildChats(ctx, t, server, user, org, model) videoData := validRecordingMP4(1000, 0xCC) @@ -901,7 +900,7 @@ func TestStopAndStoreRecording_MismatchedVideoBytesSkipped(t *testing.T) { user, org, model := seedInternalChatDeps(t, db) workspace, _, _ := seedWorkspaceBinding(t, db, user.ID) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) parent, _ := createParentChildChats(ctx, t, server, user, org, model) mockConn.EXPECT(). @@ -938,7 +937,7 @@ func TestStopAndStoreRecording_DownloadFailure(t *testing.T) { user, org, model := seedInternalChatDeps(t, db) workspace, _, _ := seedWorkspaceBinding(t, db, user.ID) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) parent, _ := createParentChildChats(ctx, t, server, user, org, model) mockConn.EXPECT(). diff --git a/coderd/x/chatd/stage_metrics_internal_test.go b/coderd/x/chatd/stage_metrics_internal_test.go index e4515e2d568..1ef28568d94 100644 --- a/coderd/x/chatd/stage_metrics_internal_test.go +++ b/coderd/x/chatd/stage_metrics_internal_test.go @@ -14,7 +14,6 @@ import ( "github.com/coder/coder/v2/coderd/database/dbtestutil" "github.com/coder/coder/v2/coderd/x/chatd/chatloop" - "github.com/coder/coder/v2/coderd/x/chatd/chatprovider" "github.com/coder/coder/v2/codersdk" "github.com/coder/quartz" ) @@ -31,7 +30,7 @@ func TestServerStageMetricsFollowExperiment(t *testing.T) { if enabled { experiments = codersdk.Experiments{codersdk.ExperimentChatStageMetrics} } - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}, + server := newInternalTestServer(t, db, ps, withInternalTestServerExperiments(experiments), withInternalTestServerRegistry(registry), ) @@ -57,7 +56,7 @@ func TestServerStageTracerUsesServerConfig(t *testing.T) { require.NoError(t, provider.Shutdown(context.Background())) }) clock := quartz.NewMock(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}, + server := newInternalTestServer(t, db, ps, withInternalTestServerClock(clock), withInternalTestServerTracerProvider(provider), ) diff --git a/coderd/x/chatd/subagent_archived_root_internal_test.go b/coderd/x/chatd/subagent_archived_root_internal_test.go index 9f41e92d72f..6fcbc54bd98 100644 --- a/coderd/x/chatd/subagent_archived_root_internal_test.go +++ b/coderd/x/chatd/subagent_archived_root_internal_test.go @@ -8,7 +8,6 @@ import ( "github.com/coder/coder/v2/coderd/database" "github.com/coder/coder/v2/coderd/database/dbtestutil" - "github.com/coder/coder/v2/coderd/x/chatd/chatprovider" "github.com/coder/coder/v2/coderd/x/chatd/chatstate" ) @@ -22,7 +21,7 @@ func TestSubagentSpawnUnderArchivedRoot(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) diff --git a/coderd/x/chatd/subagent_context_internal_test.go b/coderd/x/chatd/subagent_context_internal_test.go index 948e34eff21..7fccd5d5721 100644 --- a/coderd/x/chatd/subagent_context_internal_test.go +++ b/coderd/x/chatd/subagent_context_internal_test.go @@ -14,7 +14,6 @@ import ( "github.com/coder/coder/v2/coderd/database/dbgen" "github.com/coder/coder/v2/coderd/database/dbtestutil" "github.com/coder/coder/v2/coderd/database/dbtime" - "github.com/coder/coder/v2/coderd/x/chatd/chatprovider" "github.com/coder/coder/v2/codersdk" ) @@ -94,7 +93,7 @@ func TestSpawnComputerUseAgentInheritsPinnedContext(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) parentChat, wantSource := createWorkspaceBoundParentChat(ctx, t, db, server) @@ -106,11 +105,6 @@ func TestSpawnComputerUseAgentInheritsPinnedContext(t *testing.T) { require.NotNil(t, parentChat.ContextAggregateHash) insertEnabledAnthropicProvider(t, db, parentChat.OwnerID) - // The direct DB insert above bypasses the pubsub event that production - // uses to invalidate the provider cache. Explicitly invalidate here so the - // background processing goroutine does not serve a stale provider list - // (OpenAI only) that was cached before the Anthropic provider was inserted. - server.configCache.InvalidateProviders() tools, err := server.subagentTools(ctx, func() database.Chat { return parentChat }, parentChat.LastModelConfigID) require.NoError(t, err) diff --git a/coderd/x/chatd/subagent_internal_test.go b/coderd/x/chatd/subagent_internal_test.go index b7ca0c04723..429007fadaa 100644 --- a/coderd/x/chatd/subagent_internal_test.go +++ b/coderd/x/chatd/subagent_internal_test.go @@ -113,14 +113,13 @@ func experimentsOrDefault(experiments codersdk.Experiments) codersdk.Experiments return experiments } -// newInternalTestServer creates a passive Server for internal tests with -// custom provider API keys. Pass withInternalTestServerWorker to start the -// background chat worker for tests that need real execution. +// newInternalTestServer creates a passive Server for internal tests. Pass +// withInternalTestServerWorker to start the background chat worker for tests +// that need real execution. func newInternalTestServer( t *testing.T, db database.Store, ps pubsub.Pubsub, - keys chatprovider.ProviderAPIKeys, opts ...internalTestServerOpt, ) *Server { t.Helper() @@ -140,7 +139,6 @@ func newInternalTestServer( // Use a very long interval so the background loop // does not interfere with test assertions. PendingChatAcquireInterval: testutil.WaitLong, - ProviderAPIKeys: keys, Experiments: experimentsOrDefault(cfg.experiments), AIBridgeTransportFactory: cfg.transportFactory, Limits: cfg.limits, @@ -436,7 +434,7 @@ func TestResolveUserProviderAPIKeys_AIProvider(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, _, _ := seedInternalChatDeps(t, db) provider := insertInternalAIProvider(t, db, database.AIProviderTypeOpenai, "provider-api-key", true) @@ -462,7 +460,7 @@ func TestResolveUserProviderAPIKeys_AIProvider(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) server.allowBYOK = false ctx := chatdTestContext(t) user, _, _ := seedInternalChatDeps(t, db) @@ -487,7 +485,7 @@ func TestResolveUserProviderAPIKeys_AIProvider(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, _, _ := seedInternalChatDeps(t, db) provider := insertInternalAIProvider(t, db, database.AIProviderTypeBedrock, "", true) @@ -497,21 +495,6 @@ func TestResolveUserProviderAPIKeys_AIProvider(t *testing.T) { require.True(t, keys.HasProvider("bedrock")) require.Empty(t, keys.APIKey("bedrock")) }) - - t.Run("RejectsAmbiguousProviderTypeWithoutSelectedProvider", func(t *testing.T) { - t.Parallel() - - db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) - ctx := chatdTestContext(t) - user, _, _ := seedInternalChatDeps(t, db) - insertInternalAIProvider(t, db, database.AIProviderTypeOpenai, "first-provider-api-key", true) - insertInternalAIProvider(t, db, database.AIProviderTypeOpenai, "second-provider-api-key", true) - - keys, err := server.resolveUserProviderAPIKeys(ctx, user.ID, uuid.Nil) - require.ErrorContains(t, err, "multiple enabled AI providers use provider type") - require.Equal(t, chatprovider.ProviderAPIKeys{}, keys) - }) } func TestResolveModelConfig_DisabledProviderFallsBackToLocalDefault(t *testing.T) { @@ -529,7 +512,7 @@ func TestResolveModelConfig_DisabledProviderFallsBackToLocalDefault(t *testing.T Valid: true, }, }) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) chat := dbgen.Chat(t, db, database.Chat{ OrganizationID: org.ID, OwnerID: user.ID, @@ -541,46 +524,6 @@ func TestResolveModelConfig_DisabledProviderFallsBackToLocalDefault(t *testing.T require.Equal(t, localDefault.ID, config.ID) } -func TestResolveUserProviderAPIKeys_PreservesAnthropicKeyFromDBProvider(t *testing.T) { - t.Parallel() - - t.Run("PreservesDBProviderKeyWithoutFallback", func(t *testing.T) { - t.Parallel() - - db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) - - ctx := chatdTestContext(t) - user, _, _ := seedInternalChatDeps(t, db) - insertEnabledAnthropicProvider(t, db, user.ID) - - keys, err := server.resolveUserProviderAPIKeys(ctx, user.ID, uuid.Nil) - require.NoError(t, err) - require.Equal(t, "test-anthropic-key", keys.Anthropic) - require.Equal(t, "test-anthropic-key", keys.APIKey("anthropic")) - require.Equal(t, "test-anthropic-key", keys.ByProvider["anthropic"]) - }) - - t.Run("PrunesFallbackKeyWithoutEnabledProvider", func(t *testing.T) { - t.Parallel() - - db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{ - Anthropic: "test-anthropic-key", - }) - - ctx := chatdTestContext(t) - user, _, _ := seedInternalChatDeps(t, db) - - keys, err := server.resolveUserProviderAPIKeys(ctx, user.ID, uuid.Nil) - require.NoError(t, err) - require.Empty(t, keys.Anthropic) - require.Empty(t, keys.APIKey("anthropic")) - _, ok := keys.ByProvider["anthropic"] - require.False(t, ok) - }) -} - func insertInternalChatModelConfig( t *testing.T, db database.Store, @@ -840,7 +783,7 @@ func TestCreateChildSubagentChatInheritsWorkspaceBinding(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -914,7 +857,7 @@ func TestCreateChildSubagentChatReturnsSystemPromptReadErrors(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) store := &systemPromptReadFailStore{Store: db} - server := newInternalTestServer(t, store, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, store, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) parent := createInternalParentChat(ctx, t, server, db, org.ID, user.ID, model.ID, "prompt-read-"+name) @@ -931,7 +874,7 @@ func TestCreateChildSubagentChatResolvesOrganizationSystemPrompt(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -1104,7 +1047,7 @@ func TestCreateChildSubagentChatCopiesPlanMode(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -1141,7 +1084,7 @@ func TestSpawnAgent_GeneralInheritsParentModelWhenOmitted(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -1167,7 +1110,7 @@ func TestSpawnAgent_GeneralUsesConfiguredModelOverride(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -1322,7 +1265,7 @@ func TestSpawnAgent_GeneralHonorsPersonalModelOverrides(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, parentModel := seedInternalChatDeps(t, db) @@ -1390,7 +1333,7 @@ func TestCreateChildSubagentChat_StoresReasoningEffortOverride(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -1415,7 +1358,7 @@ func TestCreateChildSubagentChat_OverrideWorksWhenParentHasNoModel(t *testing.T) t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -1451,7 +1394,7 @@ func TestSpawnAgent_ExplicitModelConfigID(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, parentModel := seedInternalChatDeps(t, db) @@ -1504,7 +1447,7 @@ func TestSpawnAgent_ExplicitModelSkipsConfiguredOverrides(t *testing.T) { db, ps := dbtestutil.NewDB(t) store := &personalOverrideErrorStore{Store: db} - server := newInternalTestServer(t, store, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, store, ps) ctx := chatdTestContext(t) user, org, parentModel := seedInternalChatDeps(t, db) @@ -1532,7 +1475,7 @@ func TestSpawnAgent_ExplicitModelBeatsConfiguredOverrides(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, parentModel := seedInternalChatDeps(t, db) @@ -1592,7 +1535,7 @@ func TestSpawnAgent_ExplicitReasoningEffort(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, parentModel := seedInternalChatDeps(t, db) @@ -1619,7 +1562,7 @@ func TestSpawnAgent_ExplicitReasoningEffort(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, parentModel := seedInternalChatDeps(t, db) @@ -1650,7 +1593,7 @@ func TestSpawnAgent_ExplicitReasoningEffort(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, parentModel := seedInternalChatDeps(t, db) @@ -1772,7 +1715,7 @@ func TestSpawnAgent_ModelArgsRejections(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -1824,7 +1767,7 @@ func TestSpawnAgent_ComputerUseRejectsModelArgs(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -1857,7 +1800,7 @@ func TestListSubagentModels(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, defaultModel := seedInternalChatDeps(t, db) @@ -1946,7 +1889,7 @@ func TestListSubagentModels_NotAvailableForChildChats(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -1973,7 +1916,7 @@ func TestSpawnAgent_ExploreUsesConfiguredModelOverride(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -2011,7 +1954,7 @@ func TestSpawnAgent_ExploreFallsBackToCurrentTurnModel(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, parentModel := seedInternalChatDeps(t, db) @@ -2171,7 +2114,7 @@ func TestSpawnAgent_ExploreHonorsPersonalModelOverrides(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, parentModel := seedInternalChatDeps(t, db) @@ -2253,7 +2196,7 @@ func TestCreateChat_ExploreRootStartsWithoutMCPSnapshot(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -2280,7 +2223,7 @@ func TestResolveExploreToolSnapshot(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) user, org, _ := seedInternalChatDeps(t, db) approvedMCP := insertInternalMCPServerConfig( @@ -2370,7 +2313,7 @@ func TestCreateChildSubagentChatWithOptions_ExplorePersistsMCPSnapshot(t *testin t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -2407,7 +2350,7 @@ func TestSpawnAgent_ExploreSnapshotsTurnStateParentState(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -2489,9 +2432,7 @@ func TestSpawnAgent_DescriptionListsAllAvailableTypes(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{ - Anthropic: "test-anthropic-key", - }) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -2513,7 +2454,7 @@ func TestSpawnAgent_DescriptionSteersGeneralForSubstantialResearch(t *testing.T) t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -2538,7 +2479,7 @@ func TestSpawnAgent_DescriptionIncludesComputerUseWithMissingProviderKey(t *test t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -2560,9 +2501,7 @@ func TestSpawnAgent_PlanModeDescriptionOmitsComputerUse(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{ - Anthropic: "test-anthropic-key", - }) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -2600,9 +2539,7 @@ func TestSpawnAgent_PlanModeRejectsComputerUse(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{ - Anthropic: "test-anthropic-key", - }) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -2649,7 +2586,7 @@ func TestSpawnAgent_InvalidTypeAndCredentialErrorAreDistinct(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedComputerUseDeps(t, db, database.AIProviderTypeAnthropic, "", "claude-opus-5") @@ -2720,7 +2657,7 @@ func TestResolveComputerUseModel(t *testing.T) { t.Run("DefaultModel", func(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -2734,7 +2671,7 @@ func TestResolveComputerUseModel(t *testing.T) { t.Run("Override", func(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) user, org, _ := seedInternalChatDeps(t, db) insertEnabledAnthropicProvider(t, db, user.ID) override := insertInternalChatModelConfigForProvider(t, db, org.ID, "anthropic", "claude-opus-5", true) @@ -2751,7 +2688,7 @@ func TestResolveComputerUseModel(t *testing.T) { t.Run("DisabledOverrideFallsBackToDefault", func(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) user, org, model := seedInternalChatDeps(t, db) insertEnabledAnthropicProvider(t, db, user.ID) disabled := insertInternalChatModelConfigForProvider(t, db, org.ID, "anthropic", "claude-opus-5", false) @@ -2768,7 +2705,7 @@ func TestResolveComputerUseModel(t *testing.T) { t.Run("UnsupportedDefaultProviderType", func(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) user, org, _ := seedComputerUseDeps(t, db, database.AIProviderTypeGoogle, "test-key", "gemini-test") ctx := chatdTestContext(t) @@ -2781,7 +2718,7 @@ func TestResolveComputerUseModel(t *testing.T) { t.Run("BedrockClaudeDefaultModel", func(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) // Bedrock supports ambient credentials, so the provider has no key. user, org, model := seedComputerUseDeps(t, db, database.AIProviderTypeBedrock, "", "us.anthropic.claude-opus-5-5") @@ -2807,7 +2744,7 @@ func TestResolveComputerUseModel(t *testing.T) { t.Run(tt.name, func(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) user, org, model := seedInternalChatDeps(t, db) insertInternalAIProvider(t, db, database.AIProviderTypeBedrock, "", true) override := insertInternalChatModelConfigForProvider(t, db, org.ID, "bedrock", tt.model, true) @@ -2829,7 +2766,7 @@ func TestResolveComputerUseModel(t *testing.T) { t.Run("UnsupportedOverrideProviderTypeFallsBackToDefault", func(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) user, org, model := seedInternalChatDeps(t, db) insertInternalAIProvider(t, db, database.AIProviderTypeOpenrouter, "test-key", true) // The override API rejects this model, but the model API can move a @@ -2848,7 +2785,7 @@ func TestResolveComputerUseModel(t *testing.T) { t.Run("MissingCredentials", func(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) user, org, _ := seedComputerUseDeps(t, db, database.AIProviderTypeAnthropic, "", "claude-opus-5") ctx := chatdTestContext(t) @@ -2861,7 +2798,7 @@ func TestResolveComputerUseModel(t *testing.T) { t.Run("NoDefaultModel", func(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) user := dbgen.User(t, db, database.User{}) org := dbgen.Organization(t, db, database.Organization{}) @@ -2874,7 +2811,7 @@ func TestResolveComputerUseModel(t *testing.T) { t.Run("UnavailableOverrideWithoutDefaultModel", func(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) user := dbgen.User(t, db, database.User{}) org := dbgen.Organization(t, db, database.Organization{}) insertEnabledAnthropicProvider(t, db, user.ID) @@ -2890,7 +2827,7 @@ func TestResolveComputerUseModel(t *testing.T) { t.Run("UnsupportedOverrideProviderTypeWithUnsupportedDefault", func(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) user, org, _ := seedComputerUseDeps(t, db, database.AIProviderTypeGoogle, "test-key", "gemini-test") insertInternalAIProvider(t, db, database.AIProviderTypeOpenrouter, "test-key", true) override := insertInternalChatModelConfigForProvider(t, db, org.ID, "openrouter", "openai/gpt-test", true) @@ -2906,7 +2843,7 @@ func TestResolveComputerUseModel(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) authzDB := dbauthz.New(db, rbac.NewStrictCachingAuthorizer(prometheus.NewRegistry()), slogtest.Make(t, nil), nil) - server := newInternalTestServer(t, authzDB, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, authzDB, ps) org := dbgen.Organization(t, db, database.Organization{}) member := dbgen.User(t, db, database.User{}) outsider := dbgen.User(t, db, database.User{}) @@ -2941,7 +2878,7 @@ func TestSpawnAgent_ComputerUseUnavailableReasonListsModel(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedComputerUseDeps(t, db, database.AIProviderTypeGoogle, "test-key", "gemini-test") parentChat := createInternalParentChat( @@ -2968,9 +2905,7 @@ func TestSpawnAgent_ComputerUseRejectsDesktopDisabled(t *testing.T) { slices.Clone(codersdk.ExperimentsKnown), func(e codersdk.Experiment) bool { return e == codersdk.ExperimentChatVirtualDesktop }, ) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{ - Anthropic: "test-anthropic-key", - }, withInternalTestServerExperiments(experiments)) + server := newInternalTestServer(t, db, ps, withInternalTestServerExperiments(experiments)) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -2990,9 +2925,7 @@ func TestSpawnAgent_BlankTypeReturnsValidOptions(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{ - Anthropic: "test-anthropic-key", - }) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -3031,9 +2964,7 @@ func TestSpawnAgent_NotAvailableForChildChats(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{ - Anthropic: "test-anthropic-key", - }) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -3062,7 +2993,7 @@ func TestSpawnAgent_NotAvailableForExploreChats(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -3099,7 +3030,7 @@ func TestSpawnAgent_NotAvailableForExploreChats(t *testing.T) { func TestSubagentToolRoundTrip(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) parent := createInternalParentChat(ctx, t, server, db, org.ID, user.ID, model.ID, "parent-round-trip") @@ -3126,7 +3057,7 @@ func TestSubagentLifecycleToolErrorsIncludePersistedSubagentType(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -3192,7 +3123,7 @@ func TestInterruptAgentReportsWhetherItInterrupted(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) user, org, model := seedInternalChatDeps(t, db) for _, tc := range []struct { @@ -3232,7 +3163,7 @@ func TestMessageAgentSteersBusyChild(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -3264,7 +3195,7 @@ func TestSpawnAgent_ComputerUseRunsOnSelectedModel(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -3319,7 +3250,7 @@ func TestSpawnAgent_ComputerUseInheritsMCPServerIDs(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -3370,7 +3301,7 @@ func TestCreateChildSubagentChat_InheritsMCPServerIDs(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -3435,7 +3366,7 @@ func TestCreateChildSubagentChat_NoMCPServersStaysEmpty(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -3473,7 +3404,7 @@ func TestIsSubagentDescendant(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -3763,7 +3694,7 @@ func TestWaitAgentDoesNotRelayComputerUseSubagentAttachments(t *testing.T) { ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) workspace, _, agent := seedWorkspaceBinding(t, db, user.ID) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) parent, child := createComputerUseParentChild( t, server, user, org, model, workspace, agent, @@ -3818,7 +3749,7 @@ func TestWaitAgentDoesNotRelayRegularSubagentAttachments(t *testing.T) { ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) workspace, _, _ := seedWorkspaceBinding(t, db, user.ID) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) parent, child := createParentChildChats(ctx, t, server, user, org, model) require.NoError(t, WaitUntilIdleForTest(ctx, server)) @@ -3870,7 +3801,7 @@ func TestAwaitSubagentCompletion(t *testing.T) { // so they don't collide. Mock-clock subtests need their own // DB and server so the wait loop's timers stay isolated. db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) user, org, model := seedInternalChatDeps(t, db) t.Run("NotDescendant", func(t *testing.T) { @@ -3965,7 +3896,7 @@ func TestAwaitSubagentCompletion(t *testing.T) { db, _ := dbtestutil.NewDB(t) mClock := quartz.NewMock(t) ps := subscribeFailingPubsub{Pubsub: pubsub.NewInMemory()} - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}, withInternalTestServerClock(mClock)) + server := newInternalTestServer(t, db, ps, withInternalTestServerClock(mClock)) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -4014,7 +3945,7 @@ func TestAwaitSubagentCompletion(t *testing.T) { db, ps := dbtestutil.NewDB(t) mClock := quartz.NewMock(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}, withInternalTestServerClock(mClock)) + server := newInternalTestServer(t, db, ps, withInternalTestServerClock(mClock)) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -4143,7 +4074,7 @@ func TestAwaitSubagentCompletion(t *testing.T) { db, ps := dbtestutil.NewDB(t) mClock := quartz.NewMock(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}, withInternalTestServerClock(mClock)) + server := newInternalTestServer(t, db, ps, withInternalTestServerClock(mClock)) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) @@ -4212,7 +4143,7 @@ func TestAwaitSubagentCompletion(t *testing.T) { return http.DefaultTransport.RoundTrip(cloned) })} server := newInternalTestServer( - t, db, ps, chatprovider.ProviderAPIKeys{}, + t, db, ps, withInternalTestServerWorker(), withInternalTestServerTransportFactory(factory), ) @@ -4249,7 +4180,7 @@ func TestUnbilledSubagentToolNamesMatchCatalog(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) parent, _ := createParentChildChats(ctx, t, server, user, org, model) @@ -4267,7 +4198,7 @@ func TestWaitAgentToolSchema(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) parent, _ := createParentChildChats(ctx, t, server, user, org, model) @@ -4367,7 +4298,7 @@ func TestAwaitSubagent(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) clock := quartz.NewMock(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}, withInternalTestServerClock(clock)) + server := newInternalTestServer(t, db, ps, withInternalTestServerClock(clock)) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) parent, child := createParentChildChats(ctx, t, server, user, org, model) @@ -4399,7 +4330,7 @@ func TestAwaitSubagent(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) clock := quartz.NewMock(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}, withInternalTestServerClock(clock)) + server := newInternalTestServer(t, db, ps, withInternalTestServerClock(clock)) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) parent, child := createParentChildChats(ctx, t, server, user, org, model) @@ -4453,7 +4384,7 @@ func TestAwaitSubagent(t *testing.T) { t.Run(tc.name, func(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) parent, child := createParentChildChats(ctx, t, server, user, org, model) @@ -4498,7 +4429,7 @@ func TestAwaitSubagent(t *testing.T) { func TestSendAndInterruptSubagent(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) parent, child := createParentChildChats(ctx, t, server, user, org, model) @@ -4517,7 +4448,7 @@ func TestSendAndInterruptSubagent(t *testing.T) { func TestListAgents(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, model := seedInternalChatDeps(t, db) parent, err := server.CreateChat(ctx, CreateOptions{OrganizationID: org.ID, OwnerID: user.ID, Title: "list-agents", ModelConfigID: model.ID, InitialUserContent: []codersdk.ChatMessagePart{codersdk.ChatMessageText("hello")}}) @@ -4692,7 +4623,7 @@ func TestEnabledChatModelConfigsForOrganization(t *testing.T) { func TestListSubagentModels_NonDefaultOrgExcludesDefaultOrgConfigs(t *testing.T) { t.Parallel() db, ps := dbtestutil.NewDB(t) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) ctx := chatdTestContext(t) user, org, localModel := seedInternalChatDeps(t, db) diff --git a/coderd/x/chatd/toolinput_internal_test.go b/coderd/x/chatd/toolinput_internal_test.go index 25340243904..7e4444135de 100644 --- a/coderd/x/chatd/toolinput_internal_test.go +++ b/coderd/x/chatd/toolinput_internal_test.go @@ -14,7 +14,6 @@ import ( "github.com/coder/coder/v2/coderd/database/dbtestutil" "github.com/coder/coder/v2/coderd/x/chatd/chathooks" "github.com/coder/coder/v2/coderd/x/chatd/chatprompt" - "github.com/coder/coder/v2/coderd/x/chatd/chatprovider" "github.com/coder/coder/v2/coderd/x/chatd/chatstate" "github.com/coder/coder/v2/codersdk/workspacesdk" ) @@ -346,7 +345,6 @@ func TestBuiltinToolSchemasDescribeTheirInputs(t *testing.T) { t, db, ps, - chatprovider.ProviderAPIKeys{}, withInternalTestServerTransportFactory(&aibridgeTestFactory{}), ) prepared, err := server.buildTurnEnvironment(ctx, generationPrepareInput{ diff --git a/coderd/x/chatd/turn_environment_internal_test.go b/coderd/x/chatd/turn_environment_internal_test.go index a7262a25a72..5c7fac7081e 100644 --- a/coderd/x/chatd/turn_environment_internal_test.go +++ b/coderd/x/chatd/turn_environment_internal_test.go @@ -159,7 +159,7 @@ func TestBuildTurnEnvironmentSplitsPendingUserRowsFromCompactionPrompt(t *testin }) require.NoError(t, err) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}, + server := newInternalTestServer(t, db, ps, withInternalTestServerTransportFactory(&aibridgeTestFactory{}), ) env, err := server.buildTurnEnvironment(ctx, generationPrepareInput{ @@ -283,7 +283,6 @@ func TestBuildTurnEnvironmentReplacesUnsupportedMedia(t *testing.T) { t, db, ps, - chatprovider.ProviderAPIKeys{}, withInternalTestServerTransportFactory(&aibridgeTestFactory{}), ) prepared, err := server.buildTurnEnvironment(ctx, generationPrepareInput{ @@ -508,7 +507,6 @@ func TestBuildTurnEnvironmentComputerUseRunsOnChatModel(t *testing.T) { t, db, ps, - chatprovider.ProviderAPIKeys{}, withInternalTestServerTransportFactory(&aibridgeTestFactory{}), ) prepared, err := server.buildTurnEnvironment(ctx, generationPrepareInput{ @@ -606,7 +604,7 @@ func TestBuildTurnEnvironmentMemory(t *testing.T) { require.NoError(t, err) serverOpts := []internalTestServerOpt{withInternalTestServerTransportFactory(&aibridgeTestFactory{})} - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}, serverOpts...) + server := newInternalTestServer(t, db, ps, serverOpts...) prepared, err := server.buildTurnEnvironment(ctx, generationPrepareInput{Chat: created.Chat, Messages: created.InitialMessages}) require.NoError(t, err) t.Cleanup(prepared.Close) @@ -695,7 +693,7 @@ func TestBuildTurnEnvironmentWorkspaceAgentLookup(t *testing.T) { require.NoError(t, err) store := &workspaceLookupErrorStore{Store: db, workspaceID: ws.ID, err: tt.lookupErr} - server := newInternalTestServer(t, store, ps, chatprovider.ProviderAPIKeys{}, withInternalTestServerTransportFactory(&aibridgeTestFactory{})) + server := newInternalTestServer(t, store, ps, withInternalTestServerTransportFactory(&aibridgeTestFactory{})) prepared, err := server.buildTurnEnvironment(ctx, generationPrepareInput{Chat: created.Chat, Messages: created.InitialMessages}) if tt.wantErr { require.ErrorIs(t, err, tt.lookupErr) @@ -759,7 +757,6 @@ func TestBuildTurnEnvironmentSubagentUsesOwnerSyntheticAPIKey(t *testing.T) { t, db, ps, - chatprovider.ProviderAPIKeys{}, withInternalTestServerTransportFactory(&aibridgeTestFactory{}), ) prepared, err := server.buildTurnEnvironment(ctx, generationPrepareInput{ @@ -853,7 +850,7 @@ func TestBuildTurnEnvironmentToolPolicy(t *testing.T) { require.NoError(t, err) require.NoError(t, db.UpsertChatAdvisorConfig(ctx, string(advisorConfig))) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}, + server := newInternalTestServer(t, db, ps, withInternalTestServerTransportFactory(&aibridgeTestFactory{}), withInternalTestServerExperiments(codersdk.Experiments{codersdk.ExperimentChatInlineMCPServers, codersdk.ExperimentChatACPSubagents}), ) @@ -1116,7 +1113,7 @@ func TestCreateExploreChatPreservesMCPSelection(t *testing.T) { OrganizationID: org.ID, CreatedBy: uuid.NullUUID{UUID: user.ID, Valid: true}, }) - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) chat, err := server.CreateChat(ctx, CreateOptions{ OrganizationID: org.ID, @@ -1202,7 +1199,7 @@ func TestDeriveFinalTurnRunResult(t *testing.T) { require.NoError(t, err) server := newInternalTestServer( - t, db, ps, chatprovider.ProviderAPIKeys{}, + t, db, ps, withInternalTestServerTransportFactory(&aibridgeTestFactory{}), ) return server, created.Chat, extra @@ -1372,7 +1369,7 @@ func TestDeriveFinalTurnRunResult(t *testing.T) { require.NoError(t, err) chat := created.Chat - server := newInternalTestServer(t, db, ps, chatprovider.ProviderAPIKeys{}) + server := newInternalTestServer(t, db, ps) commitAssistant(t, server, chat, "the answer is 42") chat.Status = database.ChatStatusWaiting