diff --git a/CHANGELOG.md b/CHANGELOG.md index 16bd867bf..c12b04228 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ Platform releases use `vX.Y.Z` tags and publish `ghcr.io/tencent/loopforge`. LoopForge Local packages use `local-vX.Y.Z` tags and are published by manually running the `release-local` workflow. +## Unreleased + +### Platform + +- Platform administration shares model credentials per CLI instead of one CodeBuddy key. 平台管理 → 共享模型 Key holds one API Key per CLI (CodeBuddy, Codex, Claude Code), each with its own allow list of models and default; CodeBuddy keeps its network environment, Codex and Claude Code take an optional Base URL so a self-hosted gateway works, and the page can fetch the models a gateway publishes. Members without their own key for a CLI chat and run LOOP nodes on the shared one, limited to those models, while members with their own key are unaffected. The keys live in `platform_model_keys`; `migrations/050_platform_model_keys.sql` copies the earlier CodeBuddy row and the platform keeps reading the old table until then. Scheduled tasks, clarification, reports, bots and run evaluation keep using personal credentials. + ## 0.4.3 — LOOP orchestration, execution machines and asset evolution ### Platform diff --git a/chatbot/src/App.jsx b/chatbot/src/App.jsx index f534d9b6d..4edc125bb 100644 --- a/chatbot/src/App.jsx +++ b/chatbot/src/App.jsx @@ -3138,6 +3138,7 @@ export default function App() { defaultModel={chat.model} sponsoredModel={chat.sponsoredModel} sponsoredModels={chat.sponsoredModels} + sharedEngines={chat.sharedEngines} onClose={closeQuickAccess} onOpenView={(view) => navigate(view)} onCredentialsSaved={chat.refreshCredentials} diff --git a/chatbot/src/QuickAccessWizard.jsx b/chatbot/src/QuickAccessWizard.jsx index b091f5e38..81ffc2fb7 100644 --- a/chatbot/src/QuickAccessWizard.jsx +++ b/chatbot/src/QuickAccessWizard.jsx @@ -695,6 +695,7 @@ export default function QuickAccessWizard({ projectId = "", sponsoredModel = "", sponsoredModels = [], + sharedEngines = {}, onClose, onCompleted, onCredentialsSaved, @@ -1103,7 +1104,12 @@ export default function QuickAccessWizard({ const selectedRepo = (bindRepoNow && parsedRepo) || parseSavedRepo(defaultRepo, gongfengHost); const repoAccess = gitAccess(selectedRepo); const readyCLIs = EXECUTORS.filter(cli => personalEngineConfigured(storedUser, cli.id)); - const cliReady = readyCLIs.length > 0 || Boolean(sponsoredModel); + // CLIs the platform lends a key for, so a member without their own can run. + const sharedCLIs = EXECUTORS.filter(cli => (sharedEngines?.[cli.id] || []).length > 0); + const sharedCLIText = sponsoredModel + ? `平台共享模型(${sharedModelNames(sponsoredModels, sponsoredModel)})` + : sharedCLIs.length ? `平台共享 ${sharedCLIs.map(cli => cli.label).join("、")} 凭据` : ""; + const cliReady = readyCLIs.length > 0 || Boolean(sharedCLIText); const nodes = activeWorkflow?.nodes?.filter((node) => node.type === "agent") || FALLBACK_NODES; @@ -1559,13 +1565,12 @@ export default function QuickAccessWizard({ : "未配置,克隆/推送私有仓库前可在个人配置补齐"} -
  • +
  • 模型 CLI · {completedSummary?.cliNames?.join("、") || - (sponsoredModel - ? `平台共享模型(${sharedModelNames(sponsoredModels, sponsoredModel)})` - : "可在个人配置或执行机器设置中准备")} + sharedCLIText || + "可在个人配置或执行机器设置中准备"}
  • @@ -1662,8 +1667,8 @@ export default function QuickAccessWizard({

    {hasGit || readyCLIs.length ? "可以继续选择项目和仓库,也可以先补齐下面的配置。" - : sponsoredModel - ? "平台共享模型可用,可直接继续。需要操作私有仓库时,可以在这里添加 Git 凭据。" + : cliReady + ? `${sharedCLIText}可用,可直接继续。需要操作私有仓库时,可以在这里添加 Git 凭据。` : "配置任意一项即可继续。下一步选择项目和仓库。"}

    ) : null} @@ -1719,7 +1724,7 @@ export default function QuickAccessWizard({
    执行器 - {readyCLIs.length ? readyCLIs.map(cli => cli.label).join("、") : sponsoredModel ? "可使用平台共享模型" : "尚未配置执行器"} + {readyCLIs.length ? readyCLIs.map(cli => cli.label).join("、") : sharedCLIText || "尚未配置执行器"}
    @@ -2124,7 +2129,7 @@ export default function QuickAccessWizard({ {repoAccess.label} {repoAccess.ready ? "已配置" : "未配置"} · CLI · {readyCLIs.length ? readyCLIs.map(cli => cli.label).join("、") : - sponsoredModel ? "使用平台共享模型" : "未配置"} + sharedCLIText || "未配置"} diff --git a/chatbot/src/useChat.js b/chatbot/src/useChat.js index 3ab9efa9c..2a024913b 100644 --- a/chatbot/src/useChat.js +++ b/chatbot/src/useChat.js @@ -146,6 +146,7 @@ export function useChat() { [selection, setSelection] = useState(() => ({ executor: storedExecutor(), model: null, effort: null })), [codeBuddyDefault, setCodeBuddyDefault] = useState({ id: "default", name: "默认" }), [sponsoredModels, setSponsoredModels] = useState([]), + [sharedEngines, setSharedEngines] = useState({}), [providerCatalogs, setProviderCatalogs] = useState({}), [generation, setGeneration] = useState(null), [stopRequest, setStopRequest] = useState(null), @@ -337,6 +338,7 @@ export function useChat() { setCatalogEngines(catalog.engines || []); setCodeBuddyDefault({ id: catalog.default || "default", name: "默认", efforts: catalog.defaultEfforts }); setSponsoredModels(sponsoredModelList(catalog)); + setSharedEngines(catalog.sharedEngines || {}); }, []); useEffect(() => { if (!user?.id || user.isGuest) { @@ -1817,6 +1819,7 @@ export function useChat() { sponsored, sponsoredModel, sponsoredModels, + sharedEngines, generation, live, error, diff --git a/chatbot/tests/quick-access-wizard.test.jsx b/chatbot/tests/quick-access-wizard.test.jsx index 032e0f050..80cbed5aa 100644 --- a/chatbot/tests/quick-access-wizard.test.jsx +++ b/chatbot/tests/quick-access-wizard.test.jsx @@ -329,8 +329,30 @@ describe("QuickAccessWizard", () => { />, ); await screen.findByRole("dialog"); - expect(screen.getByText(/平台共享模型可用,可直接继续/)).toBeVisible(); - expect(screen.getByText("可使用平台共享模型")).toBeVisible(); + expect(screen.getByText(/平台共享模型(m1)可用,可直接继续/)).toBeVisible(); + expect(screen.getAllByText(/平台共享模型(m1)/).length).toBeGreaterThan(1); + await userAction.click(screen.getByRole("button", { name: "下一步" })); + expect(await screen.findByText("项目与仓库", { selector: "h3" })).toBeInTheDocument(); + mockState.unconfigured = false; + }); + + test("a shared CLI key lets new users skip credentials too", async () => { + mockState.unconfigured = true; + const userAction = userEvent.setup(); + render( + , + ); + await screen.findByRole("dialog"); + expect(screen.getByText(/平台共享 Codex 凭据可用,可直接继续/)).toBeVisible(); await userAction.click(screen.getByRole("button", { name: "下一步" })); expect(await screen.findByText("项目与仓库", { selector: "h3" })).toBeInTheDocument(); mockState.unconfigured = false; diff --git a/docs/deployment.md b/docs/deployment.md index 448f745cf..703971bb6 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -256,7 +256,7 @@ The installer checks the helper destinations against the staged macOS binary and When platform updates are enabled, macOS runners synchronize the helper in the background at startup. A failed version check is retried during rescans, including when an older helper remains usable. A readable, compatible local ELF or a locally configured script wrapper can be copied into a Docker workspace with executable permissions while the sync runs. Operations that need a missing helper for Git or MCP can wait up to five seconds for the initial sync. The background download continues within its own transfer timeout. -A platform administrator can share one CodeBuddy API Key under **Platform administration → Shared CodeBuddy Key** (平台共享 CodeBuddy Key): pick the network environment that issued it and the models members may use (the first is the default). Members without a key of their own then chat and run LOOPs on it, limited to those models; a role configured with another model runs on the default and the run says so. Members with their own key keep using it with any model. Clarification, reports, bots and run evaluation use the personal credentials of the relevant account. Scheduled prompts follow the selected CLI's credential and sponsorship settings. The key is stored in the database like personal keys and is never shown again after saving. `AGENTFLOW_ASSISTANT_SPONSOR_LOGIN`, which lent one account's key limited to `deepseek-v4.1-flash`, still applies while no shared key is configured. +A platform administrator can share one API Key per CLI under **Platform administration → Shared Model Key** (平台管理 → 共享模型 Key): CodeBuddy needs the network environment that issued its key, Codex and Claude Code take the key plus an optional Base URL for a gateway (empty uses the official endpoint). Each CLI has its own allow list of models, the first being the default; the page offers the CLI's built-in catalog, can fetch the models a gateway publishes, and accepts extra model IDs. Members without a key of their own for that CLI then chat and run LOOPs on the shared one, limited to those models; a role configured with another model runs on the default and the run says so. Members with their own key keep using it with any model. Clarification, reports, bots and run evaluation still use the personal credentials of the relevant account, and AI scheduled tasks follow the selected CLI's credential; CodeBuddy keeps the shared-key fallback described in [ai-scheduled-task-capabilities](ai-scheduled-task-capabilities.md). Keys are stored in the database like personal keys, one row per CLI in `platform_model_keys`, and are never shown again after saving. `migrations/050_platform_model_keys.sql` copies the CodeBuddy key of the earlier single-key table; the platform reads that table while the copy has not run, and clearing the shared CodeBuddy key removes both rows. `AGENTFLOW_ASSISTANT_SPONSOR_LOGIN`, which lent one account's CodeBuddy key limited to `deepseek-v4.1-flash`, still applies while no shared CodeBuddy key is configured. Configure provider credentials in the platform UI, not the host's global CLI configuration. Credentials are bound to the responsible actor by the upstream runtime. The home composer and LOOP roles each choose a built-in CLI independently. Select the executor beside the home model selector; its API key (and optional Codex/Claude base URL) comes from your personal settings. Changing the executor preserves the draft; saved conversations record the executor used. Main Bot writes still pass through the platform tool gateway and its approval checks. A scheduled assistant task can select any supported CLI and runs as an ordinary chat turn; Codex and Claude Code still need that account's own credential. Live model tests are opt-in; set `AGENTFLOW_LIVE_TESTS=1` only for the acceptance suites that need to load local credentials. diff --git a/internal/domain/agent.go b/internal/domain/agent.go index 337d7c061..8c63c4679 100644 --- a/internal/domain/agent.go +++ b/internal/domain/agent.go @@ -34,6 +34,34 @@ func IsAgentCLIKind(kind string) bool { }) } +// Shared model credential engines: the CLIs whose API Key a platform +// administrator may share with members who configured none of their own +// (平台管理 → 共享模型 Key). The agent CLIs above are excluded because their +// model configuration lives in a private HOME that only personal credentials +// fill. The order is the switch order on that page. +const ( + SharedModelProviderCodeBuddy = "codebuddy" + SharedModelProviderCodex = "codex" + SharedModelProviderClaude = "claude-code" +) + +var SharedModelProviders = []string{SharedModelProviderCodeBuddy, SharedModelProviderCodex, SharedModelProviderClaude} + +// NormalizeSharedModelProvider accepts the shared-credential engine names, +// including the "claude" alias older personal settings used, and returns the +// canonical one. +func NormalizeSharedModelProvider(raw string) (string, bool) { + switch strings.ToLower(strings.TrimSpace(raw)) { + case "", SharedModelProviderCodeBuddy: + return SharedModelProviderCodeBuddy, true + case SharedModelProviderCodex: + return SharedModelProviderCodex, true + case "claude", SharedModelProviderClaude: + return SharedModelProviderClaude, true + } + return "", false +} + // ValidateAgentEffort checks a role's reasoning-effort choice against the // levels published for the resolved executor kind. func ValidateAgentEffort(effort, executorKind string) error { diff --git a/internal/engine/codebuddy_auth.go b/internal/engine/codebuddy_auth.go deleted file mode 100644 index 0207912ad..000000000 --- a/internal/engine/codebuddy_auth.go +++ /dev/null @@ -1,70 +0,0 @@ -package engine - -import ( - "slices" - "strings" - - "agentflow/internal/domain" - "agentflow/internal/repo" - "agentflow/internal/runtime" -) - -const ( - codeBuddyAPIKeyEnv = "CODEBUDDY_API_KEY" - codeBuddyInternetEnv = "CODEBUDDY_INTERNET_ENVIRONMENT" -) - -// resolveCodeBuddyCredential returns the responsible user's own key, or the -// platform's shared key when the user has none (see repo.SharedCodeBuddyKey). -func resolveCodeBuddyCredential(s *repo.Store, userID int64) runtime.CodeBuddyCredential { - if s == nil || userID <= 0 { - return runtime.CodeBuddyCredential{} - } - user, ok := s.User(userID) - if !ok { - return runtime.CodeBuddyCredential{} - } - if strings.TrimSpace(user.CodeBuddyAPIKey) != "" { - return runtime.CodeBuddyUserCredential(user) - } - shared, ok := s.SharedCodeBuddyKey() - if !ok || (shared.SponsorID != 0 && shared.SponsorID == user.ID) { - return runtime.CodeBuddyCredential{InternetEnvironment: user.CodeBuddyInternetEnvironment} - } - return runtime.CodeBuddyCredential{APIKey: shared.APIKey, InternetEnvironment: shared.InternetEnvironment, Sponsored: true, SponsoredModels: shared.Models} -} - -const sponsoredRunEvent = "model.sponsored" - -// sponsoredExecutor limits a CodeBuddy node running on the shared key to the -// models the administrator allowed: the role's model when it is one of them, -// the default otherwise, and tells the user why the role's model is not used. -func (e *Engine) sponsoredExecutor(runID string, ex domain.ExecutorDefinition, models []string, sink func(domain.TelemetryEvent)) domain.ExecutorDefinition { - configured := strings.TrimSpace(ex.Model) - key := repo.SharedCodeBuddyKey{Models: models} - model, allowed := key.Model(configured) - if !allowed { - model, _ = key.Model("") - } - if model == "" { - model = repo.SponsoredCodeBuddyModel - } - ex.Model = model - message := "责任人未配置个人 CodeBuddy API Key,本节点使用平台共享 Key,模型 " + model - if configured != "" && configured != model { - message += "(角色配置的 " + configured + " 不在平台允许的模型中,本次不生效)" - } - sink(domain.TelemetryEvent{Category: "model", Name: sponsoredRunEvent, Phase: "start", Message: message, Provider: ex.Kind, Model: ex.Model, Attributes: map[string]any{"configuredModel": configured}}) - if current, ok := e.repo.RunState(runID); ok && !hasRunEvent(current, sponsoredRunEvent) { - e.updateRun(runID, func(r *domain.Run) { - if !hasRunEvent(*r, sponsoredRunEvent) { - e.event(r, "", sponsoredRunEvent, "责任人未配置个人 CodeBuddy API Key,本次运行使用平台共享 Key,只能使用平台管理员允许的模型("+strings.Join(models, "、")+")。在个人配置中配置自己的 Key 后,可使用角色配置的任意模型") - } - }) - } - return ex -} - -func hasRunEvent(run domain.Run, typ string) bool { - return slices.ContainsFunc(run.Events, func(event domain.RunEvent) bool { return event.Type == typ }) -} diff --git a/internal/engine/model_credentials.go b/internal/engine/model_credentials.go new file mode 100644 index 000000000..54cf31adb --- /dev/null +++ b/internal/engine/model_credentials.go @@ -0,0 +1,136 @@ +package engine + +import ( + "slices" + "strings" + + "agentflow/internal/domain" + "agentflow/internal/repo" + "agentflow/internal/runtime" +) + +const ( + codeBuddyAPIKeyEnv = "CODEBUDDY_API_KEY" + codeBuddyInternetEnv = "CODEBUDDY_INTERNET_ENVIRONMENT" +) + +// resolveCodeBuddyCredential returns the responsible user's own key, or the +// platform's shared CodeBuddy key when the user has none (see +// repo.SharedModelKey). +func resolveCodeBuddyCredential(s *repo.Store, userID int64) runtime.CodeBuddyCredential { + if s == nil || userID <= 0 { + return runtime.CodeBuddyCredential{} + } + user, ok := s.User(userID) + if !ok { + return runtime.CodeBuddyCredential{} + } + if strings.TrimSpace(user.CodeBuddyAPIKey) != "" { + return runtime.CodeBuddyUserCredential(user) + } + shared, ok := s.SharedModelKey(domain.SharedModelProviderCodeBuddy) + if !ok || (shared.SponsorID != 0 && shared.SponsorID == user.ID) { + return runtime.CodeBuddyCredential{InternetEnvironment: user.CodeBuddyInternetEnvironment} + } + return runtime.CodeBuddyCredential{APIKey: shared.APIKey, InternetEnvironment: shared.InternetEnvironment, Sponsored: true, SponsoredModels: shared.Models} +} + +// resolveProviderCredential returns the responsible user's own Codex or +// Claude Code credential, or the platform's shared key for that CLI when the +// user configured none (see repo.SharedModelKey). +func resolveProviderCredential(s *repo.Store, userID int64, provider string, personal runtime.ProviderCredential) runtime.ProviderCredential { + if strings.TrimSpace(personal.APIKey) != "" || s == nil || userID <= 0 { + return personal + } + user, ok := s.User(userID) + if !ok { + return personal + } + shared, ok := s.SharedModelKey(provider) + if !ok || strings.TrimSpace(shared.APIKey) == "" || len(shared.Models) == 0 { + return personal + } + if shared.SponsorID != 0 && shared.SponsorID == user.ID { + return personal + } + return runtime.ProviderCredential{APIKey: shared.APIKey, BaseURL: shared.BaseURL, Sponsored: true, SponsoredModels: shared.Models} +} + +const sponsoredRunEvent = "model.sponsored" + +// sponsoredExecutor limits a node running on a shared key to the models the +// administrator allowed for that CLI: the role's model when it is one of +// them, the default otherwise, and tells the user why the role's model is not +// used. +func (e *Engine) sponsoredExecutor(runID string, ex domain.ExecutorDefinition, provider string, models []string, sink func(domain.TelemetryEvent)) domain.ExecutorDefinition { + configured := strings.TrimSpace(ex.Model) + key := repo.SharedModelKey{Models: models} + model, allowed := key.Model(configured) + if !allowed { + model, _ = key.Model("") + } + if model == "" { + model = repo.SponsoredCodeBuddyModel + } + ex.Model = model + label := sponsoredLabel(provider) + message := "责任人未配置个人 " + label + " API Key,本节点使用平台共享 Key,模型 " + model + if configured != "" && configured != model { + message += "(角色配置的 " + configured + " 不在平台允许的模型中,本次不生效)" + } + sink(domain.TelemetryEvent{Category: "model", Name: sponsoredRunEvent, Phase: "start", Message: message, Provider: ex.Kind, Model: ex.Model, Attributes: map[string]any{"configuredModel": configured}}) + if current, ok := e.repo.RunState(runID); ok && !hasRunEvent(current, sponsoredRunEvent) { + e.updateRun(runID, func(r *domain.Run) { + if !hasRunEvent(*r, sponsoredRunEvent) { + e.event(r, "", sponsoredRunEvent, "责任人未配置个人 "+label+" API Key,本次运行使用平台共享 Key,只能使用平台管理员允许的模型("+strings.Join(models, "、")+")。在个人配置中配置自己的 Key 后,可使用角色配置的任意模型") + } + }) + } + return ex +} + +// sponsoredLabel is the CLI name shown in run messages. +func sponsoredLabel(provider string) string { + switch provider { + case domain.SharedModelProviderCodex: + return "Codex" + case domain.SharedModelProviderClaude: + return "Claude Code" + } + return "CodeBuddy" +} + +// applySponsoredExecutor pins the model of a node whose credential came from +// the platform's shared key instead of the responsible user. +func (e *Engine) applySponsoredExecutor(runID string, ex domain.ExecutorDefinition, credentials runtime.RunCredentials, sink func(domain.TelemetryEvent)) domain.ExecutorDefinition { + switch ex.Kind { + case domain.SharedModelProviderCodeBuddy: + if cb := credentials.CodeBuddy; cb.Sponsored && len(cb.SponsoredModels) > 0 { + return e.sponsoredExecutor(runID, ex, domain.SharedModelProviderCodeBuddy, cb.SponsoredModels, sink) + } + case domain.SharedModelProviderCodex: + if p := credentials.Codex; p.Sponsored && len(p.SponsoredModels) > 0 { + return e.sponsoredExecutor(runID, ex, domain.SharedModelProviderCodex, p.SponsoredModels, sink) + } + case domain.SharedModelProviderClaude: + if p := credentials.ClaudeCode; p.Sponsored && len(p.SponsoredModels) > 0 { + return e.sponsoredExecutor(runID, ex, domain.SharedModelProviderClaude, p.SponsoredModels, sink) + } + } + return ex +} + +// runnerUsesLocalLogin reports whether a node of kind dispatched to runnerID +// runs with that machine's own CLI login (see dispatchRunnerTask), so no +// platform shared key reaches it. +func (e *Engine) runnerUsesLocalLogin(run domain.Run, runnerID, kind string) bool { + if runnerID == "" { + return false + } + runner, ok := e.repo.Runner(runnerID) + return ok && sopRunnerAuthMode(run.ExecutionContext, runner, kind) == domain.RuntimeAuthLocal +} + +func hasRunEvent(run domain.Run, typ string) bool { + return slices.ContainsFunc(run.Events, func(event domain.RunEvent) bool { return event.Type == typ }) +} diff --git a/internal/engine/codebuddy_auth_test.go b/internal/engine/model_credentials_test.go similarity index 54% rename from internal/engine/codebuddy_auth_test.go rename to internal/engine/model_credentials_test.go index 05f8613f4..500a95984 100644 --- a/internal/engine/codebuddy_auth_test.go +++ b/internal/engine/model_credentials_test.go @@ -124,11 +124,11 @@ func TestSponsoredExecutorKeepsAllowedRoleModel(t *testing.T) { e := New(st, runtime.NewManager(t.TempDir())) var observed []domain.TelemetryEvent sink := func(event domain.TelemetryEvent) { observed = append(observed, event) } - got := e.sponsoredExecutor("missing-run", domain.ExecutorDefinition{Kind: "codebuddy", Model: "kimi-k2.6"}, []string{"glm-5.1", "kimi-k2.6"}, sink) + got := e.sponsoredExecutor("missing-run", domain.ExecutorDefinition{Kind: "codebuddy", Model: "kimi-k2.6"}, domain.SharedModelProviderCodeBuddy, []string{"glm-5.1", "kimi-k2.6"}, sink) if got.Model != "kimi-k2.6" || len(observed) != 1 || strings.Contains(observed[0].Message, "不生效") { t.Fatalf("allowed role model = %+v, notice %+v", got, observed) } - got = e.sponsoredExecutor("missing-run", domain.ExecutorDefinition{Kind: "codebuddy"}, []string{"glm-5.1", "kimi-k2.6"}, sink) + got = e.sponsoredExecutor("missing-run", domain.ExecutorDefinition{Kind: "codebuddy"}, domain.SharedModelProviderCodeBuddy, []string{"glm-5.1", "kimi-k2.6"}, sink) if got.Model != "glm-5.1" { t.Fatalf("role without a model uses the shared default, got %+v", got) } @@ -156,7 +156,7 @@ func TestSponsoredExecutorPinsModelAndExplains(t *testing.T) { var observed []domain.TelemetryEvent sink := func(event domain.TelemetryEvent) { observed = append(observed, event) } for range 2 { - got := e.sponsoredExecutor(run.ID, domain.ExecutorDefinition{ID: "codebuddy", Kind: "codebuddy", Model: "claude-opus-5", Effort: "high"}, []string{repo.SponsoredCodeBuddyModel}, sink) + got := e.sponsoredExecutor(run.ID, domain.ExecutorDefinition{ID: "codebuddy", Kind: "codebuddy", Model: "claude-opus-5", Effort: "high"}, domain.SharedModelProviderCodeBuddy, []string{repo.SponsoredCodeBuddyModel}, sink) if got.Model != repo.SponsoredCodeBuddyModel || got.Effort != "high" || got.Kind != "codebuddy" { t.Fatalf("executor = %+v", got) } @@ -175,3 +175,112 @@ func TestSponsoredExecutorPinsModelAndExplains(t *testing.T) { t.Fatalf("run notes = %d, events %+v", notes, current.Events) } } + +// A user without a Codex or Claude Code key of their own runs on the shared +// key of that CLI, marked sponsored so the node is limited to its models. +func TestResolveProviderCredentialFallsBackToTheSharedKey(t *testing.T) { + s, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { s.Close() }) + t.Setenv(repo.CodeBuddySponsorLoginEnv, "") + for _, user := range []domain.User{ + {ID: 31, LoginName: "owner", CodexAPIKey: "sk_own", ClaudeCodeAPIKey: "sk_own_claude"}, + {ID: 32, LoginName: "newcomer"}, + } { + if err := s.PutUser(user); err != nil { + t.Fatal(err) + } + } + for _, update := range []repo.PlatformModelKeyUpdate{ + {Provider: domain.SharedModelProviderCodex, APIKey: "sk_codex", BaseURL: "https://gateway.example.com/v1", Models: []string{"gpt-6.1-terra", "gpt-6.1-sol"}}, + {Provider: domain.SharedModelProviderClaude, APIKey: "sk_claude", Models: []string{"claude-opus-5"}}, + } { + if err := s.SetPlatformModelKey(update, 31); err != nil { + t.Fatal(err) + } + } + codex := resolveProviderCredential(s, 32, domain.SharedModelProviderCodex, runtime.ProviderCredential{}) + if codex.APIKey != "sk_codex" || codex.BaseURL != "https://gateway.example.com/v1" || !codex.Sponsored || strings.Join(codex.SponsoredModels, ",") != "gpt-6.1-terra,gpt-6.1-sol" { + t.Fatalf("shared codex credential = %+v", codex) + } + claude := resolveProviderCredential(s, 32, domain.SharedModelProviderClaude, runtime.ProviderCredential{}) + if claude.APIKey != "sk_claude" || claude.BaseURL != "" || !claude.Sponsored || len(claude.SponsoredModels) != 1 { + t.Fatalf("shared claude credential = %+v", claude) + } + if own := resolveProviderCredential(s, 31, domain.SharedModelProviderCodex, runtime.ProviderCredential{APIKey: "sk_own"}); own.Sponsored || own.APIKey != "sk_own" { + t.Fatalf("a personal key wins, got %+v", own) + } + if missing := resolveProviderCredential(s, 999, domain.SharedModelProviderCodex, runtime.ProviderCredential{}); missing.APIKey != "" || missing.Sponsored { + t.Fatalf("unknown user must not borrow, got %+v", missing) + } + if none := resolveProviderCredential(s, 32, "kimi", runtime.ProviderCredential{}); none.APIKey != "" { + t.Fatalf("agent CLIs have no shared credential, got %+v", none) + } +} + +// A Codex or Claude Code node on the shared key runs an allowed model and says +// why the role's model did not apply. +func TestSponsoredExecutorPinsModelsForEverySharedCLI(t *testing.T) { + st, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + defer st.Close() + e := New(st, runtime.NewManager(t.TempDir())) + var observed []domain.TelemetryEvent + sink := func(event domain.TelemetryEvent) { observed = append(observed, event) } + got := e.sponsoredExecutor("missing-run", domain.ExecutorDefinition{Kind: "codex", Model: "gpt-5.5"}, domain.SharedModelProviderCodex, []string{"gpt-6.1-terra", "gpt-6.1-sol"}, sink) + if got.Model != "gpt-6.1-terra" || !strings.Contains(observed[0].Message, "个人 Codex API Key") || !strings.Contains(observed[0].Message, "gpt-5.5") || !strings.Contains(observed[0].Message, "不生效") { + t.Fatalf("codex executor = %+v, notice %+v", got, observed) + } + observed = nil + got = e.sponsoredExecutor("missing-run", domain.ExecutorDefinition{Kind: "claude-code", Model: "claude-opus-5"}, domain.SharedModelProviderClaude, []string{"claude-opus-5", "claude-haiku-5-5"}, sink) + if got.Model != "claude-opus-5" || !strings.Contains(observed[0].Message, "Claude Code") || strings.Contains(observed[0].Message, "不生效") { + t.Fatalf("claude executor = %+v, notice %+v", got, observed) + } + + // The snapshot decides: a personal or runner-login credential is kept. + sponsored := runtime.RunCredentials{Codex: runtime.ProviderCredential{APIKey: "sk", Sponsored: true, SponsoredModels: []string{"gpt-6.1-sol"}}} + if ex := e.applySponsoredExecutor("missing-run", domain.ExecutorDefinition{Kind: "codex", Model: "gpt-5.5"}, sponsored, sink); ex.Model != "gpt-6.1-sol" { + t.Fatalf("sponsored snapshot must pin the model, got %+v", ex) + } + if ex := e.applySponsoredExecutor("missing-run", domain.ExecutorDefinition{Kind: "codex", Model: "gpt-5.5"}, runtime.RunCredentials{}, sink); ex.Model != "gpt-5.5" { + t.Fatalf("an own credential keeps the role model, got %+v", ex) + } +} + +// A LOOP node can be scheduled onto a CLI the platform lends a key for. +func TestSharedKeyCountsAsExecutorCredential(t *testing.T) { + st, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + defer st.Close() + t.Setenv(repo.CodeBuddySponsorLoginEnv, "") + for _, user := range []domain.User{ + {ID: 41, LoginName: "owner"}, + {ID: 42, LoginName: "newcomer"}, + } { + if err := st.PutUser(user); err != nil { + t.Fatal(err) + } + } + if err := st.SetPlatformModelKey(repo.PlatformModelKeyUpdate{ + Provider: domain.SharedModelProviderCodex, APIKey: "sk_codex", + BaseURL: "https://gateway.example.com/v1", Models: []string{"gpt-6.1-terra"}, + }, 41); err != nil { + t.Fatal(err) + } + access := newSOPExecutorAccess(st, domain.TelemetryContext{ResponsibleUserID: 42}) + if !access.hasCredential(domain.SharedModelProviderCodex) { + t.Fatal("a shared Codex key must count as a credential") + } + if access.hasCredential(domain.SharedModelProviderClaude) { + t.Fatal("a CLI without a shared key must stay unconfigured") + } + if got := access.defaults().Executor; got != domain.SharedModelProviderCodex { + t.Fatalf("default executor = %q, want codex", got) + } +} diff --git a/internal/engine/node_execute.go b/internal/engine/node_execute.go index bc7342a5a..bb3bf338d 100644 --- a/internal/engine/node_execute.go +++ b/internal/engine/node_execute.go @@ -924,10 +924,14 @@ func (e *Engine) executeNode(ctx context.Context, runID string, wf domain.Workfl options.GateResultPath = gateResultPath(nodeControlKey(current, node.ID), attempt) } ex := ex - if cb := sb.credentialSnapshot().CodeBuddy; ex.Kind == "codebuddy" && cb.Sponsored { - ex = e.sponsoredExecutor(runID, ex, cb.SponsoredModels, sink) + execMachine := e.defaultExecutionRunner(current) + // A node that runs on an execution machine with that machine's own + // CLI login uses no shared key, so its model is not pinned to the + // shared key's allowed list. + if !e.runnerUsesLocalLogin(current, execMachine, ex.Kind) { + ex = e.applySponsoredExecutor(runID, ex, sb.credentialSnapshot(), sink) } - if execMachine := e.defaultExecutionRunner(current); execMachine != "" { + if execMachine != "" { // 执行机器 mode (bind-cli): the responsible user selected a default // execution machine, so the compiled task book, asset bundle, and // repository checkout are dispatched there; Codex / Claude Code use diff --git a/internal/engine/run_environment.go b/internal/engine/run_environment.go index f2b7c6c21..fb203f111 100644 --- a/internal/engine/run_environment.go +++ b/internal/engine/run_environment.go @@ -218,8 +218,10 @@ func (e *Engine) resolveRunCredentials(run domain.Run) runtime.RunCredentials { CodeBuddy: resolveCodeBuddyCredential(e.repo, userID), } if user, ok := e.repo.User(userID); ok { - credentials.Codex = runtime.ProviderCredential{APIKey: user.CodexAPIKey, BaseURL: user.CodexBaseURL} - credentials.ClaudeCode = runtime.ProviderCredential{APIKey: user.ClaudeCodeAPIKey, BaseURL: user.ClaudeCodeBaseURL} + credentials.Codex = resolveProviderCredential(e.repo, userID, domain.SharedModelProviderCodex, + runtime.ProviderCredential{APIKey: user.CodexAPIKey, BaseURL: user.CodexBaseURL}) + credentials.ClaudeCode = resolveProviderCredential(e.repo, userID, domain.SharedModelProviderClaude, + runtime.ProviderCredential{APIKey: user.ClaudeCodeAPIKey, BaseURL: user.ClaudeCodeBaseURL}) credentials.AgentCLI = runtime.AgentCLIUserCredentials(user) } // Replay only receives the model credentials required to produce output. diff --git a/internal/engine/sop_executors.go b/internal/engine/sop_executors.go index e37ae74ea..71fe8a047 100644 --- a/internal/engine/sop_executors.go +++ b/internal/engine/sop_executors.go @@ -8,6 +8,7 @@ import ( "agentflow/internal/domain" "agentflow/internal/repo" + "agentflow/internal/runtime" ) type SOPExecutorRequirement struct { @@ -19,11 +20,13 @@ type SOPExecutorRequirement struct { var errSOPExecutorUnconfigured = errors.New("请在个人配置中添加当前执行环境可用的执行器,再重试此节点") type sopExecutorAccess struct { - user domain.User - runner domain.Runner - usesRunner bool - execution domain.TelemetryContext - sharedCodeBuddy bool + user domain.User + runner domain.Runner + usesRunner bool + execution domain.TelemetryContext + // shared marks the CLIs whose personal key the responsible user lacks and + // whose platform-shared key stands in for it. + shared map[string]bool } func (e *Engine) sopExecutorAccess(ec domain.TelemetryContext) sopExecutorAccess { @@ -33,9 +36,19 @@ func (e *Engine) sopExecutorAccess(ec domain.TelemetryContext) sopExecutorAccess func newSOPExecutorAccess(s *repo.Store, ec domain.TelemetryContext) sopExecutorAccess { user, _ := s.User(ec.ResponsibleUserID) runner, _ := s.Runner(ec.ExecutionRunnerID) + shared := map[string]bool{} + if resolveCodeBuddyCredential(s, user.ID).Sponsored { + shared[domain.SharedModelProviderCodeBuddy] = true + } + if resolveProviderCredential(s, user.ID, domain.SharedModelProviderCodex, runtime.ProviderCredential{APIKey: user.CodexAPIKey}).Sponsored { + shared[domain.SharedModelProviderCodex] = true + } + if resolveProviderCredential(s, user.ID, domain.SharedModelProviderClaude, runtime.ProviderCredential{APIKey: user.ClaudeCodeAPIKey}).Sponsored { + shared[domain.SharedModelProviderClaude] = true + } return sopExecutorAccess{ user: user, runner: runner, usesRunner: ec.ExecutionRunnerID != "", execution: ec, - sharedCodeBuddy: resolveCodeBuddyCredential(s, user.ID).Sponsored, + shared: shared, } } @@ -113,13 +126,13 @@ func (a sopExecutorAccess) configured(kind string) bool { return a.hasCredential(kind) } -// hasCredential accepts a personal key, the platform's shared CodeBuddy Key, -// or account login on the run's machine. +// hasCredential accepts a personal key, the platform's shared key for that +// CLI, or account login on the run's machine. func (a sopExecutorAccess) hasCredential(kind string) bool { if a.runner.SupportsProvider(kind) && a.runnerLogin(kind) { return true } - return a.user.HasExecutorCredential(kind) || kind == "codebuddy" && a.sharedCodeBuddy + return a.user.HasExecutorCredential(kind) || a.shared[kind] } func (a sopExecutorAccess) defaults() domain.AssistantDefaults { @@ -138,8 +151,10 @@ func (a sopExecutorAccess) defaults() domain.AssistantDefaults { return a.defaultsFor(ex, "", "") } } - if a.configured("codebuddy") { - return domain.AssistantDefaults{Executor: "codebuddy"} + for _, kind := range domain.SharedModelProviders { + if a.shared[kind] && a.configured(kind) { + return domain.AssistantDefaults{Executor: kind} + } } return domain.AssistantDefaults{} } diff --git a/internal/engine/sop_executors_test.go b/internal/engine/sop_executors_test.go index af7bd8704..2b189c5fb 100644 --- a/internal/engine/sop_executors_test.go +++ b/internal/engine/sop_executors_test.go @@ -90,8 +90,8 @@ func TestGenericSOPCopyUsesPersonalDefaultForUnpinnedRoles(t *testing.T) { func TestGenericSOPExecutorPrefersRunnerLoginOverSharedKey(t *testing.T) { access := sopExecutorAccess{ - usesRunner: true, - sharedCodeBuddy: true, + usesRunner: true, + shared: map[string]bool{"codebuddy": true}, runner: domain.Runner{Runtimes: []domain.RunnerRuntime{ {Provider: "codebuddy", AuthMode: domain.RuntimeAuthPersonal, Status: domain.RuntimeStatusOnline}, {Provider: "codex", AuthMode: domain.RuntimeAuthLocal, Status: domain.RuntimeStatusOnline}, diff --git a/internal/engine/sponsored_runner_login_test.go b/internal/engine/sponsored_runner_login_test.go new file mode 100644 index 000000000..182006ae7 --- /dev/null +++ b/internal/engine/sponsored_runner_login_test.go @@ -0,0 +1,99 @@ +package engine + +import ( + "strings" + "testing" + "time" + + "agentflow/internal/domain" + "agentflow/internal/repo" + "agentflow/internal/runtime" +) + +// A node that runs on the responsible user's machine with that machine's own +// Codex login sends no shared key, so the role's model is kept and the run +// does not claim it used the shared key. On the same machine in personal mode +// the shared key is what runs the node, so the model is still pinned. +func TestSponsoredModelPinSkipsRunnerLocalLogin(t *testing.T) { + for _, tc := range []struct { + name string + authMode string + wantModel string + sponsored bool + }{ + {"local login keeps the role model", domain.RuntimeAuthLocal, "gpt-role-model", false}, + {"personal mode runs on the shared key", domain.RuntimeAuthPersonal, "gpt-shared-only", true}, + } { + t.Run(tc.name, func(t *testing.T) { + st, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(st.Close) + if err := st.PutUser(domain.User{ID: 7, LoginName: "member"}); err != nil { + t.Fatal(err) + } + if err := st.SetPlatformModelKey(repo.PlatformModelKeyUpdate{Provider: domain.SharedModelProviderCodex, APIKey: "sk_shared", Models: []string{"gpt-shared-only"}}, 7); err != nil { + t.Fatal(err) + } + runner := domain.Runner{ID: "member-runner", Name: "member-runner", OwnerUserID: 7, Status: domain.RunnerStatusOnline, + RunnerVersion: domain.RunnerVersionWorkspaceOwnerPreparation, + Runtimes: []domain.RunnerRuntime{{Provider: "codex", Status: "ready", AuthMode: tc.authMode}}} + if err := st.PutRunner(runner); err != nil { + t.Fatal(err) + } + if err := st.PutAgent(domain.AgentDefinition{ID: "coder", Name: "Coder", ExecutorID: "codex", Model: "gpt-role-model", Prompt: "work"}); err != nil { + t.Fatal(err) + } + wf := domain.WorkflowDefinition{ID: "runner-login", Name: "Runner login", SandboxProfileID: "test-native", + Nodes: []domain.WorkflowNode{{ID: "work", Name: "Work", Type: "agent", AgentID: "coder", MaxAttempts: 1}}} + if err := st.PutWorkflow(wf); err != nil { + t.Fatal(err) + } + e := New(st, runtime.NewManager(t.TempDir())) + queued := make(chan domain.RunnerTask, 4) + e.SetRunnerDispatchNotify(func(string) { + for _, task := range st.RunnerTasks() { + if task.NodeID == "work" && task.Status == domain.RunnerTaskQueued && task.Invocation != nil { + select { + case queued <- task: + default: + } + } + } + }) + run, err := e.StartWithExecutionContext(wf.ID, "", domain.RepositoryContext{}, domain.TelemetryContext{ + ResponsibleUserID: 7, ExecutionMode: domain.ExecutionModeRunner, ExecutionRunnerID: runner.ID, ExecutionPinned: true, + RunnerWorkspaceLayout: domain.RunnerWorkspaceLayoutShared, + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = e.Cancel(run.ID) }) + var task domain.RunnerTask + select { + case task = <-queued: + case <-time.After(10 * time.Second): + current, _ := st.RunState(run.ID) + t.Fatalf("node was not dispatched to the runner: status=%s events=%+v", current.Status, current.Events) + } + inv := task.Invocation + if inv.Executor.Model != tc.wantModel { + t.Fatalf("dispatched model = %q (credential source %q), want %q", inv.Executor.Model, inv.CredentialSource, tc.wantModel) + } + if sent := inv.CodexAPIKey != ""; sent != tc.sponsored { + t.Fatalf("shared key sent = %v, want %v (credential source %q)", sent, tc.sponsored, inv.CredentialSource) + } + current, _ := st.RunState(run.ID) + noted := false + for _, event := range current.Events { + if event.Type == sponsoredRunEvent || strings.Contains(event.Message, "共享 Key") { + noted = true + } + } + if noted != tc.sponsored { + t.Fatalf("shared-key note on the run = %v, want %v: %+v", noted, tc.sponsored, current.Events) + } + }) + } +} diff --git a/internal/httpapi/assistant_engine_models_test.go b/internal/httpapi/assistant_engine_models_test.go index af1af0d54..c9c6a4cf8 100644 --- a/internal/httpapi/assistant_engine_models_test.go +++ b/internal/httpapi/assistant_engine_models_test.go @@ -18,7 +18,7 @@ func TestAssistantEngineModelsKeepPersonalCatalogOnOfficialKey(t *testing.T) { return []assistantDiscoveredModel{{ID: "remote-model", Name: "Remote"}}, nil } ids := func(user domain.User) []string { - models, _ := assistantEngineModels(context.Background(), user, nil) + models, _ := assistantEngineModels(context.Background(), user, nil, nil) var out []string for _, model := range models { out = append(out, model.ID) diff --git a/internal/httpapi/assistant_engines.go b/internal/httpapi/assistant_engines.go index 0c5d6ce1e..0b454cc75 100644 --- a/internal/httpapi/assistant_engines.go +++ b/internal/httpapi/assistant_engines.go @@ -58,6 +58,9 @@ type assistantEngineOption struct { Configured bool `json:"configured"` Personal bool `json:"personal"` Credential string `json:"credential"` + // Shared is set when the platform's shared key for this CLI stands in for + // a personal one. + Shared bool `json:"shared,omitempty"` // Missing and installable are reported only for a cloud chat hosted by this platform. ServerMissing bool `json:"serverMissing,omitempty"` ServerInstallable bool `json:"serverInstallable,omitempty"` @@ -77,19 +80,22 @@ func assistantEngineCredentialField(engine string) string { } // assistantEngineOptions lists every CLI, configured or not, so the switch -// also shows where to add a key. CodeBuddy counts as configured when the -// platform sponsors chats without one. -func assistantEngineOptions(user domain.User, sponsored bool) []assistantEngineOption { +// also shows where to add a key. shared holds the CLIs whose key the platform +// lends to this user (see assistantSharedEngineModels): such a CLI counts as +// configured without a personal key. +func assistantEngineOptions(user domain.User, shared map[string][]string) []assistantEngineOption { engines := append([]string{assistantEngineCodeBuddy}, assistantCLIEngines()...) out := make([]assistantEngineOption, 0, len(engines)) for _, engine := range engines { key, _ := assistantEngineCredential(user, engine) + sponsored := key == "" && len(shared[engine]) > 0 out = append(out, assistantEngineOption{ ID: engine, Name: assistantEngineLabel(engine), - Configured: key != "" || (engine == assistantEngineCodeBuddy && sponsored), + Configured: key != "" || len(shared[engine]) > 0, Personal: key != "", Credential: assistantEngineCredentialField(engine), + Shared: sponsored, }) } return out @@ -256,7 +262,8 @@ func assistantEngineMissingKey(engine string) string { return fmt.Sprintf("请先在个人配置中配置 %s API Key 后再使用 %s 模型", assistantEngineLabel(engine), assistantEngineLabel(engine)) } -// assistantTurnUser checks personal credentials or the chosen runner login. +// assistantTurnUser checks personal credentials, the chosen runner login, or +// the platform's shared key for the chosen CLI. func (h *assistantHandlers) assistantTurnUser(stored domain.User, model string, runnerLogin bool) (domain.User, string, string) { engine, id := assistantModelEngine(model) if engine != assistantEngineCodeBuddy { @@ -266,10 +273,21 @@ func (h *assistantHandlers) assistantTurnUser(stored domain.User, model string, if !assistantValidEngineModel(id) { return stored, "", "模型 ID 无效" } - if key, _ := assistantEngineCredential(stored, engine); !runnerLogin && key == "" { + if runnerLogin { + return stored, engine + ":" + id, "" + } + user, shared, ok := h.assistantChatUserForEngine(stored, engine) + if !ok { return stored, "", assistantEngineMissingKey(engine) } - return stored, engine + ":" + id, "" + if len(shared) > 0 { + forced, allowed := assistantSponsoredModelFor(shared, id) + if !allowed { + return stored, "", errAssistantSponsoredModel(assistantEngineLabel(engine), shared) + } + return user, engine + ":" + forced, "" + } + return user, engine + ":" + id, "" } user, shared, ok := h.assistantChatUser(stored) if !ok { @@ -278,7 +296,7 @@ func (h *assistantHandlers) assistantTurnUser(stored domain.User, model string, if len(shared) > 0 { forced, allowed := assistantSponsoredModelFor(shared, id) if !allowed { - return stored, "", errAssistantSponsoredModel(shared) + return stored, "", errAssistantSponsoredModel(assistantEngineLabel(engine), shared) } model = forced } @@ -363,9 +381,22 @@ func assistantSavedModels(user domain.User, engine string) []assistantDiscovered return listed } -func assistantEngineModels(ctx context.Context, user domain.User, runnerLogin map[string]bool) (models []assistantModel, cursorModelsPending bool) { +func assistantEngineModels(ctx context.Context, user domain.User, runnerLogin map[string]bool, shared map[string][]string) (models []assistantModel, cursorModelsPending bool) { for _, engine := range assistantCLIEngines() { key, baseURL := assistantEngineCredential(user, engine) + if key == "" && !runnerLogin[engine] && len(shared[engine]) > 0 { + // The platform's shared key stands in for this CLI: offer exactly + // the models its administrator allowed. + for _, id := range shared[engine] { + models = append(models, assistantModel{ + ID: engine + ":" + id, + Name: id, + Family: assistantModelFamily(id, engine), + Engine: engine, + }) + } + continue + } listed := assistantSavedModels(user, engine) if key == "" && !runnerLogin[engine] && len(listed) == 0 { continue @@ -729,6 +760,9 @@ func (h *assistantHandlers) assistantChatRequestModel(req assistantRequest, save if preferred := personalDefaultModel(user); preferred != "" { return preferred } + if shared := h.assistantSharedDefaultModel(user); shared != "" { + return shared + } if _, _, codeBuddyAvailable := h.assistantChatUser(user); !codeBuddyAvailable { if model, err := resolveFeatureModel(user, ""); err == nil { return model @@ -738,6 +772,24 @@ func (h *assistantHandlers) assistantChatRequestModel(req assistantRequest, save return assistantRequestModel(req.Executor, req.Model) } +// assistantSharedDefaultModel is the model a new conversation starts on when +// the caller configured no key of their own: the shared CodeBuddy default +// first, then the default of another CLI the platform shares. +func (h *assistantHandlers) assistantSharedDefaultModel(user domain.User) string { + shared := assistantSharedEngineModels(h.repo, user) + for _, engine := range domain.SharedModelProviders { + models := shared[engine] + if len(models) == 0 { + continue + } + if engine == domain.SharedModelProviderCodeBuddy { + return models[0] + } + return engine + ":" + models[0] + } + return "" +} + // assistantRequestModel maps a legacy executor field onto the model prefix // the conversation engines use. A model that already names its CLI is kept. func assistantRequestModel(executor, model string) string { diff --git a/internal/httpapi/assistant_models.go b/internal/httpapi/assistant_models.go index 71b6c9bf2..49b52c225 100644 --- a/internal/httpapi/assistant_models.go +++ b/internal/httpapi/assistant_models.go @@ -45,6 +45,9 @@ type assistantModelCatalog struct { // SponsoredModel is the first (the default). SponsoredModel string `json:"sponsoredModel,omitempty"` SponsoredModels []string `json:"sponsoredModels,omitempty"` + // SharedEngines lists, per CLI, the models the platform lends to a + // signed-in user who configured no key of their own for it. + SharedEngines map[string][]string `json:"sharedEngines,omitempty"` // Engines lists the CLIs a signed-in user can switch between. Engines []assistantEngineOption `json:"engines,omitempty"` Preferences *domain.AssistantDefaults `json:"preferences,omitempty"` @@ -222,9 +225,10 @@ func (h *assistantHandlers) models(c *gin.Context) { engine = assistantEngineClaude } var user domain.User - if h.repo != nil && (engine == runtime.AgentCLIKimi || engine == runtime.AgentCLIAntigravity) { - if current, signedIn := h.requestUser(c.Request, true); signedIn { - user, _ = h.repo.User(current.ID) + signedIn := false + if h.repo != nil { + if current, ok := h.requestUser(c.Request, true); ok { + user, signedIn = h.repo.User(current.ID) } } _, kimiBaseURL := assistantEngineCredential(user, runtime.AgentCLIKimi) @@ -239,6 +243,15 @@ func (h *assistantHandlers) models(c *gin.Context) { c.JSON(200, result) return } + if signedIn && sharedEngine(engine) { + // A caller without their own key sees only the models the + // platform's shared key allows. + if key, _ := assistantEngineCredential(user, engine); key == "" { + if shared, found := h.repo.SharedModelKey(engine); found && len(shared.Models) > 0 { + catalog = restrictExecutorCatalog(catalog, shared.Models) + } + } + } for _, item := range catalog.Models { levels := make([]string, 0, len(item.Efforts)) for _, option := range item.Efforts { @@ -260,6 +273,7 @@ func (h *assistantHandlers) models(c *gin.Context) { user, signedIn = h.repo.User(current.ID) } usingSharedKey := signedIn && shared && strings.TrimSpace(user.CodeBuddyAPIKey) == "" + sharedModels := assistantSharedEngineModels(h.repo, user) switch { case usingSharedKey: // Chat runs on the shared key, so list what that key's environment offers. @@ -294,7 +308,10 @@ func (h *assistantHandlers) models(c *gin.Context) { if strings.TrimSpace(c.Query("refresh")) == "1" { invalidateAssistantEngineDiscoveryCache(user) } - catalog.Engines = assistantEngineOptions(user, usingSharedKey) + catalog.Engines = assistantEngineOptions(user, sharedModels) + if len(sharedModels) > 0 { + catalog.SharedEngines = sharedModels + } cloudPool := false if h.engine != nil { cloudPool, _ = h.engine.CloudPoolStatus() @@ -320,7 +337,7 @@ func (h *assistantHandlers) models(c *gin.Context) { } } } - models, pending := assistantEngineModels(c.Request.Context(), user, runnerLogin) + models, pending := assistantEngineModels(c.Request.Context(), user, runnerLogin, sharedModels) catalog.Models = append(catalog.Models, models...) catalog.CursorModelsPending = pending h.saveCursorCatalog(user) diff --git a/internal/httpapi/assistant_schedule.go b/internal/httpapi/assistant_schedule.go index 0d3a64f97..2b5c808f9 100644 --- a/internal/httpapi/assistant_schedule.go +++ b/internal/httpapi/assistant_schedule.go @@ -347,7 +347,7 @@ func scheduledAssistantDefault(r *repo.Store, user domain.User, projectID, model if preferred := personalDefaultModel(user); preferred != "" { return preferred } - for _, option := range assistantEngineOptions(user, false) { + for _, option := range assistantEngineOptions(user, nil) { if !scheduleHasPersonalCredential(r, user, projectID, option.ID) { continue } diff --git a/internal/httpapi/assistant_sponsor.go b/internal/httpapi/assistant_sponsor.go index 928bdc856..bc3ce04d7 100644 --- a/internal/httpapi/assistant_sponsor.go +++ b/internal/httpapi/assistant_sponsor.go @@ -9,32 +9,38 @@ import ( "agentflow/internal/repo" ) -// Users who have not configured their own CodeBuddy API Key can still chat -// with the platform's shared key (see repo.SharedCodeBuddyKey), limited to -// the models a platform administrator allowed. LOOP runs use it the same way -// through the engine, and AI scheduled tasks through scheduleCredentialUser; -// clarification, reports and bots keep requiring the user's own key. +// Users who have not configured their own API Key for a CLI can still chat +// with the platform's shared key for that CLI (see repo.SharedModelKey), +// limited to the models a platform administrator allowed. LOOP runs use it the +// same way through the engine, and AI scheduled tasks through +// scheduleCredentialUser for CodeBuddy; clarification, reports and bots keep +// requiring the user's own key. const ( assistantSponsorLoginEnv = repo.CodeBuddySponsorLoginEnv assistantSponsoredModel = repo.SponsoredCodeBuddyModel ) -func errAssistantSponsoredModel(models []string) string { - return "未配置个人 CodeBuddy API Key 时只能使用平台管理员允许的模型(" + strings.Join(models, "、") + ")。要使用其他模型,请先在个人配置中配置自己的 CodeBuddy API Key" +func errAssistantSponsoredModel(label string, models []string) string { + return "未配置个人 " + label + " API Key 时只能使用平台管理员允许的模型(" + strings.Join(models, "、") + ")。要使用其他模型,请先在个人配置中配置自己的 " + label + " API Key" } -// assistantSharedKey returns the key users without their own borrow. -func (h *assistantHandlers) assistantSharedKey() (repo.SharedCodeBuddyKey, bool) { +// assistantSharedKey returns the CodeBuddy key users without their own borrow. +func (h *assistantHandlers) assistantSharedKey() (repo.SharedModelKey, bool) { + return h.assistantSharedModelKey(domain.SharedModelProviderCodeBuddy) +} + +// assistantSharedModelKey returns the shared credential of one CLI. +func (h *assistantHandlers) assistantSharedModelKey(provider string) (repo.SharedModelKey, bool) { if h == nil || h.deps == nil || h.repo == nil { - return repo.SharedCodeBuddyKey{}, false + return repo.SharedModelKey{}, false } - return h.repo.SharedCodeBuddyKey() + return h.repo.SharedModelKey(provider) } -// assistantChatUser returns the identity a chat turn runs as. Users with -// their own key are returned unchanged. Other turns use the shared key, -// its environment and catalog while keeping the caller's identity, -// permissions and Git credentials. +// assistantChatUser returns the identity a CodeBuddy chat turn runs as. Users +// with their own key are returned unchanged. Other turns use the shared key, +// its environment and catalog while keeping the caller's identity, permissions +// and Git credentials. func (h *assistantHandlers) assistantChatUser(user domain.User) (chatUser domain.User, shared []string, ok bool) { if strings.TrimSpace(user.CodeBuddyAPIKey) != "" { return user, nil, true @@ -50,14 +56,67 @@ func (h *assistantHandlers) assistantChatUser(user domain.User) (chatUser domain return user, key.Models, true } +// assistantChatUserForEngine is assistantChatUser for any shared CLI: it +// substitutes that CLI's shared key and Base URL when the user configured +// none, and reports the models the shared key allows. +func (h *assistantHandlers) assistantChatUserForEngine(user domain.User, engine string) (chatUser domain.User, shared []string, ok bool) { + if engine == assistantEngineCodeBuddy { + return h.assistantChatUser(user) + } + if key, _ := assistantEngineCredential(user, engine); key != "" { + return user, nil, true + } + if !sharedEngine(engine) { + return user, nil, false + } + key, found := h.assistantSharedModelKey(engine) + if !found || strings.TrimSpace(key.APIKey) == "" || len(key.Models) == 0 || (key.SponsorID != 0 && key.SponsorID == user.ID) { + return user, nil, false + } + switch engine { + case assistantEngineCodex: + user.CodexAPIKey, user.CodexBaseURL, user.CodexModels = key.APIKey, key.BaseURL, nil + case assistantEngineClaude: + user.ClaudeCodeAPIKey, user.ClaudeCodeBaseURL, user.ClaudeCodeModels = key.APIKey, key.BaseURL, nil + } + return user, key.Models, true +} + +// sharedEngine reports whether a CLI's key can be shared platform-wide. +func sharedEngine(engine string) bool { + _, ok := domain.NormalizeSharedModelProvider(engine) + return ok && engine != domain.SharedModelProviderCodeBuddy +} + +// assistantSharedEngineModels lists, per CLI, the models the platform shares +// with this user: none for a CLI the user configured, and none they lend +// themselves. +func assistantSharedEngineModels(r *repo.Store, user domain.User) map[string][]string { + shared := map[string][]string{} + if r == nil || user.ID <= 0 { + return shared + } + for _, engine := range domain.SharedModelProviders { + if key, _ := assistantEngineCredential(user, engine); key != "" { + continue + } + key, found := r.SharedModelKey(engine) + if !found || strings.TrimSpace(key.APIKey) == "" || len(key.Models) == 0 || (key.SponsorID != 0 && key.SponsorID == user.ID) { + continue + } + shared[engine] = key.Models + } + return shared +} + // 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.SharedModelKey{Models: shared}.Model(requested) } -// usesSharedKey reports whether a chat turn for user runs on the shared key: -// the stored account has no key of its own. +// usesSharedKey reports whether a CodeBuddy chat turn for user runs on the +// shared key: the stored account has no key of its own. func (h *assistantHandlers) usesSharedKey(user domain.User) bool { if h == nil || h.deps == nil || h.repo == nil || user.ID <= 0 { return false diff --git a/internal/httpapi/cli_model_efforts_test.go b/internal/httpapi/cli_model_efforts_test.go index c135b0be1..795b6e1e9 100644 --- a/internal/httpapi/cli_model_efforts_test.go +++ b/internal/httpapi/cli_model_efforts_test.go @@ -54,7 +54,7 @@ func TestModelEffortsSurviveProbeSaveAndSelection(t *testing.T) { t.Fatal(err) } owner, _ = h.repo.User(owner.ID) - models, _ := assistantEngineModels(context.Background(), owner, nil) + models, _ := assistantEngineModels(context.Background(), owner, nil, nil) for id, efforts := range map[string][]string{ "codex:gateway-reasoner": {"low", "xhigh"}, "codex:gpt-5.5": {"low", "medium", "high", "xhigh"}, @@ -150,7 +150,7 @@ func TestAutomaticDiscoveryUsesSameEffortsForColdValidation(t *testing.T) { user := domain.User{CodexAPIKey: "fixture-key", CodexBaseURL: gateway.URL} key := assistantDiscoveryKey("", user.CodexAPIKey, user.CodexBaseURL) t.Cleanup(func() { assistantDiscoveryCache.Delete(key) }) - catalog, _ := assistantEngineModels(ctx, user, nil) + catalog, _ := assistantEngineModels(ctx, user, nil, nil) if !slices.ContainsFunc(catalog, func(model assistantModel) bool { return model.ID == "codex:remote" && slices.Equal(model.Efforts, []string{"xhigh"}) }) { @@ -184,7 +184,7 @@ func TestKimiThinkingSwitchSurvivesSavedCatalog(t *testing.T) { t.Fatal(err) } owner, _ = h.repo.User(owner.ID) - chat, _ := assistantEngineModels(context.Background(), owner, nil) + chat, _ := assistantEngineModels(context.Background(), owner, nil, nil) if !slices.ContainsFunc(chat, func(model assistantModel) bool { return model.ID == "kimi:kimi-for-coding-highspeed" && slices.Equal(model.Efforts, levels) }) { @@ -198,7 +198,7 @@ func TestKimiThinkingSwitchSurvivesSavedCatalog(t *testing.T) { t.Fatal(err) } owner, _ = h.repo.User(owner.ID) - chat, _ = assistantEngineModels(context.Background(), owner, nil) + chat, _ = assistantEngineModels(context.Background(), owner, nil, nil) if !slices.ContainsFunc(chat, func(model assistantModel) bool { return model.ID == "kimi:kimi-for-coding-highspeed" && len(model.Efforts) == 0 }) { diff --git a/internal/httpapi/cli_models_probe_test.go b/internal/httpapi/cli_models_probe_test.go index 5d558c31b..1a9f21138 100644 --- a/internal/httpapi/cli_models_probe_test.go +++ b/internal/httpapi/cli_models_probe_test.go @@ -96,7 +96,7 @@ func TestAntigravityCatalogFollowsCredentialSource(t *testing.T) { user := domain.User{AgentCLICredentials: map[string]domain.AgentCLICredential{ "agy": {APIKey: "fixture-key", Protocol: domain.AgentCLIProtocolGemini}, }} - builtin, _ := assistantEngineModels(ctx, user, nil) + builtin, _ := assistantEngineModels(ctx, user, nil, nil) for id, efforts := range map[string][]string{ "gemini-4-neon-high": {"low", "medium", "high", "xhigh"}, "gemini-4-carbon-medium": {"low", "medium", "high"}, @@ -129,13 +129,13 @@ func TestAntigravityCatalogFollowsCredentialSource(t *testing.T) { cred := user.AgentCLICredentials["agy"] cred.BaseURL = service.URL user.AgentCLICredentials["agy"] = cred - custom, _ := assistantEngineModels(ctx, user, nil) + custom, _ := assistantEngineModels(ctx, user, nil, nil) if len(custom) != 1 || custom[0].ID != "agy:gemini-gateway" { t.Fatalf("custom endpoint models = %+v", custom) } cred.Protocol = domain.AgentCLIProtocolChat user.AgentCLICredentials["agy"] = cred - if fallback, _ := assistantEngineModels(ctx, user, nil); len(fallback) != 0 { + if fallback, _ := assistantEngineModels(ctx, user, nil, nil); len(fallback) != 0 { t.Fatalf("an unavailable gateway offered native models: %+v", fallback) } } diff --git a/internal/httpapi/cursor_catalog_test.go b/internal/httpapi/cursor_catalog_test.go index b41a6c63b..9effee45a 100644 --- a/internal/httpapi/cursor_catalog_test.go +++ b/internal/httpapi/cursor_catalog_test.go @@ -122,7 +122,7 @@ func TestCursorFamiliesSurviveRestart(t *testing.T) { t.Fatal("unknown model accepted an effort") } var listed []assistantModel - models, _ := assistantEngineModels(context.Background(), a, nil) + models, _ := assistantEngineModels(context.Background(), a, nil, nil) for _, model := range models { if model.Engine == runtime.AgentCLICursor { listed = append(listed, model) diff --git a/internal/httpapi/executor_models.go b/internal/httpapi/executor_models.go index 691407136..b3aced79d 100644 --- a/internal/httpapi/executor_models.go +++ b/internal/httpapi/executor_models.go @@ -132,6 +132,28 @@ func effortOptions(levels []string) []executorEffortOption { // executorModelCatalogs returns built-in options plus the caller's CodeBuddy // catalog. +// restrictExecutorCatalog keeps the allowed models in the administrator's +// order, adding the IDs the built-in catalog does not list. +func restrictExecutorCatalog(catalog executorModelCatalog, allowed []string) executorModelCatalog { + byID := map[string]executorModelInfo{} + for _, model := range catalog.Models { + byID[model.ID] = model + } + models := make([]executorModelInfo, 0, len(allowed)) + for _, id := range allowed { + model, ok := byID[id] + if !ok { + model = executorModelInfo{ID: id, Name: id} + } + models = append(models, model) + } + catalog.Models = models + if len(allowed) > 0 { + catalog.Default = allowed[0] + } + return catalog +} + func executorModelCatalogs(kimiBaseURL string, codebuddy assistantModelCatalog) map[string]executorModelCatalog { codebuddyModels := make([]executorModelInfo, 0) for _, model := range selectableCodeBuddyModels(codebuddy.Models) { diff --git a/internal/httpapi/feature_model.go b/internal/httpapi/feature_model.go index a7bb710a0..870197bd0 100644 --- a/internal/httpapi/feature_model.go +++ b/internal/httpapi/feature_model.go @@ -53,7 +53,7 @@ func resolveFeatureModel(user domain.User, requested string) (string, error) { if preferred := personalDefaultModel(user); preferred != "" { return preferred, nil } - for _, option := range assistantEngineOptions(user, false) { + for _, option := range assistantEngineOptions(user, nil) { if option.Configured { return featureDefaultModel(user, option.ID), nil } diff --git a/internal/httpapi/issues.go b/internal/httpapi/issues.go index fe8206ec2..5cfbc456f 100644 --- a/internal/httpapi/issues.go +++ b/internal/httpapi/issues.go @@ -507,11 +507,13 @@ func (h issuesHandlers) clarifyModels(c *gin.Context, issue domain.Issue) { } ctx := c.Request.Context() catalog := personalCodeBuddyCatalog(ctx, user) - catalog.Engines = assistantEngineOptions(user, false) + // Clarification runs on the owner's own credentials (resolveFeatureModel), + // so shared keys must not offer models it would then refuse. + catalog.Engines = assistantEngineOptions(user, nil) if user.AssistantDefaults != (domain.AssistantDefaults{}) { catalog.Preferences = &user.AssistantDefaults } - models, _ := assistantEngineModels(ctx, user, nil) + models, _ := assistantEngineModels(ctx, user, nil, nil) catalog.Models = append(selectableCodeBuddyModels(catalog.Models), models...) c.Header("Cache-Control", "private, no-store") c.JSON(http.StatusOK, catalog) diff --git a/internal/httpapi/platform_settings_models_test.go b/internal/httpapi/platform_model_keys_models_test.go similarity index 62% rename from internal/httpapi/platform_settings_models_test.go rename to internal/httpapi/platform_model_keys_models_test.go index e84f9da89..181adb9dc 100644 --- a/internal/httpapi/platform_settings_models_test.go +++ b/internal/httpapi/platform_model_keys_models_test.go @@ -8,8 +8,8 @@ import ( "agentflow/internal/repo" ) -func TestSharedCodeBuddyModelsTrimsAndDeduplicatesInOrder(t *testing.T) { - got, err := sharedCodeBuddyModels([]string{" glm-5.1 ", "", "kimi-k2.6", "glm-5.1", " ", "org/model:v1"}) +func TestSharedModelsTrimsAndDeduplicatesInOrder(t *testing.T) { + got, err := sharedModels([]string{" glm-5.1 ", "", "kimi-k2.6", "glm-5.1", " ", "org/model:v1"}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -18,9 +18,9 @@ func TestSharedCodeBuddyModelsTrimsAndDeduplicatesInOrder(t *testing.T) { } } -func TestSharedCodeBuddyModelsRejectsInvalidID(t *testing.T) { +func TestSharedModelsRejectsInvalidID(t *testing.T) { for _, id := range []string{"-leading-dash", "bad id", "中文模型", strings.Repeat("a", 129)} { - got, err := sharedCodeBuddyModels([]string{"glm-5.1", id}) + got, err := sharedModels([]string{"glm-5.1", id}) want := "模型 ID 格式不正确:" + strings.TrimSpace(id) if err == nil || err.Error() != want || got != nil { t.Fatalf("id %q: models=%q err=%v, want %q", id, got, err, want) @@ -28,26 +28,26 @@ func TestSharedCodeBuddyModelsRejectsInvalidID(t *testing.T) { } } -func TestSharedCodeBuddyModelsRequiresAtLeastOne(t *testing.T) { +func TestSharedModelsRequiresAtLeastOne(t *testing.T) { for _, raw := range [][]string{nil, {}, {"", " "}} { - if _, err := sharedCodeBuddyModels(raw); err == nil || err.Error() != "请至少选择一个允许使用的模型" { + if _, err := sharedModels(raw); err == nil || err.Error() != "请至少选择一个允许使用的模型" { t.Fatalf("raw %q: err = %v", raw, err) } } } -func TestSharedCodeBuddyModelsEnforcesUpperBound(t *testing.T) { +func TestSharedModelsEnforcesUpperBound(t *testing.T) { raw := make([]string, 0, repo.MaxSharedCodeBuddyModels+1) for i := 0; i < repo.MaxSharedCodeBuddyModels; i++ { raw = append(raw, fmt.Sprintf("model-%d", i)) } - got, err := sharedCodeBuddyModels(append(raw, raw[0])) + got, err := sharedModels(append(raw, raw[0])) if err != nil || len(got) != repo.MaxSharedCodeBuddyModels { t.Fatalf("at limit (with duplicate): len=%d err=%v", len(got), err) } raw = append(raw, "one-too-many") want := fmt.Sprintf("最多选择 %d 个模型", repo.MaxSharedCodeBuddyModels) - if _, err := sharedCodeBuddyModels(raw); err == nil || err.Error() != want { + if _, err := sharedModels(raw); err == nil || err.Error() != want { t.Fatalf("over limit: err = %v, want %q", err, want) } } diff --git a/internal/httpapi/platform_model_keys_test.go b/internal/httpapi/platform_model_keys_test.go new file mode 100644 index 000000000..8e8539532 --- /dev/null +++ b/internal/httpapi/platform_model_keys_test.go @@ -0,0 +1,244 @@ +package httpapi + +import ( + "context" + "encoding/json" + "net/http/httptest" + "strings" + "testing" + + "agentflow/internal/domain" + "agentflow/internal/repo" + + "github.com/gin-gonic/gin" +) + +// One shared credential per CLI: CodeBuddy keeps its network environment, +// Codex and Claude Code take a Base URL, and the admin reads them together. +func TestPlatformAdminsConfigureSharedKeysPerCLI(t *testing.T) { + st, client, owner, member := platformSettingsFixture(t) + stubCLIModelDiscovery(t) + const origin = "http://localhost" + + if w := client.call(owner, "GET", "/api/platform/model-keys/kimi", "", ""); w.Code != 400 || !strings.Contains(w.Body.String(), "CodeBuddy") { + t.Fatalf("unsupported CLI: %d %s", w.Code, w.Body.String()) + } + if w := client.call(member, "GET", "/api/platform/model-keys/codex", "", ""); w.Code != 403 { + t.Fatalf("member read: %d", w.Code) + } + if w := client.call(member, "PUT", "/api/platform/model-keys/codex", origin, `{"apiKey":"sk","models":["m"]}`); w.Code != 403 { + t.Fatalf("member save: %d", w.Code) + } + for body, want := range map[string]string{ + `{"apiKey":"sk","baseUrl":"ftp://gateway.example.com","models":["gpt-6.1-terra"]}`: "Base URL", + `{"apiKey":"sk","baseUrl":"https://gateway.example.com/v1","models":[]}`: "至少选择", + `{"apiKey":"bad key","models":["gpt-6.1-terra"]}`: "API Key", + `{"internetEnvironment":"internal","models":["gpt-6.1-terra"]}`: "API Key", + } { + if w := client.call(owner, "PUT", "/api/platform/model-keys/codex", origin, body); w.Code != 400 || !strings.Contains(w.Body.String(), want) { + t.Fatalf("invalid %s: %d %s", body, w.Code, w.Body.String()) + } + } + + save := `{"apiKey":"sk_gateway","baseUrl":"https://gateway.example.com/v1","models":["gpt-6.1-terra"," gpt-6.1-sol ","gpt-6.1-terra"]}` + if w := client.call(owner, "PUT", "/api/platform/model-keys/codex", origin, save); w.Code != 200 || strings.Contains(w.Body.String(), "sk_gateway") { + t.Fatalf("save codex: %d %s", w.Code, w.Body.String()) + } + key, ok := st.SharedModelKey(domain.SharedModelProviderCodex) + if !ok || key.APIKey != "sk_gateway" || key.BaseURL != "https://gateway.example.com/v1" || strings.Join(key.Models, ",") != "gpt-6.1-terra,gpt-6.1-sol" || key.InternetEnvironment != "" { + t.Fatalf("stored codex key = %+v", key) + } + + // Editing only the models keeps the saved key, and a network environment + // is ignored for CLIs that address their gateway by Base URL. + if w := client.call(owner, "PUT", "/api/platform/model-keys/codex", origin, `{"baseUrl":"https://gateway.example.com/v1","internetEnvironment":"internal","models":["gpt-6.1-sol"]}`); w.Code != 200 { + t.Fatalf("models-only update: %d %s", w.Code, w.Body.String()) + } + if key, _ := st.SharedModelKey(domain.SharedModelProviderCodex); key.APIKey != "sk_gateway" || key.InternetEnvironment != "" || strings.Join(key.Models, ",") != "gpt-6.1-sol" { + t.Fatalf("models-only update = %+v", key) + } + + // CodeBuddy keeps its environment and its older endpoint. + if w := client.call(owner, "PUT", "/api/platform/codebuddy-key", origin, `{"apiKey":"ck_shared","internetEnvironment":"internal","models":["glm-5.1"]}`); w.Code != 200 { + t.Fatalf("legacy codebuddy endpoint: %d %s", w.Code, w.Body.String()) + } + if key, _ := st.SharedModelKey(domain.SharedModelProviderCodeBuddy); key.APIKey != "ck_shared" || key.InternetEnvironment != "internal" { + t.Fatalf("codebuddy key = %+v", key) + } + + w := client.call(owner, "GET", "/api/platform/model-keys", "", "") + var list struct { + Keys []repo.PlatformModelKeyStatus `json:"keys"` + } + if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &list) != nil || len(list.Keys) != len(domain.SharedModelProviders) { + t.Fatalf("list: %d %s", w.Code, w.Body.String()) + } + byProvider := map[string]repo.PlatformModelKeyStatus{} + for _, status := range list.Keys { + byProvider[status.Provider] = status + } + if !byProvider["codebuddy"].Configured || byProvider["codebuddy"].InternetEnvironment != "internal" { + t.Fatalf("codebuddy status = %+v", byProvider["codebuddy"]) + } + if !byProvider["codex"].Configured || byProvider["codex"].BaseURL != "https://gateway.example.com/v1" { + t.Fatalf("codex status = %+v", byProvider["codex"]) + } + if byProvider["claude-code"].Configured { + t.Fatalf("claude-code must stay unconfigured: %+v", byProvider["claude-code"]) + } + if strings.Contains(w.Body.String(), "sk_gateway") || strings.Contains(w.Body.String(), "ck_shared") { + t.Fatal("status list must not reveal keys") + } + + if w := client.call(member, "POST", "/api/platform/model-keys/codex/probe", origin, `{}`); w.Code != 403 { + t.Fatalf("member probe: %d", w.Code) + } + if w := client.call(owner, "GET", "/api/platform/model-keys/claude-code", "", ""); w.Code != 200 || !strings.Contains(w.Body.String(), "claude-opus-5") { + t.Fatalf("claude-code catalog: %d %s", w.Code, w.Body.String()) + } + + if w := client.call(owner, "DELETE", "/api/platform/model-keys/codex", origin, ""); w.Code != 200 || strings.Contains(w.Body.String(), `"configured":true`) { + t.Fatalf("clear codex: %d %s", w.Code, w.Body.String()) + } + if _, ok := st.SharedModelKey(domain.SharedModelProviderCodex); ok { + t.Fatal("cleared codex key must not be lent") + } + if _, ok := st.SharedModelKey(domain.SharedModelProviderCodeBuddy); !ok { + t.Fatal("clearing one CLI must keep the others") + } +} + +// A member without their own Codex key chats on the shared one, limited to the +// models the administrator allowed, and the engine switch reports it. +func TestSharedCodexKeyServesChatWithoutPersonalKey(t *testing.T) { + st, newcomer := sponsorFixture(t) + stubCLIModelDiscovery(t) + if err := st.SetPlatformModelKey(repo.PlatformModelKeyUpdate{ + Provider: domain.SharedModelProviderCodex, APIKey: "codex-shared", + BaseURL: "https://gateway.example.com/v1", Models: []string{"gpt-6.1-terra"}, + }, 0); err != nil { + t.Fatal(err) + } + var used domain.User + h := &assistantHandlers{deps: &deps{repo: st}, generate: func(_ context.Context, _ string, u domain.User) (string, error) { + used = u + return `{"message":"ok","drafts":[]}`, nil + }} + + rec := sponsoredChat(h, newcomer, "codex:gpt-6.1-terra") + if rec.Code != 200 { + t.Fatalf("shared codex turn: %d %s", rec.Code, rec.Body.String()) + } + if used.ID != newcomer.ID || used.CodexAPIKey != "codex-shared" || used.CodexBaseURL != "https://gateway.example.com/v1" || used.GitToken != "newcomer-git" { + t.Fatalf("turn must run as the newcomer with the shared Codex key only: %+v", used) + } + if stored, _ := st.User(newcomer.ID); stored.CodexAPIKey != "" { + t.Fatal("the shared key must never be persisted on the member") + } + + rec = sponsoredChat(h, newcomer, "codex:gpt-6.1-sol") + if rec.Code != 400 || !strings.Contains(rec.Body.String(), "允许的模型") || !strings.Contains(rec.Body.String(), "Codex") { + t.Fatalf("other Codex models need an own key: %d %s", rec.Code, rec.Body.String()) + } + + mrec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(mrec) + c.Request = httptest.NewRequest("GET", "/api/assistant/models", nil) + c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), requestUserContextKey{}, domainUserToAuth(newcomer))) + h.models(c) + var catalog assistantModelCatalog + if mrec.Code != 200 || json.Unmarshal(mrec.Body.Bytes(), &catalog) != nil { + t.Fatalf("catalog: %d %s", mrec.Code, mrec.Body.String()) + } + var codex *assistantEngineOption + for i := range catalog.Engines { + if catalog.Engines[i].ID == "codex" { + codex = &catalog.Engines[i] + } + } + if codex == nil || !codex.Configured || codex.Personal || !codex.Shared { + t.Fatalf("the switch must offer Codex through the shared key: %+v", catalog.Engines) + } + listed := map[string]bool{} + for _, model := range catalog.Models { + listed[model.ID] = true + } + if !listed["codex:gpt-6.1-terra"] || listed["codex:gpt-6.1-sol"] { + t.Fatalf("only the allowed Codex models may be offered: %v", listed) + } + if strings.Contains(mrec.Body.String(), "codex-shared") { + t.Fatal("the catalog must not reveal the shared key") + } +} + +// The shared-key form can list the models a gateway publishes before saving, +// using the typed key and Base URL without storing them. +func TestPlatformSharedKeyProbeListsGatewayModels(t *testing.T) { + st, client, owner, _ := platformSettingsFixture(t) + stubCLIModelDiscovery(t) + previous := assistantEngineDiscover + t.Cleanup(func() { assistantEngineDiscover = previous }) + var asked []string + assistantEngineDiscover = func(_ context.Context, anthropic bool, apiKey, baseURL string) ([]assistantDiscoveredModel, error) { + asked = append(asked, apiKey+"@"+baseURL) + if anthropic { + return nil, nil + } + return []assistantDiscoveredModel{{ID: "gpt-6.1-terra", Name: "GPT-6.1-Terra"}}, nil + } + const origin = "http://localhost" + w := client.call(owner, "POST", "/api/platform/model-keys/codex/probe", origin, `{"apiKey":"sk_probe","baseUrl":"https://gateway.example.com/v1"}`) + if w.Code != 200 || !strings.Contains(w.Body.String(), "gpt-6.1-terra") { + t.Fatalf("probe: %d %s", w.Code, w.Body.String()) + } + if len(asked) != 1 || asked[0] != "sk_probe@https://gateway.example.com/v1" { + t.Fatalf("probe used %v", asked) + } + + // The stored key is write-only: probing or saving it against another + // Base URL needs it typed again, or the new URL's owner would receive it. + save := `{"apiKey":"sk_stored","baseUrl":"https://gateway.example.com/v1","models":["gpt-6.1-terra"]}` + if w := client.call(owner, "PUT", "/api/platform/model-keys/codex", origin, save); w.Code != 200 { + t.Fatalf("save: %d %s", w.Code, w.Body.String()) + } + asked = nil + for _, body := range []string{`{"baseUrl":"https://gateway.example.com/v1"}`, `{"baseUrl":"https://gateway.example.com/v1/"}`, `{}`} { + if w := client.call(owner, "POST", "/api/platform/model-keys/codex/probe", origin, body); w.Code != 200 || !strings.Contains(w.Body.String(), "gpt-6.1-terra") { + t.Fatalf("probe stored key %s: %d %s", body, w.Code, w.Body.String()) + } + } + if len(asked) != 3 || asked[0] != "sk_stored@https://gateway.example.com/v1" || asked[2] != "sk_stored@https://gateway.example.com/v1" { + t.Fatalf("stored-key probes used %v", asked) + } + asked = nil + if w := client.call(owner, "POST", "/api/platform/model-keys/codex/probe", origin, `{"baseUrl":"https://collector.example.net/v1"}`); w.Code != 200 || !strings.Contains(w.Body.String(), "重新填写") { + t.Fatalf("stored key to another Base URL: %d %s", w.Code, w.Body.String()) + } + if len(asked) != 0 { + t.Fatalf("the stored key must not reach another Base URL: %v", asked) + } + if w := client.call(owner, "POST", "/api/platform/model-keys/codex/probe", origin, `{"apiKey":"sk_new","baseUrl":"https://collector.example.net/v1"}`); w.Code != 200 || len(asked) != 1 || asked[0] != "sk_new@https://collector.example.net/v1" { + t.Fatalf("a typed key may probe any Base URL: %d %s %v", w.Code, w.Body.String(), asked) + } + for _, body := range []string{ + `{"baseUrl":"https://collector.example.net/v1","models":["gpt-6.1-terra"]}`, + `{"models":["gpt-6.1-terra"]}`, + } { + if w := client.call(owner, "PUT", "/api/platform/model-keys/codex", origin, body); w.Code != 400 || !strings.Contains(w.Body.String(), "重新填写") { + t.Fatalf("move stored key %s: %d %s", body, w.Code, w.Body.String()) + } + } + if key, _ := st.SharedModelKey(domain.SharedModelProviderCodex); key.APIKey != "sk_stored" || key.BaseURL != "https://gateway.example.com/v1" { + t.Fatalf("rejected moves must keep the stored key: %+v", key) + } + if w := client.call(owner, "PUT", "/api/platform/model-keys/codex", origin, `{"apiKey":"sk_moved","baseUrl":"https://collector.example.net/v1","models":["gpt-6.1-terra"]}`); w.Code != 200 { + t.Fatalf("move with a typed key: %d %s", w.Code, w.Body.String()) + } + + if w := client.call(owner, "POST", "/api/platform/model-keys/codex/probe", origin, `{"baseUrl":"not-a-url"}`); w.Code != 200 || !strings.Contains(w.Body.String(), "Base URL") { + t.Fatalf("invalid base URL: %d %s", w.Code, w.Body.String()) + } + if w := client.call(owner, "POST", "/api/platform/model-keys/codebuddy/probe", origin, `{}`); w.Code != 200 || !strings.Contains(w.Body.String(), "网络环境") { + t.Fatalf("codebuddy probe: %d %s", w.Code, w.Body.String()) + } +} diff --git a/internal/httpapi/platform_settings.go b/internal/httpapi/platform_settings.go index 78588fb0c..11e796215 100644 --- a/internal/httpapi/platform_settings.go +++ b/internal/httpapi/platform_settings.go @@ -1,6 +1,7 @@ package httpapi import ( + "context" "errors" "fmt" "net/http" @@ -8,6 +9,7 @@ import ( "regexp" "strconv" "strings" + "time" "agentflow/internal/domain" "agentflow/internal/repo" @@ -15,8 +17,8 @@ import ( "github.com/gin-gonic/gin" ) -// 平台管理 → 成员账号 and 平台共享 CodeBuddy Key. Only platform -// administrators may use these endpoints. +// 平台管理 → 成员账号 and the shared model credentials (共享模型 Key). Only +// platform administrators may use these endpoints. // platformAdminWrite admits a platform administrator's change: an API token, // or a same-origin browser request (the session cookie alone is not enough). @@ -155,11 +157,11 @@ func (h *usersHandlers) resetPlatformAccountPassword(c *gin.Context) { var sharedModelPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$`) -// sharedCodeBuddyModels normalizes the allow list of the shared CodeBuddy -// key: blanks and duplicates are dropped in submission order, every ID must -// match sharedModelPattern, and the list must hold 1..MaxSharedCodeBuddyModels -// entries. The error text is shown to the administrator as is. -func sharedCodeBuddyModels(raw []string) ([]string, error) { +// sharedModels normalizes the allow list of one shared credential: blanks and +// duplicates are dropped in submission order, every ID must match +// sharedModelPattern, and the list must hold 1..MaxSharedModels entries. The +// error text is shown to the administrator as is. +func sharedModels(raw []string) ([]string, error) { var models []string seen := map[string]bool{} for _, value := range raw { @@ -176,30 +178,71 @@ func sharedCodeBuddyModels(raw []string) ([]string, error) { if len(models) == 0 { return nil, errors.New("请至少选择一个允许使用的模型") } - if len(models) > repo.MaxSharedCodeBuddyModels { - return nil, fmt.Errorf("最多选择 %d 个模型", repo.MaxSharedCodeBuddyModels) + if len(models) > repo.MaxSharedModels { + return nil, fmt.Errorf("最多选择 %d 个模型", repo.MaxSharedModels) } return models, nil } -type platformCodeBuddyKeyResponse struct { - repo.PlatformCodeBuddyKeyStatus - // Catalog lists the models offered in the requested network environment. +// sharedProviderLabel is the CLI name shown on 平台管理 → 共享模型 Key. +func sharedProviderLabel(provider string) string { + switch provider { + case domain.SharedModelProviderCodex: + return "Codex" + case domain.SharedModelProviderClaude: + return "Claude Code" + } + return "CodeBuddy" +} + +// sharedProviderParam reads the engine of a shared credential. The older +// /api/platform/codebuddy-key endpoint has no path parameter and stays +// CodeBuddy-only. +func sharedProviderParam(c *gin.Context) (string, bool) { + raw := c.Param("provider") + if raw == "" { + raw = c.Query("provider") + } + provider, ok := domain.NormalizeSharedModelProvider(raw) + if !ok { + c.JSON(http.StatusBadRequest, gin.H{"error": "共享 Key 只支持 CodeBuddy、Codex 和 Claude Code"}) + return "", false + } + return provider, true +} + +type platformModelKeyResponse struct { + repo.PlatformModelKeyStatus + // Catalog lists model IDs to offer on the page: the CodeBuddy models of + // the requested network environment, or the CLI's built-in catalog. Catalog []assistantModel `json:"catalog"` } -// platformCodeBuddyKey shows and edits the shared CodeBuddy API Key. The key +// platformModelKeyList shows every shared credential, without catalogs. +func (h *usersHandlers) platformModelKeyList(c *gin.Context) { + if !h.isPlatformAdmin(c.Request) { + c.JSON(http.StatusForbidden, gin.H{"error": "只有平台管理员可以查看共享 Key"}) + return + } + c.JSON(http.StatusOK, gin.H{"keys": h.repo.PlatformModelKeyStatuses()}) +} + +// platformModelKeys shows and edits one engine's shared API Key. The key // itself is write-only: responses only say whether one is configured. -func (h *usersHandlers) platformCodeBuddyKey(c *gin.Context) { +func (h *usersHandlers) platformModelKeys(c *gin.Context) { + provider, ok := sharedProviderParam(c) + if !ok { + return + } switch c.Request.Method { case http.MethodGet: if !h.isPlatformAdmin(c.Request) { c.JSON(http.StatusForbidden, gin.H{"error": "只有平台管理员可以查看共享 Key"}) return } - status := h.repo.PlatformCodeBuddyKeyStatus() + status := h.repo.PlatformModelKeyStatus(provider) environment := status.InternetEnvironment - if raw, ok := c.GetQuery("environment"); ok { + if raw, ok := c.GetQuery("environment"); ok && provider == domain.SharedModelProviderCodeBuddy { normalized, valid := domain.NormalizeCodeBuddyInternetEnvironment(raw) if !valid { c.JSON(http.StatusBadRequest, gin.H{"error": "CodeBuddy 网络环境只能是国际站(留空)、国内站(internal)或 iOA(ioa)"}) @@ -208,35 +251,61 @@ func (h *usersHandlers) platformCodeBuddyKey(c *gin.Context) { environment = normalized } apiKey := "" - if key, ok := h.repo.SharedCodeBuddyKey(); ok && key.SponsorID == 0 && key.InternetEnvironment == environment { + if key, found := h.repo.SharedModelKey(provider); found && key.SponsorID == 0 && key.InternetEnvironment == environment { apiKey = key.APIKey } - refreshCLIModels(c.Request.Context(), environment, apiKey) - catalog := loadAssistantModels(environment, apiKey).Models - c.JSON(http.StatusOK, platformCodeBuddyKeyResponse{PlatformCodeBuddyKeyStatus: status, Catalog: catalog}) + c.JSON(http.StatusOK, platformModelKeyResponse{ + PlatformModelKeyStatus: status, + Catalog: h.sharedModelCatalog(c.Request.Context(), provider, environment, apiKey), + }) case http.MethodPut: - h.savePlatformCodeBuddyKey(c) + h.savePlatformModelKey(c, provider) case http.MethodDelete: if !h.platformAdminWrite(c) { return } - if err := h.repo.ClearPlatformCodeBuddyKey(); err != nil { + if err := h.repo.ClearPlatformModelKey(provider); err != nil { respond(c, err) return } - c.JSON(http.StatusOK, h.repo.PlatformCodeBuddyKeyStatus()) + c.JSON(http.StatusOK, h.repo.PlatformModelKeyStatus(provider)) default: c.JSON(http.StatusMethodNotAllowed, gin.H{"error": "method not allowed"}) } } -func (h *usersHandlers) savePlatformCodeBuddyKey(c *gin.Context) { +// platformCodeBuddyKey keeps the single-Key endpoint older frontends call. +func (h *usersHandlers) platformCodeBuddyKey(c *gin.Context) { + h.platformModelKeys(c) +} + +// sharedModelCatalog lists the models the page offers for an engine. CodeBuddy +// models come from the CLI in the chosen network environment; the other CLIs +// show their built-in catalog, and the page can probe a Base URL for more. +func (h *usersHandlers) sharedModelCatalog(ctx context.Context, provider, environment, apiKey string) []assistantModel { + if provider == domain.SharedModelProviderCodeBuddy { + refreshCLIModels(ctx, environment, apiKey) + return loadAssistantModels(environment, apiKey).Models + } + var catalog []assistantModel + for _, model := range assistantEngineBuiltinModels(provider) { + name := model.Name + if name == "" { + name = model.ID + } + catalog = append(catalog, assistantListedModel(model.ID, name, "")) + } + return catalog +} + +func (h *usersHandlers) savePlatformModelKey(c *gin.Context, provider string) { if !h.platformAdminWrite(c) { return } c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 16<<10) var input struct { APIKey string `json:"apiKey"` + BaseURL string `json:"baseUrl"` InternetEnvironment string `json:"internetEnvironment"` Models []string `json:"models"` } @@ -244,17 +313,29 @@ func (h *usersHandlers) savePlatformCodeBuddyKey(c *gin.Context) { c.JSON(http.StatusBadRequest, gin.H{"error": "invalid shared key request"}) return } - environment, ok := domain.NormalizeCodeBuddyInternetEnvironment(input.InternetEnvironment) - if !ok { - c.JSON(http.StatusBadRequest, gin.H{"error": "CodeBuddy 网络环境只能是国际站(留空)、国内站(internal)或 iOA(ioa)"}) - return + environment := "" + if provider == domain.SharedModelProviderCodeBuddy { + normalized, ok := domain.NormalizeCodeBuddyInternetEnvironment(input.InternetEnvironment) + if !ok { + c.JSON(http.StatusBadRequest, gin.H{"error": "CodeBuddy 网络环境只能是国际站(留空)、国内站(internal)或 iOA(ioa)"}) + return + } + environment = normalized } key := strings.TrimSpace(input.APIKey) if len(key) > 4096 || strings.ContainsAny(key, " \t\r\n") { c.JSON(http.StatusBadRequest, gin.H{"error": "API Key 格式不正确"}) return } - models, err := sharedCodeBuddyModels(input.Models) + baseURL := "" + if provider != domain.SharedModelProviderCodeBuddy { + baseURL = strings.TrimSpace(input.BaseURL) + if !validCLIBaseURL(baseURL) { + c.JSON(http.StatusBadRequest, gin.H{"error": errInvalidCLIBaseURL}) + return + } + } + models, err := sharedModels(input.Models) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return @@ -263,14 +344,100 @@ func (h *usersHandlers) savePlatformCodeBuddyKey(c *gin.Context) { if current, ok := h.requestUser(c.Request, true); ok { actorID = current.ID } - err = h.repo.SetPlatformCodeBuddyKey(repo.PlatformCodeBuddyKeyUpdate{APIKey: key, InternetEnvironment: environment, Models: models}, actorID) - if errors.Is(err, repo.ErrSharedCodeBuddyKeyRequired) { - c.JSON(http.StatusBadRequest, gin.H{"error": "请填写 CodeBuddy API Key"}) + err = h.repo.SetPlatformModelKey(repo.PlatformModelKeyUpdate{ + Provider: provider, APIKey: key, BaseURL: baseURL, + InternetEnvironment: environment, Models: models, + }, actorID) + if errors.Is(err, repo.ErrSharedModelKeyRequired) { + c.JSON(http.StatusBadRequest, gin.H{"error": "请填写 " + sharedProviderLabel(provider) + " API Key"}) + return + } + if errors.Is(err, repo.ErrSharedModelKeyBaseURLChanged) { + c.JSON(http.StatusBadRequest, gin.H{"error": "修改 Base URL 时请重新填写 " + sharedProviderLabel(provider) + " API Key"}) + return + } + if errors.Is(err, repo.ErrSharedModelKeyProvider) { + c.JSON(http.StatusBadRequest, gin.H{"error": "共享 Key 只支持 CodeBuddy、Codex 和 Claude Code"}) return } if err != nil { respond(c, err) return } - c.JSON(http.StatusOK, h.repo.PlatformCodeBuddyKeyStatus()) + c.JSON(http.StatusOK, h.repo.PlatformModelKeyStatus(provider)) +} + +// probePlatformModelKey lists the models the entered key can reach, for the +// 共享模型 Key form. Nothing is stored; like verifyGitToken it answers 200 +// with a structured result so the form can show the reason. +func (h *usersHandlers) probePlatformModelKey(c *gin.Context) { + if !h.isPlatformAdmin(c.Request) { + c.JSON(http.StatusForbidden, gin.H{"error": "只有平台管理员可以读取共享 Key 的模型"}) + return + } + provider, ok := sharedProviderParam(c) + if !ok { + return + } + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 16<<10) + var input struct { + APIKey string `json:"apiKey"` + BaseURL string `json:"baseUrl"` + } + if c.ShouldBindJSON(&input) != nil { + c.JSON(http.StatusBadRequest, cliModelProbeResult{Error: "invalid model probe request"}) + return + } + c.Header("Cache-Control", "private, no-store") + if provider == domain.SharedModelProviderCodeBuddy { + // CodeBuddy's catalog follows the network environment and the CLI + // probe the page already runs on load, not a typed Base URL. + c.JSON(http.StatusOK, cliModelProbeResult{Error: "CodeBuddy 的模型按网络环境自动读取,不需要单独获取"}) + return + } + apiKey, baseURL := strings.TrimSpace(input.APIKey), strings.TrimSpace(input.BaseURL) + if apiKey == "" { + if stored, found := h.repo.SharedModelKey(provider); found && stored.SponsorID == 0 { + if baseURL == "" { + baseURL = stored.BaseURL + } + // The stored key is write-only: probing it against a Base URL + // other than its own would hand it to whoever runs that URL. + if !repo.SameSharedModelBaseURL(baseURL, stored.BaseURL) { + c.JSON(http.StatusOK, cliModelProbeResult{Error: "修改了 Base URL,请重新填写 " + sharedProviderLabel(provider) + " API Key 再获取模型"}) + return + } + apiKey = stored.APIKey + } + } + if !validCLIBaseURL(baseURL) { + c.JSON(http.StatusOK, cliModelProbeResult{Error: errInvalidCLIBaseURL}) + return + } + if apiKey == "" { + c.JSON(http.StatusOK, cliModelProbeResult{Error: "请先填写 " + sharedProviderLabel(provider) + " API Key"}) + return + } + source := "remote" + if baseURL == "" { + source = "official" + switch provider { + case domain.SharedModelProviderCodex: + baseURL = "https://api.openai.com/v1" + case domain.SharedModelProviderClaude: + baseURL = assistantAnthropicAPIBase + } + } + ctx, cancel := context.WithTimeout(c.Request.Context(), 10*time.Second) + defer cancel() + models, err := assistantEngineDiscover(ctx, assistantEngineAnthropicModels(provider, ""), apiKey, baseURL) + if err != nil { + c.JSON(http.StatusOK, cliModelProbeResult{Error: "获取模型列表失败:" + err.Error()}) + return + } + if len(models) == 0 { + c.JSON(http.StatusOK, cliModelProbeResult{Connected: true, Error: "服务没有返回可用模型,可以手动添加模型"}) + return + } + c.JSON(http.StatusOK, cliModelProbeResult{Models: cliModelsWithEfforts(provider, cliModelsOf(models), ""), Source: source, Connected: true}) } diff --git a/internal/httpapi/platform_settings_test.go b/internal/httpapi/platform_settings_test.go index e54150cb3..8f4c899d9 100644 --- a/internal/httpapi/platform_settings_test.go +++ b/internal/httpapi/platform_settings_test.go @@ -205,7 +205,7 @@ func TestPlatformAdminsConfigureSharedCodeBuddyKey(t *testing.T) { t.Fatalf("update models: %d %s", w.Code, w.Body.String()) } w = client.call(owner, "GET", "/api/platform/codebuddy-key", "", "") - var status platformCodeBuddyKeyResponse + var status platformModelKeyResponse if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &status) != nil || !status.Configured || status.InternetEnvironment != "internal" || strings.Join(status.Models, ",") != "kimi-k2.6" || status.UpdatedBy != "owner" || len(status.Catalog) == 0 { t.Fatalf("status: %d %s", w.Code, w.Body.String()) } diff --git a/internal/httpapi/project_write_access_test.go b/internal/httpapi/project_write_access_test.go index d7e865cbe..955f9b799 100644 --- a/internal/httpapi/project_write_access_test.go +++ b/internal/httpapi/project_write_access_test.go @@ -77,6 +77,13 @@ func TestProjectContentWritesRequireMembership(t *testing.T) { if _, err := s.UpdateUserCredentials(ownerUser.ID, repo.UserCredentialUpdate{CodexAPIKey: key, CodexModels: &models}); err != nil { t.Fatal(err) } + // Clarification runs on the owner's own credentials, so the platform's + // shared keys must not add models it would then refuse. + for provider, model := range map[string]string{domain.SharedModelProviderClaude: "shared-claude", domain.SharedModelProviderCodex: "shared-codex"} { + if err := s.SetPlatformModelKey(repo.PlatformModelKeyUpdate{Provider: provider, APIKey: "shared-" + provider, Models: []string{model}}, 0); err != nil { + t.Fatal(err) + } + } for _, cookie := range []*http.Cookie{other, viewer} { if code := call(cookie, "GET", path, ""); code != 403 { t.Fatalf("clarification catalog requires project write access: %d", code) @@ -93,6 +100,11 @@ func TestProjectContentWritesRequireMembership(t *testing.T) { if len(catalog.Models) != 1 || catalog.Models[0].ID != "codex:owner-model" { t.Fatalf("want the project owner's model: %+v", catalog.Models) } + for _, engine := range catalog.Engines { + if engine.Shared { + t.Fatalf("clarification must not offer shared-key engines: %+v", catalog.Engines) + } + } }) if code := call(other, "PUT", "/api/issues", `{"id":"i1","projectId":"p1","title":"Hijacked"}`); code != 403 { t.Fatalf("non-member edit issue: %d", code) diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 94625f789..d3fe7cd6a 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -283,6 +283,13 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Serv g.GET("/api/platform/accounts", api.users.platformAccounts) g.POST("/api/platform/accounts", api.users.platformAccounts) g.PUT("/api/platform/accounts/:id/password", api.users.resetPlatformAccountPassword) + g.GET("/api/platform/model-keys", api.users.platformModelKeyList) + g.GET("/api/platform/model-keys/:provider", api.users.platformModelKeys) + g.PUT("/api/platform/model-keys/:provider", api.users.platformModelKeys) + g.DELETE("/api/platform/model-keys/:provider", api.users.platformModelKeys) + g.POST("/api/platform/model-keys/:provider/probe", api.users.probePlatformModelKey) + // The single shared CodeBuddy key endpoint stays for older cached + // frontends; the page now calls /api/platform/model-keys/:provider. g.GET("/api/platform/codebuddy-key", api.users.platformCodeBuddyKey) g.PUT("/api/platform/codebuddy-key", api.users.platformCodeBuddyKey) g.DELETE("/api/platform/codebuddy-key", api.users.platformCodeBuddyKey) diff --git a/internal/repo/codebuddy_sponsor.go b/internal/repo/codebuddy_sponsor.go deleted file mode 100644 index 4aff54f8e..000000000 --- a/internal/repo/codebuddy_sponsor.go +++ /dev/null @@ -1,213 +0,0 @@ -package repo - -import ( - "encoding/json" - "errors" - "os" - "strings" - "time" - - "agentflow/internal/domain" - - "gorm.io/gorm/clause" -) - -// Users who have not configured their own CodeBuddy API Key use the shared -// key a platform administrator configured under 平台管理, limited to the -// models the administrator allowed. It covers chat conversations and LOOP -// runs, so a new user can start working before configuring anything; -// scheduled prompts, reports, bots and run evaluation keep requiring the -// user's own key. -// -// Older deployments lent the key of the account named by -// AGENTFLOW_ASSISTANT_SPONSOR_LOGIN instead, limited to -// SponsoredCodeBuddyModel. That still applies while no shared key is -// configured. -const ( - CodeBuddySponsorLoginEnv = "AGENTFLOW_ASSISTANT_SPONSOR_LOGIN" - SponsoredCodeBuddyModel = "deepseek-v4.1-flash" - // MaxSharedCodeBuddyModels bounds the allow list of the shared key. - MaxSharedCodeBuddyModels = 32 -) - -// SharedCodeBuddyKey is the key users without their own borrow. -type SharedCodeBuddyKey struct { - APIKey string - InternetEnvironment string - // Models are the models it may run; the first is the default. - Models []string - // SponsorID is the lending account under AGENTFLOW_ASSISTANT_SPONSOR_LOGIN, - // 0 for the key configured under 平台管理. - SponsorID int64 -} - -// Model returns the model a shared-key turn runs: the requested model when it -// is allowed, the default when none is requested, and false otherwise. -func (k SharedCodeBuddyKey) Model(requested string) (string, bool) { - if len(k.Models) == 0 { - return "", false - } - requested = strings.TrimSpace(requested) - if requested == "" { - return k.Models[0], true - } - for _, id := range k.Models { - if id == requested { - return id, true - } - } - return "", false -} - -// The key is stored like personal CodeBuddy keys in user_configs: the -// database is the trust boundary, and the key is never returned by the API. -type platformCodeBuddyKeyRow struct { - ID int64 `gorm:"column:id;primaryKey;autoIncrement:false"` - APIKey string `gorm:"column:api_key;type:text;not null"` - InternetEnvironment string `gorm:"column:internet_environment;size:64;not null;default:''"` - Models string `gorm:"column:models;type:text;not null"` - UpdatedBy int64 `gorm:"column:updated_by;not null;default:0"` - Updated *time.Time `gorm:"column:updated_at"` -} - -func (platformCodeBuddyKeyRow) TableName() string { return "platform_codebuddy_keys" } - -// The table holds at most this one row. -const platformCodeBuddyKeyID = 1 - -// PlatformCodeBuddyKeyStatus is what administrators see; it never carries the key. -type PlatformCodeBuddyKeyStatus struct { - Configured bool `json:"configured"` - InternetEnvironment string `json:"internetEnvironment"` - Models []string `json:"models"` - UpdatedAt *time.Time `json:"updatedAt,omitempty"` - UpdatedBy string `json:"updatedBy,omitempty"` - // LegacySponsor is the account named by AGENTFLOW_ASSISTANT_SPONSOR_LOGIN - // whose key is lent while no shared key is configured here. - LegacySponsor string `json:"legacySponsor,omitempty"` - LegacySponsorModel string `json:"legacySponsorModel,omitempty"` -} - -// PlatformCodeBuddyKeyUpdate replaces the shared key settings. An empty -// APIKey keeps the stored key. Models must already be validated. -type PlatformCodeBuddyKeyUpdate struct { - APIKey string - InternetEnvironment string - Models []string -} - -var ( - ErrSharedCodeBuddyKeyRequired = errors.New("shared CodeBuddy API Key is required") - ErrSharedCodeBuddyModelsRequired = errors.New("at least one shared CodeBuddy model is required") -) - -func (r *UsersRepo) platformCodeBuddyKey() (platformCodeBuddyKeyRow, bool) { - var row platformCodeBuddyKeyRow - if r == nil || r.deps == nil || r.DB == nil { - return row, false - } - result := r.DB.Where("id = ?", platformCodeBuddyKeyID).Limit(1).Find(&row) - return row, result.Error == nil && result.RowsAffected > 0 -} - -func decodeSharedModels(raw string) []string { - var models []string - if json.Unmarshal([]byte(raw), &models) != nil { - return nil - } - return models -} - -// legacyCodeBuddySponsor returns the account named by -// AGENTFLOW_ASSISTANT_SPONSOR_LOGIN, if it exists and has a key. -func (r *UsersRepo) legacyCodeBuddySponsor() (domain.User, bool) { - login := strings.TrimSpace(os.Getenv(CodeBuddySponsorLoginEnv)) - if login == "" || r == nil { - return domain.User{}, false - } - sponsor, ok := r.UserByLoginName(login) - if !ok || strings.TrimSpace(sponsor.CodeBuddyAPIKey) == "" { - return domain.User{}, false - } - return sponsor, true -} - -// SharedCodeBuddyKey returns the key users without their own borrow: the one -// configured under 平台管理, else the legacy sponsor account's. -func (r *UsersRepo) SharedCodeBuddyKey() (SharedCodeBuddyKey, bool) { - if row, ok := r.platformCodeBuddyKey(); ok { - models := decodeSharedModels(row.Models) - if strings.TrimSpace(row.APIKey) != "" && len(models) > 0 { - return SharedCodeBuddyKey{APIKey: row.APIKey, InternetEnvironment: row.InternetEnvironment, Models: models}, true - } - } - sponsor, ok := r.legacyCodeBuddySponsor() - if !ok { - return SharedCodeBuddyKey{}, false - } - return SharedCodeBuddyKey{APIKey: sponsor.CodeBuddyAPIKey, InternetEnvironment: sponsor.CodeBuddyInternetEnvironment, Models: []string{SponsoredCodeBuddyModel}, SponsorID: sponsor.ID}, true -} - -// SharedCodeBuddyModels returns the models users without their own key may -// use, the default first, or nil when there is no shared key. -func (r *UsersRepo) SharedCodeBuddyModels() []string { - if key, ok := r.SharedCodeBuddyKey(); ok { - return key.Models - } - return nil -} - -// PlatformCodeBuddyKeyStatus describes the shared key for administrators. -func (r *UsersRepo) PlatformCodeBuddyKeyStatus() PlatformCodeBuddyKeyStatus { - status := PlatformCodeBuddyKeyStatus{Models: []string{}} - if row, ok := r.platformCodeBuddyKey(); ok && strings.TrimSpace(row.APIKey) != "" { - status.Configured = true - status.InternetEnvironment = row.InternetEnvironment - if models := decodeSharedModels(row.Models); models != nil { - status.Models = models - } - status.UpdatedAt = row.Updated - if user, ok := r.User(row.UpdatedBy); ok { - status.UpdatedBy = user.LoginName - } - } - if sponsor, ok := r.legacyCodeBuddySponsor(); ok { - status.LegacySponsor = sponsor.LoginName - status.LegacySponsorModel = SponsoredCodeBuddyModel - } - return status -} - -// SetPlatformCodeBuddyKey saves the shared key settings. -func (r *UsersRepo) SetPlatformCodeBuddyKey(update PlatformCodeBuddyKeyUpdate, actorID int64) error { - if len(update.Models) == 0 { - return ErrSharedCodeBuddyModelsRequired - } - row, _ := r.platformCodeBuddyKey() - if key := strings.TrimSpace(update.APIKey); key != "" { - row.APIKey = key - } - if strings.TrimSpace(row.APIKey) == "" { - return ErrSharedCodeBuddyKeyRequired - } - models, err := json.Marshal(update.Models) - if err != nil { - return err - } - now := time.Now().UTC() - row.ID = platformCodeBuddyKeyID - row.InternetEnvironment = update.InternetEnvironment - row.Models = string(models) - row.UpdatedBy = actorID - row.Updated = &now - return r.DB.Clauses(clause.OnConflict{ - Columns: []clause.Column{{Name: "id"}}, - DoUpdates: clause.AssignmentColumns([]string{"api_key", "internet_environment", "models", "updated_by", "updated_at"}), - }).Create(&row).Error -} - -// ClearPlatformCodeBuddyKey removes the shared key; users without their own -// key need one again (or fall back to the legacy sponsor account). -func (r *UsersRepo) ClearPlatformCodeBuddyKey() error { - return r.DB.Where("id = ?", platformCodeBuddyKeyID).Delete(&platformCodeBuddyKeyRow{}).Error -} diff --git a/internal/repo/models.go b/internal/repo/models.go index 6dc1ba223..6998d6c3c 100644 --- a/internal/repo/models.go +++ b/internal/repo/models.go @@ -886,7 +886,7 @@ func (knowledgeSubmissionRow) TableName() string { return "knowledge_submissions // allModels lists every table for the sqlite test schema (AutoMigrate). func allModels() []any { return []any{domain.BotUserBinding{}, domain.BotBindingChallenge{}, domain.BotConnection{}, domain.BotConversation{}, domain.BotInteraction{}, notificationBotRow{}, botCredentialRow{}, botNativeSessionRow{}, botPendingDraftRow{}, botChatOriginRow{}, botClarifySessionRow{}, domain.NotificationDelivery{}, - userRow{}, localAccountRow{}, userConfigRow{}, gitSSHKeyRow{}, gitHTTPCredentialRow{}, authIntegrationRow{}, platformCodeBuddyKeyRow{}, apiTokenRow{}, genericTemplateRow{}, + userRow{}, localAccountRow{}, userConfigRow{}, gitSSHKeyRow{}, gitHTTPCredentialRow{}, authIntegrationRow{}, platformCodeBuddyKeyRow{}, platformModelKeyRow{}, apiTokenRow{}, genericTemplateRow{}, insightSourceRow{}, insightExecutionRow{}, projectRow{}, projectMemberRow{}, projectJoinRequestRow{}, projectCredentialRow{}, repositoryRow{}, businessDomainRow{}, businessDomainAssignmentRow{}, agentRow{}, ruleRow{}, skillRow{}, skillFileRow{}, mcpServerRow{}, mcpFileRow{}, executorRow{}, diff --git a/internal/repo/platform_model_keys.go b/internal/repo/platform_model_keys.go new file mode 100644 index 000000000..973226dbe --- /dev/null +++ b/internal/repo/platform_model_keys.go @@ -0,0 +1,379 @@ +package repo + +import ( + "encoding/json" + "errors" + "os" + "strings" + "time" + + "agentflow/internal/domain" + + "gorm.io/gorm/clause" +) + +// Shared model credentials. A platform administrator configures one API Key +// per assistant engine under 平台管理 → 共享模型 Key; members who have not +// configured their own key for that engine chat and run LOOPs on the shared +// one, limited to the models the administrator allowed. It covers chat +// conversations and LOOP runs, so a new user can start working before +// configuring anything; scheduled prompts, reports, bots and run evaluation +// keep requiring the user's own key. +// +// Older deployments lent the CodeBuddy key of the account named by +// AGENTFLOW_ASSISTANT_SPONSOR_LOGIN instead, limited to +// SponsoredCodeBuddyModel. That still applies while no shared CodeBuddy key +// is configured. +const ( + CodeBuddySponsorLoginEnv = "AGENTFLOW_ASSISTANT_SPONSOR_LOGIN" + SponsoredCodeBuddyModel = "deepseek-v4.1-flash" + // MaxSharedModels bounds the allow list of one shared credential. + MaxSharedModels = 32 + // MaxSharedCodeBuddyModels is the older name of MaxSharedModels. + MaxSharedCodeBuddyModels = MaxSharedModels +) + +// SharedModelKey is the credential users without their own borrow for one +// engine. +type SharedModelKey struct { + Provider string + APIKey string + // BaseURL is the gateway the key belongs to; empty means the official + // endpoint. CodeBuddy addresses its editions through + // InternetEnvironment instead. + BaseURL string + InternetEnvironment string + // Models are the models it may run; the first is the default. + Models []string + // SponsorID is the lending account under AGENTFLOW_ASSISTANT_SPONSOR_LOGIN, + // 0 for a key configured under 平台管理. + SponsorID int64 +} + +// Model returns the model a shared-key turn runs: the requested model when it +// is allowed, the default when none is requested, and false otherwise. +func (k SharedModelKey) Model(requested string) (string, bool) { + if len(k.Models) == 0 { + return "", false + } + requested = strings.TrimSpace(requested) + if requested == "" { + return k.Models[0], true + } + for _, id := range k.Models { + if id == requested { + return id, true + } + } + return "", false +} + +// The key is stored like personal keys: the database is the trust boundary, +// and the key is never returned by the API. One row per engine. +type platformModelKeyRow struct { + Provider string `gorm:"column:provider;primaryKey;size:32"` + APIKey string `gorm:"column:api_key;type:text;not null"` + BaseURL string `gorm:"column:base_url;type:text;not null"` + InternetEnvironment string `gorm:"column:internet_environment;size:64;not null;default:''"` + Models string `gorm:"column:models;type:text;not null"` + UpdatedBy int64 `gorm:"column:updated_by;not null;default:0"` + Updated *time.Time `gorm:"column:updated_at"` +} + +func (platformModelKeyRow) TableName() string { return "platform_model_keys" } + +// platformCodeBuddyKeyRow is the CodeBuddy-only table older releases wrote. +// It stays readable so an upgraded deployment keeps lending a key configured +// before the per-engine table existed; migrations/050 copies it. +type platformCodeBuddyKeyRow struct { + ID int64 `gorm:"column:id;primaryKey;autoIncrement:false"` + APIKey string `gorm:"column:api_key;type:text;not null"` + InternetEnvironment string `gorm:"column:internet_environment;size:64;not null;default:''"` + Models string `gorm:"column:models;type:text;not null"` + UpdatedBy int64 `gorm:"column:updated_by;not null;default:0"` + Updated *time.Time `gorm:"column:updated_at"` +} + +func (platformCodeBuddyKeyRow) TableName() string { return "platform_codebuddy_keys" } + +// The legacy table holds at most this one row. +const platformCodeBuddyKeyID = 1 + +// PlatformModelKeyStatus is what administrators see; it never carries the key. +type PlatformModelKeyStatus struct { + Provider string `json:"provider"` + Configured bool `json:"configured"` + BaseURL string `json:"baseUrl,omitempty"` + InternetEnvironment string `json:"internetEnvironment"` + Models []string `json:"models"` + UpdatedAt *time.Time `json:"updatedAt,omitempty"` + UpdatedBy string `json:"updatedBy,omitempty"` + // LegacySponsor is the account named by AGENTFLOW_ASSISTANT_SPONSOR_LOGIN + // whose key is lent while no shared CodeBuddy key is configured here. + LegacySponsor string `json:"legacySponsor,omitempty"` + LegacySponsorModel string `json:"legacySponsorModel,omitempty"` +} + +// PlatformCodeBuddyKeyStatus is the CodeBuddy view of PlatformModelKeyStatus. +type PlatformCodeBuddyKeyStatus = PlatformModelKeyStatus + +// PlatformModelKeyUpdate replaces one engine's shared key. An empty APIKey +// keeps the stored key. Models must already be validated. +type PlatformModelKeyUpdate struct { + Provider string + APIKey string + BaseURL string + InternetEnvironment string + Models []string +} + +// PlatformCodeBuddyKeyUpdate is the CodeBuddy-only form of +// PlatformModelKeyUpdate; Provider may be left empty. +type PlatformCodeBuddyKeyUpdate = PlatformModelKeyUpdate + +var ( + ErrSharedModelKeyRequired = errors.New("shared model API Key is required") + ErrSharedModelsRequired = errors.New("at least one shared model is required") + ErrSharedModelKeyProvider = errors.New("unsupported shared model provider") + // ErrSharedModelKeyBaseURLChanged rejects moving a stored key to another + // gateway without typing it again: the key is write-only, so whoever can + // edit the Base URL must not be able to redirect it somewhere they read. + ErrSharedModelKeyBaseURLChanged = errors.New("shared model API Key must be re-entered when the Base URL changes") + // ErrSharedCodeBuddyKeyRequired is the older name of + // ErrSharedModelKeyRequired. + ErrSharedCodeBuddyKeyRequired = ErrSharedModelKeyRequired + ErrSharedCodeBuddyModelsRequired = ErrSharedModelsRequired +) + +func (r *UsersRepo) platformModelKey(provider string) (platformModelKeyRow, bool) { + var row platformModelKeyRow + if r == nil || r.deps == nil || r.DB == nil || provider == "" { + return row, false + } + result := r.DB.Where("provider = ?", provider).Limit(1).Find(&row) + return row, result.Error == nil && result.RowsAffected > 0 +} + +func (r *UsersRepo) legacyPlatformCodeBuddyKey() (platformCodeBuddyKeyRow, bool) { + var row platformCodeBuddyKeyRow + if r == nil || r.deps == nil || r.DB == nil { + return row, false + } + result := r.DB.Where("id = ?", platformCodeBuddyKeyID).Limit(1).Find(&row) + return row, result.Error == nil && result.RowsAffected > 0 +} + +func decodeSharedModels(raw string) []string { + var models []string + if json.Unmarshal([]byte(raw), &models) != nil { + return nil + } + return models +} + +// legacyCodeBuddySponsor returns the account named by +// AGENTFLOW_ASSISTANT_SPONSOR_LOGIN, if it exists and has a key. +func (r *UsersRepo) legacyCodeBuddySponsor() (domain.User, bool) { + login := strings.TrimSpace(os.Getenv(CodeBuddySponsorLoginEnv)) + if login == "" || r == nil { + return domain.User{}, false + } + sponsor, ok := r.UserByLoginName(login) + if !ok || strings.TrimSpace(sponsor.CodeBuddyAPIKey) == "" { + return domain.User{}, false + } + return sponsor, true +} + +// SharedModelKey returns the credential users without their own borrow for +// one engine: the key configured under 平台管理, else, for CodeBuddy, the +// legacy table and the legacy sponsor account. +func (r *UsersRepo) SharedModelKey(provider string) (SharedModelKey, bool) { + provider, ok := domain.NormalizeSharedModelProvider(provider) + if !ok { + return SharedModelKey{}, false + } + if row, found := r.platformModelKey(provider); found { + models := decodeSharedModels(row.Models) + if strings.TrimSpace(row.APIKey) != "" && len(models) > 0 { + return SharedModelKey{ + Provider: provider, APIKey: row.APIKey, BaseURL: row.BaseURL, + InternetEnvironment: row.InternetEnvironment, Models: models, + }, true + } + } + if provider != domain.SharedModelProviderCodeBuddy { + return SharedModelKey{}, false + } + if row, found := r.legacyPlatformCodeBuddyKey(); found { + models := decodeSharedModels(row.Models) + if strings.TrimSpace(row.APIKey) != "" && len(models) > 0 { + return SharedModelKey{ + Provider: provider, APIKey: row.APIKey, + InternetEnvironment: row.InternetEnvironment, Models: models, + }, true + } + } + sponsor, found := r.legacyCodeBuddySponsor() + if !found { + return SharedModelKey{}, false + } + return SharedModelKey{ + Provider: provider, APIKey: sponsor.CodeBuddyAPIKey, + InternetEnvironment: sponsor.CodeBuddyInternetEnvironment, + Models: []string{SponsoredCodeBuddyModel}, SponsorID: sponsor.ID, + }, true +} + +// SharedModelKeys returns every shared credential, keyed by engine. +func (r *UsersRepo) SharedModelKeys() map[string]SharedModelKey { + keys := map[string]SharedModelKey{} + for _, provider := range domain.SharedModelProviders { + if key, ok := r.SharedModelKey(provider); ok { + keys[provider] = key + } + } + return keys +} + +// SharedCodeBuddyKey returns the CodeBuddy credential users without their own +// borrow. +func (r *UsersRepo) SharedCodeBuddyKey() (SharedModelKey, bool) { + return r.SharedModelKey(domain.SharedModelProviderCodeBuddy) +} + +// SharedCodeBuddyModels returns the models users without their own CodeBuddy +// key may use, the default first, or nil when there is no shared key. +func (r *UsersRepo) SharedCodeBuddyModels() []string { + if key, ok := r.SharedCodeBuddyKey(); ok { + return key.Models + } + return nil +} + +// PlatformModelKeyStatus describes one engine's shared key for +// administrators. +func (r *UsersRepo) PlatformModelKeyStatus(provider string) PlatformModelKeyStatus { + provider, _ = domain.NormalizeSharedModelProvider(provider) + status := PlatformModelKeyStatus{Provider: provider, Models: []string{}} + if row, ok := r.platformModelKey(provider); ok && strings.TrimSpace(row.APIKey) != "" { + status.Configured = true + status.BaseURL = row.BaseURL + status.InternetEnvironment = row.InternetEnvironment + if models := decodeSharedModels(row.Models); models != nil { + status.Models = models + } + status.UpdatedAt = row.Updated + if user, ok := r.User(row.UpdatedBy); ok { + status.UpdatedBy = user.LoginName + } + } else if provider == domain.SharedModelProviderCodeBuddy { + if row, ok := r.legacyPlatformCodeBuddyKey(); ok && strings.TrimSpace(row.APIKey) != "" { + status.Configured = true + status.InternetEnvironment = row.InternetEnvironment + if models := decodeSharedModels(row.Models); models != nil { + status.Models = models + } + status.UpdatedAt = row.Updated + if user, ok := r.User(row.UpdatedBy); ok { + status.UpdatedBy = user.LoginName + } + } + } + if provider != domain.SharedModelProviderCodeBuddy { + return status + } + if sponsor, ok := r.legacyCodeBuddySponsor(); ok { + status.LegacySponsor = sponsor.LoginName + status.LegacySponsorModel = SponsoredCodeBuddyModel + } + return status +} + +// PlatformModelKeyStatuses describes every engine's shared key, in +// domain.SharedModelProviders order. +func (r *UsersRepo) PlatformModelKeyStatuses() []PlatformModelKeyStatus { + statuses := make([]PlatformModelKeyStatus, 0, len(domain.SharedModelProviders)) + for _, provider := range domain.SharedModelProviders { + statuses = append(statuses, r.PlatformModelKeyStatus(provider)) + } + return statuses +} + +// SetPlatformModelKey saves one engine's shared key settings. +func (r *UsersRepo) SetPlatformModelKey(update PlatformModelKeyUpdate, actorID int64) error { + provider, ok := domain.NormalizeSharedModelProvider(update.Provider) + if !ok { + return ErrSharedModelKeyProvider + } + if len(update.Models) == 0 { + return ErrSharedModelsRequired + } + row, _ := r.platformModelKey(provider) + if key := strings.TrimSpace(update.APIKey); key != "" { + row.APIKey = key + } else if strings.TrimSpace(row.APIKey) != "" && !SameSharedModelBaseURL(row.BaseURL, update.BaseURL) { + return ErrSharedModelKeyBaseURLChanged + } + if strings.TrimSpace(row.APIKey) == "" && provider == domain.SharedModelProviderCodeBuddy { + // Editing only the models of a key saved before the per-engine table + // existed must not require typing it again. + if legacy, ok := r.legacyPlatformCodeBuddyKey(); ok { + row.APIKey = legacy.APIKey + } + } + if strings.TrimSpace(row.APIKey) == "" { + return ErrSharedModelKeyRequired + } + models, err := json.Marshal(update.Models) + if err != nil { + return err + } + now := time.Now().UTC() + row.Provider = provider + row.BaseURL = strings.TrimSpace(update.BaseURL) + row.InternetEnvironment = update.InternetEnvironment + row.Models = string(models) + row.UpdatedBy = actorID + row.Updated = &now + return r.DB.Clauses(clause.OnConflict{ + Columns: []clause.Column{{Name: "provider"}}, + DoUpdates: clause.AssignmentColumns([]string{"api_key", "base_url", "internet_environment", "models", "updated_by", "updated_at"}), + }).Create(&row).Error +} + +// SameSharedModelBaseURL reports whether two Base URLs name the same gateway, +// ignoring surrounding space and a trailing slash. +func SameSharedModelBaseURL(a, b string) bool { + return strings.TrimRight(strings.TrimSpace(a), "/") == strings.TrimRight(strings.TrimSpace(b), "/") +} + +// SetPlatformCodeBuddyKey saves the shared CodeBuddy key settings. +func (r *UsersRepo) SetPlatformCodeBuddyKey(update PlatformCodeBuddyKeyUpdate, actorID int64) error { + update.Provider = domain.SharedModelProviderCodeBuddy + return r.SetPlatformModelKey(update, actorID) +} + +// ClearPlatformModelKey removes one engine's shared key; users without their +// own key for it need one again (CodeBuddy falls back to the legacy sponsor +// account). +func (r *UsersRepo) ClearPlatformModelKey(provider string) error { + provider, ok := domain.NormalizeSharedModelProvider(provider) + if !ok { + return ErrSharedModelKeyProvider + } + if err := r.DB.Where("provider = ?", provider).Delete(&platformModelKeyRow{}).Error; err != nil { + return err + } + if provider == domain.SharedModelProviderCodeBuddy { + // Clearing means "stop lending this key": drop the legacy row too so + // the older key does not resurface. + return r.DB.Where("id = ?", platformCodeBuddyKeyID).Delete(&platformCodeBuddyKeyRow{}).Error + } + return nil +} + +// ClearPlatformCodeBuddyKey removes the shared CodeBuddy key. +func (r *UsersRepo) ClearPlatformCodeBuddyKey() error { + return r.ClearPlatformModelKey(domain.SharedModelProviderCodeBuddy) +} diff --git a/internal/repo/platform_model_keys_test.go b/internal/repo/platform_model_keys_test.go new file mode 100644 index 000000000..d6cc33fdf --- /dev/null +++ b/internal/repo/platform_model_keys_test.go @@ -0,0 +1,152 @@ +package repo + +import ( + "errors" + "strings" + "testing" + + "agentflow/internal/domain" +) + +func TestSharedModelKeysAreStoredPerCLI(t *testing.T) { + st, err := OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(st.Close) + t.Setenv(CodeBuddySponsorLoginEnv, "") + if err := st.PutUser(domain.User{ID: 21, LoginName: "owner"}); err != nil { + t.Fatal(err) + } + for _, update := range []PlatformModelKeyUpdate{ + {Provider: domain.SharedModelProviderCodeBuddy, APIKey: "ck_shared", InternetEnvironment: "internal", Models: []string{"glm-5.1"}}, + {Provider: domain.SharedModelProviderCodex, APIKey: "sk_codex", BaseURL: "https://gateway.example.com/v1", Models: []string{"gpt-6.1-terra", "gpt-6.1-sol"}}, + {Provider: domain.SharedModelProviderClaude, APIKey: "sk_claude", Models: []string{"claude-opus-5"}}, + } { + if err := st.SetPlatformModelKey(update, 21); err != nil { + t.Fatalf("%s: %v", update.Provider, err) + } + } + keys := st.SharedModelKeys() + if len(keys) != 3 { + t.Fatalf("shared keys = %+v", keys) + } + if key := keys[domain.SharedModelProviderCodex]; key.APIKey != "sk_codex" || key.BaseURL != "https://gateway.example.com/v1" || strings.Join(key.Models, ",") != "gpt-6.1-terra,gpt-6.1-sol" { + t.Fatalf("codex key = %+v", key) + } + if key := keys[domain.SharedModelProviderClaude]; key.APIKey != "sk_claude" || key.BaseURL != "" { + t.Fatalf("claude key = %+v", key) + } + if key := keys[domain.SharedModelProviderCodeBuddy]; key.InternetEnvironment != "internal" { + t.Fatalf("codebuddy key = %+v", key) + } + if got, ok := keys[domain.SharedModelProviderCodex].Model("gpt-6.1-sol"); !ok || got != "gpt-6.1-sol" { + t.Fatalf("allowed model = %q %v", got, ok) + } + if _, ok := keys[domain.SharedModelProviderCodex].Model("gpt-5.5"); ok { + t.Fatal("a model outside the allow list must be refused") + } + + status := st.PlatformModelKeyStatus(domain.SharedModelProviderCodex) + if !status.Configured || status.UpdatedBy != "owner" || status.BaseURL != "https://gateway.example.com/v1" { + t.Fatalf("codex status = %+v", status) + } + if statuses := st.PlatformModelKeyStatuses(); len(statuses) != len(domain.SharedModelProviders) || statuses[0].Provider != domain.SharedModelProviderCodeBuddy { + t.Fatalf("statuses = %+v", statuses) + } + + if err := st.SetPlatformModelKey(PlatformModelKeyUpdate{Provider: "kimi", APIKey: "k", Models: []string{"kimi-k3"}}, 21); !errors.Is(err, ErrSharedModelKeyProvider) { + t.Fatalf("unsupported provider: %v", err) + } + if err := st.SetPlatformModelKey(PlatformModelKeyUpdate{Provider: domain.SharedModelProviderClaude, Models: []string{"claude-opus-5"}}, 21); err != nil { + t.Fatalf("a models-only update keeps the key: %v", err) + } + if key, _ := st.SharedModelKey(domain.SharedModelProviderClaude); key.APIKey != "sk_claude" { + t.Fatalf("claude key after models-only update = %+v", key) + } + + if err := st.ClearPlatformModelKey(domain.SharedModelProviderCodex); err != nil { + t.Fatal(err) + } + if _, ok := st.SharedModelKey(domain.SharedModelProviderCodex); ok { + t.Fatal("cleared Codex key must not be lent") + } + if _, ok := st.SharedModelKey(domain.SharedModelProviderCodeBuddy); !ok { + t.Fatal("clearing one CLI must keep the others") + } +} + +// A deployment upgraded from the CodeBuddy-only table keeps lending that key, +// and clearing it removes both rows so the older key cannot resurface. +func TestLegacyCodeBuddyKeyMovesToThePerCLITable(t *testing.T) { + st, err := OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(st.Close) + t.Setenv(CodeBuddySponsorLoginEnv, "") + if err := st.PutUser(domain.User{ID: 21, LoginName: "owner"}); err != nil { + t.Fatal(err) + } + if err := st.DB.Create(&platformCodeBuddyKeyRow{ID: platformCodeBuddyKeyID, APIKey: "ck_legacy", InternetEnvironment: "ioa", Models: `["glm-5.1"]`}).Error; err != nil { + t.Fatal(err) + } + key, ok := st.SharedModelKey(domain.SharedModelProviderCodeBuddy) + if !ok || key.APIKey != "ck_legacy" || key.InternetEnvironment != "ioa" || strings.Join(key.Models, ",") != "glm-5.1" { + t.Fatalf("legacy key = %+v", key) + } + if status := st.PlatformModelKeyStatus(domain.SharedModelProviderCodeBuddy); !status.Configured { + t.Fatalf("legacy status = %+v", status) + } + + // Editing only the models must not ask the administrator to type the key + // again. + if err := st.SetPlatformModelKey(PlatformModelKeyUpdate{ + Provider: domain.SharedModelProviderCodeBuddy, InternetEnvironment: "ioa", Models: []string{"glm-5.1", "kimi-k2.6"}, + }, 21); err != nil { + t.Fatalf("models-only update over the legacy row: %v", err) + } + if key, _ := st.SharedModelKey(domain.SharedModelProviderCodeBuddy); key.APIKey != "ck_legacy" || strings.Join(key.Models, ",") != "glm-5.1,kimi-k2.6" { + t.Fatalf("moved key = %+v", key) + } + if legacy, ok := st.legacyPlatformCodeBuddyKey(); !ok || legacy.APIKey != "ck_legacy" { + t.Fatal("the legacy row must not be rewritten in code") + } + + if err := st.ClearPlatformCodeBuddyKey(); err != nil { + t.Fatal(err) + } + if _, ok := st.SharedModelKey(domain.SharedModelProviderCodeBuddy); ok { + t.Fatal("clearing must remove the legacy row too") + } +} + +// A stored key only follows the gateway it was entered for: moving it to +// another Base URL needs the key typed again. +func TestSharedModelKeyBaseURLChangeNeedsTheKey(t *testing.T) { + s, err := OpenTest() + if err != nil { + t.Fatal(err) + } + defer s.Close() + save := func(key, baseURL string) error { + return s.SetPlatformModelKey(PlatformModelKeyUpdate{Provider: domain.SharedModelProviderClaude, APIKey: key, BaseURL: baseURL, Models: []string{"m"}}, 0) + } + if err := save("sk_one", "https://gateway.example.com"); err != nil { + t.Fatal(err) + } + if err := save("", "https://gateway.example.com/"); err != nil { + t.Fatalf("same gateway, models only: %v", err) + } + for _, baseURL := range []string{"https://collector.example.net", ""} { + if err := save("", baseURL); !errors.Is(err, ErrSharedModelKeyBaseURLChanged) { + t.Fatalf("move to %q without key: %v", baseURL, err) + } + } + if key, _ := s.SharedModelKey(domain.SharedModelProviderClaude); key.APIKey != "sk_one" || key.BaseURL != "https://gateway.example.com/" { + t.Fatalf("stored key = %+v", key) + } + if err := save("sk_two", ""); err != nil { + t.Fatalf("move with key: %v", err) + } +} diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index 1df21a991..cbea45def 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -85,9 +85,15 @@ type RunCredentials struct { } type ProviderCredential struct { - APIKey string - BaseURL string - Protocol string + APIKey string + BaseURL string + // Sponsored is set when the responsible user has no key of their own and + // the platform's shared key for this CLI is used; such runs are limited + // to SponsoredModels (the default first). A sponsored credential always + // comes from the platform, never from a runner login. + Sponsored bool + SponsoredModels []string + Protocol string // Models is the user's saved model catalog for an agent CLI; Cursor // resolves folded families from it (CursorModelID). Models []domain.CLIModel diff --git a/migrations/050_platform_model_keys.sql b/migrations/050_platform_model_keys.sql new file mode 100644 index 000000000..f8bcf34e3 --- /dev/null +++ b/migrations/050_platform_model_keys.sql @@ -0,0 +1,27 @@ +-- 050: 平台共享模型凭据按 CLI 分开存放(platform_model_keys) +-- +-- 说明: +-- - 平台管理 → 共享模型 Key 从「只支持 CodeBuddy」扩展为按 CLI(codebuddy / +-- codex / claude-code)各存一份 Key、Base URL(CodeBuddy 为网络环境)与允许模型。 +-- - 新表由 gorm 增量迁移(autoMigrateIncremental)补建;本脚本负责把旧表 +-- platform_codebuddy_keys 里的那一行搬到新表的 codebuddy 行,供不依赖代码回退的 +-- 部署使用。代码在 platform_model_keys 没有 codebuddy 行时仍会读取旧表,因此 +-- 本脚本可择机执行,执行后旧表保留不动(代码不再写入它)。 +-- - 旧表在页面上「停用共享 Key」时才会被清空。 + +CREATE TABLE IF NOT EXISTS platform_model_keys ( + provider VARCHAR(32) NOT NULL, + api_key TEXT NOT NULL, + base_url TEXT NOT NULL, + internet_environment VARCHAR(64) NOT NULL DEFAULT '', + models TEXT NOT NULL, + updated_by BIGINT NOT NULL DEFAULT 0, + updated_at DATETIME(3) NULL, + PRIMARY KEY (provider) +) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; + +INSERT INTO platform_model_keys (provider, api_key, base_url, internet_environment, models, updated_by, updated_at) +SELECT 'codebuddy', api_key, '', internet_environment, models, updated_by, updated_at +FROM platform_codebuddy_keys +WHERE id = 1 AND TRIM(api_key) <> '' + AND NOT EXISTS (SELECT 1 FROM platform_model_keys WHERE provider = 'codebuddy'); diff --git a/web/app/workbench.js b/web/app/workbench.js index a69d04521..c7a309594 100644 --- a/web/app/workbench.js +++ b/web/app/workbench.js @@ -1661,7 +1661,7 @@ function renderPlatformNav(){ const PLATFORM_TABS=[ {id:'accounts',zh:'成员账号',en:'Accounts'}, {id:'admins',zh:'平台管理员',en:'Admins'}, - {id:'sharedKey',zh:'共享 CodeBuddy Key',en:'Shared CodeBuddy Key'}, + {id:'sharedKey',zh:'共享模型 Key',en:'Shared Model Key'}, {id:'gitHostTrust',zh:'Git 主机信任',en:'Git Host Trust'}, {id:'publicUrl',zh:'外部访问地址',en:'Public Address'}, ]; @@ -1886,21 +1886,32 @@ function platformAccountsHTML(){ `; } +// The CLIs whose API Key the platform may share. Order matches +// domain.SharedModelProviders. +const SHARED_KEY_PROVIDERS=[ + {id:'codebuddy',label:'CodeBuddy',keyPlaceholder:'ck_ 开头的 CodeBuddy API Key'}, + {id:'codex',label:'Codex',keyPlaceholder:'Codex API Key,例如 sk-…',baseURLPlaceholder:'留空用官方地址;自建网关如 https://gateway.example.com/v1'}, + {id:'claude-code',label:'Claude Code',keyPlaceholder:'Claude Code API Key',baseURLPlaceholder:'留空用官方地址;自建网关如 https://gateway.example.com'}, +]; +function sharedProviderMeta(id){return SHARED_KEY_PROVIDERS.find(p=>p.id===id)||SHARED_KEY_PROVIDERS[0]} function platformSharedKeyHTML(){ const envOptions=CODEBUDDY_ENVIRONMENTS.map(env=>``).join(''); + const providers=SHARED_KEY_PROVIDERS.map(p=>``).join(''); return `

    给没配 Key 的成员用

    -

    成员没配自己的 CodeBuddy API Key 时,对话和 LOOP 会用这里的 Key,并且只能用下面勾选的模型。成员配了自己的 Key 就用自己的,不受限制。

    +

    成员没配自己的 API Key 时,对话和 LOOP 会用这里对应 CLI 的共享 Key,并且只能用下面勾选的模型。成员配了自己的 Key 就用自己的,不受限制。

    ${lfT('加载中','Loading')}
    +
    ${providers}
    - + +
    @@ -1912,6 +1923,7 @@ function platformSharedKeyHTML(){
    允许使用的模型

    正在读取可用模型…

    +
    @@ -2011,24 +2023,31 @@ async function loadPlatformAccounts(host){ async function loadPlatformSharedKey(host){ const card=host.querySelector('#platformSharedKeyCard');if(!card)return; const form=card.querySelector('#platformSharedKeyForm'); - const env=form.elements.internetEnvironment,key=form.elements.apiKey,extra=form.elements.extraModels,defaultSelect=form.elements.defaultModel; + const env=form.elements.internetEnvironment,key=form.elements.apiKey,baseURL=form.elements.baseUrl,extra=form.elements.extraModels,defaultSelect=form.elements.defaultModel; const modelsHost=card.querySelector('[data-shared-models]'),badge=card.querySelector('[data-shared-key-badge]'),meta=card.querySelector('[data-shared-key-meta]'); const link=card.querySelector('[data-shared-key-link]'),warning=card.querySelector('[data-shared-key-warning]'),clear=card.querySelector('[data-shared-key-clear]'); - let status=null,catalog=[],selected=[]; + const envField=card.querySelector('[data-shared-env-field]'),baseURLField=card.querySelector('[data-shared-baseurl-field]'),probe=card.querySelector('[data-shared-probe]'); + const modelCount=card.querySelector('[data-shared-models-count]'),tabState=host.querySelector('[data-platform-tab-state]'); + const statuses={}; + let provider='codebuddy',status=null,catalog=[],selected=[]; + const labelOf=id=>sharedProviderMeta(id).label; + const endpoint=id=>`/api/platform/model-keys/${encodeURIComponent(id)}`; const extraIDs=()=>String(extra.value||'').split(/[,,\s]+/).map(s=>s.trim()).filter(Boolean); const chosen=()=>{const all=[...selected];for(const id of extraIDs())if(!all.includes(id))all.push(id);return all}; - const modelCount=card.querySelector('[data-shared-models-count]'),tabState=host.querySelector('[data-platform-tab-state]'); const renderDefault=()=>{ const models=chosen(),current=defaultSelect.value; if(modelCount)modelCount.textContent=models.length?lfT(`已选 ${models.length} 个`,`${models.length} selected`):''; - defaultSelect.innerHTML=models.length?models.map(id=>``).join(''):''; + defaultSelect.innerHTML=models.length?models.map(id=>``).join(''):``; defaultSelect.value=models.includes(current)?current:(models[0]||''); }; const renderModels=()=>{ const listed=catalog.filter(m=>m&&m.id&&m.id!=='default'); 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。

    '; + const empty=provider==='codebuddy' + ?lfT('这个网络环境暂时没有读到模型列表,可以在下面直接填模型 ID。','No models read for this network environment yet; type model IDs below.') + :lfT('还没有读到模型,可以点「获取可用模型」或直接填模型 ID。','No models read yet; fetch them or type model IDs below.'); + modelsHost.innerHTML=listed.length?listed.map(m=>``).join(''):`

    ${escapeHTML(empty)}

    `; modelsHost.querySelectorAll('input[type="checkbox"]').forEach(box=>box.onchange=()=>{ selected=box.checked?[...selected.filter(id=>id!==box.value),box.value]:selected.filter(id=>id!==box.value); renderDefault(); @@ -2036,73 +2055,158 @@ async function loadPlatformSharedKey(host){ renderDefault(); }; const renderLink=()=>{link.href=codeBuddyKeyURL(env.value);link.textContent=`${codeBuddyKeyLinkLabel(env.value)} ↗`}; + const renderTabs=()=>{ + card.querySelectorAll('[data-shared-provider]').forEach(btn=>{ + const on=btn.dataset.sharedProvider===provider; + btn.classList.toggle('active',on);btn.setAttribute('aria-selected',String(on)); + const state=btn.querySelector('[data-shared-provider-state]'); + if(state){const configured=!!statuses[btn.dataset.sharedProvider]?.configured;state.hidden=!configured;state.className='platform-provider-state'+(configured?' is-on':'');state.title=configured?lfT('已配置','Configured'):''} + }); + const anyConfigured=SHARED_KEY_PROVIDERS.some(p=>statuses[p.id]?.configured); + const legacy=!!statuses.codebuddy?.legacySponsor; + const tone=anyConfigured?'on':legacy?'legacy':'off'; + if(tabState){tabState.className=`platform-tab-state is-${tone}`;tabState.title=anyConfigured?lfT('已启用','Enabled'):lfT('未启用','Not enabled');tabState.hidden=false} + }; const renderStatus=()=>{ - const on=!!status?.configured,envInfo=CODEBUDDY_ENVIRONMENTS.find(e=>e.value===(status?.internetEnvironment||''))||CODEBUDDY_ENVIRONMENTS[0]; - const tone=on?'on':status?.legacySponsor?'legacy':'off'; - badge.textContent=on?'已启用':status?.legacySponsor?'使用旧配置':'未启用'; + const active=status||{},on=!!active.configured,legacy=!!active.legacySponsor; + const tone=on?'on':legacy?'legacy':'off'; + badge.textContent=on?lfT('已启用','Enabled'):legacy?lfT('使用旧配置','Legacy config'):lfT('未启用','Not enabled'); badge.classList.remove('is-on','is-legacy','is-off');badge.classList.add(`is-${tone}`); - if(tabState){tabState.className=`platform-tab-state is-${tone}`;tabState.title=badge.textContent;tabState.hidden=false} - key.placeholder=on?'已配置,留空保持不变':'ck_ 开头的 CodeBuddy API Key'; - clear.hidden=!on; const parts=[]; if(on){ - const n=(status.models||[]).length,first=sharedModelLabel(status.models?.[0]),by=status.updatedBy||''; - parts.push(lfT(`当前:${envInfo.label},${n} 个模型,默认 ${first}${by?`,${by} 最后修改`:''}。`,`Current: ${envInfo.label}, ${n} model${n===1?'':'s'}, default ${first}${by?`, last changed by ${by}`:''}.`)); + const n=(active.models||[]).length,first=sharedModelLabel(active.models?.[0]),by=active.updatedBy||''; + const where=provider==='codebuddy' + ?(CODEBUDDY_ENVIRONMENTS.find(e=>e.value===(active.internetEnvironment||''))||CODEBUDDY_ENVIRONMENTS[0]).label + :(active.baseUrl||lfT('官方地址','official endpoint')); + parts.push(lfT(`当前:${where},${n} 个模型,默认 ${first}${by?`,${by} 最后修改`:''}。`,`Current: ${where}, ${n} model${n===1?'':'s'}, default ${first}${by?`, last changed by ${by}`:''}.`)); + }else{ + parts.push(lfT(`还没有配置 ${labelOf(provider)} 的共享 Key,没配 Key 的成员需要先配自己的 Key 才能用 ${labelOf(provider)} 对话和跑 LOOP。`,`No shared ${labelOf(provider)} key yet; members without their own key must add one before chatting or running LOOPs on ${labelOf(provider)}.`)); + } + if(provider==='codebuddy'&&legacy){ + const sponsor=active.legacySponsor; + parts.push(on + ?lfT(`配置后不再使用环境变量 AGENTFLOW_ASSISTANT_SPONSOR_LOGIN 指定的账号 ${sponsor} 的 Key。`,`The key of ${sponsor} (AGENTFLOW_ASSISTANT_SPONSOR_LOGIN) is no longer used.`) + :lfT(`现在沿用环境变量 AGENTFLOW_ASSISTANT_SPONSOR_LOGIN 指定的账号 ${sponsor} 的 Key,只能用 ${sharedModelLabel(active.legacySponsorModel)}。`,`For now the key of ${sponsor} (AGENTFLOW_ASSISTANT_SPONSOR_LOGIN) is shared, limited to ${sharedModelLabel(active.legacySponsorModel)}.`)); } - else parts.push(lfT('还没有配置共享 Key,没配 Key 的成员需要先配自己的 Key 才能对话和跑 LOOP。','No shared key yet; members without their own key must add one before chatting or running LOOPs.')); - const sponsor=status?.legacySponsor; - if(sponsor)parts.push(on - ?lfT(`配置后不再使用环境变量 AGENTFLOW_ASSISTANT_SPONSOR_LOGIN 指定的账号 ${sponsor} 的 Key。`,`The key of ${sponsor} (AGENTFLOW_ASSISTANT_SPONSOR_LOGIN) is no longer used.`) - :lfT(`现在沿用环境变量 AGENTFLOW_ASSISTANT_SPONSOR_LOGIN 指定的账号 ${sponsor} 的 Key,只能用 ${sharedModelLabel(status.legacySponsorModel)}。`,`For now the key of ${sponsor} (AGENTFLOW_ASSISTANT_SPONSOR_LOGIN) is shared, limited to ${sharedModelLabel(status.legacySponsorModel)}.`)); meta.textContent=parts.join(lfT('',' ')); }; + const renderFields=()=>{ + const info=sharedProviderMeta(provider),codeBuddy=provider==='codebuddy',on=!!status?.configured; + envField.hidden=!codeBuddy;baseURLField.hidden=codeBuddy;probe.hidden=codeBuddy;link.hidden=!codeBuddy; + if(codeBuddy){renderLink();env.value=status?.internetEnvironment||''} + else{baseURL.value=status?.baseUrl||'';baseURL.placeholder=info.baseURLPlaceholder||'留空用官方地址'} + key.placeholder=on?(codeBuddy?lfT('已配置,留空保持不变','Configured; leave blank to keep'):lfT('已配置,留空保持不变;改 Base URL 时需重新填写','Configured; leave blank to keep. Re-enter it when changing the Base URL')):info.keyPlaceholder; + clear.hidden=!on; + }; const syncBootstrap=()=>{ if(!state.data)return; - const models=status?.configured?(status.models||[]):(status?.legacySponsor?[status.legacySponsorModel]:[]); + const cb=statuses.codebuddy; + const models=cb?.configured?(cb.models||[]):(cb?.legacySponsor?[cb.legacySponsorModel]:[]); state.data.sponsoredModels=models;state.data.sponsoredModel=models[0]||''; }; - const fetchStatus=async environment=>{ - const query=environment===undefined?'':`?environment=${encodeURIComponent(environment)}`; - const result=await api('/api/platform/codebuddy-key'+query); - catalog=Array.isArray(result?.catalog)?result.catalog:[]; + // Tab clicks and environment changes can overlap; only the latest request + // may fill the form, or a slow reply would show (and save) another CLI's + // models and Base URL under the current tab. + let loadSeq=0,loading=false; + const loadProvider=async(id,{keepSelection=false}={})=>{ + const seq=++loadSeq;loading=true; + const query=id==='codebuddy'&&env.value!==undefined&&card.dataset.sharedLoaded==='1'?`?environment=${encodeURIComponent(env.value)}`:''; + const stale=()=>seq!==loadSeq||id!==provider; + let result; + // A stale request's failure must not clear the tab a later request filled. + try{result=await api(endpoint(id)+query)} + catch(e){if(stale()){renderTabs();return null}throw e} + finally{if(seq===loadSeq)loading=false} + statuses[id]=result; + if(stale()){renderTabs();return null} + status=result;catalog=Array.isArray(result?.catalog)?result.catalog:[]; + if(!keepSelection){ + selected=result?.configured?[...(result.models||[])]:(id==='codebuddy'&&result?.legacySponsorModel?[result.legacySponsorModel]:[]); + key.value='';extra.value='';warning.hidden=true; + } return result; }; try{ - status=await fetchStatus(); - env.value=status?.internetEnvironment||''; - selected=status?.configured?[...(status.models||[])]:(status?.legacySponsorModel?[status.legacySponsorModel]:[]); - renderStatus();renderLink();renderModels(); + const list=await api('/api/platform/model-keys'); + for(const item of (Array.isArray(list?.keys)?list.keys:[]))if(item?.provider)statuses[item.provider]=item; + await loadProvider(provider); + card.dataset.sharedLoaded='1'; + renderTabs();renderFields();renderStatus();renderModels(); }catch(e){ - badge.textContent='加载失败';modelsHost.innerHTML=`

    ${escapeHTML(e.message||'加载共享 Key 失败')}

    `; + badge.textContent=lfT('加载失败','Load failed');modelsHost.innerHTML=`

    ${escapeHTML(e.message||'加载共享 Key 失败')}

    `; return; } + card.querySelectorAll('[data-shared-provider]').forEach(btn=>btn.onclick=async()=>{ + if(provider===btn.dataset.sharedProvider)return; + const id=provider=btn.dataset.sharedProvider; + status=statuses[id]||null;catalog=[];selected=[];key.value='';extra.value='';warning.hidden=true; + renderTabs();renderFields();renderStatus(); + modelsHost.innerHTML='

    正在读取可用模型…

    '; + let result; + try{result=await loadProvider(id)}catch(e){if(id!==provider)return;status=null;catalog=[];toast(e.message,'err')} + if(result===null)return; + renderTabs();renderFields();renderStatus();renderModels(); + }); env.onchange=async()=>{ + if(provider!=='codebuddy')return; renderLink(); modelsHost.innerHTML='

    正在读取可用模型…

    '; - try{await fetchStatus(env.value)}catch(e){catalog=[]} - renderModels(); + let result; + try{result=await loadProvider('codebuddy',{keepSelection:true})}catch(e){if(provider!=='codebuddy')return;catalog=[]} + if(result===null)return; + renderStatus();renderModels(); + }; + // Save, stop and probe reply after the request; the tab may have changed + // meanwhile, so each writes back only to the CLI it was sent for. + probe.onclick=async()=>{ + const id=provider; + probe.disabled=true; + try{ + const result=await api(`${endpoint(id)}/probe`,{method:'POST',body:JSON.stringify({apiKey:key.value.trim(),baseUrl:baseURL.value.trim()})}); + if(id!==provider)return; + if(result?.error){toast(result.error,'err');return} + const ids=(result?.models||[]).map(m=>String(m?.id||'')).filter(Boolean); + if(!ids.length){toast('没有读到模型,可以手动填写模型 ID','err');return} + const listed=ids.map(id=>({id,name:(result.models.find(m=>m?.id===id)?.name)||id})); + catalog=[...listed,...catalog.filter(m=>m&&m.id&&!ids.includes(m.id))]; + renderModels(); + toast(lfT(`读到 ${ids.length} 个模型`,`${ids.length} models fetched`),'ok'); + }catch(err){toast(err.message,'err')} + finally{probe.disabled=false} }; extra.oninput=renderDefault; - key.oninput=()=>{const text=credentialSecretWarning(credentialKind('codeBuddyApiKey'),key.value);warning.textContent=text;warning.hidden=!text}; + key.oninput=()=>{const text=credentialSecretWarning(credentialKind(provider==='codex'?'codexApiKey':provider==='claude-code'?'claudeCodeApiKey':'codeBuddyApiKey'),key.value);warning.textContent=text;warning.hidden=!text}; form.onsubmit=async e=>{ e.preventDefault(); - const models=chosen(); + if(loading)return toast(lfT('正在读取当前 CLI 的配置,请稍候再保存','Still loading this CLI; save again in a moment'),'err'); + const id=provider,models=chosen(); if(!models.length)return toast('请至少勾选一个允许使用的模型','err'); - if(!status?.configured&&!key.value.trim())return toast('请填写 CodeBuddy API Key','err'); + if(!status?.configured&&!key.value.trim())return toast(`请填写 ${labelOf(id)} API Key`,'err'); const first=defaultSelect.value&&models.includes(defaultSelect.value)?defaultSelect.value:models[0]; - const ordered=[first,...models.filter(id=>id!==first)]; + const ordered=[first,...models.filter(m=>m!==first)]; + const body={apiKey:key.value.trim(),models:ordered}; + if(id==='codebuddy')body.internetEnvironment=env.value;else body.baseUrl=baseURL.value.trim(); const submit=form.querySelector('button[type="submit"]');if(submit)submit.disabled=true; try{ - status=await api('/api/platform/codebuddy-key',{method:'PUT',body:JSON.stringify({apiKey:key.value.trim(),internetEnvironment:env.value,models:ordered})}); + const result=await api(endpoint(id),{method:'PUT',body:JSON.stringify(body)}); + statuses[id]=result; + if(id!==provider){renderTabs();syncBootstrap();toast(lfT(`${labelOf(id)} 的共享 Key 已保存`,`Shared ${labelOf(id)} key saved`),'ok');return} + status=result; key.value='';warning.hidden=true;extra.value='';selected=[...(status.models||ordered)]; - renderStatus();renderModels();syncBootstrap();toast('共享 Key 已保存','ok'); + renderTabs();renderFields();renderStatus();renderModels();syncBootstrap();toast('共享 Key 已保存','ok'); }catch(err){toast(err.message,'err')} finally{if(submit)submit.disabled=false} }; clear.onclick=async()=>{ - if(!await afConfirm({title:'停用共享 Key',message:'停用后,没配自己 Key 的成员将不能再用共享 Key 对话和跑 LOOP。确定停用?',danger:true,confirmText:'停用'}))return; - try{status=await api('/api/platform/codebuddy-key',{method:'DELETE'});renderStatus();syncBootstrap();toast('共享 Key 已停用','ok')} - catch(err){toast(err.message,'err')} + const id=provider,label=labelOf(id); + if(!await afConfirm({title:'停用共享 Key',message:`停用后,没配自己 Key 的成员将不能再用 ${label} 的共享 Key 对话和跑 LOOP。确定停用?`,danger:true,confirmText:'停用'}))return; + try{ + const result=await api(endpoint(id),{method:'DELETE'}); + statuses[id]=result; + if(id!==provider){renderTabs();syncBootstrap();toast(lfT(`${label} 的共享 Key 已停用`,`Shared ${label} key stopped`),'ok');return} + status=result;selected=[]; + renderTabs();renderFields();renderStatus();renderModels();syncBootstrap();toast('共享 Key 已停用','ok'); + }catch(err){toast(err.message,'err')} }; } async function loadPlatformAdmins(host){ diff --git a/web/i18n-en.js b/web/i18n-en.js index a45637a32..1c37c688f 100644 --- a/web/i18n-en.js +++ b/web/i18n-en.js @@ -1164,6 +1164,14 @@ Object.assign(window.LF_I18N_EN, { "在对话里澄清和改代码": "Clarify and change code in chat", "这条需求不使用 LOOP,在对话里澄清需求、直接改代码;定时任务不会自动认领它。": "This requirement uses no LOOP: clarify and change code in chat; scheduled jobs won't pick it up.", }); +Object.assign(window.LF_I18N_EN, { + "共享模型 Key": "Shared model keys", + "成员没配自己的 API Key 时,对话和 LOOP 会用这里对应 CLI 的共享 Key,并且只能用下面勾选的模型。成员配了自己的 Key 就用自己的,不受限制。": "Members without their own API key chat and run LOOPs on the shared key of the matching CLI, limited to the models checked below. Members with their own key keep using it without limits.", + "获取可用模型": "Fetch models", + "还没有读到模型,可以点「获取可用模型」或直接填模型 ID。": "No models read yet; fetch them or type model IDs below.", + "共享 Key 对应的 CLI": "CLI of the shared key", +}); + // 执行机器 page: static copy in index.html. runners.js renders its dynamic copy with lfT. Object.assign(window.LF_I18N_EN, { "连接电脑或 CVM,可将机器共享给多个项目。": "Connect a computer or CVM and share it with multiple projects.", diff --git a/web/platform.css b/web/platform.css index c48dc0ec8..f472ab0a9 100644 --- a/web/platform.css +++ b/web/platform.css @@ -1566,6 +1566,12 @@ textarea.pa-input{height:auto;min-height:76px;padding:9px 11px;resize:vertical;l .platform-note.is-ok{border-color:color-mix(in srgb,var(--hui-success) 28%,transparent);background:color-mix(in srgb,var(--hui-success) 7%,var(--hui-surface));color:var(--text)} .platform-note.is-warn{border-color:color-mix(in srgb,var(--hui-warn) 28%,transparent);background:color-mix(in srgb,var(--hui-warn) 8%,var(--hui-surface));color:var(--hui-warn)} .platform-account-created[hidden]{display:none} +.platform-shared-key-providers{align-self:flex-start} +.platform-shared-key-providers .platform-filter-btn{display:inline-flex;align-items:center;gap:6px} +.platform-provider-state{width:7px;height:7px;border-radius:50%;background:var(--muted-2)} +.platform-provider-state[hidden]{display:none} +.platform-provider-state.is-on{background:var(--hui-success,var(--green))} +.platform-shared-key-probe{align-self:flex-start} .platform-shared-key-form{display:flex;flex-direction:column;gap:18px} .platform-shared-key-grid{display:grid;grid-template-columns:minmax(280px,1fr) minmax(0,1.5fr);gap:20px 28px;align-items:start} .platform-shared-key-col{display:flex;flex-direction:column;gap:16px;min-width:0} diff --git a/webtest/tests/platform-admin.test.mjs b/webtest/tests/platform-admin.test.mjs index 9934606b1..9d27491cb 100644 --- a/webtest/tests/platform-admin.test.mjs +++ b/webtest/tests/platform-admin.test.mjs @@ -49,7 +49,14 @@ test('platform admin tabs separate all five settings sections and support keyboa app.evaluate(`state.currentUser={...state.data.users[0],isGuest:false,isPlatformAdmin:true}`); app.router.get('/api/platform/admins', [{ userId: 1, loginName: 'owner', chineseName: '', source: 'granted', revocable: true }]); app.router.get('/api/platform/accounts', { signupEnabled: true, accounts: [1, 2, 3].map((id) => ({ userId: id, loginName: `user${id}`, admin: id === 1, password: true, codeBuddyApiKeyConfigured: false })) }); - app.router.get(/^\/api\/platform\/codebuddy-key/, { configured: true, internetEnvironment: '', models: ['glm-5.1'], updatedBy: 'owner', catalog: [{ id: 'glm-5.1', name: 'GLM-5.1' }, { id: 'kimi-k2.6', name: 'Kimi-K2.6' }] }); + app.router.get('/api/platform/model-keys', { keys: [ + { provider: 'codebuddy', configured: true, internetEnvironment: '', models: ['glm-5.1'] }, + { provider: 'codex', configured: false, baseUrl: '', models: [] }, + { provider: 'claude-code', configured: false, baseUrl: '', models: [] }, + ] }); + app.router.get(/^\/api\/platform\/model-keys\/codebuddy(\?|$)/, { provider: 'codebuddy', configured: true, internetEnvironment: '', models: ['glm-5.1'], updatedBy: 'owner', catalog: [{ id: 'glm-5.1', name: 'GLM-5.1' }, { id: 'kimi-k2.6', name: 'Kimi-K2.6' }] }); + app.router.get('/api/platform/model-keys/codex', { provider: 'codex', configured: false, baseUrl: '', models: [], catalog: [{ id: 'gpt-6.1-terra', name: 'GPT-6.1-Terra' }] }); + app.router.get('/api/platform/model-keys/claude-code', { provider: 'claude-code', configured: false, baseUrl: '', models: [], catalog: [{ id: 'claude-opus-5', name: 'Claude Opus 5' }] }); app.router.get('/api/platform/public-url', { source: 'env', value: 'https://loopforge.example.com', envValue: 'https://loopforge.example.com' }); app.evaluate(`renderPlatformAdminPanel()`); await settle(8); @@ -273,7 +280,7 @@ test('platform admins create accounts and reset passwords from the page', async assert.equal(card.querySelectorAll('[data-account-row]').length, 1); }); -test('platform admins share a CodeBuddy key limited to the models they pick', async (t) => { +test('platform admins share model keys per CLI, limited to the models they pick', async (t) => { const app = await loadApp(); t.after(app.close); app.evaluate(`state.currentUser={...state.data.users[0],isGuest:false,isPlatformAdmin:true}`); @@ -281,20 +288,31 @@ test('platform admins share a CodeBuddy key limited to the models they pick', as '': [{ id: 'default', name: 'CLI 默认模型' }, { id: 'glm-5.1', name: 'GLM-5.1', credits: '0.2x' }, { id: 'kimi-k2.6', name: 'Kimi-K2.6' }], internal: [{ id: 'default', name: 'CLI 默认模型' }, { id: 'deepseek-v4.1-flash', name: 'Deepseek-V4.1-Flash' }, { id: 'glm-5.1', name: 'GLM-5.1' }], }; - let saved = { configured: false, internetEnvironment: '', models: [], legacySponsor: 'sponsor', legacySponsorModel: 'deepseek-v4.1-flash' }; + const saved = { + codebuddy: { provider: 'codebuddy', configured: false, internetEnvironment: '', models: [], legacySponsor: 'sponsor', legacySponsorModel: 'deepseek-v4.1-flash' }, + codex: { provider: 'codex', configured: false, baseUrl: '', models: [] }, + 'claude-code': { provider: 'claude-code', configured: false, baseUrl: '', models: [] }, + }; app.router.get('/api/platform/admins', []); app.router.get('/api/platform/accounts', { accounts: [], signupEnabled: true }); - app.router.get(/^\/api\/platform\/codebuddy-key/, (call) => { - const env = call.url.searchParams.has('environment') ? call.url.searchParams.get('environment') : saved.internetEnvironment; - return { ...saved, catalog: catalogs[env] || [] }; + app.router.get('/api/platform/model-keys', () => ({ keys: Object.values(saved) })); + app.router.get(/^\/api\/platform\/model-keys\/codebuddy(\?|$)/, (call) => { + const env = call.url.searchParams.has('environment') ? call.url.searchParams.get('environment') : saved.codebuddy.internetEnvironment; + return { ...saved.codebuddy, catalog: catalogs[env] || [] }; + }); + app.router.get('/api/platform/model-keys/codex', () => ({ ...saved.codex, catalog: [{ id: 'gpt-6.1-terra', name: 'GPT-6.1-Terra' }] })); + app.router.get('/api/platform/model-keys/claude-code', () => ({ ...saved['claude-code'], catalog: [{ id: 'claude-opus-5', name: 'Claude Opus 5' }] })); + app.router.put('/api/platform/model-keys/codebuddy', (call) => { + saved.codebuddy = { ...saved.codebuddy, configured: true, internetEnvironment: call.body.internetEnvironment, models: call.body.models, updatedBy: 'owner' }; + return saved.codebuddy; }); - app.router.put('/api/platform/codebuddy-key', (call) => { - saved = { ...saved, configured: true, internetEnvironment: call.body.internetEnvironment, models: call.body.models, updatedBy: 'owner' }; - return saved; + app.router.put('/api/platform/model-keys/codex', (call) => { + saved.codex = { ...saved.codex, configured: true, baseUrl: call.body.baseUrl, models: call.body.models, updatedBy: 'owner' }; + return saved.codex; }); - app.router.delete('/api/platform/codebuddy-key', () => { - saved = { ...saved, configured: false, models: [] }; - return saved; + app.router.delete('/api/platform/model-keys/codebuddy', () => { + saved.codebuddy = { ...saved.codebuddy, configured: false, models: [] }; + return saved.codebuddy; }); app.evaluate(`renderPlatformAdminPanel()`); await settle(8); @@ -305,14 +323,15 @@ test('platform admins share a CodeBuddy key limited to the models they pick', as assert.ok(!card.querySelector('[data-shared-models] input[value="default"]'), 'the CLI default is not offered'); assert.ok(card.querySelector('[data-shared-models] input[value="deepseek-v4.1-flash"]').checked, 'the legacy sponsor model starts selected'); assert.ok(card.querySelector('[data-shared-key-clear]').hidden); + assert.equal(card.querySelector('[data-shared-baseurl-field]').hidden, true, 'CodeBuddy uses a network environment'); form.elements.internetEnvironment.value = 'internal'; form.elements.internetEnvironment.dispatchEvent(new app.window.Event('change', { bubbles: true })); await settle(6); assert.equal(card.querySelector('[data-shared-key-link]').getAttribute('href'), 'https://copilot.tencent.com/profile/'); - const box = (id) => card.querySelector(`[data-shared-models] input[value="${id}"]`); - box('glm-5.1').checked = true; - box('glm-5.1').dispatchEvent(new app.window.Event('change', { bubbles: true })); + const codeBuddyBox = (id) => card.querySelector(`[data-shared-models] input[value="${id}"]`); + codeBuddyBox('glm-5.1').checked = true; + codeBuddyBox('glm-5.1').dispatchEvent(new app.window.Event('change', { bubbles: true })); form.elements.extraModels.value = 'custom-model'; form.elements.extraModels.dispatchEvent(new app.window.Event('input', { bubbles: true })); assert.deepEqual([...form.elements.defaultModel.options].map((o) => o.value), ['deepseek-v4.1-flash', 'glm-5.1', 'custom-model']); @@ -330,26 +349,119 @@ test('platform admins share a CodeBuddy key limited to the models they pick', as assert.equal(card.querySelector('[data-shared-key-warning]').hidden, true); form.dispatchEvent(new app.window.Event('submit', { bubbles: true, cancelable: true })); await settle(6); - const put = app.router.calls.find((call) => call.method === 'PUT' && call.path === '/api/platform/codebuddy-key'); - assert.deepEqual(put.body, { apiKey: 'ck_shared', internetEnvironment: 'internal', models: ['glm-5.1', 'deepseek-v4.1-flash', 'custom-model'] }); + const put = app.router.calls.find((call) => call.method === 'PUT' && call.path === '/api/platform/model-keys/codebuddy'); + assert.deepEqual(put.body, { apiKey: 'ck_shared', models: ['glm-5.1', 'deepseek-v4.1-flash', 'custom-model'], internetEnvironment: 'internal' }); assert.equal(form.elements.apiKey.value, '', 'the key is not kept in the page'); assert.equal(form.elements.apiKey.placeholder, '已配置,留空保持不变'); assert.match(card.querySelector('[data-shared-key-badge]').textContent, /已启用/); assert.match(card.querySelector('[data-shared-key-meta]').textContent, /国内站,3 个模型,默认 glm-5.1/); assert.deepEqual(app.evaluate(`state.data.sponsoredModels`), ['glm-5.1', 'deepseek-v4.1-flash', 'custom-model']); assert.equal(app.evaluate(`sharedModelSummary()`), 'glm-5.1、Deepseek-V4.1-Flash、custom-model'); + assert.ok(card.querySelector('[data-shared-provider="codebuddy"] [data-shared-provider-state]').classList.contains('is-on')); + + // Codex and Claude Code take a Base URL instead of a network environment. + card.querySelector('[data-shared-provider="codex"]').click(); + await settle(6); + assert.ok(card.querySelector('[data-shared-provider="codex"]').classList.contains('active')); + assert.equal(card.querySelector('[data-shared-env-field]').hidden, true); + assert.equal(card.querySelector('[data-shared-baseurl-field]').hidden, false); + assert.equal(card.querySelector('[data-shared-probe]').hidden, false, 'a gateway can be probed for models'); + assert.ok(card.querySelector('[data-shared-models] input[value="gpt-6.1-terra"]'), 'the built-in Codex catalog is offered'); + form.elements.baseUrl.value = 'https://gateway.example.com/v1'; + const codexBox = card.querySelector('[data-shared-models] input[value="gpt-6.1-terra"]'); + codexBox.checked = true; + codexBox.dispatchEvent(new app.window.Event('change', { bubbles: true })); + form.elements.apiKey.value = 'sk-gateway'; + form.dispatchEvent(new app.window.Event('submit', { bubbles: true, cancelable: true })); + await settle(6); + const codexPut = app.router.calls.find((call) => call.method === 'PUT' && call.path === '/api/platform/model-keys/codex'); + assert.deepEqual(codexPut.body, { apiKey: 'sk-gateway', models: ['gpt-6.1-terra'], baseUrl: 'https://gateway.example.com/v1' }); + assert.match(card.querySelector('[data-shared-key-meta]').textContent, /https:\/\/gateway\.example\.com\/v1,1 个模型,默认 gpt-6\.1-terra/); + card.querySelector('[data-shared-provider="codebuddy"]').click(); + await settle(6); const clear = card.querySelector('[data-shared-key-clear]'); assert.equal(clear.hidden, false); clear.click(); await settle(); app.document.querySelector('#confirmOkBtn').click(); await settle(6); - assert.ok(app.router.calls.some((call) => call.method === 'DELETE' && call.path === '/api/platform/codebuddy-key')); + assert.ok(app.router.calls.some((call) => call.method === 'DELETE' && call.path === '/api/platform/model-keys/codebuddy')); assert.match(card.querySelector('[data-shared-key-badge]').textContent, /使用旧配置/); assert.equal(app.evaluate(`state.data.sponsoredModel`), 'deepseek-v4.1-flash'); }); +// A slow reply for the tab the admin already left must not fill the form of +// the tab now shown; saving would otherwise write another CLI's models and an +// empty Base URL under it. +test('shared model key tabs ignore a late reply from the tab that was left', async (t) => { + const app = await loadApp(); + t.after(app.close); + app.evaluate(`state.currentUser={...state.data.users[0],isGuest:false,isPlatformAdmin:true}`); + const saved = { + codebuddy: { provider: 'codebuddy', configured: true, internetEnvironment: '', models: ['cb-model-1'] }, + codex: { provider: 'codex', configured: false, baseUrl: '', models: [] }, + 'claude-code': { provider: 'claude-code', configured: true, baseUrl: 'http://127.0.0.1:18511', models: ['claude-opus-5'] }, + }; + const held = []; + let holdCodeBuddy = false; + app.router.get('/api/platform/admins', []); + app.router.get('/api/platform/accounts', { accounts: [], signupEnabled: true }); + app.router.get('/api/platform/model-keys', () => ({ keys: Object.values(saved) })); + app.router.get(/^\/api\/platform\/model-keys\/codebuddy(\?|$)/, () => { + const reply = { ...saved.codebuddy, catalog: [{ id: 'cb-model-1', name: 'CB Model 1' }] }; + if (!holdCodeBuddy) return reply; + return new Promise((resolve) => held.push(() => resolve(reply))); + }); + app.router.get('/api/platform/model-keys/codex', () => ({ ...saved.codex, catalog: [{ id: 'gpt-6.1-terra', name: 'GPT-6.1-Terra' }] })); + app.router.get('/api/platform/model-keys/claude-code', () => ({ ...saved['claude-code'], catalog: [{ id: 'claude-opus-5', name: 'Claude Opus 5' }] })); + app.router.put('/api/platform/model-keys/claude-code', (call) => ({ ...saved['claude-code'], ...call.body, configured: true })); + app.evaluate(`renderPlatformAdminPanel()`); + await settle(8); + const card = app.document.querySelector('#platformSharedKeyCard'); + const form = card.querySelector('#platformSharedKeyForm'); + const boxes = () => [...card.querySelectorAll('[data-shared-models] input[type="checkbox"]')].filter((box) => box.checked).map((box) => box.value); + card.querySelector('[data-shared-provider="codex"]').click(); + await settle(6); + + // Start loading CodeBuddy, then switch to Claude Code before it replies. + holdCodeBuddy = true; + card.querySelector('[data-shared-provider="codebuddy"]').click(); + await settle(2); + assert.equal(held.length, 1, 'the CodeBuddy request is pending'); + card.querySelector('[data-shared-provider="claude-code"]').click(); + await settle(6); + assert.equal(form.elements.baseUrl.value, 'http://127.0.0.1:18511'); + assert.deepEqual(boxes(), ['claude-opus-5']); + + held.shift()(); + await settle(6); + assert.ok(card.querySelector('[data-shared-provider="claude-code"]').classList.contains('active')); + assert.equal(card.querySelector('[data-shared-baseurl-field]').hidden, false, 'the late CodeBuddy reply did not switch the fields'); + assert.equal(form.elements.baseUrl.value, 'http://127.0.0.1:18511', 'the Claude Code Base URL is kept'); + assert.deepEqual(boxes(), ['claude-opus-5'], 'CodeBuddy models were not checked under Claude Code'); + assert.ok(!card.querySelector('[data-shared-models] input[value="cb-model-1"]'), 'the CodeBuddy catalog is not shown'); + + form.dispatchEvent(new app.window.Event('submit', { bubbles: true, cancelable: true })); + await settle(6); + const put = app.router.calls.find((call) => call.method === 'PUT' && call.path === '/api/platform/model-keys/claude-code'); + assert.deepEqual(put.body, { apiKey: '', models: ['claude-opus-5'], baseUrl: 'http://127.0.0.1:18511' }); + assert.ok(!app.router.calls.some((call) => call.method === 'PUT' && call.path !== '/api/platform/model-keys/claude-code')); + + // Saving while the shown tab is still loading is refused instead of saving + // what the form showed for the previous tab. + holdCodeBuddy = true; + card.querySelector('[data-shared-provider="codebuddy"]').click(); + await settle(2); + const puts = app.router.calls.filter((call) => call.method === 'PUT').length; + form.dispatchEvent(new app.window.Event('submit', { bubbles: true, cancelable: true })); + await settle(4); + assert.equal(app.router.calls.filter((call) => call.method === 'PUT').length, puts, 'no save while loading'); + held.shift()(); + await settle(6); + assert.deepEqual(boxes(), ['cb-model-1']); +}); + test('platform admins authorize HTTPS and HTTP separately in the Git host trust tab', async (t) => { const app = await loadApp(); t.after(app.close); @@ -442,3 +554,96 @@ test('platform admins authorize HTTPS and HTTP separately in the Git host trust assert.equal(new Headers(plainRevoke.options.headers).get('If-Match'), '"plain"'); assert.equal(plainCard.querySelector('[data-http-host-revoke]'), null); }); + +// Save, stop and a failed load reply after the request; the admin may have +// switched tabs meanwhile. Each reply belongs to the CLI it was sent for: a +// Codex save that returns under Claude Code must not check Codex's models +// there (saving would write them into Claude Code's shared key), and a stale +// failure must not clear a tab a later request already filled. +test('shared model key saves, stops and failed loads write back only to their own CLI', async (t) => { + const app = await loadApp(); + t.after(app.close); + app.evaluate(`state.currentUser={...state.data.users[0],isGuest:false,isPlatformAdmin:true}`); + const saved = { + codebuddy: { provider: 'codebuddy', configured: true, internetEnvironment: '', models: ['cb-model-1'] }, + codex: { provider: 'codex', configured: true, baseUrl: '', models: ['gpt-shared-only'] }, + 'claude-code': { provider: 'claude-code', configured: true, baseUrl: '', models: ['claude-shared-only'] }, + }; + const held = []; + let holdCodex = false, failCodex = false; + const hold = (reply) => new Promise((resolve) => held.push(() => resolve(reply))); + app.router.get('/api/platform/admins', []); + app.router.get('/api/platform/accounts', { accounts: [], signupEnabled: true }); + app.router.get('/api/platform/model-keys', () => ({ keys: Object.values(saved) })); + app.router.get(/^\/api\/platform\/model-keys\/codebuddy(\?|$)/, () => ({ ...saved.codebuddy, catalog: [{ id: 'cb-model-1', name: 'CB Model 1' }] })); + app.router.get('/api/platform/model-keys/codex', () => { + const reply = failCodex ? { status: 502, body: { error: 'codex upstream down' } } : { ...saved.codex, catalog: [{ id: 'gpt-shared-only', name: 'GPT Shared' }] }; + return holdCodex ? hold(reply) : reply; + }); + app.router.get('/api/platform/model-keys/claude-code', () => ({ ...saved['claude-code'], catalog: [{ id: 'claude-shared-only', name: 'Claude Shared' }] })); + app.router.put('/api/platform/model-keys/codex', (call) => hold({ ...saved.codex, ...call.body, configured: true })); + app.router.put('/api/platform/model-keys/claude-code', (call) => ({ ...saved['claude-code'], ...call.body, configured: true })); + app.router.delete('/api/platform/model-keys/codex', () => hold({ provider: 'codex', configured: false, baseUrl: '', models: [] })); + app.evaluate(`renderPlatformAdminPanel()`); + await settle(8); + const card = app.document.querySelector('#platformSharedKeyCard'); + const form = card.querySelector('#platformSharedKeyForm'); + const boxes = () => [...card.querySelectorAll('[data-shared-models] input[type="checkbox"]')].filter((box) => box.checked).map((box) => box.value); + const submit = () => form.dispatchEvent(new app.window.Event('submit', { bubbles: true, cancelable: true })); + const tab = (id) => card.querySelector(`[data-shared-provider="${id}"]`).click(); + + // Save Codex, switch to Claude Code before the save replies. + tab('codex'); + await settle(6); + assert.deepEqual(boxes(), ['gpt-shared-only']); + submit(); + await settle(2); + assert.equal(held.length, 1, 'the Codex save is pending'); + tab('claude-code'); + await settle(6); + held.shift()(); + await settle(6); + assert.ok(card.querySelector('[data-shared-provider="claude-code"]').classList.contains('active')); + assert.deepEqual(boxes(), ['claude-shared-only'], 'the Codex save did not check its models under Claude Code'); + assert.equal(form.elements.baseUrl.value, ''); + submit(); + await settle(6); + const claudePut = app.router.calls.filter((call) => call.method === 'PUT' && call.path === '/api/platform/model-keys/claude-code'); + assert.equal(claudePut.length, 1); + assert.deepEqual(claudePut[0].body, { apiKey: '', models: ['claude-shared-only'], baseUrl: '' }); + + // Stop Codex, switch to Claude Code before the stop replies. + tab('codex'); + await settle(6); + card.querySelector('[data-shared-key-clear]').click(); + await settle(2); + app.document.querySelector('#confirmOkBtn').click(); + await settle(2); + assert.equal(held.length, 1, 'the Codex stop is pending'); + tab('claude-code'); + await settle(6); + held.shift()(); + await settle(6); + assert.deepEqual(boxes(), ['claude-shared-only'], 'stopping Codex did not clear the Claude Code selection'); + assert.match(card.querySelector('[data-shared-key-badge]').textContent, /已启用/, 'Claude Code still shows as enabled'); + assert.equal(card.querySelector('[data-shared-provider="codex"] [data-shared-provider-state]').hidden, true, 'the Codex tab shows it was stopped'); + + // A failed Codex load that replies after a later Codex load succeeded must + // not clear that tab. + holdCodex = true; failCodex = true; + tab('codex'); + await settle(2); + tab('claude-code'); + await settle(6); + holdCodex = false; failCodex = false; + saved.codex = { provider: 'codex', configured: true, baseUrl: 'http://127.0.0.1:19650/v1', models: ['gpt-shared-only'] }; + tab('codex'); + await settle(6); + assert.equal(form.elements.baseUrl.value, 'http://127.0.0.1:19650/v1'); + assert.deepEqual(boxes(), ['gpt-shared-only']); + held.shift()(); + await settle(6); + assert.equal(form.elements.baseUrl.value, 'http://127.0.0.1:19650/v1', 'the stale failure kept the loaded Base URL'); + assert.deepEqual(boxes(), ['gpt-shared-only'], 'the stale failure kept the loaded models'); + assert.ok(!app.document.body.textContent.includes('codex upstream down'), 'no error toast for the stale load'); +});