diff --git a/CHANGELOG.md b/CHANGELOG.md index aef1c05e5..d1cc102b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ Platform releases use `vX.Y.Z` tags and publish `ghcr.io/tencent/loopforge`. Loo - The orchestrator panel embeds the chatbot (`/chatbot/?surface=sop-designer`) instead of its own hand-written chat. Replies render Markdown with the execution trace, a running turn can be stopped, the turn runs as a background generation, so closing the panel or reloading the page no longer loses it, and reopening a SOP shows its earlier conversation. The CLI and model choice keeps its own memory as before. Each reply's draft shows its warnings and can be put on the canvas again. The canvas and the chat talk only through `agentflow-sop-designer-*` window messages; the canvas still animates nodes and wires as the draft streams in. - Editing a SOP in the orchestrator no longer rewrites the whole graph. On a canvas with steps the model submits `operations` (`add_node`, `update_node`, `remove_node`, `add_edge`, `remove_edge`, `update_workflow`) and the server applies them to the canvas it received, so steps, prompts, scripts, layout and the 「构建静态站点」 node the user did not mention stay exactly as they were. An operation that does not fit the canvas (an unknown node, a duplicate edge, removing a node another step rejects to) goes back to the model with the reason instead of reaching the canvas. The canvas no longer guesses intent from the wording: it no longer matches 「重新…」 or 「去掉预览」 phrases or SOP names in the message; the server lists the project's SOPs and the model reads the one the user means. A draft with a different SOP id replaces the canvas only after the user confirms. - The orchestrator offers the model only roles a SOP save accepts: roles of this project and roles another project shares. A built-in role that belongs to no project used to be offered, and the draft then failed on save with 「角色 … 不属于当前项目且尚未共享」. `workflows_save` drafts from any conversation now warn about such a role before saving. A script longer than 400 characters reaches the model as a marker that says it is omitted, not as an empty string; the model used to report the script as empty and offer to write one, and a marker copied back into a draft is replaced by the canvas's script. +- 「CLI 默认模型」(`default`) is gone. `GET /api/assistant/models`, `?executor=…` and `/api/executor-models` no longer list it. Every picker (AI 对话, roles, schedules, Bots, clarification, run evals, the SOP preview) starts on the first listed model, and a setting without a model runs on the first model its catalog lists. Settings saved earlier with `default` read as no model chosen (`domain.ChosenModel`). - Scheduled tasks keep an execution history with a session mode, keep conversations per job and gain row actions (#958). AI jobs run with the key of the user who saved them and fall back to the shared key (#966). - Requirements can be created directly and clarified in a chat (#965). Settled execution history can be force-deleted (#210). - Conversation workspaces open by sandbox with agent-owned Git (#947), run native agent CLIs on bound execution machines (#494), can be bound to project SOP workspaces through `workspaceRunId` (#974), and install a missing CLI from the failure message (#183). diff --git a/chatbot/src/useChat.js b/chatbot/src/useChat.js index cc6cfc51e..264918450 100644 --- a/chatbot/src/useChat.js +++ b/chatbot/src/useChat.js @@ -111,7 +111,7 @@ 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: "默认" }), + [codeBuddyDefault, setCodeBuddyDefault] = useState({ id: "", name: "" }), [sponsoredModels, setSponsoredModels] = useState([]), [providerCatalogs, setProviderCatalogs] = useState({}), [generation, setGeneration] = useState(null), @@ -251,7 +251,7 @@ export function useChat() { } const applyModelCatalog = useCallback((catalog) => { setModels(catalog.models || []); - setCodeBuddyDefault({ id: catalog.default || "default", name: "默认", efforts: catalog.defaultEfforts }); + setCodeBuddyDefault({ id: catalog.default || "", name: catalog.default || "", efforts: catalog.defaultEfforts }); setSponsoredModels(sponsoredModelList(catalog)); }, []); useEffect(() => { @@ -1024,11 +1024,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 +1033,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 +1080,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((member) => member.id === user?.id); + 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) ?? user; + if (!fresh.codeBuddyApiKeyConfigured) { if (viewingTarget()) setError("请先在个人配置中配置自己的 CodeBuddy API Key"); return false; } + if (missingKey || !composerModel.activeModel) 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 d16bb7d9d..292fa0755 100644 --- a/chatbot/tests/hooks.test.jsx +++ b/chatbot/tests/hooks.test.jsx @@ -713,6 +713,30 @@ describe("conversation hooks", () => { } }); + test.each([ + [false, "请先在个人配置中配置自己的 CodeBuddy API Key"], + [true, "当前 CLI 暂无可用模型"], + ])("explains how to send with an empty catalog (key configured: %s)", async (configured, reason) => { + localStorage.removeItem("loopforge.assistant.executor"); + const original = apiMock.getMockImplementation(); + const user = { id: 1, loginName: "tester", codeBuddyApiKeyConfigured: configured }; + apiMock.mockImplementation(async (path, options) => { + if (path === "/api/auth/current") return { user }; + if (path === "/api/users") return [user]; + if (path === "/api/assistant/models") return { default: "", models: [] }; + return original(path, options); + }); + try { + const { result } = renderHook(() => useChat()); + await waitFor(() => expect(result.current.ready).toBe(true)); + await act(async () => expect(await result.current.send({ text: "草稿" })).toBe(false)); + expect(result.current.error).toContain(reason); + expect(writeMock).not.toHaveBeenCalled(); + } 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(); diff --git a/e2e/api/62-integrations.test.mjs b/e2e/api/62-integrations.test.mjs index d28afaedc..c8eafe558 100644 --- a/e2e/api/62-integrations.test.mjs +++ b/e2e/api/62-integrations.test.mjs @@ -34,7 +34,7 @@ test('notification bots: create, update, secret stays write-only, delete', async assert.equal(bot.secretConfigured, true); assert.equal(bot.ownerId, me.id); assert.equal(bot.health, 'unchecked'); - assert.ok(bot.model, 'a default report model is assigned'); + assert.equal(bot.model || '', '', 'an unselected model is resolved for the responsible account when the report runs'); const bots = await api('GET', `/api/notification-bots?projectId=${P}`, undefined, { raw: true }); assert.ok(list(bots.data).some(b => b.id === bot.id)); diff --git a/e2e/public/executors.spec.mjs b/e2e/public/executors.spec.mjs index 23bb0d376..c42a2e936 100644 --- a/e2e/public/executors.spec.mjs +++ b/e2e/public/executors.spec.mjs @@ -74,8 +74,10 @@ test('executor selection has independent models, credentials and a persistent ch expect(models.ok()).toBe(true); const catalog=await models.json(); expect(Array.isArray(catalog.models)).toBe(true); - if(id==='codebuddy')expect(catalog.default).toBeTruthy(); - else expect(catalog.models.length).toBeGreaterThan(0); + if(id==='codebuddy'){ + const first=catalog.models.find(model=>!model.engine||model.engine==='codebuddy'); + expect(catalog.default).toBe(first?.id??''); + }else expect(catalog.models.length).toBeGreaterThan(0); } await choose('Codex'); await page.reload(); diff --git a/internal/domain/model.go b/internal/domain/model.go new file mode 100644 index 000000000..0f8fa770f --- /dev/null +++ b/internal/domain/model.go @@ -0,0 +1,15 @@ +package domain + +import "strings" + +// ChosenModel returns the model a setting names, or "" when it names none. +// A setting without a model runs on the first model its picker lists. +// Settings saved by earlier versions may hold "default", the retired +// placeholder for "let the CLI pick"; it reads as no model chosen. +func ChosenModel(id string) string { + id = strings.TrimSpace(id) + if id == "default" { + return "" + } + return id +} diff --git a/internal/domain/notification.go b/internal/domain/notification.go index 1c85ae648..4803ed406 100644 --- a/internal/domain/notification.go +++ b/internal/domain/notification.go @@ -35,8 +35,6 @@ type NotificationBinding struct { } type NodeNotification = NotificationBinding -const DefaultNotificationReportModel = "default" - type NotificationReportRequest struct { Binding NotificationBinding Context NotificationContext diff --git a/internal/domain/preview.go b/internal/domain/preview.go index 234652941..3c05d37c3 100644 --- a/internal/domain/preview.go +++ b/internal/domain/preview.go @@ -36,7 +36,6 @@ const ( PreviewBuildNodeID = "af-preview-build" PreviewBuildAgentID = "af-preview-builder" PreviewBuildExecutor = "codebuddy" - PreviewDefaultModel = "default" PreviewDefaultSource = "dist" PreviewBuildEdgeID = "af-preview-build-edge" PreviewMaxRetentionSec = int64(30 * 24 * 3600) @@ -105,14 +104,14 @@ func (c *PreviewContract) ExecutorOrCodeBuddy() string { return PreviewBuildExecutor } -func (c *PreviewContract) ModelOrDefault() string { +// ChosenModel is the model the preview build runs on. Saving an SOP fills +// in the first listed CodeBuddy model when none is chosen (see +// attachPreviewBuild in internal/httpapi/catalog.go). +func (c *PreviewContract) ChosenModel() string { if c == nil { - return PreviewDefaultModel + return "" } - if model := strings.TrimSpace(c.Model); model != "" { - return model - } - return PreviewDefaultModel + return ChosenModel(c.Model) } func (c *PreviewContract) Retention() time.Duration { @@ -136,7 +135,7 @@ func (c *PreviewContract) Normalize() { } c.Kind = c.KindOrStatic() c.ExecutorID = c.ExecutorOrCodeBuddy() - c.Model = c.ModelOrDefault() + c.Model = c.ChosenModel() c.SourcePath = c.SourceOrDist() c.IndexFile = c.Index() if c.RetentionSec <= 0 || c.RetentionSec > PreviewMaxRetentionSec { @@ -155,9 +154,6 @@ func (c *PreviewContract) Validate() error { if !strings.EqualFold(c.ExecutorID, PreviewBuildExecutor) { return fmt.Errorf("frontend preview currently supports CodeBuddy CLI only") } - if strings.TrimSpace(c.Model) == "" { - return fmt.Errorf("frontend preview requires a CodeBuddy model") - } if strings.Contains(c.SourcePath, "..") || strings.HasPrefix(c.SourcePath, "/") { return fmt.Errorf("frontend preview sourcePath %q is invalid", c.SourcePath) } diff --git a/internal/domain/preview_build.go b/internal/domain/preview_build.go index 2ca3eeffc..c183a755d 100644 --- a/internal/domain/preview_build.go +++ b/internal/domain/preview_build.go @@ -84,7 +84,7 @@ func PreviewBuildAgent(contract *PreviewContract) AgentDefinition { Name: "构建静态站点", Description: "系统步骤:用 CodeBuddy 产出可托管的静态站点,再由预览收尾归档。", ExecutorID: PreviewBuildExecutor, - Model: contract.ModelOrDefault(), + Model: contract.ChosenModel(), Prompt: PreviewBuildPrompt(contract), ArtifactOutputs: []ArtifactContract{PreviewBuildArtifact(contract)}, Loop: AgentLoopPolicy{ diff --git a/internal/httpapi/agent_tool_native_terminal_test.go b/internal/httpapi/agent_tool_native_terminal_test.go index 0c63e524d..0a9e9f995 100644 --- a/internal/httpapi/agent_tool_native_terminal_test.go +++ b/internal/httpapi/agent_tool_native_terminal_test.go @@ -123,7 +123,7 @@ func TestCodeBuddyWaitsForSessionGatewayBeforeFirstRequest(t *testing.T) { } } h := &streamHandlers{} - _, out, _, err := h.runClarifyTurn(context.Background(), root, bin, clarifyDefaultModel, "p", "clarify-wait", "af-wait", filepath.Join(root, "clarify-home"), false, + _, out, _, err := h.runClarifyTurn(context.Background(), root, bin, clarifyTestModel, "p", "clarify-wait", "af-wait", filepath.Join(root, "clarify-home"), false, runtime.RunCredentials{CodeBuddy: runtime.CodeBuddyCredential{APIKey: "test-key"}}, func(string, any) {}, clarifyTurnOpts{Native: true, MCPConfig: files.MCPConfig, Settings: files.Settings}) if err != nil || !strings.Contains(out, want) { t.Fatalf("clarify: got %q err=%v, want %q", out, err, want) diff --git a/internal/httpapi/agent_tool_session_test.go b/internal/httpapi/agent_tool_session_test.go index 505b3a1a2..f70c752ac 100644 --- a/internal/httpapi/agent_tool_session_test.go +++ b/internal/httpapi/agent_tool_session_test.go @@ -185,7 +185,7 @@ func TestNativeClarifyCommandKeepsReadAndSessionMCP(t *testing.T) { } t.Cleanup(files.Cleanup) command, err := prepareClarifyCommandWith(clarifyCommandOpts{ - Bin: "codebuddy", Model: clarifyDefaultModel, Prompt: "p", RunID: "r", SessionID: "af1", + Bin: "codebuddy", Model: clarifyTestModel, Prompt: "p", RunID: "r", SessionID: "af1", Native: true, MCPConfig: files.MCPConfig, Settings: files.Settings, }) if err != nil { diff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.go index 05941a2f4..f250cbb97 100644 --- a/internal/httpapi/assistant.go +++ b/internal/httpapi/assistant.go @@ -234,12 +234,12 @@ func (h *assistantHandlers) chat(c *gin.Context) { return } catalogEngine, _ := assistantModelEngine(req.Model) - catalog := assistantChatCatalog(c.Request.Context(), user.CodeBuddyInternetEnvironment, nil) + catalog := assistantChatCatalog(c.Request.Context(), user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey, nil) if catalogEngine == assistantEngineCodeBuddy { catalog = h.turnCatalog(c.Request.Context(), user, req.Model) } if !runnerLogin { - selected, err := assistantTurnCatalogModel(req.Model, catalog, user, req.RequireExactModel) + selected, err := assistantTurnCatalogModel(c.Request.Context(), req.Model, catalog, user, req.RequireExactModel) if err != nil { c.JSON(400, gin.H{"error": err.Error()}) return @@ -473,11 +473,10 @@ func (h *assistantHandlers) chat(c *gin.Context) { nativeContinuationReady := false var turnUsage assistantTurnUsage replyModel := strings.TrimSpace(req.Model) - if replyModel == "" { - replyModel = assistantDefaultModel - } if report, ok := modelCtx.Value(scheduledUsageReportKey{}).(scheduledUsageReport); ok && report.GenerationID == assistantControlScopeFrom(modelCtx).GenerationID && report.Report != nil { - defer func() { report.Report(replyModel, turnUsage.snapshot()) }() + // Preserve the usage record for CLIs that use their own default and + // do not report a concrete model. + defer func() { report.Report(firstNonEmpty(replyModel, assistantDefaultModel), turnUsage.snapshot()) }() } var turn string generate := h.generate @@ -1884,7 +1883,7 @@ type assistantCommandOpts struct { } func prepareAssistantCommand(opts assistantCommandOpts) (runtime.CommandSpec, error) { - model := strings.TrimSpace(opts.Model) + model := domain.ChosenModel(opts.Model) if model == "" { model = assistantFixedCatalog().Default } diff --git a/internal/httpapi/assistant_approval_review_test.go b/internal/httpapi/assistant_approval_review_test.go index 0b9f34b9e..a728a688a 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 := assistantChatCatalog(context.Background(), "", "", nil) 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(context.Background(), "", "", []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_codebuddy_default_test.go b/internal/httpapi/assistant_codebuddy_default_test.go index 655b8d00d..90bd7f78f 100644 --- a/internal/httpapi/assistant_codebuddy_default_test.go +++ b/internal/httpapi/assistant_codebuddy_default_test.go @@ -18,11 +18,11 @@ func TestCodeBuddyPersonalModelsDefaultMatchesPicker(t *testing.T) { t.Fatalf("default = %q, want the first saved model", catalog.Default) } for _, id := range []string{"env-default", "env-other", "personal-a", "personal-b"} { - if got := assistantAllowedUserModel(id, catalog, user); got != id { + if got := assistantAllowedUserModel(context.Background(), id, catalog, user); got != id { t.Fatalf("model %s not accepted: %q", id, got) } } - if got := assistantAllowedUserModel("", catalog, user); got != "personal-a" { + if got := assistantAllowedUserModel(context.Background(), "", catalog, user); got != "personal-a" { t.Fatalf("empty request runs on %q, want personal-a", got) } diff --git a/internal/httpapi/assistant_effort_test.go b/internal/httpapi/assistant_effort_test.go index f846f9626..0718f7094 100644 --- a/internal/httpapi/assistant_effort_test.go +++ b/internal/httpapi/assistant_effort_test.go @@ -14,7 +14,7 @@ import ( ) func TestAssistantEffortReachesNativeCLIAndPersists(t *testing.T) { - t.Setenv("AGENTFLOW_ASSISTANT_MODELS", assistantChatDefaultModel) + t.Setenv("AGENTFLOW_ASSISTANT_MODELS", assistantChatDefaultModel+",hy4-preview-ioa") h, user := workbenchFixture(t) _, calls := nativeCLIRecorder(t) // calls counts conversation turns; keep model discovery off the fake CLI. diff --git a/internal/httpapi/assistant_engines.go b/internal/httpapi/assistant_engines.go index 16d15be82..e3588d4bf 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 @@ -286,20 +286,42 @@ func (h *assistantHandlers) assistantTurnUser(stored domain.User, model string, // assistantAllowedUserModel is assistantAllowedModel plus the caller's CLI // models. Any well-formed model ID is accepted for a configured CLI: the // gateway behind the Base URL decides what exists, and a discovery outage -// must not silently move the conversation back to CodeBuddy. -func assistantAllowedUserModel(id string, catalog assistantModelCatalog, user domain.User) string { +// must not silently move the conversation back to CodeBuddy. A CLI turn +// without a model runs on the first model that CLI lists. +func assistantAllowedUserModel(ctx context.Context, id string, catalog assistantModelCatalog, user domain.User) string { engine, model := assistantModelEngine(id) if engine == assistantEngineCodeBuddy { return assistantAllowedModel(id, catalog) } - if key, _ := assistantEngineCredential(user, engine); key == "" || !assistantValidEngineModel(model) { + if key, _ := assistantEngineCredential(user, engine); key == "" { + return catalog.Default + } + if domain.ChosenModel(model) == "" { + if first := assistantEngineFirstModel(ctx, user, engine); first != "" { + return first + } + return catalog.Default + } + if !assistantValidEngineModel(model) { return catalog.Default } return engine + ":" + model } -func assistantTurnCatalogModel(requested string, catalog assistantModelCatalog, user domain.User, exact bool) (string, error) { - model := assistantAllowedUserModel(requested, catalog, user) +// assistantEngineFirstModel is the first model engine lists for user, with +// its CLI prefix, or "" when it lists none. +func assistantEngineFirstModel(ctx context.Context, user domain.User, engine string) string { + models, _ := assistantEngineModels(ctx, user, nil) + for _, model := range models { + if model.Engine == engine { + return model.ID + } + } + return "" +} + +func assistantTurnCatalogModel(ctx context.Context, requested string, catalog assistantModelCatalog, user domain.User, exact bool) (string, error) { + model := assistantAllowedUserModel(ctx, requested, catalog, user) engine, id := assistantModelEngine(requested) useDefault := id == "" || id == assistantDefaultModel || (engine == assistantEngineCodeBuddy && codeBuddyIsDefaultModel(id)) @@ -318,6 +340,12 @@ func assistantTurnCatalogModel(requested string, catalog assistantModelCatalog, // the owner's account when it runs (see scheduledRunModel). func assistantScheduledModel(id string, catalog assistantModelCatalog) string { engine, model := assistantModelEngine(id) + if engine != assistantEngineCodeBuddy && domain.ChosenModel(model) == "" { + // Existing jobs may select a runner login without a concrete model. + // Keep the selected CLI until the run-as account is known. + return engine + ":" + assistantDefaultModel + } + model = domain.ChosenModel(model) if engine != assistantEngineCodeBuddy && assistantValidEngineModel(model) { return engine + ":" + model } diff --git a/internal/httpapi/assistant_generation.go b/internal/httpapi/assistant_generation.go index 014a07c8c..48b44520f 100644 --- a/internal/httpapi/assistant_generation.go +++ b/internal/httpapi/assistant_generation.go @@ -131,12 +131,12 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) { return } catalogEngine, _ := assistantModelEngine(req.Model) - catalog := assistantChatCatalog(c.Request.Context(), user.CodeBuddyInternetEnvironment, nil) + catalog := assistantChatCatalog(c.Request.Context(), user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey, nil) if catalogEngine == assistantEngineCodeBuddy { catalog = h.turnCatalog(c.Request.Context(), user, req.Model) } if !runnerLogin { - selected, err := assistantTurnCatalogModel(req.Model, catalog, user, req.RequireExactModel) + selected, err := assistantTurnCatalogModel(c.Request.Context(), req.Model, catalog, user, req.RequireExactModel) if err != nil { c.JSON(400, gin.H{"error": err.Error()}) return @@ -577,12 +577,12 @@ 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 := assistantChatCatalog(c.Request.Context(), user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey, nil) if engine, _ := assistantModelEngine(model); engine == assistantEngineCodeBuddy { catalog = h.turnCatalog(c.Request.Context(), user, model) } if !runnerLogin { - selected, err := assistantTurnCatalogModel(model, catalog, user, body.RequireExactModel) + selected, err := assistantTurnCatalogModel(c.Request.Context(), model, catalog, user, body.RequireExactModel) if err != nil { c.JSON(400, gin.H{"error": err.Error()}) return diff --git a/internal/httpapi/assistant_models.go b/internal/httpapi/assistant_models.go index 32f5b8819..fab59e230 100644 --- a/internal/httpapi/assistant_models.go +++ b/internal/httpapi/assistant_models.go @@ -4,9 +4,11 @@ import ( "context" "crypto/sha256" "encoding/hex" + "maps" "os" "os/exec" "regexp" + "slices" "strings" "sync" "time" @@ -17,14 +19,14 @@ import ( "github.com/gin-gonic/gin" ) -const assistantDefaultModel = "default" - // assistantChatDefaultModel is the model the legacy sponsor account lends. -// New chat conversations preselect the shared key's default model when one is -// configured; otherwise chat uses the operator's default, like clarification, -// scheduled prompts, reports and executors. +// New chat conversations preselect the shared key's first model when one is +// configured; otherwise every picker starts on the first model it lists. const assistantChatDefaultModel = assistantSponsoredModel +// Legacy saved selections may contain this provider-default alias. +const assistantDefaultModel = "default" + type assistantModel struct { ID string `json:"id"` Name string `json:"name"` @@ -63,9 +65,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 +135,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() } @@ -149,9 +150,10 @@ func assistantKnownCatalog() assistantModelCatalog { } cliModelMu.Lock() defer cliModelMu.Unlock() - for _, entry := range cliModelCache { + for _, key := range slices.Sorted(maps.Keys(cliModelCache)) { + entry := cliModelCache[key] for _, id := range entry.models { - if !seen[id] { + if !codeBuddyIsDefaultModel(id) && !seen[id] { catalog.Models = append(catalog.Models, assistantListedModel(id, id, "")) seen[id] = true } @@ -160,24 +162,10 @@ func assistantKnownCatalog() assistantModelCatalog { return catalog } -func cachedCLIModels(environment string) []string { +func cachedCLIModels(environment, apiKey string) []string { 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[cliModelCacheKey(strings.TrimSpace(environment), apiKey)].models } // models returns the chat model catalog for the caller's CodeBuddy @@ -199,7 +187,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 @@ -217,10 +205,7 @@ func (h *assistantHandlers) models(c *gin.Context) { } result.Models = append(result.Models, assistantModel{ID: item.ID, Name: item.Name, Family: item.Family, Engine: engine, Efforts: levels}) } - if len(result.Models) > 0 { - result.Default = result.Models[0].ID - } - c.JSON(200, result) + c.JSON(200, result.withFirstDefault()) return } @@ -235,20 +220,18 @@ 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(c.Request.Context(), 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) - if saved := codeBuddyPersonalModels(user); len(saved) > 0 { + catalog = assistantChatCatalog(c.Request.Context(), user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey, nil) + if saved := selectableCodeBuddyModels(codeBuddyPersonalModels(user)); len(saved) > 0 { catalog.Default = saved[0].ID - if listed := selectableCodeBuddyModels(saved); len(listed) > 0 { - catalog.Models = listed - } + catalog.Models = saved } default: - catalog = assistantChatCatalog(c.Request.Context(), "", nil) + catalog = assistantChatCatalog(c.Request.Context(), "", "", nil) } if catalog.Default == assistantDefaultModel { models := user.CodeBuddyModels @@ -283,7 +266,7 @@ func (h *assistantHandlers) models(c *gin.Context) { c.JSON(200, catalog) } -// Keep the CLI default as an execution fallback and for older saved records. +// Older personal settings may still contain the CLI-default placeholder. // The model pickers offer the concrete models available to the caller. func selectableCodeBuddyModels(models []assistantModel) []assistantModel { listed := make([]assistantModel, 0, len(models)) @@ -299,11 +282,17 @@ func codeBuddyIsDefaultModel(id string) bool { return id == assistantDefaultModel || id == "default-model" } +func codeBuddyAccountModel(ctx context.Context, user domain.User, id string) string { + refreshCLIModels(ctx, user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey) + catalog := withCodeBuddyPersonalModels(loadAssistantModels(ctx, user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey), user) + return assistantAllowedModel(id, catalog) +} + // withCodeBuddyPersonalModels accepts the user's saved CodeBuddy models and // defaults requests without a model to the first of them. The environment's // models stay accepted. func withCodeBuddyPersonalModels(catalog assistantModelCatalog, user domain.User) assistantModelCatalog { - saved := codeBuddyPersonalModels(user) + saved := selectableCodeBuddyModels(codeBuddyPersonalModels(user)) if len(saved) == 0 { return catalog } @@ -332,8 +321,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(ctx context.Context, env, apiKey string, shared []string) assistantModelCatalog { + catalog := loadAssistantModels(ctx, env, apiKey) if len(shared) == 0 { return catalog } @@ -357,45 +346,46 @@ func assistantChatCatalog(ctx context.Context, env string, shared []string) assi // loadAssistantModels never blocks on discovery; validation accepts models the // caller's environment has advertised. -func loadAssistantModels(_ context.Context, environment string) assistantModelCatalog { +func loadAssistantModels(_ context.Context, environment, apiKey string) assistantModelCatalog { catalog := assistantFixedCatalog() seen := map[string]bool{} for _, model := range catalog.Models { seen[model.ID] = true } - for _, id := range cachedCLIModels(environment) { - if !seen[id] { + for _, id := range cachedCLIModels(environment, apiKey) { + if !codeBuddyIsDefaultModel(id) && !seen[id] { catalog.Models = append(catalog.Models, assistantListedModel(id, id, "")) seen[id] = true } } - return catalog + return catalog.withFirstDefault() } -// 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 -// is pinned by live roles (and was the old built-in executor default), and -// hy4-preview-ioa stays alongside hy4std for existing users. +// withFirstDefault makes the first listed model the default. A catalog +// with no models has no default. +func (c assistantModelCatalog) withFirstDefault() assistantModelCatalog { + c.Default = "" + if len(c.Models) > 0 { + c.Default = c.Models[0].ID + } + return c +} + +// assistantFixedCatalog lists the models the operator configured: +// AGENTFLOW_ASSISTANT_MODEL first, then AGENTFLOW_ASSISTANT_MODELS. The +// models CodeBuddy advertises (`codebuddy --help`) follow them in the +// catalogs built on this one. func assistantFixedCatalog() assistantModelCatalog { - defaultID := strings.TrimSpace(os.Getenv("AGENTFLOW_ASSISTANT_MODEL")) - if defaultID == "" { - defaultID = assistantDefaultModel - } - defaultName := defaultID - if defaultID == assistantDefaultModel { - defaultName = "CLI 默认模型" - } - models := []assistantModel{assistantListedModel(defaultID, defaultName, "")} - seen := map[string]bool{defaultID: true} - for _, id := range strings.Split(os.Getenv("AGENTFLOW_ASSISTANT_MODELS"), ",") { - id = strings.TrimSpace(id) - if id != "" && !seen[id] { + var models []assistantModel + seen := map[string]bool{} + for _, id := range append([]string{os.Getenv("AGENTFLOW_ASSISTANT_MODEL")}, strings.Split(os.Getenv("AGENTFLOW_ASSISTANT_MODELS"), ",")...) { + id = domain.ChosenModel(id) + if id != "" && !codeBuddyIsDefaultModel(id) && !seen[id] { models = append(models, assistantListedModel(id, id, "")) seen[id] = true } } - return assistantModelCatalog{Default: defaultID, Models: models} + return assistantModelCatalog{Models: models}.withFirstDefault() } func assistantListedModel(id, name, credits string) assistantModel { @@ -449,8 +439,10 @@ func assistantModelFamily(id, engine string) string { } } +// assistantAllowedModel is id when catalog lists it, else the first listed +// model. func assistantAllowedModel(id string, catalog assistantModelCatalog) string { - id = strings.TrimSpace(id) + id = domain.ChosenModel(id) if id == "" { return catalog.Default } diff --git a/internal/httpapi/assistant_models_test.go b/internal/httpapi/assistant_models_test.go index 4e99c3390..b8a4174da 100644 --- a/internal/httpapi/assistant_models_test.go +++ b/internal/httpapi/assistant_models_test.go @@ -1,6 +1,7 @@ package httpapi import ( + "agentflow/internal/domain" "bytes" "context" "encoding/json" @@ -21,19 +22,19 @@ func TestAssistantModelPickerOmitsCodeBuddyCLIDefault(t *testing.T) { if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &catalog) != nil { t.Fatalf("model picker: %d %s", rec.Code, rec.Body) } - if catalog.Default != assistantDefaultModel || len(catalog.DefaultEfforts) == 0 || + if catalog.Default != "model-a" || 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 { - t.Fatalf("an omitted request model should still use the CLI fallback, got %q", got) + if got := assistantAllowedModel("", h.chatCatalog(context.Background(), user)); got != "model-a" { + t.Fatalf("an omitted request model should use the first offered model, got %q", got) } t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "") c, rec = workbenchContext(user, http.MethodGet, "/api/assistant/models", bytes.NewBuffer(nil)) h.models(c) var unconfigured assistantModelCatalog if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &unconfigured) != nil || - unconfigured.Default != assistantDefaultModel || unconfigured.Models == nil || len(unconfigured.Models) != 0 { + unconfigured.Default != "" || unconfigured.Models == nil || len(unconfigured.Models) != 0 { t.Fatalf("unconfigured picker: %d %s", rec.Code, rec.Body) } } @@ -70,8 +71,9 @@ 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") - 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" { + ioa := loadAssistantModels(context.Background(), "ioa", "") + // The first listed model is the default; an unlisted one falls back to it. + if ioa.Default != "claude-sonnet-5" || assistantAllowedModel("claude-sonnet-5", ioa) != "claude-sonnet-5" || assistantAllowedModel("gpt-5.5", ioa) != "claude-sonnet-5" || assistantAllowedModel("claude-opus-5.5", ioa) != "claude-sonnet-5" { t.Fatalf("ioa catalog: %+v", ioa) } for range 2 { @@ -80,10 +82,40 @@ 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" { + if ioa = loadAssistantModels(context.Background(), "ioa", "user-key"); assistantAllowedModel("claude-opus-5.5", ioa) != "claude-opus-5.5" { t.Fatalf("account models must be listed: %+v", ioa) } - if intl := loadAssistantModels(context.Background(), ""); assistantAllowedModel("gpt-5.5", intl) != "gpt-5.5" { + if intl := loadAssistantModels(context.Background(), "", ""); assistantAllowedModel("gpt-5.5", intl) != "gpt-5.5" { t.Fatalf("international catalog: %+v", intl) } } + +func TestCodeBuddyImplicitModelStaysWithItsAccount(t *testing.T) { + t.Setenv("AGENTFLOW_ASSISTANT_MODEL", "") + t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "") + h, _ := workbenchFixture(t) + stubCLIModelDiscovery(t) + discoverCLIModels = func(_ context.Context, env, key string) []string { + return []string{key + "-first", "shared"} + } + ctx := context.Background() + // Load both accounts from a cold cache through the normal turn entry point. + for _, account := range []string{"a", "b"} { + user := domain.User{CodeBuddyAPIKey: account, CodeBuddyInternetEnvironment: "ioa"} + if got := h.turnCatalog(ctx, user, "").Default; got != account+"-first" { + t.Fatalf("cold account %s default %q", account, got) + } + } + for range 256 { + for _, account := range []string{"a", "b"} { + u := domain.User{CodeBuddyAPIKey: account, CodeBuddyInternetEnvironment: "ioa"} + catalog := h.chatCatalog(ctx, u) + if got := assistantAllowedUserModel(ctx, "", catalog, u); got != account+"-first" { + t.Fatalf("account %q defaulted to %q", account, got) + } + if len(catalog.Models) != 2 || catalog.Models[1].ID != "shared" { + t.Fatalf("account %q catalog = %+v", account, catalog.Models) + } + } + } +} diff --git a/internal/httpapi/assistant_native_session_test.go b/internal/httpapi/assistant_native_session_test.go index 787381330..b81feb48b 100644 --- a/internal/httpapi/assistant_native_session_test.go +++ b/internal/httpapi/assistant_native_session_test.go @@ -61,6 +61,10 @@ if [ "$1" = "--version" ]; then echo 2.185.0 exit 0 fi +if [ "$1" = "--help" ]; then + echo 'Currently supported: (fixture-model)' + exit 0 +fi previous='' config='' sid='' diff --git a/internal/httpapi/assistant_notification_report.go b/internal/httpapi/assistant_notification_report.go index aaf392101..7dc1f7ddd 100644 --- a/internal/httpapi/assistant_notification_report.go +++ b/internal/httpapi/assistant_notification_report.go @@ -16,8 +16,9 @@ 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) - if assistantAllowedModel(model, catalog) != model { + requested := domain.ChosenModel(model) + model = codeBuddyAccountModel(ctx, user, requested) + if model == "" || (requested != "" && model != requested) { return domain.AINotificationContent{}, notification.ErrReportModel } diff --git a/internal/httpapi/assistant_notification_report_test.go b/internal/httpapi/assistant_notification_report_test.go index dcb0a6152..59c309070 100644 --- a/internal/httpapi/assistant_notification_report_test.go +++ b/internal/httpapi/assistant_notification_report_test.go @@ -29,6 +29,7 @@ func activeReportSession(t *testing.T) *AgentToolSession { } func TestSOPReportUsesResponsibleUserAndMCPSubmission(t *testing.T) { + t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "glm-5.1") store, err := repo.OpenTest() if err != nil { t.Fatal(err) @@ -70,12 +71,12 @@ func TestSOPReportUsesResponsibleUserAndMCPSubmission(t *testing.T) { return "not a JSON result", context.Canceled // The committed tool result survives CLI cancellation. } run := domain.Run{ID: "run-report", ExecutionContext: domain.TelemetryContext{ResponsibleUserID: 42, ProjectID: "report-project"}} - report, err := h.generateSOPReport(context.Background(), run, domain.DefaultNotificationReportModel, "资料") + report, err := h.generateSOPReport(context.Background(), run, "", "资料") if err != nil || report.Body != "最终验证通过 [redacted]" || calls != 1 { t.Fatalf("report=%+v calls=%d err=%v", report, calls, err) } run.ExecutionContext.ResponsibleUserID = 99 - if _, err = h.generateSOPReport(context.Background(), run, domain.DefaultNotificationReportModel, "资料"); !errors.Is(err, notification.ErrReportCredentials) { + if _, err = h.generateSOPReport(context.Background(), run, "", "资料"); !errors.Is(err, notification.ErrReportCredentials) { t.Fatal("borrowed owner key") } command, err := prepareAssistantCommand(assistantCommandOpts{Bin: "codebuddy", Config: "{}", Prompt: "资料", ReportOnly: true, Native: true}) @@ -91,6 +92,7 @@ func TestSOPReportUsesResponsibleUserAndMCPSubmission(t *testing.T) { } func TestSOPReportMissingSubmissionRetriesWithoutParsingText(t *testing.T) { + t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "glm-5.1") store, _ := repo.OpenTest() defer store.Close() store.PutUser(domain.User{ID: 42, LoginName: "executor", CodeBuddyAPIKey: "key"}) @@ -100,7 +102,7 @@ func TestSOPReportMissingSubmissionRetriesWithoutParsingText(t *testing.T) { calls++ return "```notification\n{\"body\":\"looks valid\"}\n```", nil } - _, err := h.generateSOPReport(context.Background(), domain.Run{ExecutionContext: domain.TelemetryContext{ResponsibleUserID: 42}}, domain.DefaultNotificationReportModel, "资料") + _, err := h.generateSOPReport(context.Background(), domain.Run{ExecutionContext: domain.TelemetryContext{ResponsibleUserID: 42}}, "", "资料") if !errors.Is(err, notification.ErrReportFormat) || calls != nativeTerminalMaxRetries+1 { t.Fatalf("calls=%d err=%v", calls, err) } @@ -116,7 +118,7 @@ func TestSOPReportMissingSubmissionRetriesWithoutParsingText(t *testing.T) { _, err := gateway.callTool(ctx, session, args) return "", err } - report, err := h.generateSOPReport(context.Background(), domain.Run{ExecutionContext: domain.TelemetryContext{ResponsibleUserID: 42}}, domain.DefaultNotificationReportModel, "资料") + report, err := h.generateSOPReport(context.Background(), domain.Run{ExecutionContext: domain.TelemetryContext{ResponsibleUserID: 42}}, "", "资料") if err != nil || calls != 2 || report.Body != "补交成功" { t.Fatalf("repair report=%+v calls=%d err=%v", report, calls, err) } diff --git a/internal/httpapi/assistant_process.go b/internal/httpapi/assistant_process.go index ea9221587..6134f69d6 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 = loadAssistantModels(ctx, user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey).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 801bde442..43c84ee29 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(context.Background(), user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey)) } else { req.Model = strings.TrimSpace(req.Model) if len(req.Model) > 256 || strings.ContainsAny(req.Model, "\r\n\x00") { @@ -131,7 +131,7 @@ func prepareAlternateAssistantCommand(ctx context.Context, req assistantCLIReque } else { args = []string{"-p", "--bare", "--output-format", "stream-json", "--verbose", "--include-partial-messages", "--max-turns", nativeAssistantUnlimitedTurns, "--system-prompt", sys, "--tools", "", "--mcp-config", req.MCPConfig, "--strict-mcp-config", "--setting-sources", "", "--permission-mode", "dontAsk", "--allowedTools", "mcp__agentflow_session__*", "--no-session-persistence"} } - if req.Model != "" && req.Model != "default" { + if req.Model != "" { args = append(args, "--model", req.Model) } args = append([]string{bin}, append(args, req.Prompt)...) diff --git a/internal/httpapi/assistant_schedule.go b/internal/httpapi/assistant_schedule.go index dcfe18731..b37f03dc2 100644 --- a/internal/httpapi/assistant_schedule.go +++ b/internal/httpapi/assistant_schedule.go @@ -106,7 +106,7 @@ func (h *assistantHandlers) runScheduleJobPromptResult(job domain.ScheduleJob, o if shared != nil { // On the shared key a run only uses the models the administrator // allows, and never silently switches to another one. - allowed, ok := assistantSponsoredModelFor(shared, scheduleSharedRequestedModel(model)) + allowed, ok := assistantSponsoredModelFor(shared, model) if !ok { return result, fmt.Errorf("定时任务使用平台共享 Key 执行,只能用平台管理员允许的模型(%s),任务指定的 %s 不在其中,本次没有运行;请在定时任务里改选允许的模型,或在个人配置中填写自己的 Key", strings.Join(shared, "、"), model) } diff --git a/internal/httpapi/assistant_sponsor.go b/internal/httpapi/assistant_sponsor.go index 7bf677115..153c08905 100644 --- a/internal/httpapi/assistant_sponsor.go +++ b/internal/httpapi/assistant_sponsor.go @@ -52,7 +52,7 @@ func (h *assistantHandlers) assistantChatUser(user domain.User) (chatUser domain // assistantSponsoredModelFor limits shared-key turns to the allowed models. // An empty request picks the default; any other model is refused. func assistantSponsoredModelFor(shared []string, requested string) (string, bool) { - return repo.SharedCodeBuddyKey{Models: shared}.Model(requested) + return repo.SharedCodeBuddyKey{Models: shared}.Model(domain.ChosenModel(requested)) } // usesSharedKey reports whether a chat turn for user runs on the shared key: @@ -72,24 +72,24 @@ func (h *assistantHandlers) usesSharedKey(user domain.User) bool { func (h *assistantHandlers) chatCatalog(ctx context.Context, user domain.User) assistantModelCatalog { key, shared := h.assistantSharedKey() if !shared || !h.usesSharedKey(user) { - return withCodeBuddyPersonalModels(assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, nil), user) + return withCodeBuddyPersonalModels(assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey, nil), user) } - return restrictAssistantCatalog(assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, key.Models), key.Models) + return restrictAssistantCatalog(assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey, key.Models), key.Models) } // turnCatalog is chatCatalog for a turn on model. The CodeBuddy model list is // cached in memory per instance, so a model picked from another instance's -// list, or before a restart, would otherwise be replaced by the default -// without a word. A miss refreshes the list once before deciding. +// list, or before a restart, would otherwise be replaced by the first listed +// model 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) - model = strings.TrimSpace(model) - if model == "" || assistantCatalogLists(catalog, model) { + model = domain.ChosenModel(model) + if (model == "" && catalog.Default != "") || assistantCatalogLists(catalog, model) { return catalog } refreshCLIModels(ctx, user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey) catalog = h.chatCatalog(ctx, user) - if !assistantCatalogLists(catalog, model) { + if model != "" && !assistantCatalogLists(catalog, model) { log.Printf("assistant model %q is not offered to user %d after catalog refresh", model, user.ID) } return catalog diff --git a/internal/httpapi/assistant_sponsor_test.go b/internal/httpapi/assistant_sponsor_test.go index a460801c6..2e7a42a34 100644 --- a/internal/httpapi/assistant_sponsor_test.go +++ b/internal/httpapi/assistant_sponsor_test.go @@ -181,7 +181,8 @@ func TestOwnKeyKeepsItsEnvironmentDefaultWhileAKeyIsShared(t *testing.T) { used = u return `{"message":"ok","drafts":[]}`, nil }} - operatorDefault := assistantFixedCatalog().Default + // The first model of the user's own environment, not the shared key's. + operatorDefault := "claude-opus-5" var catalog assistantModelCatalog mrec := httptest.NewRecorder() @@ -340,7 +341,8 @@ func TestAssistantModelsPerExecutor(t *testing.T) { } for executor, family := range map[string]string{"codex": "gpt", "claude": "claude", "claude-code": "claude"} { rec, catalog := get(executor) - if rec.Code != 200 || len(catalog.Models) < 2 || catalog.Default != catalog.Models[0].ID { + // No CLI-default entry: the first listed model is the default. + if rec.Code != 200 || len(catalog.Models) == 0 || catalog.Default != catalog.Models[0].ID || strings.Contains(rec.Body.String(), `"id":"default"`) { t.Fatalf("%s catalog: %d %s", executor, rec.Code, rec.Body.String()) } for _, model := range catalog.Models { @@ -408,8 +410,8 @@ func TestChatCatalogsListTheDefaultFirst(t *testing.T) { 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": assistantChatCatalog(ctx, "", "", nil), + "shared key": restrictAssistantCatalog(assistantChatCatalog(ctx, "", "", 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_steer_test.go b/internal/httpapi/assistant_steer_test.go index 8eef04945..b9a5a714b 100644 --- a/internal/httpapi/assistant_steer_test.go +++ b/internal/httpapi/assistant_steer_test.go @@ -272,6 +272,7 @@ func TestCommitTurnTranscriptKeepsSameSteerOnce(t *testing.T) { } func TestSteerKeepsConversationCLI(t *testing.T) { + t.Setenv("AGENTFLOW_ASSISTANT_MODEL", "test-codebuddy") for _, tc := range []struct { name, executor, savedModel, requested, wantModel string runnerLogin, missingKey bool @@ -285,7 +286,7 @@ func TestSteerKeepsConversationCLI(t *testing.T) { {"cursor prefixed", "cursor", "cursor:old", "cursor:selected", "cursor:selected", false, false, 200}, {"cursor unprefixed", "cursor", "cursor:old", "selected", "cursor:selected", false, false, 200}, {"cursor legacy", "cursor", "old", "selected", "cursor:selected", false, false, 200}, - {"codebuddy", "codebuddy", "default", "default", "default", false, false, 200}, + {"codebuddy", "codebuddy", "default", "default", "test-codebuddy", false, false, 200}, {"codex missing key", "codex", "codex:gpt-old", "gpt-selected", "", false, true, 400}, {"cursor missing key", "cursor", "cursor:old", "selected", "", false, true, 400}, {"codex to cursor", "codex", "codex:gpt-old", "cursor:selected", "", true, false, 409}, diff --git a/internal/httpapi/assistant_task_engines_test.go b/internal/httpapi/assistant_task_engines_test.go index 353be25b9..8fd14f29e 100644 --- a/internal/httpapi/assistant_task_engines_test.go +++ b/internal/httpapi/assistant_task_engines_test.go @@ -54,8 +54,12 @@ func TestScheduledRunModelRefreshesAndNeverFallsBack(t *testing.T) { if got, err := scheduledRunModel(context.Background(), "deepseek-v4.1-flash", owner); err != nil || got != "deepseek-v4.1-flash" { t.Fatalf("model = %q, %v", got, err) } - if got, err := scheduledRunModel(context.Background(), "", owner); err != nil || got != assistantFixedCatalog().Default { - t.Fatalf("empty model = %q, %v", got, err) + // No model, or the retired "default" placeholder, runs on the first + // model the owner's account lists. + for _, requested := range []string{"", "default"} { + if got, err := scheduledRunModel(context.Background(), requested, owner); err != nil || got != "deepseek-v4.1-flash" { + t.Fatalf("%q model = %q, %v", requested, 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) @@ -161,6 +165,7 @@ func joinScheduledProject(t *testing.T, st *repo.Store, projectID string, userID // A scheduled run is an ordinary chat turn: a live generation the page can // follow, a transcript saved by chat, and the scheduled session's metadata. func TestScheduledTaskRunsAsChatTurn(t *testing.T) { + t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "glm-5.1") st := cvAStore(t) _ = st.PutProject(domain.Project{ID: "turn-project", Name: "Turn"}) _ = st.PutUser(domain.User{LoginName: "turn-user", CodeBuddyAPIKey: "secret"}) diff --git a/internal/httpapi/assistant_tasks.go b/internal/httpapi/assistant_tasks.go index da88e359e..b6d3064de 100644 --- a/internal/httpapi/assistant_tasks.go +++ b/internal/httpapi/assistant_tasks.go @@ -494,16 +494,17 @@ 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) - model := assistantAllowedUserModel(requested, catalog, user) - if requested == "" || model == requested { - return model, nil - } - if engine, _ := assistantModelEngine(requested); engine == assistantEngineCodeBuddy { + catalog := withCodeBuddyPersonalModels(loadAssistantModels(ctx, env, user.CodeBuddyAPIKey), user) + model := assistantAllowedUserModel(ctx, requested, catalog, user) + engine, chosen := assistantModelEngine(requested) + implicit := domain.ChosenModel(chosen) == "" + if engine == assistantEngineCodeBuddy && ((implicit && model == "") || (!implicit && model != requested)) { refreshCLIModels(ctx, env, user.CodeBuddyAPIKey) - if model = assistantAllowedUserModel(requested, loadAssistantModels(ctx, env), user); model == requested { - return model, nil - } + catalog = withCodeBuddyPersonalModels(loadAssistantModels(ctx, env, user.CodeBuddyAPIKey), user) + model = assistantAllowedUserModel(ctx, requested, catalog, user) + } + if implicit || model == requested { + return model, nil } return "", fmt.Errorf("定时任务指定的模型 %s 在负责人的账号下不可用,本次没有运行;请在定时任务里改选可用的模型", requested) } diff --git a/internal/httpapi/assistant_test.go b/internal/httpapi/assistant_test.go index 5f8b31789..8dc4798e3 100644 --- a/internal/httpapi/assistant_test.go +++ b/internal/httpapi/assistant_test.go @@ -357,10 +357,12 @@ func TestAssistantFixedCatalog(t *testing.T) { if assistantAllowedModel("unknown", got) != "public-model" || assistantAllowedModel("other-model", got) != "other-model" { t.Fatal("model selection") } - t.Setenv("AGENTFLOW_ASSISTANT_MODEL", "") + // No CLI-default entry: without configured models the list is empty, + // and the retired "default" placeholder is not listed. + t.Setenv("AGENTFLOW_ASSISTANT_MODEL", "default") t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "") - if got := assistantFixedCatalog(); got.Default != "default" || len(got.Models) != 1 { - t.Fatalf("default catalog: %+v", got) + if got := assistantFixedCatalog(); got.Default != "" || len(got.Models) != 0 { + t.Fatalf("unconfigured catalog: %+v", got) } } diff --git a/internal/httpapi/assistant_title.go b/internal/httpapi/assistant_title.go index 3c114da9b..c98e3a30f 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(ctx, user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey, nil) if len(shared) > 0 { - catalog = restrictAssistantCatalog(assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, shared), shared) + catalog = restrictAssistantCatalog(assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey, shared), shared) } if chosen := assistantApprovalReviewModel(catalog); chosen != "" { return chosen, "" diff --git a/internal/httpapi/assistant_title_test.go b/internal/httpapi/assistant_title_test.go index 181f15b67..4c7ca5668 100644 --- a/internal/httpapi/assistant_title_test.go +++ b/internal/httpapi/assistant_title_test.go @@ -75,7 +75,8 @@ func TestAssistantTitleModelReusesSessionModelOnOtherCLIs(t *testing.T) { if model, effort := assistantTitleModel(context.Background(), domain.User{}, assistantChatDefaultModel, []string{assistantSponsoredModel}); model != assistantSponsoredModel || effort != "" { t.Fatalf("sponsored CodeBuddy title = %q/%q", model, effort) } - if model, effort := assistantTitleModel(context.Background(), domain.User{}, assistantChatDefaultModel, nil); model == "" || effort != "" { + t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "glm-5.1") + if model, effort := assistantTitleModel(context.Background(), domain.User{}, assistantChatDefaultModel, nil); model != "glm-5.1" || effort != "" { t.Fatalf("CodeBuddy title without prices = %q/%q", model, effort) } } diff --git a/internal/httpapi/assistant_usage_test.go b/internal/httpapi/assistant_usage_test.go index 9702d7301..a505fae87 100644 --- a/internal/httpapi/assistant_usage_test.go +++ b/internal/httpapi/assistant_usage_test.go @@ -65,6 +65,7 @@ func generateWithFakeCLI(t *testing.T, script string) (assistantMessage, []byte) t.Fatal(err) } t.Setenv("AGENTFLOW_CODEBUDDY_BIN", bin) + t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "glm-5.1") sid := "usage-" + filepath.Base(t.TempDir()) body, _ := json.Marshal(assistantRequest{SessionID: sid, ProjectID: "workbench", Messages: []assistantMessage{{Role: "user", Content: "检查文件"}}}) c, rec := workbenchContext(user, "POST", "/api/assistant/generations", bytes.NewBuffer(body)) diff --git a/internal/httpapi/bot_interactions.go b/internal/httpapi/bot_interactions.go index c48d0b066..8240e37a3 100644 --- a/internal/httpapi/bot_interactions.go +++ b/internal/httpapi/bot_interactions.go @@ -74,11 +74,12 @@ func (h *assistantHandlers) generateBotReply(ctx context.Context, bot domain.Not if strings.TrimSpace(user.CodeBuddyAPIKey) == "" { return "你的平台账号尚未配置 CodeBuddy Key,请在平台个人配置中配置。", nil } - model := bot.Model + catalog := loadAssistantModels(ctx, user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey) + model := domain.ChosenModel(bot.Model) if model == "" { - model = domain.DefaultNotificationReportModel + model = catalog.Default } - if assistantAllowedModel(model, loadAssistantModels(ctx, user.CodeBuddyInternetEnvironment)) != model { + if model == "" || assistantAllowedModel(model, catalog) != 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 21136cb33..3dd933ffe 100644 --- a/internal/httpapi/bot_interactions_test.go +++ b/internal/httpapi/bot_interactions_test.go @@ -23,7 +23,7 @@ func botFixture(t *testing.T) (*repo.Store, *assistantHandlers, domain.Notificat s.PutUser(domain.User{ID: 42, LoginName: "bot-owner", CodeBuddyAPIKey: "owner-key", CodeBuddyInternetEnvironment: "ioa"}) s.PutUser(domain.User{ID: 43, LoginName: "other-user", CodeBuddyAPIKey: "other-key", CodeBuddyInternetEnvironment: "ioa"}) s.PutProject(domain.Project{ID: "p", OwnerID: 42, Members: []domain.ProjectMember{{UserID: 43, Role: "member"}}}) - bot := domain.NotificationBot{ID: "b", BotID: "external", ProjectID: "p", OwnerID: 42, Enabled: true, InteractionEnabled: true, Model: domain.DefaultNotificationReportModel} + bot := domain.NotificationBot{ID: "b", BotID: "external", ProjectID: "p", OwnerID: 42, Enabled: true, InteractionEnabled: true} if err = s.SaveNotificationBot(bot, "secret"); err != nil { t.Fatal(err) } @@ -38,6 +38,7 @@ func botFixture(t *testing.T) (*repo.Store, *assistantHandlers, domain.Notificat return s, h, bot } func TestBotUsesBoundSenderIdentityAutoModeAndSharedChatContext(t *testing.T) { + t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "glm-5.1") 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" { @@ -127,6 +128,7 @@ func TestBotTerminalRetryCannotRepeatCachedWriteTool(t *testing.T) { } func TestBotMissingSubmissionRetriesOnlyTerminalStep(t *testing.T) { + t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "glm-5.1") _, h, bot := botFixture(t) calls := 0 h.generate = func(ctx context.Context, prompt string, user domain.User) (string, error) { diff --git a/internal/httpapi/bot_reply_messages_limits_test.go b/internal/httpapi/bot_reply_messages_limits_test.go index 30d9deddb..78cb2c2eb 100644 --- a/internal/httpapi/bot_reply_messages_limits_test.go +++ b/internal/httpapi/bot_reply_messages_limits_test.go @@ -56,6 +56,7 @@ func TestBotReplyMessagesKeepsCurrentMessageAndQuoteInFull(t *testing.T) { // generateBotReply must use the filtered history: binding links and unbind // exchanges never reach the model prompt, ordinary history still does. func TestGenerateBotReplyOmitsBindingExchangesFromPrompt(t *testing.T) { + t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "glm-5.1") _, h, bot := botFixture(t) var prompt string h.generate = func(ctx context.Context, p string, user domain.User) (string, error) { diff --git a/internal/httpapi/catalog.go b/internal/httpapi/catalog.go index 54fd64141..a55170067 100644 --- a/internal/httpapi/catalog.go +++ b/internal/httpapi/catalog.go @@ -1080,7 +1080,7 @@ func (h *catalogHandlers) workflows(c *gin.Context) { if _, ok := h.requireWorkflowSandbox(c, v); !ok { return } - v, err := domain.AttachPreviewBuild(v) + v, err := h.attachPreviewBuild(c, v) if err != nil { c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()}) return @@ -1097,7 +1097,7 @@ func (h *catalogHandlers) workflows(c *gin.Context) { c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()}) return } - v, err := domain.AttachPreviewBuild(v) + v, err := h.attachPreviewBuild(c, v) if err != nil { c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()}) return @@ -1380,3 +1380,20 @@ func workflowHasNotifications(workflow domain.WorkflowDefinition) bool { } return false } + +// attachPreviewBuild adds the preview build node. A preview without a model +// is saved on the first CodeBuddy model listed, so the build does not leave +// the model to the CLI. +func (h *catalogHandlers) attachPreviewBuild(c *gin.Context, v domain.WorkflowDefinition) (domain.WorkflowDefinition, error) { + if v.Preview != nil && v.Preview.Enabled && v.Preview.ChosenModel() == "" { + preview := *v.Preview + preview.Model = assistantFixedCatalog().Default + if current, ok := h.requestUser(c.Request, true); ok { + if user, found := h.repo.User(current.ID); found { + preview.Model = codeBuddyAccountModel(c.Request.Context(), user, "") + } + } + v.Preview = &preview + } + return domain.AttachPreviewBuild(v) +} diff --git a/internal/httpapi/clarify_mcp.go b/internal/httpapi/clarify_mcp.go index 59110f6b7..907b1e33f 100644 --- a/internal/httpapi/clarify_mcp.go +++ b/internal/httpapi/clarify_mcp.go @@ -14,19 +14,11 @@ import ( "agentflow/internal/tracker" ) -const ( - clarifyDefaultModel = assistantDefaultModel -) - var ( tapdURLRe = regexp.MustCompile(`(?i)https?://(?:www\.)?(?:tapd\.example\.com|tapd\.cn)[^\s<>"')】\]]+`) gongfengIssueURLRe = regexp.MustCompile(`(?i)https?://git\.example\.com/[^\s<>"')】\]]+/issues/\d+`) ) -func clarifyAllowedModel(id string) string { - return assistantAllowedModel(id, assistantKnownCatalog()) -} - // errClarifyNeedsCodeBuddy is returned when a clarification asks for a model of // another CLI: clarification runs on CodeBuddy only, so a "codex:…" id must be // refused instead of being swapped for the CodeBuddy default. diff --git a/internal/httpapi/clarify_mcp_test.go b/internal/httpapi/clarify_mcp_test.go index b307692de..8065d6712 100644 --- a/internal/httpapi/clarify_mcp_test.go +++ b/internal/httpapi/clarify_mcp_test.go @@ -14,20 +14,22 @@ import ( ) func TestClarifyAllowedModelFallsBackToCatalog(t *testing.T) { - 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) + stubCLIModelDiscovery(t) + t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "first-model,public-model") + // No model, an unknown one and the retired "default" placeholder all + // run on the first listed model. + for _, requested := range []string{"", "not-a-model", "default"} { + if got := codeBuddyAccountModel(t.Context(), domain.User{}, requested); got != "first-model" { + t.Fatalf("%q = %q", requested, got) + } } - if got := clarifyAllowedModel("public-model"); got != "public-model" { + if got := codeBuddyAccountModel(t.Context(), domain.User{}, "public-model"); got != "public-model" { t.Fatalf("listed model = %q", got) } } func TestClarifyCommandKeepsReadGrepGlob(t *testing.T) { - command, err := prepareClarifyCommand("codebuddy", clarifyDefaultModel, "prompt", "clarify-test", "af1", false) + command, err := prepareClarifyCommand("codebuddy", clarifyTestModel, "prompt", "clarify-test", "af1", false) if err != nil { t.Fatal(err) } @@ -48,7 +50,7 @@ func TestClarifyCommandKeepsReadGrepGlob(t *testing.T) { if arg == "--no-session-persistence" { foundNoPersist = true } - if arg == "--model" && i+1 < len(command.Argv) && command.Argv[i+1] != clarifyDefaultModel { + if arg == "--model" && i+1 < len(command.Argv) && command.Argv[i+1] != clarifyTestModel { t.Fatalf("model = %q", command.Argv[i+1]) } } @@ -65,7 +67,7 @@ func TestClarifyCommandKeepsReadGrepGlob(t *testing.T) { func TestPrepareClarifyCommandSubmitOnlyDisallowsRead(t *testing.T) { command, err := prepareClarifyCommandWith(clarifyCommandOpts{ - Bin: "codebuddy", Model: clarifyDefaultModel, Prompt: "submit", RunID: "clarify-test", SessionID: "af1", + Bin: "codebuddy", Model: clarifyTestModel, Prompt: "submit", RunID: "clarify-test", SessionID: "af1", Native: true, SubmitOnly: true, }) if err != nil { @@ -78,7 +80,7 @@ func TestPrepareClarifyCommandSubmitOnlyDisallowsRead(t *testing.T) { } func TestPrepareClarifyCommandResumeUsesResumeFlag(t *testing.T) { - command, err := prepareClarifyCommand("codebuddy", clarifyDefaultModel, "继续", "clarify-test", "af1", true) + command, err := prepareClarifyCommand("codebuddy", clarifyTestModel, "继续", "clarify-test", "af1", true) if err != nil { t.Fatal(err) } @@ -384,3 +386,5 @@ func TestDispatchClarifyMCPCallReadOnlyTAPD(t *testing.T) { t.Fatalf("write should be rejected: %v", err) } } + +const clarifyTestModel = "glm-5.1" diff --git a/internal/httpapi/clarify_session_test.go b/internal/httpapi/clarify_session_test.go index 7b291d8c7..be92bbbfe 100644 --- a/internal/httpapi/clarify_session_test.go +++ b/internal/httpapi/clarify_session_test.go @@ -179,6 +179,7 @@ func TestRunClarifyTurnDetectsMissingSessionWithZeroExitCode(t *testing.T) { } func TestExecuteClarifyRebuildsSessionFromHistory(t *testing.T) { + stubCLIModelDiscovery(t) for _, tc := range []struct { name string owner int64 diff --git a/internal/httpapi/executor_models.go b/internal/httpapi/executor_models.go index c96344a3c..ee87975b0 100644 --- a/internal/httpapi/executor_models.go +++ b/internal/httpapi/executor_models.go @@ -128,15 +128,14 @@ func effortOptions(levels []string) []executorEffortOption { // 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 { +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("", assistantFixedCatalog())) 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(c.Request.Context(), user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey)) if antigravityUsesCustomEndpoint(user) { catalog := catalogs[runtime.AgentCLIAntigravity] catalog.Models = []executorModelInfo{} @@ -264,6 +263,7 @@ func (h *catalogHandlers) executorModels(c *gin.Context) { }) } if len(catalog.Models) > 0 { + catalog.Default = catalog.Models[0].ID catalogs[id] = catalog } } diff --git a/internal/httpapi/notifications.go b/internal/httpapi/notifications.go index e11d1df85..f1a8173ce 100644 --- a/internal/httpapi/notifications.go +++ b/internal/httpapi/notifications.go @@ -153,19 +153,15 @@ func (h *notificationHandlers) save(c *gin.Context, old *domain.NotificationBot) bot.InteractionEnabled = *req.InteractionEnabled } if req.Model != nil { - model := strings.TrimSpace(*req.Model) - if model == "" { - model = domain.DefaultNotificationReportModel - } - if assistantAllowedModel(model, assistantKnownCatalog()) != model { + // No model reports on the first listed model when the report runs. + model := domain.ChosenModel(*req.Model) + if model != "" && assistantAllowedModel(model, assistantKnownCatalog()) != model { c.JSON(400, gin.H{"error": "请选择有效的 CodeBuddy 模型"}) return } bot.Model = model } - if bot.Model == "" { - bot.Model = domain.DefaultNotificationReportModel - } + bot.Model = domain.ChosenModel(bot.Model) if !h.access(c, bot.ProjectID, true) { return } diff --git a/internal/httpapi/notifications_test.go b/internal/httpapi/notifications_test.go index a8c187191..53c5244cb 100644 --- a/internal/httpapi/notifications_test.go +++ b/internal/httpapi/notifications_test.go @@ -91,8 +91,8 @@ func TestNotificationBotAPIAuthBindingAndSecrets(t *testing.T) { if err = json.Unmarshal(rsp.Body.Bytes(), &bot); err != nil { t.Fatal(err) } - if bot.Model != domain.DefaultNotificationReportModel { - t.Fatal("missing default Bot model") + if bot.Model != "" { + t.Fatalf("a Bot without a model saved %q", bot.Model) } storedSecret, err := s.BotCredential(bot.ID) if err != nil || storedSecret != "super-secret" { diff --git a/internal/httpapi/platform_settings.go b/internal/httpapi/platform_settings.go index cf7e2fc7d..f28b548b7 100644 --- a/internal/httpapi/platform_settings.go +++ b/internal/httpapi/platform_settings.go @@ -204,11 +204,12 @@ func (h *usersHandlers) platformCodeBuddyKey(c *gin.Context) { environment = normalized } apiKey := "" + var saved []string if key, ok := h.repo.SharedCodeBuddyKey(); ok && key.SponsorID == 0 && key.InternetEnvironment == environment { - apiKey = key.APIKey + apiKey, saved = key.APIKey, key.Models } refreshCLIModels(c.Request.Context(), environment, apiKey) - catalog := loadAssistantModels(c.Request.Context(), environment).Models + catalog := selectableCodeBuddyModels(assistantChatCatalog(c.Request.Context(), environment, apiKey, saved).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 56d6aa3d6..1caf17d4c 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 := loadAssistantModels(c.Request.Context(), user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey) 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 e6129670d..158827eb6 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, loadAssistantModels(c.Request.Context(), "", "")) } if job.ProjectID == "" { job.ProjectID = "platform" @@ -277,7 +277,7 @@ func (h *scheduleHandlers) bindScheduleRunAs(c *gin.Context, job *domain.Schedul return false } if shared != nil { - model, allowed := assistantSponsoredModelFor(shared, scheduleSharedRequestedModel(requestedModel)) + model, allowed := assistantSponsoredModelFor(shared, requestedModel) if !allowed { if stopOnly() { return false @@ -312,15 +312,6 @@ func scheduleRunConfigUnchanged(prior, job domain.ScheduleJob) bool { maps.Equal(prior.ParameterValues, job.ParameterValues) } -// scheduleSharedRequestedModel treats the CLI-default placeholder as "no -// model chosen", which the shared key resolves to its own default. -func scheduleSharedRequestedModel(model string) string { - if model = strings.TrimSpace(model); model == assistantDefaultModel { - return "" - } - return model -} - func scheduleMissingKeyError(engine string) string { if assistantSupportsRunnerLogin(engine) { return fmt.Sprintf("你还没有可用的 %s 凭据,请在默认执行机器启用账号登录(Runner %s 及以上),或在个人配置填写 API Key", assistantEngineLabel(engine), domain.RunnerVersionCLISettings) diff --git a/internal/httpapi/schedule_runner_login_test.go b/internal/httpapi/schedule_runner_login_test.go index 895086b44..1008ed14d 100644 --- a/internal/httpapi/schedule_runner_login_test.go +++ b/internal/httpapi/schedule_runner_login_test.go @@ -29,6 +29,9 @@ func testScheduleJobUsesSaversDefaultRunnerLogin(t *testing.T, cliEngine string) t.Setenv("TMPDIR", t.TempDir()) t.Setenv("AGENTFLOW_AUTH_REQUIRED", "true") t.Setenv("AGENTFLOW_SESSION_SECRET", "schedule-runner-login-test") + // The test drives each run explicitly and controls the runner connection. + t.Setenv("AGENTFLOW_SCHEDULER_ENABLED", "false") + stubCLIModelDiscovery(t) h, owner := workbenchFixture(t) st := h.repo if err := st.PutUser(domain.User{LoginName: "schedule-runner-saver"}); err != nil { @@ -144,7 +147,10 @@ func testScheduleJobUsesSaversDefaultRunnerLogin(t *testing.T, cliEngine string) sessions := st.ListAssistantSessionsByTask(domain.AssistantSourceScheduled, saved.ID) if len(sessions) != 1 || sessions[0].UserID != saver.ID || sessions[0].Execution().RunnerID != machine.ID || !sessions[0].ExecutionLocked() { - t.Fatal("scheduled session did not retain the saver and their machine") + if len(sessions) != 1 { + t.Fatalf("expected one scheduled runner session, got %d", len(sessions)) + } + t.Fatalf("scheduled runner session owner=%d target=%v locked=%t, want owner=%d runner=%s", sessions[0].UserID, sessions[0].Execution(), sessions[0].ExecutionLocked(), saver.ID, machine.ID) } machine.Status = domain.RunnerStatusOffline if err := st.PutRunner(machine); err != nil { @@ -168,9 +174,11 @@ func testScheduleJobUsesSaversDefaultRunnerLogin(t *testing.T, cliEngine string) t.Fatalf("offline runner without a key = %v, attempts = %d", err, keyAttempts) } - update := repo.UserCredentialUpdate{ClaudeCodeAPIKey: saverKey} + savedModels := []domain.CLIModel{{ID: "sonnet"}} + update := repo.UserCredentialUpdate{ClaudeCodeAPIKey: saverKey, ClaudeCodeModels: &savedModels} if cliEngine == runtime.AgentCLIAntigravity { - update = repo.UserCredentialUpdate{AgentCLICredentials: map[string]repo.AgentCLICredentialUpdate{cliEngine: {APIKey: saverKey}}} + savedModels = []domain.CLIModel{{ID: "gemini-4-hydrogen-high"}} + update = repo.UserCredentialUpdate{AgentCLICredentials: map[string]repo.AgentCLICredentialUpdate{cliEngine: {APIKey: saverKey, Models: &savedModels}}} } if _, err := st.UpdateUserCredentials(saver.ID, update); err != nil { t.Fatal(err) @@ -184,8 +192,8 @@ func testScheduleJobUsesSaversDefaultRunnerLogin(t *testing.T, cliEngine string) sessions = st.ListAssistantSessionsByTask(domain.AssistantSourceScheduled, saved.ID) cloud := slices.IndexFunc(sessions, func(s domain.AssistantSession) bool { return s.ID != runnerSession }) if len(sessions) != 2 || cloud < 0 || sessions[cloud].UserID != saver.ID || - sessions[cloud].Execution().Pool != domain.ExecutionModeCloud || sessions[cloud].Model != saved.AssistantModel { - t.Fatal("offline fallback did not run the same model and user in the cloud") + sessions[cloud].Execution().Pool != domain.ExecutionModeCloud || sessions[cloud].Model != cliEngine+":"+savedModels[0].ID { + t.Fatalf("expected two sessions and a cloud session using %s:%s for user %d, got %d sessions (cloud index %d)", cliEngine, savedModels[0].ID, saver.ID, len(sessions), cloud) } keyError = assistantCredentialError{engine: cliEngine} diff --git a/internal/httpapi/stream.go b/internal/httpapi/stream.go index fabb88383..f198df637 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 := codeBuddyAccountModel(ctx, 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), diff --git a/internal/notification/report_test.go b/internal/notification/report_test.go index ad4aedb8f..a4bf56e78 100644 --- a/internal/notification/report_test.go +++ b/internal/notification/report_test.go @@ -25,7 +25,7 @@ func TestIndependentReportFrozenAcrossSendRetries(t *testing.T) { if err := svc.Store.PutRun(run); err != nil { t.Fatal(err) } - bot.Model = domain.DefaultNotificationReportModel + bot.Model = "" if err := svc.Store.SaveNotificationBot(bot, ""); err != nil { t.Fatal(err) } diff --git a/internal/notification/service_test.go b/internal/notification/service_test.go index 50cdd3e1c..712829008 100644 --- a/internal/notification/service_test.go +++ b/internal/notification/service_test.go @@ -224,7 +224,7 @@ func TestSOPCompletionSendsOnceAfterAllNodeEvents(t *testing.T) { } svc.GenerateReport = func(_ context.Context, actual domain.Run, model, prompt string) (domain.AINotificationContent, error) { calls++ - if actual.ID != "sop-report" || model != domain.DefaultNotificationReportModel || !strings.Contains(prompt, "校验通过") { + if actual.ID != "sop-report" || model != "" || !strings.Contains(prompt, "校验通过") { t.Fatal("missing report input") } return domain.AINotificationContent{Title: "需求已完成", Body: "已实现功能,校验通过"}, nil diff --git a/internal/repo/notifications.go b/internal/repo/notifications.go index 78d519f99..178966612 100644 --- a/internal/repo/notifications.go +++ b/internal/repo/notifications.go @@ -339,10 +339,7 @@ func (r *NotificationsRepo) enqueueNotification(tx *gorm.DB, key string, binding } item.ReportRequest = string(request) item.ReportState = "pending" - item.ReportModel = bot.Model - if item.ReportModel == "" { - item.ReportModel = domain.DefaultNotificationReportModel - } + item.ReportModel = domain.ChosenModel(bot.Model) } item.CreatedAt = time.Now().UTC() item.NextAttemptAt = item.CreatedAt diff --git a/internal/runtime/agent_cli_zcode.go b/internal/runtime/agent_cli_zcode.go index 2fccfcc58..09393ed33 100644 --- a/internal/runtime/agent_cli_zcode.go +++ b/internal/runtime/agent_cli_zcode.go @@ -74,10 +74,10 @@ func nonEmpty(value any) bool { // exists only until ZCode has read it: ZCode accepts a literal key and // nothing else, and the key must not stay on disk. func applyZCodeCredential(home AgentCLIHome, homeEnv, key, baseURL, protocol, model, effort string, argv []string) ([]string, map[string]string, error) { - // The private provider has no model of its own, so "CLI default" (sent as - // "default") must name a real one: BigModel's coding model on the default - // endpoint, while a custom endpoint has no model we could guess. - if model == "" || model == "default" { + // The private provider has no model of its own, so a role without a model + // must name a real one: BigModel's coding model on the default endpoint, + // while a custom endpoint has no model we could guess. + if model = domain.ChosenModel(model); model == "" { if baseURL != "" { return nil, nil, fmt.Errorf("%s 需要指定模型", AgentCLILabel(AgentCLIZCode)) } diff --git a/internal/runtime/provider.go b/internal/runtime/provider.go index 76b1e59fa..23fea94f1 100644 --- a/internal/runtime/provider.go +++ b/internal/runtime/provider.go @@ -196,9 +196,7 @@ func ProviderRequirements(kind string) SandboxRequirements { // PrepareProviderCommand exposes the same provider flag and credential-binding // policy to control-plane call sites that do not run a workflow node. func PrepareProviderCommand(executor domain.ExecutorDefinition, prompt, driver string, options InvocationOptions) (CommandSpec, error) { - if executor.Model == "default" { - executor.Model = "" - } + executor.Model = domain.ChosenModel(executor.Model) return providerForKind(executor.Kind).Prepare(providerInvocation{ Executor: executor, Prompt: prompt, diff --git a/web/app/agents.js b/web/app/agents.js index aa9b56d4b..400881781 100644 --- a/web/app/agents.js +++ b/web/app/agents.js @@ -162,6 +162,9 @@ function paintAgentPicker(pickerId,item){ const label=toggle?.querySelector('[data-model-label]'); if(toggle&&label&&label.scrollWidth<=label.clientWidth){toggle.removeAttribute('title');toggle.removeAttribute('data-hui-title')} } +// A role starts on the first model its CLI lists; there is no CLI-default +// choice. +function agentFirstModel(executorId){return (executorModelCatalogs()[executorId]?.models||[])[0]?.id||''} function renderAgentModelPicker(){ const picker=$('#agentModelPicker');if(!picker)return; const current=picker.querySelector('[name="modelChoice"]').value; @@ -199,9 +202,10 @@ function renderAgentEffortPicker(modelChanged=false){ function applyAgentModelUI(executorId,model,effort,pickFirst=false){ const picker=$('#agentModelPicker');if(!picker||!$('#agentEffortPicker'))return; const cat=executorModelCatalogs()[executorId]||{}; - // Keep cached models available for manual picks while the catalog refreshes. - let choice=model||(pickFirst&&!executorModelCatalogRequest?(cat.models||[]).find(item=>item.id!=='default')?.id:'')||''; - if(choice&&choice!=='default'&&!(cat.models||[]).some(m=>m.id===choice)&&cat.customModel)choice=AGENT_CUSTOM_MODEL; + // Roles saved by earlier versions may hold "default", the retired + // placeholder for "let the CLI pick": they start on the first model too. + let choice=model&&model!=='default'?model:(pickFirst && !executorModelCatalogRequest ? agentFirstModel(executorId) : ''); + if(choice&&!(cat.models||[]).some(m=>m.id===choice)&&cat.customModel)choice=AGENT_CUSTOM_MODEL; picker.querySelector('[name="modelChoice"]').value=choice; const customInput=$('#agentModelCustomField')?.querySelector('input[name="model"]'); if(customInput&&choice===AGENT_CUSTOM_MODEL)customInput.value=model||''; diff --git a/web/app/assistant-models.js b/web/app/assistant-models.js index ee9f6daad..1714ad4ab 100644 --- a/web/app/assistant-models.js +++ b/web/app/assistant-models.js @@ -5,7 +5,6 @@ // Only the picker chrome lives here; per-feature selections stay in the // callers (localStorage keys, hidden inputs, form fields). (() => { - const DEFAULT_MODEL = 'default'; const FAMILY_MARK = {claude:'',gpt:'',glm:'智',gemini:'G',kimi:'K',deepseek:'D',minimax:'M',hunyuan:'混',mimo:'Mi',echo:'E',other:'AI'}; const FAMILY_ICON = { claude:'/images/credentials/claude.svg', @@ -31,10 +30,9 @@ opencode:'opencode.svg', cursor:'cursor.svg', agy:'antigravity.svg', kimi:'kimi-code.png', pi:'pi.svg', dsh:'deepseek.svg', zcode:'glm.svg' }; - let catalog = { - default: DEFAULT_MODEL, - models: [] - }; + // Every picker starts on the first listed model; there is no CLI-default + // entry. The list is empty until /api/assistant/models answers. + let catalog = {default: '', models: []}; let loading = null; function familyOf(id) { @@ -69,8 +67,7 @@ return (source.engines || []).some(e => e.id === prefix) ? prefix : 'codebuddy'; } function modelMeta(id) { - const value = id || DEFAULT_MODEL; - return catalog.models.find(m => m.id === value) || {id: value, family: familyOf(value), name: value === DEFAULT_MODEL ? '默认' : value}; + return (catalog.models || []).find(m => m.id === id) || {id: id || '', family: familyOf(id), name: id || '选择模型'}; } function fillModelIcon(el, family, id) { if (!el) return; @@ -158,13 +155,23 @@ function renderCodeBuddyList(menu, selectedId, onPick) { renderOptions(menu, codeBuddyModels(), selectedId, onPick); } - // codeBuddyModel keeps a CodeBuddy id and turns an empty id, or a saved id - // of another CLI, into the CLI default the server resolves itself. + // firstModel is the first listed model: what a picker without a saved + // choice selects. It is '' until the catalog has loaded. + function firstModel() { + return catalog.default || (catalog.models || [])[0]?.id || ''; + } + function firstCodeBuddyModel() { + return codeBuddyModels()[0]?.id || ''; + } + // codeBuddyModel keeps a listed CodeBuddy id and turns an empty id, a saved + // id of another CLI, or one the loaded list no longer offers into the first + // CodeBuddy model. function codeBuddyModel(id) { const value = String(id || '').trim(); // The catalog may not have landed yet; the built-in CLI prefixes still count. - if (!value || /^(codex|claude-code):/.test(value) || engineOf(value) !== 'codebuddy') return DEFAULT_MODEL; - return value; + if (!value || /^(codex|claude-code):/.test(value) || engineOf(value) !== 'codebuddy') return firstCodeBuddyModel(); + const listed = codeBuddyModels(); + return !listed.length || listed.some(m => m.id === value) ? value : listed[0].id; } async function fetchCatalog() { const resp = await fetch('/api/assistant/models', {headers: {Accept: 'application/json'}, credentials: 'same-origin'}); @@ -176,8 +183,8 @@ if (!loading) { loading = fetchCatalog().then(data => { if (Array.isArray(data?.models)) { - const models = data.models.filter(m => m.id !== DEFAULT_MODEL && m.id !== `${m.engine}:default`); - catalog = {default: data.default || DEFAULT_MODEL, models, engines: data.engines || []}; + const models = data.models.filter(m => m.id !== 'default' && m.id !== `${m.engine}:default`); + catalog = {default: (models.some(m => m.id === data.default) ? data.default : models[0]?.id) || '', models, engines: data.engines || []}; } return catalog; }).catch(() => catalog).finally(() => { loading = null; }); @@ -185,11 +192,12 @@ return loading; } window.AgentFlowAssistantModels = { - DEFAULT: DEFAULT_MODEL, catalog: () => catalog, cliIcon: id => Object.hasOwn(CLI_ICON, id) ? '/images/credentials/' + CLI_ICON[id] : '', codeBuddyModel, codeBuddyModels, + firstCodeBuddyModel, + firstModel, engineOf, load, paint, diff --git a/web/app/bots.js b/web/app/bots.js index 3dd633204..75a0f03d2 100644 --- a/web/app/bots.js +++ b/web/app/bots.js @@ -1,11 +1,13 @@ function loadBotModels(){return window.AgentFlowAssistantModels?.load?.()||Promise.resolve()} -function botModelPickerHTML(bot){return `
这个网络环境暂时没有读到模型列表,可以在下面直接填模型 ID。
'; diff --git a/web/assistant_models_test.js b/web/assistant_models_test.js index b45b2f6a3..779b7d80d 100644 --- a/web/assistant_models_test.js +++ b/web/assistant_models_test.js @@ -91,7 +91,6 @@ vm.runInContext(moduleSource, ctx); for (const name of ['catalog', 'load', 'paint', 'paintItem', 'renderList', 'renderOptions']) { assert.equal(typeof api[name], 'function', `AgentFlowAssistantModels.${name}`); } - assert.equal(api.DEFAULT, 'default'); assert.equal(api.cliIcon('agy'), '/images/credentials/antigravity.svg'); assert.equal(api.cliIcon('kimi'), '/images/credentials/kimi-code.png'); assert.equal(api.cliIcon('pi'), '/images/credentials/pi.svg'); @@ -123,11 +122,13 @@ vm.runInContext(moduleSource, ctx); assert.equal(icon.dataset.family, family); assert.ok(icon.innerHTML.includes(`/images/credentials/${family}.svg`)); } - // Pickers keep painting before the catalog lands, so the built-in fallback - // must already render a usable label. - assert.equal(api.codeBuddyModel('codex:gpt-5.5'), 'default', 'codex ids fall back before the catalog loads'); - api.paint(toggle, api.DEFAULT); - assert.equal(label.textContent, '默认'); + assert.equal(api.DEFAULT, undefined, 'there is no CLI-default model'); + // Pickers keep painting before the catalog lands: nothing is listed yet, + // so nothing is selected and the toggle asks for a model. + assert.equal(api.firstModel(), ''); + assert.equal(api.codeBuddyModel('codex:gpt-5.5'), '', 'codex ids fall back before the catalog loads'); + api.paint(toggle, api.firstModel()); + assert.equal(label.textContent, '选择模型'); assert.equal(icon.dataset.family, 'other'); assert.equal(api.codeBuddyModels().length, 0, 'the placeholder is not selectable before loading'); @@ -137,8 +138,11 @@ vm.runInContext(moduleSource, ctx); // Issue #228: clarification runs on CodeBuddy only, so CodeBuddy-only // pickers hide other CLIs and a saved "codex:…" id falls back. assert.deepEqual(api.codeBuddyModels().map(m => m.id), ['model-a', 'model-b']); - assert.equal(api.codeBuddyModel('codex:gpt-5.5'), 'default'); - assert.equal(api.codeBuddyModel(''), 'default'); + // Without a usable saved id a picker starts on the first CodeBuddy model, + // also for the retired "default" placeholder. + assert.equal(api.codeBuddyModel('codex:gpt-5.5'), 'model-a'); + assert.equal(api.codeBuddyModel(''), 'model-a'); + assert.equal(api.codeBuddyModel('default'), 'model-a'); assert.equal(api.codeBuddyModel('model-a'), 'model-a'); // Pull the real picker helpers out of the bundle and bind them to the stub host. @@ -166,6 +170,6 @@ vm.runInContext(moduleSource, ctx); // A Codex id saved before this fix must not reach chat-clarify. store.set('agentflow.clarifyModel', 'codex:gpt-5.5'); - assert.equal(ctx.selectedClarifyModel(), 'default'); + assert.equal(ctx.selectedClarifyModel(), 'model-a'); console.log('assistant models ok'); })().catch(err => { console.error(err); process.exit(1); }); diff --git a/web/bots_test.go b/web/bots_test.go index 5c0d52163..01e3cfa3c 100644 --- a/web/bots_test.go +++ b/web/bots_test.go @@ -37,6 +37,7 @@ assert.equal(ctx.botStepAllowed({id:'b1',target:{id:'g'}},3),true); assert.equal(ctx.botStepAllowed({id:'b1',target:{id:'g'},_targetChanged:true},3),false,'unsaved target must not unlock the test step'); const bots=[{id:'b1',name:'研发通知',enabled:true,health:'ready',ownerId:1,target:{type:'group',name:'研发群'}},{id:'b2',name:'<夜间>',enabled:false,health:'unchecked',ownerId:2}]; +ctx.AgentFlowAssistantModels={firstCodeBuddyModel:()=>'glm-5.1'}; const list=ctx.botListHTML(bots); assert.deepEqual([...list.matchAll(/