From 29b260bb185397bde5a4e032e37e10e7e4d18278 Mon Sep 17 00:00:00 2001 From: roberttwang Date: Tue, 17 Nov 2026 11:02:23 +0000 Subject: [PATCH 1/7] fix(chatbot): drop the CLI default model from the chat model picker MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The chat model picker listed 「CLI 默认模型」 (default) first, so a new conversation without a remembered model started on it. Chat now starts on the remembered model, else the first listed one, and no longer offers the CLI default for CodeBuddy or for the catalog of a CLI without a key. A conversation saved on default moves to that model when opened, edited or regenerated. default stays listed only when CodeBuddy has no other model, or when the shared key is limited to it. The backend catalog and the classic pickers are unchanged. --- CHANGELOG.md | 1 + chatbot/src/useChat.js | 34 +++++++++++++++----- chatbot/tests/hooks.test.jsx | 60 +++++++++++++++++++++++++++++++----- 3 files changed, 79 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 27e29087f..70dd5c574 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ Platform releases use `vX.Y.Z` tags and publish `ghcr.io/tencent/loopforge`. Loo ## Unreleased +- The AI 对话 model picker no longer offers 「CLI 默认模型」 (`default`), for CodeBuddy and for the catalog of a CLI without a key (`CLI default`). A new conversation starts on the remembered model, else on the first listed one. A conversation saved on `default` also moves to that model when it is opened, edited or regenerated. `default` stays listed only when CodeBuddy has no other model to offer, or when the administrator limited the shared key to it. `GET /api/assistant/models` is unchanged, so the role, scheduler and clarification pickers still list it, and the backend still accepts `default`. - A conversation's 子 Agent shows the model it ran on: its row in the artifacts list reads 「已完成 · 模型 …」, the header of an opened subagent names the model next to its status, and each dispatch in 会话过程 notes 「模型 · …」 under the task it was given. The model is the one the subagent reports running on: its first line in the CLI stream is saved as an `agentModel` activity event under the dispatch, so an alias such as `lite` shows the model it resolved to. Until it reports, and for replies saved before this change, the panel falls back to the model the Agent call named (the `model` argument), else the model of the reply that dispatched it, which the subagent inherits; a dispatch still running uses the model the running reply was sent with. Activity events of an Agent call carry the new `model` field only when the call named one. - The built-in backend, frontend and defect-fix SOPs gain a 「发起 MR」 node between 人工验收 and 交付汇总 (#717). It commits the work branch, pushes it and opens an MR/PR against the run's target branch, then records the link, branches and commit SHA in `mr-body.md`. Its command gate checks every writable repository of the run: one with commits beyond the target branch fails while it has uncommitted changes, while its checkout is off the run's work branch, or until `git ls-remote origin` shows that work branch at HEAD. A repository the run left unchanged is skipped. A second gate of the new mode `mr` has the engine look the MR up on the host with the same lookup delivery tracking uses (GitHub and Gongfeng): every writable repository whose work branch on origin carries commits beyond the target branch needs an MR from that work branch into that target branch that carries the pushed tip: an open one whose head is the tip (or whose host reports no head), or a merged one whose head is the tip. An agent that reports pass without opening an MR, opens it against the wrong branch, or leaves only an earlier merged MR on a reused work branch does not reach 交付汇总. The lookup runs as the run: on GitHub with the Git token the run pushed with (its responsible user's), falling back to the Owner of the run's own project; on Gongfeng through the run project's MCP as the responsible user. A repository bound to several projects is no longer checked as whichever project bound it first, and a failed lookup names the identity it used. A host the platform cannot query (an SSH repository, a failed lookup) goes straight to a person. `mr` gates take no commands, and the role editor keeps them when a role is saved. The gates retry once with their feedback and then wait for a person, so a run no longer succeeds with every source change left in a workspace that is reclaimed right after success. Run-scoped commands now get `AGENTFLOW_WORK_BRANCHES` (one `dirwork branchtarget branch` line per writable repository) and repository-scoped commands get `AGENTFLOW_WORK_BRANCH` and `AGENTFLOW_BASE_BRANCH`; the target branch is the one frozen into the run, including a requirement's release branch and a scheduled SOP's integration branch. 交付汇总 no longer pushes or opens a PR itself. Runs without a bound repository still deliver from the task workspace. New installs get the new templates from the seed. Existing installs keep their templates until an operator runs `migrations/033_generic_sop_mr_node.sql` by hand (see docs/deployment.md); it rewrites a template only while its node graph and 交付汇总 position are the shipped original and its 交付汇总 prompt only while unedited. SOPs already adopted into a project are copies and keep their old graph. The product SOP delivers documents only and is unchanged. - A conversation reply that is still running keeps running through a slow heartbeat. A poll, the conversation list, a follow-up message or a steer used to record it as interrupted after 45 seconds without a stored heartbeat; the process then cancelled the CLI and the next message failed with 「工作区正在使用或保存,请稍后重试」 for up to 15 minutes. Reads of a turn this process executes no longer reap it, and an unchanged heartbeat on MySQL no longer counts as a lost turn. On MySQL a heartbeat's age is measured on the database clock that stamped it, so skew between an API host and MySQL neither reaps a live turn nor keeps a dead one; whether a lease holder stopped renewing is likewise judged from `run_workspace_checkpoints.lease_renewed_at`, stamped on the database clock, not from another replica's `lease_until`. When a turn whose process died is reaped, the workspace lease it recorded is released if nothing renewed it for 45 seconds, so the next message starts at once; a lease another turn took, one still renewed on another replica, and a background save are kept. `migrations/032_assistant_generation_workspace_lease.sql` adds the three columns by hand; startup AutoMigrate adds them too. diff --git a/chatbot/src/useChat.js b/chatbot/src/useChat.js index 1ca76ec10..23d8cecd0 100644 --- a/chatbot/src/useChat.js +++ b/chatbot/src/useChat.js @@ -74,6 +74,20 @@ function rememberModel(executor, id) { const codeBuddyModels = (models) => (models || []).filter((m) => !m.engine || m.engine === "codebuddy"); const executorModelList = (models, executor) => executor === "codebuddy" ? codeBuddyModels(models) : engineModels(models, executor); +// "default" leaves the model to the CLI. Chat does not offer it: a +// conversation starts on the first listed model instead. It stays only when +// the list has no other model, or when the shared key is limited to it. +const CLI_DEFAULT_MODEL = "default"; +export function chatModelList(models, keep = []) { + const list = models || []; + const listed = list.filter((m) => m.id !== CLI_DEFAULT_MODEL || keep.includes(m.id)); + return codeBuddyModels(listed).length || !codeBuddyModels(list).length ? listed : list; +} +// sessionModel is the model a saved conversation continues on. One saved on +// the CLI default moves to the first listed model like a new conversation, +// unless the list still offers the default. +const sessionModel = (id, list) => + id === CLI_DEFAULT_MODEL && !(list || []).some((m) => m.id === id) ? "" : id || ""; // The model a new conversation on executor starts with: the remembered one // while list still offers it, else the first listed. Before a CLI's list has // loaded the remembered model (or that CLI's own default) holds the place. @@ -245,10 +259,11 @@ export function useChat() { setUsers(users || []); setProjects(projectRows || []); setSandboxes(sandboxRows || []); - setModels(catalog.models || []); + const listed = chatModelList(catalog.models, sponsoredModelList(catalog)); + setModels(listed); setSponsoredModels(sponsoredModelList(catalog)); const startExecutor = storedExecutor(); - setModel(preferredModel(executorModelList(catalog.models, startExecutor), startExecutor)); + setModel(preferredModel(executorModelList(listed, startExecutor), startExecutor)); await refreshSessions(); if (!current) return; const recovered = connectionError; @@ -288,7 +303,8 @@ export function useChat() { const storedEngine = knownExecutor(locked || stored.executor); setExecutorState(storedEngine); // A conversation shows the model it runs on. - setModel(stored.model || preferredModel(executorModelList(models, storedEngine), storedEngine)); + const listed = executorModelList(models, storedEngine); + setModel(sessionModel(stored.model, listed) || preferredModel(listed, storedEngine)); setEffort(stored.effort || ""); setProjectId(stored.projectId || ""); syncProject(stored.projectId || ""); @@ -570,13 +586,14 @@ export function useChat() { api(`/api/assistant/models?executor=${encodeURIComponent(executor)}`) .then((catalog) => { if (!current) return; - setProviderCatalogs((old) => ({ ...old, [executor]: catalog })); + const listed = chatModelList(catalog.models); + setProviderCatalogs((old) => ({ ...old, [executor]: { ...catalog, models: listed } })); // An open conversation keeps the model it runs on: the catalog lists // bare IDs without the CLI prefix, and no gateway models. setModel((old) => - (catalog.models || []).some((m) => m.id === old) || (old && old === sessionRef.current?.model) + listed.some((m) => m.id === old) || (old && old === sessionRef.current?.model) ? old - : preferredModel(catalog.models, executor), + : preferredModel(listed, executor), ); }) .catch((e) => current && setError(e.message)); @@ -969,7 +986,7 @@ export function useChat() { ); open(stored.id); setSession(stored); - setModel(stored.model || preferredModel(executorModels, executor)); + setModel(sessionModel(stored.model, executorModels) || preferredModel(executorModels, executor)); setEffort(stored.effort || ""); await refreshSessions(); return stored; @@ -986,7 +1003,8 @@ export function useChat() { setSubmitting(true); open(stored.id); setSession(stored); - const chosen = sponsored ? sharedModelFor(stored.model || model) : stored.model || model; + const continued = sessionModel(stored.model, executorModels) || model; + const chosen = sponsored ? sharedModelFor(continued) : continued; setModel(chosen); setEffort(stored.effort || ""); const g = await write("/api/assistant/generations", { diff --git a/chatbot/tests/hooks.test.jsx b/chatbot/tests/hooks.test.jsx index b61713433..f393b14e4 100644 --- a/chatbot/tests/hooks.test.jsx +++ b/chatbot/tests/hooks.test.jsx @@ -43,7 +43,7 @@ vi.mock("../src/api.js", async (original) => ({ newId: () => "new-session", })); -import { EXECUTORS, useChat } from "../src/useChat.js"; +import { EXECUTORS, chatModelList, useChat } from "../src/useChat.js"; import { isLocalConversation, useLocalConversations, @@ -81,9 +81,10 @@ describe("conversation hooks", () => { expect(result.current.executor).toBe("codebuddy"); expect(result.current.executors.map((item) => item.id)).toEqual(EXECUTORS.map((item) => item.id)); act(() => result.current.setExecutor("codex")); - await waitFor(() => expect(result.current.models.map((m) => m.id)).toEqual(["default", "gpt-5"])); + // The CLI's own default is not offered: the first listed model is. + await waitFor(() => expect(result.current.models.map((m) => m.id)).toEqual(["gpt-5"])); expect(localStorage.getItem("loopforge.assistant.executor")).toBe("codex"); - expect(result.current.model).toBe("default"); + expect(result.current.model).toBe("gpt-5"); expect(result.current.effort).toBe(""); expect(result.current.sponsored).toBe(false); act(() => result.current.setExecutor("unknown")); @@ -91,7 +92,7 @@ describe("conversation hooks", () => { await act(() => result.current.send({ text: "你好" })); expect(writeMock).toHaveBeenCalledWith( "/api/assistant/generations", - expect.objectContaining({ executor: "codex", model: "default", effort: "" }), + expect.objectContaining({ executor: "codex", model: "gpt-5", effort: "" }), ); act(() => result.current.setExecutor("codebuddy")); expect(result.current.model).toBe("m1"); @@ -138,8 +139,9 @@ describe("conversation hooks", () => { try { const first = renderHook(() => useChat()); await waitFor(() => expect(first.result.current.ready).toBe(true)); - // Nothing remembered yet: the first listed model. - expect(first.result.current.model).toBe("default"); + // Nothing remembered yet: the first listed model, not the CLI default. + expect(first.result.current.models.map((m) => m.id)).toEqual(["claude-opus-5.5"]); + expect(first.result.current.model).toBe("claude-opus-5.5"); act(() => { first.result.current.setModel("claude-opus-5.5"); }); expect(localStorage.getItem("loopforge.assistant.model.codebuddy")).toBe("claude-opus-5.5"); // A new conversation no longer goes back to the default model. @@ -153,7 +155,7 @@ describe("conversation hooks", () => { // Another CLI keeps its own pick and does not overwrite CodeBuddy's. act(() => first.result.current.newChat()); act(() => first.result.current.setExecutor("codex")); - await waitFor(() => expect(first.result.current.models.map((m) => m.id)).toEqual(["default", "gpt-5"])); + await waitFor(() => expect(first.result.current.models.map((m) => m.id)).toEqual(["gpt-5"])); act(() => { first.result.current.setModel("gpt-5"); }); act(() => first.result.current.setExecutor("codebuddy")); expect(first.result.current.model).toBe("claude-opus-5.5"); @@ -169,13 +171,55 @@ describe("conversation hooks", () => { // A remembered model that is no longer offered falls back to the list. localStorage.setItem("loopforge.assistant.model.codebuddy", "retired-model"); act(() => reloaded.result.current.newChat()); - expect(reloaded.result.current.model).toBe("default"); + expect(reloaded.result.current.model).toBe("claude-opus-5.5"); } finally { apiMock.mockImplementation(original); localStorage.removeItem("loopforge.assistant.executor"); } }); + test("chat lists the CLI default only when nothing else is offered", () => { + const ids = (list) => list.map((m) => m.id); + const cliDefault = { id: "default", name: "CLI 默认模型" }; + const opus = { id: "claude-opus-5.5", name: "Opus" }; + const codex = { id: "codex:gpt-5", name: "GPT-5", engine: "codex" }; + expect(ids(chatModelList([cliDefault, opus, codex]))).toEqual(["claude-opus-5.5", "codex:gpt-5"]); + // CodeBuddy has nothing else to offer: keep its default so chat still works. + expect(ids(chatModelList([cliDefault, codex]))).toEqual(["default", "codex:gpt-5"]); + expect(ids(chatModelList([cliDefault]))).toEqual(["default"]); + // The administrator limited the shared key to it. + expect(ids(chatModelList([cliDefault, opus], ["default", "claude-opus-5.5"]))).toEqual(["default", "claude-opus-5.5"]); + expect(chatModelList(undefined)).toEqual([]); + }); + + test("a conversation saved on the CLI default continues on the first listed model", async () => { + localStorage.removeItem("loopforge.assistant.executor"); + localStorage.removeItem("loopforge.assistant.model.codebuddy"); + const original = apiMock.getMockImplementation(); + const saved = { + id: "s8", title: "旧会话", projectId: "p1", model: "default", effort: "", + updatedAt: "2026-01-01T00:00:00Z", + messages: [{ role: "user", content: "hi" }, { role: "assistant", content: "ok", model: "default" }], + }; + apiMock.mockImplementation(async (path, options) => { + if (path === "/api/assistant/models") + return { default: "default", models: [{ id: "default", name: "CLI 默认模型" }, { id: "glm-5.1", name: "GLM" }] }; + if (path === "/api/assistant/sessions/s8") return structuredClone(saved); + return original(path, options); + }); + try { + const { result } = renderHook(() => useChat()); + await waitFor(() => expect(result.current.ready).toBe(true)); + act(() => result.current.open("s8")); + await waitFor(() => expect(result.current.session?.id).toBe("s8")); + expect(result.current.model).toBe("glm-5.1"); + await act(() => result.current.regenerate(saved)); + expect(writeMock).toHaveBeenLastCalledWith("/api/assistant/generations", expect.objectContaining({ model: "glm-5.1" })); + } finally { + apiMock.mockImplementation(original); + } + }); + test("regenerating after an edit follows the composer's approval mode", async () => { const { result } = renderHook(() => useChat()); await waitFor(() => expect(result.current.ready).toBe(true)); From b48effffe60d7431a4d7873e5a528a31c1b5a316 Mon Sep 17 00:00:00 2001 From: roberttwang Date: Tue, 17 Nov 2026 11:52:45 +0000 Subject: [PATCH 2/7] fix: remove the CLI default model; settings without a model use the first listed one --- CHANGELOG.md | 2 +- chatbot/src/useChat.js | 39 ++++------- chatbot/tests/hooks.test.jsx | 65 ++++--------------- internal/domain/model.go | 15 +++++ internal/domain/notification.go | 2 - internal/domain/preview.go | 18 ++--- internal/domain/preview_build.go | 2 +- .../agent_tool_native_terminal_test.go | 2 +- internal/httpapi/agent_tool_session_test.go | 2 +- internal/httpapi/assistant.go | 9 +-- internal/httpapi/assistant_effort_test.go | 2 +- internal/httpapi/assistant_engines.go | 28 +++++++- internal/httpapi/assistant_generation.go | 2 +- internal/httpapi/assistant_models.go | 57 ++++++++-------- internal/httpapi/assistant_models_test.go | 3 +- .../httpapi/assistant_notification_report.go | 5 +- .../assistant_notification_report_test.go | 10 +-- internal/httpapi/assistant_provider.go | 2 +- internal/httpapi/assistant_schedule.go | 2 +- internal/httpapi/assistant_sponsor.go | 10 +-- internal/httpapi/assistant_sponsor_test.go | 6 +- .../httpapi/assistant_task_engines_test.go | 9 ++- internal/httpapi/assistant_tasks.go | 6 +- internal/httpapi/assistant_test.go | 8 ++- internal/httpapi/assistant_title_test.go | 3 +- internal/httpapi/assistant_usage_test.go | 1 + internal/httpapi/bot_interactions.go | 7 +- internal/httpapi/bot_interactions_test.go | 4 +- .../httpapi/bot_reply_messages_limits_test.go | 1 + internal/httpapi/catalog.go | 16 ++++- internal/httpapi/catalog_test.go | 1 + internal/httpapi/clarify_mcp.go | 4 -- internal/httpapi/clarify_mcp_test.go | 23 ++++--- internal/httpapi/notifications.go | 12 ++-- internal/httpapi/notifications_test.go | 4 +- internal/httpapi/schedule.go | 11 +--- internal/notification/report_test.go | 2 +- internal/notification/service_test.go | 2 +- internal/repo/notifications.go | 5 +- internal/runtime/agent_cli_zcode.go | 10 +-- internal/runtime/provider.go | 4 +- web/app/agents.js | 15 ++--- web/app/assistant-models.js | 33 ++++++---- web/app/bots.js | 12 ++-- web/app/flows.js | 11 ++-- web/app/runs.js | 2 +- web/app/sync-schedule.js | 12 ++-- web/app/workbench.js | 4 +- web/assistant_models_test.js | 22 ++++--- web/bots_test.go | 3 +- web/i18n-en.js | 2 +- web/index.html | 2 +- web/workbench.js | 2 +- webtest/tests/platform-admin.test.mjs | 4 +- 54 files changed, 270 insertions(+), 270 deletions(-) create mode 100644 internal/domain/model.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 70dd5c574..66807cd9f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ Platform releases use `vX.Y.Z` tags and publish `ghcr.io/tencent/loopforge`. Loo ## Unreleased -- The AI 对话 model picker no longer offers 「CLI 默认模型」 (`default`), for CodeBuddy and for the catalog of a CLI without a key (`CLI default`). A new conversation starts on the remembered model, else on the first listed one. A conversation saved on `default` also moves to that model when it is opened, edited or regenerated. `default` stays listed only when CodeBuddy has no other model to offer, or when the administrator limited the shared key to it. `GET /api/assistant/models` is unchanged, so the role, scheduler and clarification pickers still list it, and the backend still accepts `default`. +- 「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`). - A conversation's 子 Agent shows the model it ran on: its row in the artifacts list reads 「已完成 · 模型 …」, the header of an opened subagent names the model next to its status, and each dispatch in 会话过程 notes 「模型 · …」 under the task it was given. The model is the one the subagent reports running on: its first line in the CLI stream is saved as an `agentModel` activity event under the dispatch, so an alias such as `lite` shows the model it resolved to. Until it reports, and for replies saved before this change, the panel falls back to the model the Agent call named (the `model` argument), else the model of the reply that dispatched it, which the subagent inherits; a dispatch still running uses the model the running reply was sent with. Activity events of an Agent call carry the new `model` field only when the call named one. - The built-in backend, frontend and defect-fix SOPs gain a 「发起 MR」 node between 人工验收 and 交付汇总 (#717). It commits the work branch, pushes it and opens an MR/PR against the run's target branch, then records the link, branches and commit SHA in `mr-body.md`. Its command gate checks every writable repository of the run: one with commits beyond the target branch fails while it has uncommitted changes, while its checkout is off the run's work branch, or until `git ls-remote origin` shows that work branch at HEAD. A repository the run left unchanged is skipped. A second gate of the new mode `mr` has the engine look the MR up on the host with the same lookup delivery tracking uses (GitHub and Gongfeng): every writable repository whose work branch on origin carries commits beyond the target branch needs an MR from that work branch into that target branch that carries the pushed tip: an open one whose head is the tip (or whose host reports no head), or a merged one whose head is the tip. An agent that reports pass without opening an MR, opens it against the wrong branch, or leaves only an earlier merged MR on a reused work branch does not reach 交付汇总. The lookup runs as the run: on GitHub with the Git token the run pushed with (its responsible user's), falling back to the Owner of the run's own project; on Gongfeng through the run project's MCP as the responsible user. A repository bound to several projects is no longer checked as whichever project bound it first, and a failed lookup names the identity it used. A host the platform cannot query (an SSH repository, a failed lookup) goes straight to a person. `mr` gates take no commands, and the role editor keeps them when a role is saved. The gates retry once with their feedback and then wait for a person, so a run no longer succeeds with every source change left in a workspace that is reclaimed right after success. Run-scoped commands now get `AGENTFLOW_WORK_BRANCHES` (one `dirwork branchtarget branch` line per writable repository) and repository-scoped commands get `AGENTFLOW_WORK_BRANCH` and `AGENTFLOW_BASE_BRANCH`; the target branch is the one frozen into the run, including a requirement's release branch and a scheduled SOP's integration branch. 交付汇总 no longer pushes or opens a PR itself. Runs without a bound repository still deliver from the task workspace. New installs get the new templates from the seed. Existing installs keep their templates until an operator runs `migrations/033_generic_sop_mr_node.sql` by hand (see docs/deployment.md); it rewrites a template only while its node graph and 交付汇总 position are the shipped original and its 交付汇总 prompt only while unedited. SOPs already adopted into a project are copies and keep their old graph. The product SOP delivers documents only and is unchanged. - A conversation reply that is still running keeps running through a slow heartbeat. A poll, the conversation list, a follow-up message or a steer used to record it as interrupted after 45 seconds without a stored heartbeat; the process then cancelled the CLI and the next message failed with 「工作区正在使用或保存,请稍后重试」 for up to 15 minutes. Reads of a turn this process executes no longer reap it, and an unchanged heartbeat on MySQL no longer counts as a lost turn. On MySQL a heartbeat's age is measured on the database clock that stamped it, so skew between an API host and MySQL neither reaps a live turn nor keeps a dead one; whether a lease holder stopped renewing is likewise judged from `run_workspace_checkpoints.lease_renewed_at`, stamped on the database clock, not from another replica's `lease_until`. When a turn whose process died is reaped, the workspace lease it recorded is released if nothing renewed it for 45 seconds, so the next message starts at once; a lease another turn took, one still renewed on another replica, and a background save are kept. `migrations/032_assistant_generation_workspace_lease.sql` adds the three columns by hand; startup AutoMigrate adds them too. diff --git a/chatbot/src/useChat.js b/chatbot/src/useChat.js index 23d8cecd0..8f165c727 100644 --- a/chatbot/src/useChat.js +++ b/chatbot/src/useChat.js @@ -74,26 +74,13 @@ function rememberModel(executor, id) { const codeBuddyModels = (models) => (models || []).filter((m) => !m.engine || m.engine === "codebuddy"); const executorModelList = (models, executor) => executor === "codebuddy" ? codeBuddyModels(models) : engineModels(models, executor); -// "default" leaves the model to the CLI. Chat does not offer it: a -// conversation starts on the first listed model instead. It stays only when -// the list has no other model, or when the shared key is limited to it. -const CLI_DEFAULT_MODEL = "default"; -export function chatModelList(models, keep = []) { - const list = models || []; - const listed = list.filter((m) => m.id !== CLI_DEFAULT_MODEL || keep.includes(m.id)); - return codeBuddyModels(listed).length || !codeBuddyModels(list).length ? listed : list; -} -// sessionModel is the model a saved conversation continues on. One saved on -// the CLI default moves to the first listed model like a new conversation, -// unless the list still offers the default. -const sessionModel = (id, list) => - id === CLI_DEFAULT_MODEL && !(list || []).some((m) => m.id === id) ? "" : id || ""; // The model a new conversation on executor starts with: the remembered one // while list still offers it, else the first listed. Before a CLI's list has -// loaded the remembered model (or that CLI's own default) holds the place. +// loaded the remembered model holds the place; with none remembered the +// server runs the turn on that CLI's first listed model. function preferredModel(list, executor) { const remembered = storedModel(executor); - if (!list?.length) return remembered || (executor === "codebuddy" ? "" : "default"); + if (!list?.length) return remembered; return list.some((m) => m.id === remembered) ? remembered : list[0].id; } @@ -259,11 +246,10 @@ export function useChat() { setUsers(users || []); setProjects(projectRows || []); setSandboxes(sandboxRows || []); - const listed = chatModelList(catalog.models, sponsoredModelList(catalog)); - setModels(listed); + setModels(catalog.models || []); setSponsoredModels(sponsoredModelList(catalog)); const startExecutor = storedExecutor(); - setModel(preferredModel(executorModelList(listed, startExecutor), startExecutor)); + setModel(preferredModel(executorModelList(catalog.models, startExecutor), startExecutor)); await refreshSessions(); if (!current) return; const recovered = connectionError; @@ -303,8 +289,7 @@ export function useChat() { const storedEngine = knownExecutor(locked || stored.executor); setExecutorState(storedEngine); // A conversation shows the model it runs on. - const listed = executorModelList(models, storedEngine); - setModel(sessionModel(stored.model, listed) || preferredModel(listed, storedEngine)); + setModel(stored.model || preferredModel(executorModelList(models, storedEngine), storedEngine)); setEffort(stored.effort || ""); setProjectId(stored.projectId || ""); syncProject(stored.projectId || ""); @@ -586,14 +571,13 @@ export function useChat() { api(`/api/assistant/models?executor=${encodeURIComponent(executor)}`) .then((catalog) => { if (!current) return; - const listed = chatModelList(catalog.models); - setProviderCatalogs((old) => ({ ...old, [executor]: { ...catalog, models: listed } })); + setProviderCatalogs((old) => ({ ...old, [executor]: catalog })); // An open conversation keeps the model it runs on: the catalog lists // bare IDs without the CLI prefix, and no gateway models. setModel((old) => - listed.some((m) => m.id === old) || (old && old === sessionRef.current?.model) + (catalog.models || []).some((m) => m.id === old) || (old && old === sessionRef.current?.model) ? old - : preferredModel(listed, executor), + : preferredModel(catalog.models, executor), ); }) .catch((e) => current && setError(e.message)); @@ -986,7 +970,7 @@ export function useChat() { ); open(stored.id); setSession(stored); - setModel(sessionModel(stored.model, executorModels) || preferredModel(executorModels, executor)); + setModel(stored.model || preferredModel(executorModels, executor)); setEffort(stored.effort || ""); await refreshSessions(); return stored; @@ -1003,8 +987,7 @@ export function useChat() { setSubmitting(true); open(stored.id); setSession(stored); - const continued = sessionModel(stored.model, executorModels) || model; - const chosen = sponsored ? sharedModelFor(continued) : continued; + const chosen = sponsored ? sharedModelFor(stored.model || model) : stored.model || model; setModel(chosen); setEffort(stored.effort || ""); const g = await write("/api/assistant/generations", { diff --git a/chatbot/tests/hooks.test.jsx b/chatbot/tests/hooks.test.jsx index f393b14e4..0233f8565 100644 --- a/chatbot/tests/hooks.test.jsx +++ b/chatbot/tests/hooks.test.jsx @@ -17,7 +17,7 @@ const { apiMock, writeMock } = vi.hoisted(() => { return { result: { structuredContent: { data: { id: "saved" } } } }; if (path === "/api/auth/current") return { user: { id: 1, loginName: "tester", codeBuddyApiKeyConfigured: true } }; if (path === "/api/projects") return [{ id: "p1", name: "项目一", ownerId: 1, members: [1] }]; - if (path === "/api/assistant/models?executor=codex") return { default: "default", models: [{ id: "default", name: "CLI default", family: "gpt" }, { id: "gpt-5", name: "GPT-5", family: "gpt" }] }; + if (path === "/api/assistant/models?executor=codex") return { default: "gpt-5", models: [{ id: "gpt-5", name: "GPT-5", family: "gpt" }, { id: "gpt-5.5", name: "GPT-5.5", family: "gpt" }] }; if (path === "/api/assistant/models") return { default: "m1", sponsoredModel: "m1", models: [{ id: "m1", name: "模型一", effort: true }] }; if (path === "/api/users") return [{ id: 1, loginName: "tester", codeBuddyApiKeyConfigured: true }]; if (path === "/api/assistant/sessions") return [baseSession]; @@ -43,7 +43,7 @@ vi.mock("../src/api.js", async (original) => ({ newId: () => "new-session", })); -import { EXECUTORS, chatModelList, useChat } from "../src/useChat.js"; +import { EXECUTORS, useChat } from "../src/useChat.js"; import { isLocalConversation, useLocalConversations, @@ -81,9 +81,9 @@ describe("conversation hooks", () => { expect(result.current.executor).toBe("codebuddy"); expect(result.current.executors.map((item) => item.id)).toEqual(EXECUTORS.map((item) => item.id)); act(() => result.current.setExecutor("codex")); - // The CLI's own default is not offered: the first listed model is. - await waitFor(() => expect(result.current.models.map((m) => m.id)).toEqual(["gpt-5"])); + await waitFor(() => expect(result.current.models.map((m) => m.id)).toEqual(["gpt-5", "gpt-5.5"])); expect(localStorage.getItem("loopforge.assistant.executor")).toBe("codex"); + // The first listed model, not a CLI-default placeholder. expect(result.current.model).toBe("gpt-5"); expect(result.current.effort).toBe(""); expect(result.current.sponsored).toBe(false); @@ -133,15 +133,14 @@ describe("conversation hooks", () => { const original = apiMock.getMockImplementation(); apiMock.mockImplementation(async (path, options) => { if (path === "/api/assistant/models") - return { default: "default", models: [{ id: "default", name: "CLI 默认模型" }, { id: "claude-opus-5.5", name: "Opus" }] }; + return { default: "glm-5.1", models: [{ id: "glm-5.1", name: "GLM" }, { id: "claude-opus-5.5", name: "Opus" }] }; return original(path, options); }); try { const first = renderHook(() => useChat()); await waitFor(() => expect(first.result.current.ready).toBe(true)); - // Nothing remembered yet: the first listed model, not the CLI default. - expect(first.result.current.models.map((m) => m.id)).toEqual(["claude-opus-5.5"]); - expect(first.result.current.model).toBe("claude-opus-5.5"); + // Nothing remembered yet: the first listed model. + expect(first.result.current.model).toBe("glm-5.1"); act(() => { first.result.current.setModel("claude-opus-5.5"); }); expect(localStorage.getItem("loopforge.assistant.model.codebuddy")).toBe("claude-opus-5.5"); // A new conversation no longer goes back to the default model. @@ -155,12 +154,12 @@ describe("conversation hooks", () => { // Another CLI keeps its own pick and does not overwrite CodeBuddy's. act(() => first.result.current.newChat()); act(() => first.result.current.setExecutor("codex")); - await waitFor(() => expect(first.result.current.models.map((m) => m.id)).toEqual(["gpt-5"])); - act(() => { first.result.current.setModel("gpt-5"); }); + await waitFor(() => expect(first.result.current.models.map((m) => m.id)).toEqual(["gpt-5", "gpt-5.5"])); + act(() => { first.result.current.setModel("gpt-5.5"); }); act(() => first.result.current.setExecutor("codebuddy")); expect(first.result.current.model).toBe("claude-opus-5.5"); act(() => first.result.current.setExecutor("codex")); - expect(first.result.current.model).toBe("gpt-5"); + expect(first.result.current.model).toBe("gpt-5.5"); act(() => first.result.current.setExecutor("codebuddy")); first.unmount(); // Reloading the home page starts on the remembered model too. @@ -171,55 +170,13 @@ describe("conversation hooks", () => { // A remembered model that is no longer offered falls back to the list. localStorage.setItem("loopforge.assistant.model.codebuddy", "retired-model"); act(() => reloaded.result.current.newChat()); - expect(reloaded.result.current.model).toBe("claude-opus-5.5"); + expect(reloaded.result.current.model).toBe("glm-5.1"); } finally { apiMock.mockImplementation(original); localStorage.removeItem("loopforge.assistant.executor"); } }); - test("chat lists the CLI default only when nothing else is offered", () => { - const ids = (list) => list.map((m) => m.id); - const cliDefault = { id: "default", name: "CLI 默认模型" }; - const opus = { id: "claude-opus-5.5", name: "Opus" }; - const codex = { id: "codex:gpt-5", name: "GPT-5", engine: "codex" }; - expect(ids(chatModelList([cliDefault, opus, codex]))).toEqual(["claude-opus-5.5", "codex:gpt-5"]); - // CodeBuddy has nothing else to offer: keep its default so chat still works. - expect(ids(chatModelList([cliDefault, codex]))).toEqual(["default", "codex:gpt-5"]); - expect(ids(chatModelList([cliDefault]))).toEqual(["default"]); - // The administrator limited the shared key to it. - expect(ids(chatModelList([cliDefault, opus], ["default", "claude-opus-5.5"]))).toEqual(["default", "claude-opus-5.5"]); - expect(chatModelList(undefined)).toEqual([]); - }); - - test("a conversation saved on the CLI default continues on the first listed model", async () => { - localStorage.removeItem("loopforge.assistant.executor"); - localStorage.removeItem("loopforge.assistant.model.codebuddy"); - const original = apiMock.getMockImplementation(); - const saved = { - id: "s8", title: "旧会话", projectId: "p1", model: "default", effort: "", - updatedAt: "2026-01-01T00:00:00Z", - messages: [{ role: "user", content: "hi" }, { role: "assistant", content: "ok", model: "default" }], - }; - apiMock.mockImplementation(async (path, options) => { - if (path === "/api/assistant/models") - return { default: "default", models: [{ id: "default", name: "CLI 默认模型" }, { id: "glm-5.1", name: "GLM" }] }; - if (path === "/api/assistant/sessions/s8") return structuredClone(saved); - return original(path, options); - }); - try { - const { result } = renderHook(() => useChat()); - await waitFor(() => expect(result.current.ready).toBe(true)); - act(() => result.current.open("s8")); - await waitFor(() => expect(result.current.session?.id).toBe("s8")); - expect(result.current.model).toBe("glm-5.1"); - await act(() => result.current.regenerate(saved)); - expect(writeMock).toHaveBeenLastCalledWith("/api/assistant/generations", expect.objectContaining({ model: "glm-5.1" })); - } finally { - apiMock.mockImplementation(original); - } - }); - test("regenerating after an edit follows the composer's approval mode", async () => { const { result } = renderHook(() => useChat()); await waitFor(() => expect(result.current.ready).toBe(true)); 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 4226058e8..0a8f1d611 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 887ee753e..092b1079a 100644 --- a/internal/httpapi/assistant.go +++ b/internal/httpapi/assistant.go @@ -189,7 +189,7 @@ func (h *assistantHandlers) chat(c *gin.Context) { if catalogEngine == assistantEngineCodeBuddy { catalog = h.turnCatalog(c.Request.Context(), user, req.Model) } - req.Model = assistantAllowedUserModel(req.Model, catalog, user) + req.Model = assistantAllowedUserModel(c.Request.Context(), req.Model, catalog, user) cliEngine, _ = assistantModelEngine(req.Model) req.Executor = cliEngine if err := validateAssistantEffort(user, req.Model, req.Effort); err != nil { @@ -413,9 +413,6 @@ func (h *assistantHandlers) chat(c *gin.Context) { nativeContinuationReady := false var turnUsage assistantTurnUsage replyModel := strings.TrimSpace(req.Model) - if replyModel == "" { - replyModel = assistantDefaultModel - } generate := h.generate if generate == nil { resume := false @@ -1699,9 +1696,9 @@ 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 + model = assistantKnownCatalog().Default } sys := strings.TrimSpace(opts.SystemPrompt) if sys == "" { diff --git a/internal/httpapi/assistant_effort_test.go b/internal/httpapi/assistant_effort_test.go index c7d33c211..2e82ea492 100644 --- a/internal/httpapi/assistant_effort_test.go +++ b/internal/httpapi/assistant_effort_test.go @@ -10,7 +10,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 d5c589ed0..3d5b4d54d 100644 --- a/internal/httpapi/assistant_engines.go +++ b/internal/httpapi/assistant_engines.go @@ -274,24 +274,46 @@ 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 } +// 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 { + for _, model := range assistantEngineModels(ctx, user) { + if model.Engine == engine { + return model.ID + } + } + return "" +} + // assistantScheduledModel normalizes the model of an AI scheduled task on // save. The run uses the project owner's keys and CodeBuddy environment, not // the editor's, so a well-formed model is kept as-is; it is checked against // the owner's account when it runs (see scheduledRunModel). func assistantScheduledModel(id string, catalog assistantModelCatalog) string { engine, model := assistantModelEngine(id) + 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 6533aa238..74f04cc62 100644 --- a/internal/httpapi/assistant_generation.go +++ b/internal/httpapi/assistant_generation.go @@ -97,7 +97,7 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) { if catalogEngine == assistantEngineCodeBuddy { catalog = h.turnCatalog(c.Request.Context(), user, req.Model) } - req.Model = assistantAllowedUserModel(req.Model, catalog, user) + req.Model = assistantAllowedUserModel(c.Request.Context(), req.Model, catalog, user) cliEngine, _ = assistantModelEngine(req.Model) req.Executor = cliEngine if err := validateAssistantEffort(user, req.Model, req.Effort); err != nil { diff --git a/internal/httpapi/assistant_models.go b/internal/httpapi/assistant_models.go index 4a4fd6e9c..51726ee86 100644 --- a/internal/httpapi/assistant_models.go +++ b/internal/httpapi/assistant_models.go @@ -16,12 +16,9 @@ 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 type assistantModel struct { @@ -35,6 +32,7 @@ type assistantModel struct { } type assistantModelCatalog struct { + // Default is the first listed model: what a setting without a model runs on. Default string `json:"default"` Models []assistantModel `json:"models"` // SponsoredModels is set when users without their own CodeBuddy API Key @@ -154,7 +152,7 @@ func assistantKnownCatalog() assistantModelCatalog { } } } - return catalog + return catalog.withFirstDefault() } func cachedCLIModels(environment string) []string { @@ -188,11 +186,11 @@ func (h *assistantHandlers) models(c *gin.Context) { c.JSON(400, gin.H{"error": "不支持的执行器"}) return } - result := assistantModelCatalog{Default: "default", Models: []assistantModel{{ID: "default", Name: "CLI default", Family: map[string]string{"codex": "gpt", "claude": "claude"}[id]}}} + var result assistantModelCatalog for _, item := range catalog.Models { result.Models = append(result.Models, assistantModel{ID: item.ID, Name: item.Name, Family: map[string]string{"codex": "gpt", "claude": "claude"}[id]}) } - c.JSON(200, result) + c.JSON(200, result.withFirstDefault()) return } @@ -266,33 +264,34 @@ func loadAssistantModels(_ context.Context, environment string) assistantModelCa 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. -func assistantFixedCatalog() assistantModelCatalog { - defaultID := strings.TrimSpace(os.Getenv("AGENTFLOW_ASSISTANT_MODEL")) - if defaultID == "" { - defaultID = assistantDefaultModel - } - defaultName := defaultID - if defaultID == assistantDefaultModel { - defaultName = "CLI 默认模型" +// 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 } - 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) + 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 { + 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 != "" && !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 { @@ -325,8 +324,10 @@ func assistantModelFamily(id 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 6426f6c12..033a79b31 100644 --- a/internal/httpapi/assistant_models_test.go +++ b/internal/httpapi/assistant_models_test.go @@ -39,7 +39,8 @@ func TestCodeBuddyModelDiscoveryPerEnvironment(t *testing.T) { 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" { + // 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 { diff --git a/internal/httpapi/assistant_notification_report.go b/internal/httpapi/assistant_notification_report.go index aaf392101..e436c617e 100644 --- a/internal/httpapi/assistant_notification_report.go +++ b/internal/httpapi/assistant_notification_report.go @@ -17,7 +17,10 @@ func (h *assistantHandlers) generateReport(ctx context.Context, run domain.Run, return domain.AINotificationContent{}, notification.ErrReportCredentials } catalog := loadAssistantModels(ctx, user.CodeBuddyInternetEnvironment) - if assistantAllowedModel(model, catalog) != model { + if model = domain.ChosenModel(model); model == "" { + model = catalog.Default + } + if model == "" || assistantAllowedModel(model, catalog) != model { 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_provider.go b/internal/httpapi/assistant_provider.go index 62dfa2ea7..8eceb4817 100644 --- a/internal/httpapi/assistant_provider.go +++ b/internal/httpapi/assistant_provider.go @@ -130,7 +130,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 44a6929a3..f53c75fa4 100644 --- a/internal/httpapi/assistant_schedule.go +++ b/internal/httpapi/assistant_schedule.go @@ -74,7 +74,7 @@ func (h *assistantHandlers) runScheduleJobPromptReporting(job domain.ScheduleJob 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 "", "", 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 a4c7c7da6..5a6ca35cf 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: @@ -79,11 +79,11 @@ func (h *assistantHandlers) chatCatalog(ctx context.Context, user domain.User) a // 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) + model = domain.ChosenModel(model) if model == "" || assistantCatalogLists(catalog, model) { return catalog } @@ -91,7 +91,7 @@ func (h *assistantHandlers) turnCatalog(ctx context.Context, user domain.User, m catalog = h.chatCatalog(ctx, user) if !assistantCatalogLists(catalog, model) { // The list is fresh (or discovery failed) and still lacks the model: - // the turn falls back to the default, so leave a trace of why. + // the turn falls back to the first listed model, so leave a trace of why. log.Printf("assistant model %q is not offered to user %d; the turn runs on %q", model, user.ID, catalog.Default) } return catalog diff --git a/internal/httpapi/assistant_sponsor_test.go b/internal/httpapi/assistant_sponsor_test.go index 1a432c6ee..cd4e6e562 100644 --- a/internal/httpapi/assistant_sponsor_test.go +++ b/internal/httpapi/assistant_sponsor_test.go @@ -129,7 +129,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() @@ -288,7 +289,8 @@ func TestAssistantModelsPerExecutor(t *testing.T) { } for executor, family := range map[string]string{"codex": "gpt", "claude": "claude"} { rec, catalog := get(executor) - if rec.Code != 200 || catalog.Default != "default" || len(catalog.Models) < 2 || catalog.Models[0].ID != "default" { + // 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 { 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 ad40b1fce..ca682395f 100644 --- a/internal/httpapi/assistant_tasks.go +++ b/internal/httpapi/assistant_tasks.go @@ -460,13 +460,13 @@ func firstNonEmpty(values ...string) string { func scheduledRunModel(ctx context.Context, requested string, user domain.User) (string, error) { requested = strings.TrimSpace(requested) env := user.CodeBuddyInternetEnvironment - model := assistantAllowedUserModel(requested, loadAssistantModels(ctx, env), user) - if requested == "" || model == requested { + model := assistantAllowedUserModel(ctx, requested, loadAssistantModels(ctx, env), user) + if _, chosen := assistantModelEngine(requested); domain.ChosenModel(chosen) == "" || model == requested { return model, nil } if engine, _ := assistantModelEngine(requested); engine == assistantEngineCodeBuddy { refreshCLIModels(ctx, env, user.CodeBuddyAPIKey) - if model = assistantAllowedUserModel(requested, loadAssistantModels(ctx, env), user); model == requested { + if model = assistantAllowedUserModel(ctx, requested, loadAssistantModels(ctx, env), user); model == requested { return model, nil } } diff --git a/internal/httpapi/assistant_test.go b/internal/httpapi/assistant_test.go index fbf5ee6a8..edf7b2b0c 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_test.go b/internal/httpapi/assistant_title_test.go index b62aaac25..174356e67 100644 --- a/internal/httpapi/assistant_title_test.go +++ b/internal/httpapi/assistant_title_test.go @@ -74,7 +74,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 032ce4e24..908693f23 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..7d37791e0 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) + 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 dc2a80ef6..ded7e1d56 100644 --- a/internal/httpapi/catalog.go +++ b/internal/httpapi/catalog.go @@ -1052,7 +1052,7 @@ func (h *catalogHandlers) workflows(c *gin.Context) { if _, ok := h.requireWorkflowSandbox(c, v); !ok { return } - v, err := domain.AttachPreviewBuild(v) + v, err := attachPreviewBuild(v) if err != nil { c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()}) return @@ -1069,7 +1069,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 := attachPreviewBuild(v) if err != nil { c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()}) return @@ -1340,3 +1340,15 @@ 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 attachPreviewBuild(v domain.WorkflowDefinition) (domain.WorkflowDefinition, error) { + if v.Preview != nil && v.Preview.Enabled && v.Preview.ChosenModel() == "" { + preview := *v.Preview + preview.Model = assistantKnownCatalog().Default + v.Preview = &preview + } + return domain.AttachPreviewBuild(v) +} diff --git a/internal/httpapi/catalog_test.go b/internal/httpapi/catalog_test.go index 539ecebd1..f828c7235 100644 --- a/internal/httpapi/catalog_test.go +++ b/internal/httpapi/catalog_test.go @@ -40,6 +40,7 @@ func TestPutAgentValidatesEffortLevel(t *testing.T) { } func TestExecutorModelsCatalogListsPerCLI(t *testing.T) { + t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "glm-5.1") s, err := repo.OpenTest() if err != nil { t.Fatal(err) diff --git a/internal/httpapi/clarify_mcp.go b/internal/httpapi/clarify_mcp.go index 077b4c36f..3f5de0867 100644 --- a/internal/httpapi/clarify_mcp.go +++ b/internal/httpapi/clarify_mcp.go @@ -14,10 +14,6 @@ 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+`) diff --git a/internal/httpapi/clarify_mcp_test.go b/internal/httpapi/clarify_mcp_test.go index b307692de..61f9cf194 100644 --- a/internal/httpapi/clarify_mcp_test.go +++ b/internal/httpapi/clarify_mcp_test.go @@ -14,12 +14,13 @@ 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) + 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 := clarifyAllowedModel(requested); got != "first-model" { + t.Fatalf("%q = %q", requested, got) + } } if got := clarifyAllowedModel("public-model"); got != "public-model" { t.Fatalf("listed model = %q", got) @@ -27,7 +28,7 @@ func TestClarifyAllowedModelFallsBackToCatalog(t *testing.T) { } 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 +49,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 +66,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 +79,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 +385,5 @@ func TestDispatchClarifyMCPCallReadOnlyTAPD(t *testing.T) { t.Fatalf("write should be rejected: %v", err) } } + +const clarifyTestModel = "glm-5.1" 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/schedule.go b/internal/httpapi/schedule.go index 3635a2f3c..83da6a05f 100644 --- a/internal/httpapi/schedule.go +++ b/internal/httpapi/schedule.go @@ -271,7 +271,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 @@ -306,15 +306,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 engine != assistantEngineCodeBuddy { return fmt.Sprintf("你还没有配置 %s API Key,平台共享 Key 只支持 CodeBuddy 模型:请先在个人配置中填写,或改选 CodeBuddy 模型", assistantEngineLabel(engine)) 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 02b954690..4abd42d20 100644 --- a/internal/runtime/agent_cli_zcode.go +++ b/internal/runtime/agent_cli_zcode.go @@ -7,6 +7,8 @@ import ( "io/fs" "reflect" "strings" + + "agentflow/internal/domain" ) const ( @@ -72,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 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 38df8dfd6..4e354052a 100644 --- a/internal/runtime/provider.go +++ b/internal/runtime/provider.go @@ -187,9 +187,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 b8db2ed0d..0f6ce4f51 100644 --- a/web/app/agents.js +++ b/web/app/agents.js @@ -151,16 +151,13 @@ 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')} } -// The empty choice runs the CLI's own default model; name it instead of -// showing an unset 「选择模型」. -function agentDefaultModelItem(executorId){ - const exec=(state.data?.executors||[]).find(x=>x.id===executorId); - return {id:'',name:exec?.model?`默认 · ${exec.model}`:'默认模型',icon:false}; -} +// 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; - const items=[agentDefaultModelItem(currentAgentExecutorId())].concat(agentModelItems(currentAgentExecutorId(),current)); + const items=agentModelItems(currentAgentExecutorId(),current); const menu=picker.querySelector('.ai-model-menu'); agentModelAPI()?.renderOptions?.(menu,items,current,id=>{ picker.querySelector('[name="modelChoice"]').value=id; @@ -191,7 +188,9 @@ function renderAgentEffortPicker(){ function applyAgentModelUI(executorId,model,effort){ const picker=$('#agentModelPicker');if(!picker||!$('#agentEffortPicker'))return; const cat=executorModelCatalogs()[executorId]||{}; - let choice=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: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"]'); diff --git a/web/app/assistant-models.js b/web/app/assistant-models.js index 5d580664e..8b327760e 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', @@ -18,10 +17,9 @@ hunyuan:'/images/credentials/hunyuan.svg', mimo:'/images/credentials/mimo.svg' }; - let catalog = { - default: DEFAULT_MODEL, - models: [{id: DEFAULT_MODEL, name: 'CLI 默认模型', family: 'other'}] - }; + // 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) { @@ -48,7 +46,7 @@ return (catalog.engines || []).some(e => e.id === prefix) ? prefix : 'codebuddy'; } function modelMeta(id) { - return (catalog.models || []).find(m => m.id === id) || {id: id || DEFAULT_MODEL, family: familyOf(id), name: id || DEFAULT_MODEL}; + return (catalog.models || []).find(m => m.id === id) || {id: id || '', family: familyOf(id), name: id || '选择模型'}; } function fillModelIcon(el, family, id) { if (!el) return; @@ -132,13 +130,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'}); @@ -150,17 +158,18 @@ function load() { if (!loading) { loading = fetchCatalog().then(data => { - if (data?.models?.length) catalog = {default: data.default || DEFAULT_MODEL, models: data.models, engines: data.engines || []}; + if (data?.models?.length) catalog = {default: data.default || data.models[0].id, models: data.models, engines: data.engines || []}; return catalog; }).catch(() => catalog).finally(() => { loading = null; }); } return loading; } window.AgentFlowAssistantModels = { - DEFAULT: DEFAULT_MODEL, catalog: () => catalog, 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 `
`} +function botModelPickerHTML(bot){return `
`} function closeBotModelPicker(){const picker=document.querySelector('#botModelPicker');if(!picker)return;picker.querySelector('.ai-model-menu').hidden=true;picker.querySelector('[data-model-toggle]').setAttribute('aria-expanded','false')} function bindBotModelPicker(host){ const picker=host.querySelector('#botModelPicker'),models=window.AgentFlowAssistantModels; if(!picker||!models)return; const toggle=picker.querySelector('[data-model-toggle]'),menu=picker.querySelector('.ai-model-menu'),value=picker.querySelector('[name="model"]'); - models.paint(toggle,value.value); + // A Bot without a model replies on the first listed CodeBuddy model. + const settle=()=>{value.value=models.codeBuddyModel(value.value);models.paint(toggle,value.value)}; + settle();Promise.resolve(models.load?.()).then(settle,()=>{}); toggle.onclick=event=>{ event.stopPropagation();if(toggle.disabled||toggle.closest('fieldset')?.disabled)return; const open=menu.hidden;closeBotModelPicker();if(!open)return; @@ -21,7 +23,7 @@ function bindBotModelPicker(host){ } // Project-scoped enterprise chat notifications. const botUI={projectId:'',items:[],deliveries:[],selected:null,sessions:[],query:'',loading:false,error:'',busy:false,busyAction:'',revision:0,tab:'list',step:1,recordsTab:'deliveries',interactionBotId:'',interaction:null,interactionLoading:false,interactionError:'',testResult:'',flashId:'',motion:null,animations:[],shownCount:null,shownError:'',watchTimer:0,watchCount:0,deletingId:''}; -const BOT_TABS=['list','edit','records'],BOT_STEPS=[[1,'填写凭据'],[2,'选择接收会话'],[3,'发送测试']],BOT_DEFAULT_MODEL='glm-5.3-flash-ioa'; +const BOT_TABS=['list','edit','records'],BOT_STEPS=[[1,'填写凭据'],[2,'选择接收会话'],[3,'发送测试']]; // In-progress states breathe; terminal states stay still. const BOT_LIVE_STATES=['pending','sending','connecting','reconnecting','queued','running','ready']; const BOT_CONNECTION={connected:['已连接','success'],connecting:['连接中','info'],reconnecting:['重连中','info'],error:['连接异常','error'],offline:['未连接','neutral']}; @@ -39,7 +41,7 @@ function canManageBot(bot){ function botStepAllowed(bot,step){return step===1||(step===2&&!!bot?.id)||(step===3&&!!bot?.id&&!!bot?.target&&!bot._targetChanged)} function botStepDone(bot,step){return step===1?!!bot?.id:step===2?botStepAllowed(bot,3):false} function botStoredBot(bot){return bot?.id?botUI.items.find(b=>b.id===bot.id):null} -function botCredentialsDirty(bot){const stored=botStoredBot(bot);if(!stored)return !!bot;return !!bot._secret||(bot.name||'')!==(stored.name||'')||(bot.botId||'')!==(stored.botId||'')||(bot.model||BOT_DEFAULT_MODEL)!==(stored.model||BOT_DEFAULT_MODEL)||!!bot.enabled!==!!stored.enabled||!!bot.interactionEnabled!==!!stored.interactionEnabled} +function botCredentialsDirty(bot){const stored=botStoredBot(bot);if(!stored)return !!bot;return !!bot._secret||(bot.name||'')!==(stored.name||'')||(bot.botId||'')!==(stored.botId||'')||(bot.model||'')!==(stored.model||'')||!!bot.enabled!==!!stored.enabled||!!bot.interactionEnabled!==!!stored.interactionEnabled} function botIcon(name){return ``} // Harness StatusBadge: in-progress states breathe, settled states carry a glyph so colour is never the only cue. @@ -75,7 +77,7 @@ function botPanelHeadHTML(){ function botTargetHTML(target){return target?`${botTypeLabel(target.type)}${escapeHTML(target.name)}`:'尚未选择接收会话'} function botRowHTML(bot){ const id=escapeHTML(bot.id),name=escapeHTML(bot.name),manage=canManageBot(bot),target=botTargetHTML(bot.target); - const sub=escapeHTML(bot.model||BOT_DEFAULT_MODEL)+(bot.interactionEnabled?' · 已启用对话':''); + const sub=escapeHTML(bot.model||globalThis.AgentFlowAssistantModels?.firstCodeBuddyModel?.()||'')+(bot.interactionEnabled?' · 已启用对话':''); return `
${botIcon('robot')}${name}${sub}${target}
${target}${botEnabledBadge(bot.enabled)}${botHealthBadge(bot.health)}
${manage?``:''}
`; } function botListHTML(items){ diff --git a/web/app/flows.js b/web/app/flows.js index a52efd57c..aa5d74b47 100644 --- a/web/app/flows.js +++ b/web/app/flows.js @@ -4,7 +4,6 @@ function workflowPreviewContract(wf){ const PREVIEW_BUILD_NODE_ID='af-preview-build'; const PREVIEW_BUILD_AGENT_ID='af-preview-builder'; const PREVIEW_MODEL_FALLBACK=[ - {id:'default',name:'GLM-5.3-Flash'}, {id:'glm-5.3-ioa',name:'GLM-5.3'}, {id:'gpt-5.6-terra',name:'GPT-5.6-Terra'}, {id:'gpt-5.6-luna',name:'GPT-5.6-Luna'}, @@ -16,9 +15,9 @@ const PREVIEW_MODEL_FALLBACK=[ function isPreviewBuildNode(id){return id===PREVIEW_BUILD_NODE_ID} function workflowPreviewModel(wf){ const api=window.AgentFlowAssistantModels; - const fallback=(api&&api.DEFAULT)||'default'; const model=(workflowPreviewContract(wf)||{}).model; - return (model&&String(model).trim())||fallback; + if(api?.codeBuddyModel)return api.codeBuddyModel(model); + return (model&&String(model).trim())||previewModelChoices()[0]?.id||''; } function previewModelChoices(){ const api=window.AgentFlowAssistantModels; @@ -30,7 +29,7 @@ function previewModelChoices(){ function fillPreviewModelSelect(sel, selected){ if(!sel)return; const items=previewModelChoices(); - const keep=selected||items[0]?.id||'default'; + const keep=selected||items[0]?.id||''; if(keep&&!items.some(m=>m.id===keep))items.unshift({id:keep,name:keep}); sel.innerHTML=items.map(m=>``).join(''); } @@ -38,7 +37,7 @@ function ensurePreviewContract(){ const wf=state.workflow;if(!wf)return null; const prev=workflowPreviewContract(wf)||{}; const api=window.AgentFlowAssistantModels; - const model=(prev.model&&String(prev.model).trim())||(api&&api.DEFAULT)||'default'; + const model=api?.codeBuddyModel?api.codeBuddyModel(prev.model):((prev.model&&String(prev.model).trim())||previewModelChoices()[0]?.id||''); wf.preview={ ...prev, enabled:true, @@ -919,7 +918,7 @@ function renderAgentHookEditors(d){ function renderAgentSummary(){ const f=$('#agentForm'),d=state.agentDraft||{}; const exec=(state.data.executors||[]).find(x=>x.id===(f?.elements?.executorId?.value||d.executorId)); - const chosen=agentEffectiveModel(f),model=chosen||(exec?.model?`${exec.model}(默认)`:'默认模型'); + const chosen=agentEffectiveModel(f),model=chosen||agentFirstModel(exec?.id||'codebuddy')||'选择模型'; const effort=(f?.elements?.effort?.value||'').trim(); const meta=$('#agentRuntimeMeta'); if(meta)meta.textContent=[exec?.name,effort?`${model} · ${effort}`:model].filter(Boolean).join(' · '); diff --git a/web/app/runs.js b/web/app/runs.js index 4838622d9..4ef17bf39 100644 --- a/web/app/runs.js +++ b/web/app/runs.js @@ -1278,7 +1278,7 @@ function defaultRunEval(){return{enabled:true,version:1,threshold:70,dimensions: {id:'delivery',name:'交付完整',question:'终态、产物和验证信号是否齐全?',weight:10} ]}} // Run evals run on CodeBuddy only; a saved "codex:…" id falls back. -function runEvalModel(){const api=window.AgentFlowAssistantModels,stored=state.runEvalModel||localStorage.getItem('agentflow.runEvalModel')||'';if(api?.codeBuddyModel)return api.codeBuddyModel(stored);return stored||(api&&api.DEFAULT)||'default'} +function runEvalModel(){const api=window.AgentFlowAssistantModels,stored=state.runEvalModel||localStorage.getItem('agentflow.runEvalModel')||'';if(api?.codeBuddyModel)return api.codeBuddyModel(stored);return stored} function setRunEvalModel(id){state.runEvalModel=id;localStorage.setItem('agentflow.runEvalModel',id)} function runEvalHasKey(){return !!(userById(state.currentUser?.id)||state.currentUser||{}).codeBuddyApiKeyConfigured} function runEvalApplyable(rec){if(!rec||rec.status==='applied')return false;const action=((rec.target||'')+'.'+(rec.action||'')).replace(/^\./,'').toLowerCase();const full=rec.action&&rec.action.includes('.')?rec.action.toLowerCase():action;return ['workflow.update_node','agent.upsert_gate','agent.remove_gate','agent.append_instructions','agent.append_task_prompt'].includes(full)} diff --git a/web/app/sync-schedule.js b/web/app/sync-schedule.js index 6f07377bd..3113f367b 100644 --- a/web/app/sync-schedule.js +++ b/web/app/sync-schedule.js @@ -103,7 +103,7 @@ function selectedClarifyModel(){ const stored=localStorage.getItem('agentflow.clarifyModel')||''; // Clarification runs on CodeBuddy only; a saved "codex:…" id falls back. if(api?.codeBuddyModel)return api.codeBuddyModel(stored); - return stored||(api&&api.DEFAULT)||'default'; + return stored; } function setClarifyModel(id){ if(!id)return; @@ -211,7 +211,7 @@ function bindScheduleModelPicker(){ const open=menu.hidden; closeScheduleModelMenu(); if(!open)return; - const selected=form.elements.assistantModel.value||api.DEFAULT; + const selected=form.elements.assistantModel.value||api.firstModel(); api.renderOptions(menu, scheduleEngineModels(scheduleModelEngine(selected)), selected, id=>{ paintScheduleModel(id); closeScheduleModelMenu(); @@ -224,7 +224,7 @@ function bindScheduleModelPicker(){ if(engine)engine.onchange=()=>{ const api=scheduleModelAPI(); const models=scheduleEngineModels(engine.value); - const fallback=engine.value==='codebuddy'?(api?.catalog?.().default||api?.DEFAULT):''; + const fallback=engine.value==='codebuddy'?api?.firstCodeBuddyModel?.():''; const next=models.some(m=>m.id===fallback)?fallback:models[0]?.id; if(next)paintScheduleModel(next); }; @@ -238,7 +238,7 @@ async function loadScheduleModels(){ const api=scheduleModelAPI(); if(!api)return; try{await api.load()}catch{} - paintScheduleModel($('#scheduleJobForm')?.elements.assistantModel.value||api.DEFAULT); + paintScheduleModel($('#scheduleJobForm')?.elements.assistantModel.value||api.firstModel()); } function paintScheduleModel(selected){ const api=scheduleModelAPI(); @@ -246,7 +246,7 @@ function paintScheduleModel(selected){ const f=$('#scheduleJobForm'); if(!api||!host||!f)return; const catalog=api.catalog?.()||{}; - const keep=selected||f.elements.assistantModel.value||catalog.default||api.DEFAULT; + const keep=selected||f.elements.assistantModel.value||api.firstModel(); f.elements.assistantModel.value=keep; api.paint(host.querySelector('[data-model-toggle]'), keep); paintScheduleEngines(keep); @@ -320,7 +320,7 @@ function fillScheduleJobForm(job={}){ if(!cron)f.elements.intervalSec.value=interval; f.elements.jobKind.value=job.id?scheduleJobKind(job):scheduleEditorKind; f.elements.assistantPrompt.value=job.assistantPrompt||''; - f.elements.assistantModel.value=job.assistantModel||scheduleModelAPI()?.DEFAULT||'default'; + f.elements.assistantModel.value=job.assistantModel||scheduleModelAPI()?.firstModel?.()||''; fillScheduleSessionMode(f,job); f.elements.useIssueWorkflow.checked=job.id?!!job.useIssueWorkflow:true; f.elements.maxDispatch.value=job.maxDispatch||''; diff --git a/web/app/workbench.js b/web/app/workbench.js index b2c7b93f7..bfe791fa4 100644 --- a/web/app/workbench.js +++ b/web/app/workbench.js @@ -70,7 +70,7 @@ const CREDENTIAL_KINDS=[ guide:[['先在下方选择 CodeBuddy 账号所在的网络环境:国际站、国内站或 iOA'],['登录该站点的 API Key 页面,新建 API Key',codeBuddyKeyURL,codeBuddyKeyLinkLabel],['复制以 ck_ 开头的密钥粘贴到下方;DeepSeek、OpenAI 等第三方模型的 Key 不能填在这里']], placeholder:'请输入个人 ck_ key', extra:{name:'codeBuddyInternetEnvironment',label:'网络环境',options:CODEBUDDY_ENVIRONMENTS}, - impact:'AI 对话将只能使用默认模型,CodeBuddy 执行器节点会失败。'}, + impact:'AI 对话将只能使用平台共享 Key 允许的模型,CodeBuddy 执行器节点会失败。'}, {key:'codexApiKey',group:'model',name:'Codex',short:'Codex API Key',logo:'codex',monochrome:true, use:'AI 对话选择 Codex 执行器,以及以 Codex 运行的 SOP 节点', description:'AI 对话切换到 Codex 后可选用模型目录里的模型,SOP 在执行机器上以 Codex 运行的节点也使用它。目录为空时,未填 Base URL 使用 Codex 自带模型,填写后跟随服务发布的模型;也可以自己挑选、排序和命名。', @@ -1554,7 +1554,7 @@ async function loadPlatformSharedKey(host){ defaultSelect.value=models.includes(current)?current:(models[0]||''); }; const renderModels=()=>{ - const listed=catalog.filter(m=>m&&m.id&&m.id!=='default'); + const listed=catalog.filter(m=>m&&m.id); const ids=new Set(listed.map(m=>m.id)); for(const id of selected)if(!ids.has(id)){listed.push({id,name:id});ids.add(id)} modelsHost.innerHTML=listed.length?listed.map(m=>``).join(''):'

这个网络环境暂时没有读到模型列表,可以在下面直接填模型 ID。

'; diff --git a/web/assistant_models_test.js b/web/assistant_models_test.js index 76b4285b6..c462947a6 100644 --- a/web/assistant_models_test.js +++ b/web/assistant_models_test.js @@ -90,12 +90,13 @@ 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'); - // 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, 'CLI 默认模型'); + 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'); await api.load(); @@ -104,8 +105,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. @@ -133,6 +137,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(/]*)?>(?:)?([^<]*)/g)].map(m=>m[1]),['名称','接收会话','启用状态','连接健康','操作']); assert.equal((list.match(/群聊<\/span>glm-5.3-flash-ioaglm-5.1触发配置 - +