From 8293c66603d2c8b925f8ab225f2235592de4111d Mon Sep 17 00:00:00 2001 From: roberttwang Date: Sat, 21 Nov 2026 18:18:06 +0800 Subject: [PATCH 1/3] fix: isolate CodeBuddy model discovery per account --- internal/httpapi/assistant.go | 2 +- internal/httpapi/assistant_approval_review.go | 2 +- .../httpapi/assistant_approval_review_test.go | 4 +- internal/httpapi/assistant_engines.go | 2 +- internal/httpapi/assistant_generation.go | 4 +- internal/httpapi/assistant_models.go | 67 +++++++------ internal/httpapi/assistant_models_test.go | 98 ++++++++++++++++--- .../httpapi/assistant_notification_report.go | 2 +- internal/httpapi/assistant_process.go | 2 +- internal/httpapi/assistant_provider.go | 2 +- internal/httpapi/assistant_sponsor.go | 19 +--- internal/httpapi/assistant_sponsor_test.go | 13 ++- .../httpapi/assistant_task_engines_test.go | 5 + internal/httpapi/assistant_tasks.go | 4 +- internal/httpapi/assistant_title.go | 4 +- internal/httpapi/bot_interactions.go | 2 +- internal/httpapi/bot_interactions_test.go | 28 +++++- internal/httpapi/clarify_mcp.go | 4 +- internal/httpapi/clarify_mcp_test.go | 27 +++-- internal/httpapi/executor_models.go | 15 ++- internal/httpapi/platform_settings.go | 2 +- internal/httpapi/run_eval.go | 2 +- internal/httpapi/schedule.go | 2 +- internal/httpapi/stream.go | 2 +- 24 files changed, 208 insertions(+), 106 deletions(-) diff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.go index 05941a2f..1e8f5ccd 100644 --- a/internal/httpapi/assistant.go +++ b/internal/httpapi/assistant.go @@ -234,7 +234,7 @@ func (h *assistantHandlers) chat(c *gin.Context) { return } catalogEngine, _ := assistantModelEngine(req.Model) - catalog := assistantChatCatalog(c.Request.Context(), user.CodeBuddyInternetEnvironment, nil) + catalog := loadAssistantModels(user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey) if catalogEngine == assistantEngineCodeBuddy { catalog = h.turnCatalog(c.Request.Context(), user, req.Model) } diff --git a/internal/httpapi/assistant_approval_review.go b/internal/httpapi/assistant_approval_review.go index c98929aa..b1afcd5d 100644 --- a/internal/httpapi/assistant_approval_review.go +++ b/internal/httpapi/assistant_approval_review.go @@ -143,7 +143,7 @@ func (h *assistantHandlers) approvalReviewer(req assistantRequest, user domain.U if h.reviewCatalog != nil { catalog = h.reviewCatalog(user.CodeBuddyInternetEnvironment) } else { - catalog = h.chatCatalog(context.Background(), user) + catalog = h.chatCatalog(user) } models := assistantApprovalReviewModels(catalog) var modelMu sync.Mutex diff --git a/internal/httpapi/assistant_approval_review_test.go b/internal/httpapi/assistant_approval_review_test.go index 0b9f34b9..4dd4c896 100644 --- a/internal/httpapi/assistant_approval_review_test.go +++ b/internal/httpapi/assistant_approval_review_test.go @@ -46,7 +46,7 @@ func TestAssistantApprovalReviewUsesConfiguredDefaultWithoutPrices(t *testing.T) func TestAssistantChatCatalogPreselectsSponsoredModelOnlyWithSponsor(t *testing.T) { t.Setenv("AGENTFLOW_ASSISTANT_MODEL", "team-model") - catalog := assistantChatCatalog(context.Background(), "", nil) + catalog := loadAssistantModels("", "") if catalog.Default != "team-model" { t.Fatal("chat default without sponsor", catalog) } @@ -55,7 +55,7 @@ func TestAssistantChatCatalogPreselectsSponsoredModelOnlyWithSponsor(t *testing. t.Fatal("sponsored model listed without sponsor", catalog) } } - catalog = assistantChatCatalog(context.Background(), "", []string{assistantSponsoredModel, "shared-extra"}) + catalog = assistantChatCatalog("", "shared-key", []string{assistantSponsoredModel, "shared-extra"}) listed := 0 for _, model := range catalog.Models { if model.ID == assistantSponsoredModel || model.ID == "shared-extra" { diff --git a/internal/httpapi/assistant_engines.go b/internal/httpapi/assistant_engines.go index 16d15be8..fa209d76 100644 --- a/internal/httpapi/assistant_engines.go +++ b/internal/httpapi/assistant_engines.go @@ -157,7 +157,7 @@ func assistantEngineBuiltinModels(engine string) []assistantDiscoveredModel { catalogKey = "claude" } var out []assistantDiscoveredModel - for _, model := range executorModelCatalogs("")[catalogKey].Models { + for _, model := range executorModelCatalogs("", assistantFixedCatalog())[catalogKey].Models { out = append(out, assistantDiscoveredModel{ID: model.ID, Name: model.Name}) } return out diff --git a/internal/httpapi/assistant_generation.go b/internal/httpapi/assistant_generation.go index 014a07c8..403f094b 100644 --- a/internal/httpapi/assistant_generation.go +++ b/internal/httpapi/assistant_generation.go @@ -131,7 +131,7 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) { return } catalogEngine, _ := assistantModelEngine(req.Model) - catalog := assistantChatCatalog(c.Request.Context(), user.CodeBuddyInternetEnvironment, nil) + catalog := loadAssistantModels(user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey) if catalogEngine == assistantEngineCodeBuddy { catalog = h.turnCatalog(c.Request.Context(), user, req.Model) } @@ -577,7 +577,7 @@ func (h *assistantHandlers) steerGeneration(c *gin.Context) { } // A CodeBuddy model this instance has not listed yet refreshes the list // first, like a new turn, instead of silently becoming the default. - catalog := assistantChatCatalog(c.Request.Context(), user.CodeBuddyInternetEnvironment, nil) + catalog := loadAssistantModels(user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey) if engine, _ := assistantModelEngine(model); engine == assistantEngineCodeBuddy { catalog = h.turnCatalog(c.Request.Context(), user, model) } diff --git a/internal/httpapi/assistant_models.go b/internal/httpapi/assistant_models.go index 32f5b881..060ce9e1 100644 --- a/internal/httpapi/assistant_models.go +++ b/internal/httpapi/assistant_models.go @@ -63,9 +63,8 @@ var ( const cliModelTTL = time.Hour type cliModelEntry struct { - environment string - models []string - at time.Time + models []string + at time.Time } // cliModelCacheKey separates accounts within one environment: without a key @@ -134,7 +133,7 @@ func refreshCLIModels(ctx context.Context, environment, apiKey string) { models := discoverCLIModels(ctx, environment, apiKey) cliModelMu.Lock() if models != nil || !ok { - cliModelCache[cacheKey] = cliModelEntry{environment: environment, models: models, at: time.Now()} + cliModelCache[cacheKey] = cliModelEntry{models: models, at: time.Now()} } cliModelMu.Unlock() } @@ -160,24 +159,11 @@ func assistantKnownCatalog() assistantModelCatalog { return catalog } -func cachedCLIModels(environment string) []string { +func cachedCLIModels(environment, apiKey string) []string { + cacheKey := cliModelCacheKey(strings.TrimSpace(environment), apiKey) cliModelMu.Lock() defer cliModelMu.Unlock() - environment = strings.TrimSpace(environment) - var models []string - seen := map[string]bool{} - for _, entry := range cliModelCache { - if entry.environment != environment { - continue - } - for _, id := range entry.models { - if !seen[id] { - models = append(models, id) - seen[id] = true - } - } - } - return models + return cliModelCache[cacheKey].models } // models returns the chat model catalog for the caller's CodeBuddy @@ -199,7 +185,7 @@ func (h *assistantHandlers) models(c *gin.Context) { } } _, kimiBaseURL := assistantEngineCredential(user, runtime.AgentCLIKimi) - catalog, ok := executorModelCatalogs(kimiBaseURL)[id] + catalog, ok := executorModelCatalogs(kimiBaseURL, assistantFixedCatalog())[id] if !ok { c.JSON(400, gin.H{"error": "不支持的执行器"}) return @@ -235,12 +221,12 @@ func (h *assistantHandlers) models(c *gin.Context) { case usingSharedKey: // Chat runs on the shared key, so list what that key's environment offers. refreshCLIModels(c.Request.Context(), key.InternetEnvironment, key.APIKey) - catalog = restrictAssistantCatalog(assistantChatCatalog(c.Request.Context(), key.InternetEnvironment, key.Models), key.Models) + catalog = restrictAssistantCatalog(assistantChatCatalog(key.InternetEnvironment, key.APIKey, key.Models), key.Models) case signedIn: // A user's own key keeps their environment's models and default: the // shared key's default may not exist in that environment. refreshCLIModels(c.Request.Context(), user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey) - catalog = assistantChatCatalog(c.Request.Context(), user.CodeBuddyInternetEnvironment, nil) + catalog = loadAssistantModels(user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey) if saved := codeBuddyPersonalModels(user); len(saved) > 0 { catalog.Default = saved[0].ID if listed := selectableCodeBuddyModels(saved); len(listed) > 0 { @@ -248,7 +234,7 @@ func (h *assistantHandlers) models(c *gin.Context) { } } default: - catalog = assistantChatCatalog(c.Request.Context(), "", nil) + catalog = loadAssistantModels("", "") } if catalog.Default == assistantDefaultModel { models := user.CodeBuddyModels @@ -332,8 +318,8 @@ func codeBuddyPersonalModels(user domain.User) []assistantModel { // assistantChatCatalog is the catalog used by chat conversations: the same // models, with the shared key's models listed and its default preselected. // Pass shared only for turns that run on the shared key (see chatCatalog). -func assistantChatCatalog(ctx context.Context, env string, shared []string) assistantModelCatalog { - catalog := loadAssistantModels(ctx, env) +func assistantChatCatalog(environment, apiKey string, shared []string) assistantModelCatalog { + catalog := loadAssistantModels(environment, apiKey) if len(shared) == 0 { return catalog } @@ -355,15 +341,15 @@ func assistantChatCatalog(ctx context.Context, env string, shared []string) assi return catalog } -// loadAssistantModels never blocks on discovery; validation accepts models the -// caller's environment has advertised. -func loadAssistantModels(_ context.Context, environment string) assistantModelCatalog { +// loadAssistantModels combines configured models with the discovery cache for +// this credential and network environment. +func loadAssistantModels(environment, apiKey string) assistantModelCatalog { catalog := assistantFixedCatalog() seen := map[string]bool{} for _, model := range catalog.Models { seen[model.ID] = true } - for _, id := range cachedCLIModels(environment) { + for _, id := range cachedCLIModels(environment, apiKey) { if !seen[id] { catalog.Models = append(catalog.Models, assistantListedModel(id, id, "")) seen[id] = true @@ -372,6 +358,27 @@ func loadAssistantModels(_ context.Context, environment string) assistantModelCa return catalog } +// assistantModelsForRequest refreshes an execution account's catalog when a +// selected model is missing, including after a process restart. +func assistantModelsForRequest(ctx context.Context, user domain.User, model string) assistantModelCatalog { + environment, apiKey := user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey + catalog := loadAssistantModels(environment, apiKey) + if model = strings.TrimSpace(model); model != "" && !assistantCatalogLists(catalog, model) { + refreshCLIModels(ctx, environment, apiKey) + catalog = loadAssistantModels(environment, apiKey) + } + return catalog +} + +func assistantCatalogLists(catalog assistantModelCatalog, id string) bool { + for _, model := range catalog.Models { + if model.ID == id { + return true + } + } + return false +} + // assistantFixedCatalog mirrors `codebuddy --help` (CodeBuddy Code 2.180.0) // --model list, names/credits from the CLI's remote product catalog. Two ids // are kept although the CLI no longer advertises them: deepseek-v4-flash-ioa diff --git a/internal/httpapi/assistant_models_test.go b/internal/httpapi/assistant_models_test.go index 4e99c339..abda264c 100644 --- a/internal/httpapi/assistant_models_test.go +++ b/internal/httpapi/assistant_models_test.go @@ -5,8 +5,10 @@ import ( "context" "encoding/json" "net/http" - "reflect" + "slices" "testing" + + "agentflow/internal/domain" ) func TestAssistantModelPickerOmitsCodeBuddyCLIDefault(t *testing.T) { @@ -25,7 +27,7 @@ func TestAssistantModelPickerOmitsCodeBuddyCLIDefault(t *testing.T) { assistantCatalogLists(catalog, assistantDefaultModel) || assistantCatalogLists(catalog, "default-model") || !assistantCatalogLists(catalog, "model-b") { t.Fatalf("model picker shows the wrong choices: %+v", catalog) } - if got := assistantAllowedModel("", h.chatCatalog(context.Background(), user)); got != assistantDefaultModel { + if got := assistantAllowedModel("", h.chatCatalog(user)); got != assistantDefaultModel { t.Fatalf("an omitted request model should still use the CLI fallback, got %q", got) } t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "") @@ -38,15 +40,86 @@ func TestAssistantModelPickerOmitsCodeBuddyCLIDefault(t *testing.T) { } } +func TestCodeBuddyModelPickersUseOnlyTheCurrentAccount(t *testing.T) { + t.Setenv("AGENTFLOW_ASSISTANT_MODEL", "") + t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "") + t.Setenv(assistantSponsorLoginEnv, "") + h, first := workbenchFixture(t) + if err := h.repo.PutUser(domain.User{LoginName: "second-account", CodeBuddyAPIKey: "second-key"}); err != nil { + t.Fatal(err) + } + second, _ := h.repo.UserByLoginName("second-account") + stubCLIModelDiscovery(t) + discoverCLIModels = func(_ context.Context, environment, key string) []string { + switch key { + case first.CodeBuddyAPIKey: + return []string{"first-account-model"} + case second.CodeBuddyAPIKey: + return []string{"second-account-model"} + case "": + return []string{"public-model"} + default: + t.Fatalf("unexpected discovery account in environment %q", environment) + return nil + } + } + for _, user := range []domain.User{first, second, {}} { + refreshCLIModels(context.Background(), user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey) + } + + executors := &catalogHandlers{deps: h.deps} + for _, tc := range []struct { + name string + user domain.User + want string + }{ + {"first", first, "first-account-model"}, + {"second", second, "second-account-model"}, + {"guest", domain.User{}, "public-model"}, + } { + t.Run(tc.name, func(t *testing.T) { + c, rec := workbenchContext(tc.user, http.MethodGet, "/api/assistant/models", &bytes.Buffer{}) + var chat assistantModelCatalog + h.models(c) + if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &chat) != nil { + t.Fatalf("chat models: %d %s", rec.Code, rec.Body) + } + var chatIDs []string + for _, model := range chat.Models { + if model.Engine == "" || model.Engine == assistantEngineCodeBuddy { + chatIDs = append(chatIDs, model.ID) + } + } + if !slices.Equal(chatIDs, []string{tc.want}) { + t.Errorf("chat models = %v, want only %q", chatIDs, tc.want) + } + + c, rec = workbenchContext(tc.user, http.MethodGet, "/api/executor-models", &bytes.Buffer{}) + var catalog map[string]executorModelCatalog + executors.executorModels(c) + if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &catalog) != nil { + t.Fatalf("executor models: %d %s", rec.Code, rec.Body) + } + var executorIDs []string + for _, model := range catalog["codebuddy"].Models { + executorIDs = append(executorIDs, model.ID) + } + if !slices.Equal(executorIDs, []string{tc.want}) { + t.Errorf("executor models = %v, want only %q", executorIDs, tc.want) + } + }) + } +} + func TestCodeBuddyModelDiscoveryPerEnvironment(t *testing.T) { help := " --model Model for the current session. Currently supported: (gpt-5.5, glm-5.3, echo, custom-local:glm-5.2, kimi-k3)\n" - if got := parseCodeBuddyModels(help); !reflect.DeepEqual(got, []string{"gpt-5.5", "glm-5.3", "kimi-k3"}) { + if got := parseCodeBuddyModels(help); !slices.Equal(got, []string{"gpt-5.5", "glm-5.3", "kimi-k3"}) { t.Fatalf("parsed %v", got) } t.Setenv("AGENTFLOW_ASSISTANT_MODEL", "") t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "") calls := map[string]int{} - old := discoverCLIModels + stubCLIModelDiscovery(t) discoverCLIModels = func(_ context.Context, environment, apiKey string) []string { calls[environment+"|"+apiKey]++ if environment == "ioa" && apiKey != "" { @@ -57,12 +130,6 @@ func TestCodeBuddyModelDiscoveryPerEnvironment(t *testing.T) { } return []string{"gpt-5.5"} } - t.Cleanup(func() { - discoverCLIModels = old - cliModelMu.Lock() - cliModelCache = map[string]cliModelEntry{} - cliModelMu.Unlock() - }) for range 2 { refreshCLIModels(context.Background(), "ioa", "") } @@ -70,7 +137,7 @@ func TestCodeBuddyModelDiscoveryPerEnvironment(t *testing.T) { if calls["ioa|"] != 1 || calls["|"] != 1 { t.Fatalf("discovery must be cached per environment: %v", calls) } - ioa := loadAssistantModels(context.Background(), "ioa") + ioa := loadAssistantModels("ioa", "") if ioa.Default != "default" || assistantAllowedModel("claude-sonnet-5", ioa) != "claude-sonnet-5" || assistantAllowedModel("gpt-5.5", ioa) != "default" || assistantAllowedModel("claude-opus-5.5", ioa) != "default" { t.Fatalf("ioa catalog: %+v", ioa) } @@ -80,10 +147,13 @@ func TestCodeBuddyModelDiscoveryPerEnvironment(t *testing.T) { if calls["ioa|user-key"] != 1 { t.Fatalf("keyed discovery must be cached per account: %v", calls) } - if ioa = loadAssistantModels(context.Background(), "ioa"); assistantAllowedModel("claude-opus-5.5", ioa) != "claude-opus-5.5" { - t.Fatalf("account models must be listed: %+v", ioa) + if account := loadAssistantModels("ioa", "user-key"); !assistantCatalogLists(account, "claude-opus-5.5") { + t.Fatalf("account models must be listed: %+v", account) + } + if public := loadAssistantModels("ioa", ""); assistantCatalogLists(public, "claude-opus-5.5") { + t.Fatalf("account models appeared in the public catalog: %+v", public) } - if intl := loadAssistantModels(context.Background(), ""); assistantAllowedModel("gpt-5.5", intl) != "gpt-5.5" { + if intl := loadAssistantModels("", ""); assistantAllowedModel("gpt-5.5", intl) != "gpt-5.5" { t.Fatalf("international catalog: %+v", intl) } } diff --git a/internal/httpapi/assistant_notification_report.go b/internal/httpapi/assistant_notification_report.go index aaf39210..87c0907a 100644 --- a/internal/httpapi/assistant_notification_report.go +++ b/internal/httpapi/assistant_notification_report.go @@ -16,7 +16,7 @@ func (h *assistantHandlers) generateReport(ctx context.Context, run domain.Run, if !ok || strings.TrimSpace(user.CodeBuddyAPIKey) == "" { return domain.AINotificationContent{}, notification.ErrReportCredentials } - catalog := loadAssistantModels(ctx, user.CodeBuddyInternetEnvironment) + catalog := assistantModelsForRequest(ctx, user, model) if assistantAllowedModel(model, catalog) != model { return domain.AINotificationContent{}, notification.ErrReportModel } diff --git a/internal/httpapi/assistant_process.go b/internal/httpapi/assistant_process.go index ea922158..42418b94 100644 --- a/internal/httpapi/assistant_process.go +++ b/internal/httpapi/assistant_process.go @@ -503,7 +503,7 @@ func (h *assistantHandlers) testRunnerCLI(ctx context.Context, runnerID, provide defer os.RemoveAll(root) model := provider + ":default" if provider == assistantEngineCodeBuddy { - model = loadAssistantModels(ctx, user.CodeBuddyInternetEnvironment).Default + model = assistantFixedCatalog().Default } else if !runnerLogin { models, _ := assistantDiscoveredModelsFor(ctx, user, provider) if len(models) == 0 { diff --git a/internal/httpapi/assistant_provider.go b/internal/httpapi/assistant_provider.go index 801bde44..d58e8b98 100644 --- a/internal/httpapi/assistant_provider.go +++ b/internal/httpapi/assistant_provider.go @@ -45,7 +45,7 @@ func validateAssistantProvider(req *assistantRequest, user domain.User) error { return fmt.Errorf("请先在个人设置中配置 %s API Key", label) } if req.Executor == "codebuddy" { - req.Model = assistantAllowedModel(req.Model, loadAssistantModels(context.Background(), user.CodeBuddyInternetEnvironment)) + req.Model = assistantAllowedModel(req.Model, loadAssistantModels(user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey)) } else { req.Model = strings.TrimSpace(req.Model) if len(req.Model) > 256 || strings.ContainsAny(req.Model, "\r\n\x00") { diff --git a/internal/httpapi/assistant_sponsor.go b/internal/httpapi/assistant_sponsor.go index 7bf67711..a2366b74 100644 --- a/internal/httpapi/assistant_sponsor.go +++ b/internal/httpapi/assistant_sponsor.go @@ -69,12 +69,12 @@ func (h *assistantHandlers) usesSharedKey(user domain.User) bool { // turn on the shared key only sees the allowed models, defaulting to the // first; a user with their own key keeps their environment's catalog and // default, which the shared key's models must not replace. -func (h *assistantHandlers) chatCatalog(ctx context.Context, user domain.User) assistantModelCatalog { +func (h *assistantHandlers) chatCatalog(user domain.User) assistantModelCatalog { key, shared := h.assistantSharedKey() if !shared || !h.usesSharedKey(user) { - return withCodeBuddyPersonalModels(assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, nil), user) + return withCodeBuddyPersonalModels(loadAssistantModels(user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey), user) } - return restrictAssistantCatalog(assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, key.Models), key.Models) + return restrictAssistantCatalog(assistantChatCatalog(key.InternetEnvironment, key.APIKey, key.Models), key.Models) } // turnCatalog is chatCatalog for a turn on model. The CodeBuddy model list is @@ -82,28 +82,19 @@ func (h *assistantHandlers) chatCatalog(ctx context.Context, user domain.User) a // list, or before a restart, would otherwise be replaced by the default // without a word. A miss refreshes the list once before deciding. func (h *assistantHandlers) turnCatalog(ctx context.Context, user domain.User, model string) assistantModelCatalog { - catalog := h.chatCatalog(ctx, user) + catalog := h.chatCatalog(user) model = strings.TrimSpace(model) if model == "" || assistantCatalogLists(catalog, model) { return catalog } refreshCLIModels(ctx, user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey) - catalog = h.chatCatalog(ctx, user) + catalog = h.chatCatalog(user) if !assistantCatalogLists(catalog, model) { log.Printf("assistant model %q is not offered to user %d after catalog refresh", model, user.ID) } return catalog } -func assistantCatalogLists(catalog assistantModelCatalog, id string) bool { - for _, model := range catalog.Models { - if model.ID == id { - return true - } - } - return false -} - // restrictAssistantCatalog keeps the allowed models, in the allowed order. func restrictAssistantCatalog(catalog assistantModelCatalog, allowed []string) assistantModelCatalog { byID := map[string]assistantModel{} diff --git a/internal/httpapi/assistant_sponsor_test.go b/internal/httpapi/assistant_sponsor_test.go index a460801c..80239bef 100644 --- a/internal/httpapi/assistant_sponsor_test.go +++ b/internal/httpapi/assistant_sponsor_test.go @@ -200,7 +200,7 @@ func TestOwnKeyKeepsItsEnvironmentDefaultWhileAKeyIsShared(t *testing.T) { t.Fatalf("own-key catalog must list the user's environment only: %s", mrec.Body.String()) } - chat := h.chatCatalog(context.Background(), stored) + chat := h.chatCatalog(stored) if got := assistantAllowedModel("", chat); got != operatorDefault { t.Fatalf("a new own-key conversation resolves to %q, want %q", got, operatorDefault) } @@ -217,7 +217,7 @@ func TestOwnKeyKeepsItsEnvironmentDefaultWhileAKeyIsShared(t *testing.T) { } stored, _ = st.User(member.ID) borrowed, _, _ := h.assistantChatUser(stored) - if got := assistantAllowedModel("", h.chatCatalog(context.Background(), borrowed)); got != "glm-5.1" { + if got := assistantAllowedModel("", h.chatCatalog(borrowed)); got != "glm-5.1" { t.Fatalf("a shared-key conversation resolves to %q, want glm-5.1", got) } } @@ -302,7 +302,7 @@ func TestPlatformSharedKeyLimitsChatToAllowedModels(t *testing.T) { if rec.Code != 200 || used.CodeBuddyAPIKey != "platform-secret" || used.CodeBuddyInternetEnvironment != "ioa" { t.Fatalf("model %q: %d %s used=%+v", model, rec.Code, rec.Body.String(), used) } - if got := assistantAllowedModel(model, h.chatCatalog(context.Background(), used)); got != want { + if got := assistantAllowedModel(model, h.chatCatalog(used)); got != want { t.Fatalf("model %q resolves to %q, want %q", model, got, want) } } @@ -384,7 +384,7 @@ func TestTurnCatalogRefreshesBeforeFallingBackToTheDefault(t *testing.T) { } stored, _ := st.User(member.ID) h := &assistantHandlers{deps: &deps{repo: st}} - if got := assistantAllowedModel("claude-opus-5.5", h.chatCatalog(context.Background(), stored)); got == "claude-opus-5.5" { + if got := assistantAllowedModel("claude-opus-5.5", h.chatCatalog(stored)); got == "claude-opus-5.5" { t.Fatalf("precondition: a cold cache must not list the model yet") } if got := assistantAllowedModel("claude-opus-5.5", h.turnCatalog(context.Background(), stored, "claude-opus-5.5")); got != "claude-opus-5.5" { @@ -405,11 +405,10 @@ func TestTurnCatalogRefreshesBeforeFallingBackToTheDefault(t *testing.T) { func TestChatCatalogsListTheDefaultFirst(t *testing.T) { t.Setenv("AGENTFLOW_ASSISTANT_MODEL", "glm-5.3-flash-ioa") t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "claude-opus-5.5,glm-5.3-flash-ioa") - ctx := context.Background() shared := []string{"deepseek-v4.1-flash", "glm-5.3-flash-ioa"} for name, catalog := range map[string]assistantModelCatalog{ - "own key": assistantChatCatalog(ctx, "", nil), - "shared key": restrictAssistantCatalog(assistantChatCatalog(ctx, "", shared), shared), + "own key": loadAssistantModels("", "user-key"), + "shared key": restrictAssistantCatalog(assistantChatCatalog("", "shared-key", shared), shared), } { if len(catalog.Models) == 0 || catalog.Models[0].ID != catalog.Default { t.Fatalf("%s: default %q is not listed first in %+v", name, catalog.Default, catalog.Models) diff --git a/internal/httpapi/assistant_task_engines_test.go b/internal/httpapi/assistant_task_engines_test.go index 353be25b..c4e8f6d5 100644 --- a/internal/httpapi/assistant_task_engines_test.go +++ b/internal/httpapi/assistant_task_engines_test.go @@ -34,6 +34,8 @@ func TestAssistantScheduledModelKeepsCLIModels(t *testing.T) { // The CodeBuddy model list is empty after a restart: a scheduled run refreshes // it with the owner's key and never swaps an unavailable model for the default. func TestScheduledRunModelRefreshesAndNeverFallsBack(t *testing.T) { + t.Setenv("AGENTFLOW_ASSISTANT_MODEL", "") + t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "") old := discoverCLIModels discoverCLIModels = func(_ context.Context, environment, apiKey string) []string { if environment == "internal" && apiKey == "owner-key" { @@ -57,6 +59,9 @@ func TestScheduledRunModelRefreshesAndNeverFallsBack(t *testing.T) { if got, err := scheduledRunModel(context.Background(), "", owner); err != nil || got != assistantFixedCatalog().Default { t.Fatalf("empty model = %q, %v", got, err) } + if got, err := scheduledRunModel(context.Background(), assistantDefaultModel, owner); err != nil || got != assistantDefaultModel { + t.Fatalf("legacy CLI default = %q, %v", got, err) + } if got, err := scheduledRunModel(context.Background(), "gone-model", owner); err == nil || !strings.Contains(err.Error(), "gone-model") { t.Fatalf("unavailable model = %q, %v", got, err) } diff --git a/internal/httpapi/assistant_tasks.go b/internal/httpapi/assistant_tasks.go index da88e359..53c4ac99 100644 --- a/internal/httpapi/assistant_tasks.go +++ b/internal/httpapi/assistant_tasks.go @@ -494,14 +494,14 @@ func firstNonEmpty(values ...string) string { func scheduledRunModel(ctx context.Context, requested string, user domain.User) (string, error) { requested = strings.TrimSpace(requested) env := user.CodeBuddyInternetEnvironment - catalog := withCodeBuddyPersonalModels(loadAssistantModels(ctx, env), user) + catalog := withCodeBuddyPersonalModels(loadAssistantModels(env, user.CodeBuddyAPIKey), user) model := assistantAllowedUserModel(requested, catalog, user) if requested == "" || model == requested { return model, nil } if engine, _ := assistantModelEngine(requested); engine == assistantEngineCodeBuddy { refreshCLIModels(ctx, env, user.CodeBuddyAPIKey) - if model = assistantAllowedUserModel(requested, loadAssistantModels(ctx, env), user); model == requested { + if model = assistantAllowedUserModel(requested, loadAssistantModels(env, user.CodeBuddyAPIKey), user); model == requested { return model, nil } } diff --git a/internal/httpapi/assistant_title.go b/internal/httpapi/assistant_title.go index 3c114da9..494ea353 100644 --- a/internal/httpapi/assistant_title.go +++ b/internal/httpapi/assistant_title.go @@ -125,9 +125,9 @@ func assistantTitleModel(ctx context.Context, user domain.User, model string, sh } return model, "" } - catalog := assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, nil) + catalog := assistantChatCatalog(user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey, shared) if len(shared) > 0 { - catalog = restrictAssistantCatalog(assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, shared), shared) + catalog = restrictAssistantCatalog(catalog, shared) } if chosen := assistantApprovalReviewModel(catalog); chosen != "" { return chosen, "" diff --git a/internal/httpapi/bot_interactions.go b/internal/httpapi/bot_interactions.go index c48d0b06..61946389 100644 --- a/internal/httpapi/bot_interactions.go +++ b/internal/httpapi/bot_interactions.go @@ -78,7 +78,7 @@ func (h *assistantHandlers) generateBotReply(ctx context.Context, bot domain.Not if model == "" { model = domain.DefaultNotificationReportModel } - if assistantAllowedModel(model, loadAssistantModels(ctx, user.CodeBuddyInternetEnvironment)) != model { + if assistantAllowedModel(model, assistantModelsForRequest(ctx, user, model)) != model { return "所选模型不可用,请在 Bot 管理中重新选择。", nil } if err = ensureAssistantSessionDirs(user.ID); err != nil { diff --git a/internal/httpapi/bot_interactions_test.go b/internal/httpapi/bot_interactions_test.go index 21136cb3..6ea1513a 100644 --- a/internal/httpapi/bot_interactions_test.go +++ b/internal/httpapi/bot_interactions_test.go @@ -38,6 +38,17 @@ func botFixture(t *testing.T) (*repo.Store, *assistantHandlers, domain.Notificat return s, h, bot } func TestBotUsesBoundSenderIdentityAutoModeAndSharedChatContext(t *testing.T) { + t.Setenv("AGENTFLOW_ASSISTANT_MODEL", "") + t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "") + stubCLIModelDiscovery(t) + discoveries := 0 + discoverCLIModels = func(_ context.Context, environment, key string) []string { + discoveries++ + if key != "other-key" || environment != "ioa" { + t.Fatal("model discovery did not use the sender's credentials") + } + return []string{"sender-model"} + } s, h, bot := botFixture(t) h.generate = func(ctx context.Context, prompt string, user domain.User) (string, error) { if user.ID != 43 || user.CodeBuddyAPIKey != "other-key" || user.CodeBuddyInternetEnvironment != "ioa" { @@ -60,14 +71,23 @@ func TestBotUsesBoundSenderIdentityAutoModeAndSharedChatContext(t *testing.T) { session.commitFinal(AgentTerminalResult{Kind: AgentTerminalAssistant, Assistant: &assistantReply{Message: "查询完成 other-key"}}) return "", context.Canceled } - reply, err := h.generateBotReply(context.Background(), bot, domain.BotConversation{SessionID: "session", ChatID: "new-group", ChatType: "group"}, []domain.BotInteraction{{SenderID: "first-member", Content: "历史提问", Reply: "历史回复"}}, domain.BotInteraction{SenderID: "new-wecom-user", Content: "现在有什么进展"}) - if err != nil || reply != "查询完成 [redacted]" { - t.Fatal(reply, err) + for _, model := range []string{"", assistantDefaultModel, "sender-model"} { + bot.Model = model + reply, err := h.generateBotReply(context.Background(), bot, domain.BotConversation{SessionID: "session", ChatID: "new-group", ChatType: "group"}, []domain.BotInteraction{{SenderID: "first-member", Content: "历史提问", Reply: "历史回复"}}, domain.BotInteraction{SenderID: "new-wecom-user", Content: "现在有什么进展"}) + if err != nil || reply != "查询完成 [redacted]" { + t.Fatalf("model %q: reply = %q, error = %v", model, reply, err) + } + if model != "sender-model" && discoveries != 0 { + t.Fatal("the CLI default should work with a cold cache") + } + } + if discoveries != 1 { + t.Fatalf("expected discovery for the concrete model, got %d", discoveries) } // No fallback to the Bot owner when the sender has a different identity. bot.InteractionEnabled = false s.SaveNotificationBot(bot, "") - if _, err = h.botExecutionUser(bot, "new-wecom-user"); err == nil { + if _, err := h.botExecutionUser(bot, "new-wecom-user"); err == nil { t.Fatal("disabled Bot executed") } } diff --git a/internal/httpapi/clarify_mcp.go b/internal/httpapi/clarify_mcp.go index 59110f6b..15c5fdba 100644 --- a/internal/httpapi/clarify_mcp.go +++ b/internal/httpapi/clarify_mcp.go @@ -23,8 +23,8 @@ var ( gongfengIssueURLRe = regexp.MustCompile(`(?i)https?://git\.example\.com/[^\s<>"')】\]]+/issues/\d+`) ) -func clarifyAllowedModel(id string) string { - return assistantAllowedModel(id, assistantKnownCatalog()) +func clarifyAllowedModel(ctx context.Context, user domain.User, id string) string { + return assistantAllowedModel(id, assistantModelsForRequest(ctx, user, id)) } // errClarifyNeedsCodeBuddy is returned when a clarification asks for a model of diff --git a/internal/httpapi/clarify_mcp_test.go b/internal/httpapi/clarify_mcp_test.go index b307692d..421bf66b 100644 --- a/internal/httpapi/clarify_mcp_test.go +++ b/internal/httpapi/clarify_mcp_test.go @@ -1,6 +1,7 @@ package httpapi import ( + "context" "encoding/json" "fmt" "io" @@ -14,15 +15,25 @@ import ( ) func TestClarifyAllowedModelFallsBackToCatalog(t *testing.T) { + t.Setenv("AGENTFLOW_ASSISTANT_MODEL", "") t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "public-model") - if got := clarifyAllowedModel(""); got != clarifyDefaultModel { - t.Fatalf("empty model = %q", got) - } - if got := clarifyAllowedModel("not-a-model"); got != clarifyDefaultModel { - t.Fatalf("unknown model = %q", got) - } - if got := clarifyAllowedModel("public-model"); got != "public-model" { - t.Fatalf("listed model = %q", got) + stubCLIModelDiscovery(t) + discoverCLIModels = func(_ context.Context, _, key string) []string { + return []string{key + "-model"} + } + ctx := context.Background() + refreshCLIModels(ctx, "ioa", "another-key") + user := domain.User{CodeBuddyInternetEnvironment: "ioa", CodeBuddyAPIKey: "responsible-key"} + for requested, want := range map[string]string{ + "": clarifyDefaultModel, + "another-key-model": clarifyDefaultModel, + "not-a-model": clarifyDefaultModel, + "public-model": "public-model", + "responsible-key-model": "responsible-key-model", + } { + if got := clarifyAllowedModel(ctx, user, requested); got != want { + t.Errorf("requested %q: model = %q, want %q", requested, got, want) + } } } diff --git a/internal/httpapi/executor_models.go b/internal/httpapi/executor_models.go index c96344a3..b1603d61 100644 --- a/internal/httpapi/executor_models.go +++ b/internal/httpapi/executor_models.go @@ -126,17 +126,16 @@ func effortOptions(levels []string) []executorEffortOption { return options } -// executorModelCatalogs returns the fixed per-CLI catalog. The CodeBuddy list -// reuses the assistant catalog so the wizard, AI 助手 and 澄清 stay in sync. -func executorModelCatalogs(kimiBaseURL string) map[string]executorModelCatalog { +// executorModelCatalogs returns built-in options plus the caller's CodeBuddy +// catalog. +func executorModelCatalogs(kimiBaseURL string, codebuddy assistantModelCatalog) map[string]executorModelCatalog { codebuddyModels := make([]executorModelInfo, 0) - known := assistantKnownCatalog() - for _, model := range selectableCodeBuddyModels(known.Models) { + for _, model := range selectableCodeBuddyModels(codebuddy.Models) { codebuddyModels = append(codebuddyModels, executorModelInfo{ID: model.ID, Name: model.Name, Credits: model.Credits}) } catalogs := map[string]executorModelCatalog{ "codebuddy": { - Default: known.Default, + Default: codebuddy.Default, Models: codebuddyModels, Efforts: effortOptions(domain.ExecutorEffortLevels["codebuddy"]), }, @@ -214,7 +213,7 @@ func cursorCatalogModels() []executorModelInfo { func (h *catalogHandlers) executorModels(c *gin.Context) { c.Header("Cache-Control", "private, no-store") if c.Query("builtin") == "1" { - c.JSON(http.StatusOK, executorModelCatalogs("")) + c.JSON(http.StatusOK, executorModelCatalogs("", loadAssistantModels("", ""))) return } var user domain.User @@ -225,7 +224,7 @@ func (h *catalogHandlers) executorModels(c *gin.Context) { } } _, kimiBaseURL := assistantEngineCredential(user, runtime.AgentCLIKimi) - catalogs := executorModelCatalogs(kimiBaseURL) + catalogs := executorModelCatalogs(kimiBaseURL, loadAssistantModels(user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey)) if antigravityUsesCustomEndpoint(user) { catalog := catalogs[runtime.AgentCLIAntigravity] catalog.Models = []executorModelInfo{} diff --git a/internal/httpapi/platform_settings.go b/internal/httpapi/platform_settings.go index cf7e2fc7..333670c0 100644 --- a/internal/httpapi/platform_settings.go +++ b/internal/httpapi/platform_settings.go @@ -208,7 +208,7 @@ func (h *usersHandlers) platformCodeBuddyKey(c *gin.Context) { apiKey = key.APIKey } refreshCLIModels(c.Request.Context(), environment, apiKey) - catalog := loadAssistantModels(c.Request.Context(), environment).Models + catalog := loadAssistantModels(environment, apiKey).Models c.JSON(http.StatusOK, platformCodeBuddyKeyResponse{PlatformCodeBuddyKeyStatus: status, Catalog: catalog}) case http.MethodPut: h.savePlatformCodeBuddyKey(c) diff --git a/internal/httpapi/run_eval.go b/internal/httpapi/run_eval.go index 56d6aa3d..da7b11ed 100644 --- a/internal/httpapi/run_eval.go +++ b/internal/httpapi/run_eval.go @@ -122,7 +122,7 @@ func (h *runsHandlers) startRunEval(c *gin.Context) { c.JSON(http.StatusBadRequest, map[string]string{"error": "运行评测目前只支持 CodeBuddy 模型,请改选 CodeBuddy 模型"}) return } - catalog := loadAssistantModels(c.Request.Context(), user.CodeBuddyInternetEnvironment) + catalog := assistantModelsForRequest(c.Request.Context(), user, req.Model) model := assistantAllowedModel(req.Model, catalog) project, _ := h.repo.Project(run.ExecutionContext.ProjectID) rec := domain.RunEvalRecord{ diff --git a/internal/httpapi/schedule.go b/internal/httpapi/schedule.go index e6129670..89c676e2 100644 --- a/internal/httpapi/schedule.go +++ b/internal/httpapi/schedule.go @@ -121,7 +121,7 @@ func (h *scheduleHandlers) scheduleJobs(c *gin.Context) { } requestedModel := job.AssistantModel if job.SkipDispatch { - job.AssistantModel = assistantScheduledModel(job.AssistantModel, loadAssistantModels(c.Request.Context(), "")) + job.AssistantModel = assistantScheduledModel(job.AssistantModel, assistantFixedCatalog()) } if job.ProjectID == "" { job.ProjectID = "platform" diff --git a/internal/httpapi/stream.go b/internal/httpapi/stream.go index fabb8838..51299d0a 100644 --- a/internal/httpapi/stream.go +++ b/internal/httpapi/stream.go @@ -649,7 +649,7 @@ func (h *streamHandlers) executeClarify(ctx context.Context, issue domain.Issue, } userMsg := prompt.String() clarifyID := fmt.Sprintf("clarify-%d", time.Now().UnixNano()) - modelID := clarifyAllowedModel(request.Model) + modelID := clarifyAllowedModel(modelCtx, responsible, request.Model) credentials := runtime.RunCredentials{ CodeBuddy: runtime.CodeBuddyCredential{APIKey: strings.TrimSpace(responsible.CodeBuddyAPIKey), InternetEnvironment: strings.TrimSpace(responsible.CodeBuddyInternetEnvironment)}, GitHTTPCredentials: h.repo.GitHTTPCredentialSecrets(ctx, responsible.ID), From f9f9f491bc536d0c4a82dcb6b4ee20b4c5be45b3 Mon Sep 17 00:00:00 2001 From: roberttwang Date: Sat, 21 Nov 2026 21:25:25 +0800 Subject: [PATCH 2/3] fix(chat): require a concrete model before sending --- chatbot/src/engines.js | 3 +- chatbot/src/useChat.js | 42 +++++++++--------- chatbot/tests/hooks.test.jsx | 82 ++++++++++++++++++++++++++++++++++++ 3 files changed, 103 insertions(+), 24 deletions(-) diff --git a/chatbot/src/engines.js b/chatbot/src/engines.js index 63ba8745..a54a2c00 100644 --- a/chatbot/src/engines.js +++ b/chatbot/src/engines.js @@ -35,7 +35,8 @@ export function engineOfModel(id, models = []) { } export const concreteModel = (model, engine = modelEngine(model)) => - !!model?.id && model.id !== "default" && model.id !== `${engine}:default`; + !!model?.id && model.id !== "default" && model.id !== `${engine}:default` && + (engine !== "codebuddy" || (model.id !== "default-model" && model.id !== "codebuddy:default-model")); export const engineModels = (models, engine) => (models || []).filter((m) => modelEngine(m) === engine && concreteModel(m, engine)); diff --git a/chatbot/src/useChat.js b/chatbot/src/useChat.js index cc6cfc51..2690c4a6 100644 --- a/chatbot/src/useChat.js +++ b/chatbot/src/useChat.js @@ -56,11 +56,10 @@ function effortPreference(executor, model) { } // Prefer the remembered model when supplied, then the first available model. -// CodeBuddy also supports a server-configured fallback when the list is empty. -function preferredModel(list, executor, codeBuddyDefault, remembered) { +function preferredModel(list, executor, remembered) { const available = list.filter((model) => !model.disabled && !model.unavailable); const listed = findExecutorModel(available, executor, remembered); - return (listed && remembered) || available[0]?.id || (executor === "codebuddy" ? codeBuddyDefault : ""); + return (listed && remembered) || available[0]?.id || ""; } // Mirrors errAssistantSponsoredModel in internal/httpapi/assistant_sponsor.go; @@ -111,7 +110,6 @@ export function useChat() { [revealId, setRevealId] = useState(activeId), [projectId, setProjectId] = useState(initialProject), [selection, setSelection] = useState(() => ({ executor: storedExecutor(), model: null, effort: null })), - [codeBuddyDefault, setCodeBuddyDefault] = useState({ id: "default", name: "默认" }), [sponsoredModels, setSponsoredModels] = useState([]), [providerCatalogs, setProviderCatalogs] = useState({}), [generation, setGeneration] = useState(null), @@ -251,7 +249,6 @@ export function useChat() { } const applyModelCatalog = useCallback((catalog) => { setModels(catalog.models || []); - setCodeBuddyDefault({ id: catalog.default || "default", name: "默认", efforts: catalog.defaultEfforts }); setSponsoredModels(sponsoredModelList(catalog)); }, []); useEffect(() => { @@ -653,15 +650,14 @@ export function useChat() { : listed; const sponsored = codeBuddy && missingKey && !user.isGuest && !!sponsoredModel; const listedModel = findExecutorModel(executorModels, executor, model); - const hasSelectedModel = model !== null && !listedModel?.disabled && !listedModel?.unavailable && + const hasSelectedModel = concreteModel({ id: model }, executor) && !listedModel?.disabled && !listedModel?.unavailable && (conversation || !executorModels.length || listedModel); const selectedModel = hasSelectedModel ? model : preferredModel( - executorModels, executor, codeBuddyDefault.id, + executorModels, executor, draft ? readComposerPreference(`model.${executor}`) : null, ); const availableModel = sponsored && !sponsoredModels.includes(selectedModel) ? sponsoredModel : selectedModel; - const catalogEntry = findExecutorModel(executorModels, executor, availableModel) ?? - (codeBuddy && availableModel === codeBuddyDefault.id ? codeBuddyDefault : undefined); + const catalogEntry = findExecutorModel(executorModels, executor, availableModel); const activeModel = catalogEntry?.id ?? availableModel; const requestedModelId = unprefixedModel(executor, availableModel); const unavailableAgyVariant = agyAccountKey && providerCatalog && !catalogEntry && @@ -1024,11 +1020,6 @@ export function useChat() { setError("会话仍在加载,请稍候再发送。"); return false; } - const modelError = composerModelError(composerModel); - if (modelError) { - setError(modelError); - return false; - } const currentProjectId = sessionRef.current?.projectId || ""; const approval = fromQueue ? queuedApproval({ approvalMode, approvalUserId, approvalProjectId }, user?.id, currentProjectId) @@ -1038,6 +1029,11 @@ export function useChat() { generation?.status === "running" || steeringRef.current?.sessionId === currentId.current ) { + const modelError = composerModelError(composerModel); + if (modelError) { + setError(modelError); + return false; + } // Internal follow-ups (confirmed drafts) never queue or interrupt. if (messagesOverride || fromQueue || !currentId.current) { setError("当前回复仍在生成,请稍后再试。"); @@ -1080,20 +1076,20 @@ export function useChat() { try { // Recheck credentials before creating the session in case the user // configured a key elsewhere after this tab loaded. - if ( - codeBuddy && - !sponsoredModel && - users.find((u) => u.id === user?.id)?.codeBuddyApiKeyConfigured === undefined && - user && - !user.isGuest - ) { + const account = users.find((u) => u.id === user?.id) ?? user; + if (codeBuddy && user && !user.isGuest && !sponsoredModel && !account?.codeBuddyApiKeyConfigured) { const rows = await api("/api/users").catch(() => null); if (rows) setUsers(rows); - const fresh = rows?.find((u) => u.id === user.id); - if (fresh && !fresh.codeBuddyApiKeyConfigured) { + const fresh = rows?.find((u) => u.id === user.id) ?? account; + if (!fresh?.codeBuddyApiKeyConfigured) { if (viewingTarget()) setError("请先在个人配置中配置自己的 CodeBuddy API Key"); return false; } + requestModelCatalogRefresh((revision) => revision + 1); + if (!composerModel.activeModel) { + if (viewingTarget()) setError("CodeBuddy 凭证已更新,正在刷新模型列表,请稍后重试。"); + return false; + } } const chosen = await modelForRequest({ executor, model, effort }, s, composerModel); if (!s) { diff --git a/chatbot/tests/hooks.test.jsx b/chatbot/tests/hooks.test.jsx index d16bb7d9..184dd65c 100644 --- a/chatbot/tests/hooks.test.jsx +++ b/chatbot/tests/hooks.test.jsx @@ -713,6 +713,88 @@ describe("conversation hooks", () => { } }); + test.each([ + [false, "请先在个人配置中配置自己的 CodeBuddy API Key"], + [true, "当前 CLI 暂无可用模型,请在个人配置中获取或添加模型。"], + ])("blocks sends without a usable CodeBuddy model (key configured: %s)", async (configured, message) => { + localStorage.removeItem("loopforge.assistant.executor"); + const original = apiMock.getMockImplementation(); + const user = { id: 1, loginName: "tester", codeBuddyApiKeyConfigured: configured }; + apiMock.mockImplementation((path, options) => { + if (path === "/api/auth/current") return Promise.resolve({ user }); + if (path === "/api/users") return Promise.resolve([user]); + if (path === "/api/assistant/models") return Promise.resolve({ + default: "default", models: [{ id: "default" }, { id: "default-model" }], + }); + return original(path, options); + }); + try { + const { result } = renderHook(useChat); + await waitFor(() => expect(result.current.ready && result.current.machinesReady).toBe(true)); + expect(result.current.models).toEqual([]); + expect(result.current.model).toBe(""); + await act(async () => expect(await result.current.send({ text: "草稿" })).toBe(false)); + expect(result.current.error).toBe(message); + expect(writeMock).not.toHaveBeenCalled(); + } finally { + apiMock.mockImplementation(original); + } + }); + + test("reloads the model list if a CodeBuddy key was added in another tab", async () => { + localStorage.removeItem("loopforge.assistant.executor"); + const original = apiMock.getMockImplementation(); + const user = { id: 1, loginName: "tester" }; + let configured = false; + apiMock.mockImplementation((path, options) => { + if (path === "/api/auth/current") return Promise.resolve({ user }); + if (path === "/api/users") return Promise.resolve([{ ...user, codeBuddyApiKeyConfigured: configured }]); + if (path === "/api/assistant/models") return Promise.resolve({ + default: "default", models: configured ? [{ id: "deepseek-v4.1-flash" }] : [], + }); + return original(path, options); + }); + try { + const { result } = renderHook(useChat); + await waitFor(() => expect(result.current.ready && result.current.machinesReady).toBe(true)); + configured = true; + await act(async () => expect(await result.current.send({ text: "草稿" })).toBe(false)); + expect(result.current.error).toContain("正在刷新模型列表"); + expect(writeMock).not.toHaveBeenCalled(); + await waitFor(() => expect(result.current.model).toBe("deepseek-v4.1-flash")); + await act(async () => expect(await result.current.send({ text: "草稿" })).toBe(true)); + expect(writeMock).toHaveBeenCalledWith("/api/assistant/generations", expect.objectContaining({ + executor: "codebuddy", model: "deepseek-v4.1-flash", + })); + } finally { + apiMock.mockImplementation(original); + } + }); + + test("opens and regenerates a conversation saved with a CLI default on a concrete model", async () => { + localStorage.removeItem("loopforge.assistant.executor"); + const original = apiMock.getMockImplementation(); + const saved = { + id: "s1", projectId: "p1", executor: "codebuddy", model: "codebuddy:default", + messages: [{ role: "user", content: "继续" }], + }; + apiMock.mockImplementation((path, options) => + path === "/api/assistant/sessions/s1" ? Promise.resolve(saved) : original(path, options)); + try { + const { result } = renderHook(useChat); + await waitFor(() => expect(result.current.ready && result.current.machinesReady).toBe(true)); + act(() => result.current.open(saved.id)); + await waitFor(() => expect(result.current.session?.id).toBe(saved.id)); + expect(result.current.model).toBe("m1"); + await act(() => result.current.regenerate(saved, "confirm")); + expect(writeMock).toHaveBeenCalledWith("/api/assistant/generations", expect.objectContaining({ + sessionId: saved.id, executor: "codebuddy", model: "m1", + })); + } finally { + apiMock.mockImplementation(original); + } + }); + test("without an own key chat is limited to the administrator's shared models", async () => { localStorage.removeItem("loopforge.assistant.executor"); const original = apiMock.getMockImplementation(); From 807784be5b5599d91444564ebc8da26298a22ba1 Mon Sep 17 00:00:00 2001 From: roberttwang Date: Sat, 21 Nov 2026 21:37:39 +0800 Subject: [PATCH 3/3] fix(chat): honor personal model defaults for legacy conversations --- chatbot/src/useChat.js | 27 +++++++++++++++++++++------ chatbot/tests/hooks.test.jsx | 23 +++++++++++++++++------ 2 files changed, 38 insertions(+), 12 deletions(-) diff --git a/chatbot/src/useChat.js b/chatbot/src/useChat.js index 2690c4a6..9ecc016b 100644 --- a/chatbot/src/useChat.js +++ b/chatbot/src/useChat.js @@ -55,11 +55,15 @@ function effortPreference(executor, model) { return `effort.${executor}.${unprefixedModel(executor, model)}`; } -// Prefer the remembered model when supplied, then the first available model. -function preferredModel(list, executor, remembered) { +// Use the first requested preference that is available for this executor. +function preferredModel(list, executor, ...preferences) { const available = list.filter((model) => !model.disabled && !model.unavailable); - const listed = findExecutorModel(available, executor, remembered); - return (listed && remembered) || available[0]?.id || ""; + for (const id of preferences) { + if (!concreteModel({ id }, executor)) continue; + const listed = findExecutorModel(available, executor, id); + if (listed) return id; + } + return available[0]?.id || ""; } // Mirrors errAssistantSponsoredModel in internal/httpapi/assistant_sponsor.go; @@ -110,6 +114,8 @@ export function useChat() { [revealId, setRevealId] = useState(activeId), [projectId, setProjectId] = useState(initialProject), [selection, setSelection] = useState(() => ({ executor: storedExecutor(), model: null, effort: null })), + [accountDefaults, setAccountDefaults] = useState(null), + [codeBuddyCatalogDefault, setCodeBuddyCatalogDefault] = useState(""), [sponsoredModels, setSponsoredModels] = useState([]), [providerCatalogs, setProviderCatalogs] = useState({}), [generation, setGeneration] = useState(null), @@ -249,6 +255,8 @@ export function useChat() { } const applyModelCatalog = useCallback((catalog) => { setModels(catalog.models || []); + setAccountDefaults(catalog.preferences || null); + setCodeBuddyCatalogDefault(catalog.default || ""); setSponsoredModels(sponsoredModelList(catalog)); }, []); useEffect(() => { @@ -650,10 +658,15 @@ export function useChat() { : listed; const sponsored = codeBuddy && missingKey && !user.isGuest && !!sponsoredModel; const listedModel = findExecutorModel(executorModels, executor, model); - const hasSelectedModel = concreteModel({ id: model }, executor) && !listedModel?.disabled && !listedModel?.unavailable && + const concrete = concreteModel({ id: model }, executor); + const hasSelectedModel = concrete && !listedModel?.disabled && !listedModel?.unavailable && (conversation || !executorModels.length || listedModel); + const inheritsDefault = !!conversation && !concrete; + const personalDefault = inheritsDefault && !sponsored && accountDefaults?.executor === executor ? accountDefaults : null; const selectedModel = hasSelectedModel ? model : preferredModel( executorModels, executor, + personalDefault?.model, + inheritsDefault ? (codeBuddy ? codeBuddyCatalogDefault : providerCatalog?.default) : null, draft ? readComposerPreference(`model.${executor}`) : null, ); const availableModel = sponsored && !sponsoredModels.includes(selectedModel) ? sponsoredModel : selectedModel; @@ -667,7 +680,9 @@ export function useChat() { ? catalogEntry?.efforts?.find((level) => catalogEntry.effortModelIds?.[level] === requestedModelId) : undefined; // null follows the browser preference, while "" is the CLI's default level. - const preferredEffort = ((model === null || hasSelectedModel) ? effort : null) ?? + const defaultEffort = personalDefault && catalogEntry && catalogEntry === findExecutorModel(executorModels, executor, personalDefault.model) + ? personalDefault.effort : null; + const preferredEffort = (inheritsDefault ? defaultEffort : ((model === null || hasSelectedModel) ? effort : null)) ?? (draft ? readComposerPreference(effortPreference(executor, availableModel)) : null); // Custom models can remain usable without a picker entry. Keep their // saved effort visible and let the server validate it on send. diff --git a/chatbot/tests/hooks.test.jsx b/chatbot/tests/hooks.test.jsx index 184dd65c..e4201d2a 100644 --- a/chatbot/tests/hooks.test.jsx +++ b/chatbot/tests/hooks.test.jsx @@ -771,24 +771,35 @@ describe("conversation hooks", () => { } }); - test("opens and regenerates a conversation saved with a CLI default on a concrete model", async () => { + test.each([ + ["personal default", "codebuddy:default", { executor: "codebuddy", model: "m3", effort: "high" }, "m2", "m3", "high"], + ["catalog default for the original CLI", "codebuddy:default", { executor: "codex", model: "gpt-5" }, "m2", "m2", ""], + ["first available model", "codebuddy:default", { executor: "codebuddy", model: "retired" }, "default", "m1", ""], + ["explicitly selected model", "m1", { executor: "codebuddy", model: "m3" }, "m2", "m1", ""], + ])("uses the %s when reopening and regenerating an old conversation", async (_name, savedModel, preferences, catalogDefault, expectedModel, expectedEffort) => { localStorage.removeItem("loopforge.assistant.executor"); const original = apiMock.getMockImplementation(); const saved = { - id: "s1", projectId: "p1", executor: "codebuddy", model: "codebuddy:default", + id: "s1", projectId: "p1", executor: "codebuddy", model: savedModel, messages: [{ role: "user", content: "继续" }], }; - apiMock.mockImplementation((path, options) => - path === "/api/assistant/sessions/s1" ? Promise.resolve(saved) : original(path, options)); + apiMock.mockImplementation((path, options) => { + if (path === "/api/assistant/models") return Promise.resolve({ + default: catalogDefault, preferences, models: [{ id: "m1" }, { id: "m2" }, { id: "m3", efforts: ["high"] }], + }); + if (path === "/api/assistant/sessions/s1") return Promise.resolve(saved); + return original(path, options); + }); try { const { result } = renderHook(useChat); await waitFor(() => expect(result.current.ready && result.current.machinesReady).toBe(true)); act(() => result.current.open(saved.id)); await waitFor(() => expect(result.current.session?.id).toBe(saved.id)); - expect(result.current.model).toBe("m1"); + expect(result.current.model).toBe(expectedModel); + expect(result.current.effort).toBe(expectedEffort); await act(() => result.current.regenerate(saved, "confirm")); expect(writeMock).toHaveBeenCalledWith("/api/assistant/generations", expect.objectContaining({ - sessionId: saved.id, executor: "codebuddy", model: "m1", + sessionId: saved.id, executor: "codebuddy", model: expectedModel, effort: expectedEffort, })); } finally { apiMock.mockImplementation(original);