Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.
JavaScript agent-orchestrationagentic-workflowai-agentsai-codingclaude-codecode-reviewcodebuddycodexcoding-agentscursordeveloper-toolshuman-on-the-loopllmmcpmulti-agentsdlcself-hostedsopworkflow-automationworkflow-engine
feat(platform): member accounts and a shared CodeBuddy key in 平台管理; arm64 images (#110)
Robert06223dab8fbc456d
diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 7afa4bb6..90798081 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -71,6 +71,12 @@ jobs:echo "prerelease=${prerelease}"} >> "$GITHUB_OUTPUT"+ # arm64 lets Apple silicon and arm servers pull the image; only the final+ # stage runs under emulation, the Go and chatbot builds cross-compile.+ - uses: docker/setup-qemu-action@v4+ with:+ platforms: arm64+- uses: docker/setup-buildx-action@v4- uses: docker/login-action@v4@@ -94,6 +100,7 @@ jobs:id: pushwith:context: .+ platforms: linux/amd64,linux/arm64push: truetags: ${{ steps.metadata.outputs.tags }}labels: ${{ steps.metadata.outputs.labels }}diff --git a/AGENTS.md b/AGENTS.mdindex 6cc4958b..66164a32 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -17,7 +17,7 @@ Preserve the platform architecture; keep deployment-specific adapters isolated.| `ProjectsRepo` | projects、project members || `IssuesRepo` | issues、issue comments || `TasksRepo` | tasks(跨实例幂等记录) |-| `UsersRepo` | users、credentials、platform admins |+| `UsersRepo` | users、credentials(含平台共享 CodeBuddy Key)、platform admins || `TokensRepo` | API tokens || `AssistantRepo` | Studio 助手会话、定时 prompts || `RunsRepo` | runs 及其子资源、run leases、workflow metrics、run evals |diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 814da569..b90531e0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,16 @@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 administrators create accounts and reset passwords under 平台管理 → 成员账号, so teams that turn off self sign-up no longer need the `loopforge-account` command.+- Platform administrators can share one CodeBuddy API Key under 平台管理 → 共享 CodeBuddy Key and choose the models it may run. Members without their own key chat and run SOPs on it within those models; `AGENTFLOW_ASSISTANT_SPONSOR_LOGIN` still applies while none is configured. Members with their own key keep their own network environment's models and default model; previously a configured sponsor also changed their default.+- A stored CodeBuddy network environment such as `china` can be saved again as-is to rewrite it, and the quick-access wizard no longer keeps an environment switched back to 国际站 elsewhere.+- In English, the navigation, the top bar and the 个人配置 page (now "Personal settings") no longer show Chinese labels, tooltips or credential descriptions.+- The platform image is published for linux/amd64 and linux/arm64, so Apple silicon Macs and arm servers can pull it. On a native arm64 host the bundled CodeBuddy and Codex CLIs, chat, and SOP runs in the Docker sandbox behave and perform like amd64. Under QEMU emulation (an arm64 image on an x86 host) CodeBuddy starts about ten times slower and the model list cannot be read; use the amd64 image there.++Existing installations may apply `migrations/024_platform_codebuddy_key.sql`; the platform also creates the table on startup.+## 0.3.3 — Codex and Claude Code roles in Docker sandboxes- Codex SOP roles in Docker sandboxes run with `--sandbox danger-full-access`: the container is the isolation boundary, and Codex's own bubblewrap sandbox cannot create namespaces inside it, so every shell command, file write and `submit_gate_result` call failed.diff --git a/Dockerfile b/Dockerfileindex d9e4bb0e..48591483 100644--- a/Dockerfile+++ b/Dockerfile@@ -1,11 +1,17 @@-FROM node:22-bookworm-slim AS chatbot+# The chatbot bundle and the Go binaries are architecture independent to build,+# so those stages run on the builder's own platform and Go cross-compiles for+# TARGETARCH. Only the final stage runs as the target (emulated for arm64 on an+# amd64 builder), which keeps multi-platform releases fast.+FROM --platform=$BUILDPLATFORM node:22-bookworm-slim AS chatbotWORKDIR /srcCOPY chatbot/package.json chatbot/package-lock.json chatbot/RUN --mount=type=cache,target=/root/.npm npm --prefix chatbot ci --include=dev --no-audit --no-fundCOPY chatbot/ chatbot/COPY web/app/ web/app/RUN npm --prefix chatbot run build && test -f web/native-chat/index.html-FROM golang:1.26.10-bookworm AS build+FROM --platform=$BUILDPLATFORM golang:1.26.10-bookworm AS build+ARG TARGETOS+ARG TARGETARCHWORKDIR /src# Empty lets build-binaries.sh size parallelism from the builder's CPUs and memory.ARG LOOPFORGE_BUILD_JOBS=@@ -14,9 +20,11 @@ COPY go.mod go.sum ./RUN --mount=type=cache,target=/go/pkg/mod go mod downloadCOPY . .# Helpers do not embed the web UI, so they compile while the chatbot stage builds.-RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build bash scripts/build-binaries.sh --helpers /out+# The runner and gate binaries are built for every OS/arch regardless; GOOS and+# GOARCH pick the architecture of the binaries that run inside this image.+RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build GOOS=${TARGETOS} GOARCH=${TARGETARCH} bash scripts/build-binaries.sh --helpers /outCOPY --from=chatbot /src/web/native-chat/ web/native-chat/-RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build bash scripts/build-binaries.sh --platform /out+RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build GOOS=${TARGETOS} GOARCH=${TARGETARCH} bash scripts/build-binaries.sh --platform /outFROM node:22-bookwormRUN --mount=type=cache,target=/root/.npm apt-get update && apt-get install -y --no-install-recommends ca-certificates git bash curl python3 ripgrep \&& rm -rf /var/lib/apt/lists/* \diff --git a/chatbot/src/App.jsx b/chatbot/src/App.jsxindex f590402e..52353417 100644--- a/chatbot/src/App.jsx+++ b/chatbot/src/App.jsx@@ -2332,6 +2332,7 @@ export default function App() {projectId={chat.projectId}defaultModel={chat.model}sponsoredModel={chat.sponsoredModel}+ sponsoredModels={chat.sponsoredModels}onClose={() => setQuickAccessOpen(false)}onOpenView={(view) => navigate(view)}onCompleted={async (nextProjectId) => {diff --git a/chatbot/src/QuickAccessWizard.jsx b/chatbot/src/QuickAccessWizard.jsxindex a693740f..7470677b 100644--- a/chatbot/src/QuickAccessWizard.jsx+++ b/chatbot/src/QuickAccessWizard.jsx@@ -15,6 +15,8 @@ import { usePanelPresence } from "./usePanelPresence";import {CODEBUDDY_ENVIRONMENTS,codeBuddyEnvironment,+ codeBuddyEnvironmentIntent,+ codeBuddyEnvironmentLegacy,codeBuddyKeyURL,codeBuddyKeyWarning,openCredentialSettings,@@ -23,6 +25,24 @@ import "./quick-access-wizard.css";const DEFAULT_SOP_ID = "generic-backend-delivery";+// Display names for the models users without their own key may use.+export function sharedModelNames(models, fallback = "") {+ const list = Array.isArray(models) && models.length ? models : fallback ? [fallback] : [];+ return list+ .map((id) => (id === "deepseek-v4.1-flash" ? "Deepseek-V4.1-Flash" : id))+ .join("、");+}++// The users API omits an empty (国际站) environment, so a full user response+// must clear one that was switched to 国际站 elsewhere instead of keeping it.+export function mergeFreshUser(prev, fresh) {+ return {+ ...prev,+ ...fresh,+ codeBuddyInternetEnvironment: fresh?.codeBuddyInternetEnvironment || "",+ };+}+const STEPS = [{id: "auth",@@ -748,6 +768,7 @@ export default function QuickAccessWizard({projects = [],projectId = "",sponsoredModel = "",+ sponsoredModels = [],onClose,onCompleted,onOpenView,@@ -961,7 +982,7 @@ export default function QuickAccessWizard({(usersRes || []).find((item) => Number(item.id) === Number(user?.id),) || user;- setStoredUser({ ...user, ...freshUser });+ setStoredUser(mergeFreshUser(user, freshUser));if (freshUser?.gitTokenConfigured && freshUser?.id) {void verifyStoredGitToken(freshUser.id);}@@ -1045,7 +1066,7 @@ export default function QuickAccessWizard({(item) => Number(item.id) === Number(user?.id),);if (fresh) {- setStoredUser((prev) => ({ ...prev, ...fresh }));+ setStoredUser((prev) => mergeFreshUser(prev, fresh));if (fresh.gitTokenConfigured) {void verifyStoredGitToken(fresh.id);}@@ -1126,8 +1147,14 @@ export default function QuickAccessWizard({const codeBuddyReady = Boolean(storedUser?.codeBuddyApiKeyConfigured || codeBuddyApiKey.trim(),);+ // The CLI gets the stored text as-is: an old value such as china preselects+ // what it meant, and still differs from it, so 下一步 rewrites it.+ const storedCodeBuddyEnvRaw = String(+ storedUser?.codeBuddyInternetEnvironment || "",+ ).trim();const storedCodeBuddyEnv =- codeBuddyEnvironment(storedUser?.codeBuddyInternetEnvironment)?.value ?? "";+ codeBuddyEnvironmentIntent(storedCodeBuddyEnvRaw)?.value ?? "";+ const codeBuddyEnvLegacy = codeBuddyEnvironmentLegacy(storedCodeBuddyEnvRaw);const codeBuddyEnv = codeBuddyEnvChoice ?? storedCodeBuddyEnv;const codeBuddyEnvInfo =codeBuddyEnvironment(codeBuddyEnv) || CODEBUDDY_ENVIRONMENTS[0];@@ -1149,7 +1176,7 @@ export default function QuickAccessWizard({if (codeBuddyApiKey.trim())payload.codeBuddyApiKey = codeBuddyApiKey.trim();// A key is always saved with the environment it was issued for.- if (codeBuddyApiKey.trim() || codeBuddyEnv !== storedCodeBuddyEnv)+ if (codeBuddyApiKey.trim() || codeBuddyEnv !== storedCodeBuddyEnvRaw)payload.codeBuddyInternetEnvironment = codeBuddyEnv;if (!Object.keys(payload).length) return storedUser;const saved = await write(@@ -1625,7 +1652,7 @@ export default function QuickAccessWizard({{completedSummary?.codeBuddyReady? "已配置": sponsoredModel- ? "未配置。对话和 SOP 都会使用平台共享模型 Deepseek-V4.1-Flash,可以直接开始;配置自己的 Key 后可选用其他模型"+ ? `未配置。对话和 SOP 都会使用平台共享 Key(可用模型:${sharedModelNames(sponsoredModels, sponsoredModel)}),可以直接开始;配置自己的 Key 后可选用任意模型`: "未配置。对话可用平台默认模型,但运行 SOP 时节点需要它调模型,请先在个人配置补齐"}</span></li>@@ -1855,7 +1882,7 @@ export default function QuickAccessWizard({role="status">{codeBuddyWarning ||- `Key 只能在创建它的站点使用:当前选择${codeBuddyEnvInfo.label}(${codeBuddyEnvInfo.site}),「获取 API Key」会打开该站点的密钥页。`}+ `${codeBuddyEnvLegacy && codeBuddyEnvChoice === null ? `原来填写的「${storedCodeBuddyEnvRaw}」无法识别,CodeBuddy 实际按国际站连接,点下一步改为当前选择。` : ""}Key 只能在创建它的站点使用:当前选择${codeBuddyEnvInfo.label}(${codeBuddyEnvInfo.site}),「获取 API Key」会打开该站点的密钥页。`}</p></div></section>diff --git a/chatbot/src/credentials.js b/chatbot/src/credentials.jsindex 57d185f8..df86f939 100644--- a/chatbot/src/credentials.js+++ b/chatbot/src/credentials.js@@ -44,7 +44,15 @@ const CODEBUDDY_ENVIRONMENT_ALIASES = new Map([]);// codeBuddyEnvironment returns null for a value the CLI would not recognize.+// The CLI receives the stored text as-is, so only the exact values count.export function codeBuddyEnvironment(value) {+ const key = String(value || "").trim();+ return CODEBUDDY_ENVIRONMENTS.find((env) => env.value === key) || null;+}++// codeBuddyEnvironmentIntent guesses what an old free-text value meant+// (china → 国内站) so the fix can be preselected.+export function codeBuddyEnvironmentIntent(value) {const key = String(value || "").trim().toLowerCase();const normalized = CODEBUDDY_ENVIRONMENT_ALIASES.has(key)? CODEBUDDY_ENVIRONMENT_ALIASES.get(key)@@ -52,8 +60,16 @@ export function codeBuddyEnvironment(value) {return CODEBUDDY_ENVIRONMENTS.find((env) => env.value === normalized) || null;}+// codeBuddyEnvironmentLegacy is true for a stored value the CLI does not take+// as written; it connects to 国际站 until the value is saved again.+export function codeBuddyEnvironmentLegacy(value) {+ const raw = String(value || "").trim();+ return !!raw && !codeBuddyEnvironment(raw);+}+export function codeBuddyKeyURL(value) {- return (codeBuddyEnvironment(value) || CODEBUDDY_ENVIRONMENTS[0]).keyUrl;+ return (codeBuddyEnvironmentIntent(value) || CODEBUDDY_ENVIRONMENTS[0])+ .keyUrl;}// Advisory only: a third-party model key is accepted but CodeBuddy answers it@@ -108,7 +124,7 @@ export function credentialGuide(field, owner) {const guide = CREDENTIAL_GUIDES[field];if (!guide || field !== "codeBuddyApiKey") return guide || null;const env =- codeBuddyEnvironment(owner?.codeBuddyInternetEnvironment) ||+ codeBuddyEnvironmentIntent(owner?.codeBuddyInternetEnvironment) ||CODEBUDDY_ENVIRONMENTS[0];return { ...guide, url: env.keyUrl, link: `打开 CodeBuddy ${env.label}创建 Key` };}diff --git a/chatbot/src/useChat.js b/chatbot/src/useChat.jsindex 094177c2..9e494d3e 100644--- a/chatbot/src/useChat.js+++ b/chatbot/src/useChat.js@@ -41,8 +41,16 @@ function storedExecutor() {// Mirrors errAssistantSponsoredModel in internal/httpapi/assistant_sponsor.go;// credentialHint turns it into a "去配置" button.-export const sponsoredModelMessage =- "未配置个人 CodeBuddy API Key 时只能使用 Deepseek-V4.1-Flash。要使用其他模型,请先在个人配置中配置自己的 CodeBuddy API Key";+export function sponsoredModelMessage(models = []) {+ return `未配置个人 CodeBuddy API Key 时只能使用平台管理员允许的模型(${models.join("、")})。要使用其他模型,请先在个人配置中配置自己的 CodeBuddy API Key`;+}++// The models a user without their own key may chat with, the default first.+export function sponsoredModelList(catalog) {+ const listed = Array.isArray(catalog?.sponsoredModels) ? catalog.sponsoredModels.filter(Boolean) : [];+ if (listed.length) return listed;+ return catalog?.sponsoredModel ? [catalog.sponsoredModel] : [];+}const PROJECT_LIST_TOOLS = new Set(["projects_save","projects_delete",@@ -73,7 +81,7 @@ export function useChat() {[projectId, setProjectId] = useState(initialProject),[model, setModel] = useState(""),[effort, setEffort] = useState(""),- [sponsoredModel, setSponsoredModel] = useState(""),+ [sponsoredModels, setSponsoredModels] = useState([]),[executor, setExecutorState] = useState(storedExecutor),[providerCatalogs, setProviderCatalogs] = useState({}),[generation, setGeneration] = useState(null),@@ -184,7 +192,7 @@ export function useChat() {setSandboxes(sandboxRows || []);setModels(catalog.models || []);defaultModel.current = catalog.default || "";- setSponsoredModel(catalog.sponsoredModel || "");+ setSponsoredModels(sponsoredModelList(catalog));setModel(catalog.default);await refreshSessions();if (!current) return;@@ -471,9 +479,12 @@ export function useChat() {const codeBuddy = executor === "codebuddy";const executorModels = codeBuddy ? models : providerCatalogs[executor]?.models || [];const missingKey = !!user && !user.codeBuddyApiKeyConfigured;- // Without their own key users chat on the platform's sponsored model only.+ // Without their own key users chat on the platform's shared key, limited to+ // the models the administrator allowed (the first is the default).+ const sponsoredModel = sponsoredModels[0] || "";const sponsored = codeBuddy && missingKey && !user.isGuest && !!sponsoredModel;- const activeModel = sponsored ? sponsoredModel : model;+ const sharedModelFor = (id) => (sponsoredModels.includes(id) ? id : sponsoredModel);+ const activeModel = sponsored ? sharedModelFor(model) : model;// Reasoning effort is a CodeBuddy model option; the other CLIs use their defaults.const activeEffort = codeBuddy ? modelEffort(models.find((m) => m.id === activeModel), effort) : "";useEffect(() => {@@ -505,15 +516,15 @@ export function useChat() {);const chooseModel = useCallback((id) => {- if (sponsored && id !== sponsoredModel) {- setError(sponsoredModelMessage);+ if (sponsored && !sponsoredModels.includes(id)) {+ setError(sponsoredModelMessage(sponsoredModels));return false;}setModel(id);setEffort((value) => modelEffort(executorModels.find((m) => m.id === id), value));return true;},- [sponsored, sponsoredModel, executorModels],+ [sponsored, sponsoredModels, executorModels],);useEffect(() => {if (!ready) return;@@ -862,15 +873,16 @@ export function useChat() {setSubmitting(true);open(stored.id);setSession(stored);- setModel(sponsored ? sponsoredModel : stored.model || model);+ const chosen = sponsored ? sharedModelFor(stored.model || model) : stored.model || model;+ setModel(chosen);setEffort(stored.effort || "");const g = await write("/api/assistant/generations", {sessionId: stored.id,projectId: stored.projectId || "",runId: stored.runId || "",executor,- model: sponsored ? sponsoredModel : stored.model || model,- effort: codeBuddy ? modelEffort(models.find((m) => m.id === (sponsored ? sponsoredModel : stored.model || model)), stored.effort || "") : "",+ model: chosen,+ effort: codeBuddy ? modelEffort(models.find((m) => m.id === chosen), stored.effort || "") : "",messages: stored.messages,approvalMode: "confirm",});@@ -1070,6 +1082,7 @@ export function useChat() {setEffort,sponsored,sponsoredModel,+ sponsoredModels,generation,live,error,diff --git a/chatbot/tests/credentials.test.mjs b/chatbot/tests/credentials.test.mjsindex 21a623b6..377c3e90 100644--- a/chatbot/tests/credentials.test.mjs+++ b/chatbot/tests/credentials.test.mjs@@ -3,6 +3,8 @@ import assert from "node:assert/strict";import {CREDENTIAL_GUIDES,codeBuddyEnvironment,+ codeBuddyEnvironmentIntent,+ codeBuddyEnvironmentLegacy,codeBuddyKeyURL,codeBuddyKeyWarning,credentialGuide,@@ -17,9 +19,26 @@ test("CodeBuddy key links follow the selected network environment", () => {"https://tencent.sso.copilot.tencent.com/profile/keys",);assert.equal(codeBuddyKeyURL("typo"), "https://www.codebuddy.ai/profile/keys");- assert.equal(codeBuddyEnvironment("china")?.value, "internal");- assert.equal(codeBuddyEnvironment("public")?.value, "");- assert.equal(codeBuddyEnvironment("private-net"), null);+ assert.equal(codeBuddyKeyURL("china"), "https://copilot.tencent.com/profile/");+ // The CLI gets the stored text as-is, so only exact values are recognized.+ assert.equal(codeBuddyEnvironment(" internal ")?.value, "internal");+ for (const raw of ["china", "public", "iOA", "private-net"])+ assert.equal(codeBuddyEnvironment(raw), null, raw);+ assert.equal(codeBuddyEnvironmentIntent("china")?.value, "internal");+ assert.equal(codeBuddyEnvironmentIntent("public")?.value, "");+ assert.equal(codeBuddyEnvironmentIntent(" iOA ")?.value, "ioa");+ assert.equal(codeBuddyEnvironmentIntent("private-net"), null);+ assert.deepEqual(+ ["", "internal", "ioa", "china", "iOA", "private-net"].map(+ codeBuddyEnvironmentLegacy,+ ),+ [false, false, false, true, true, true],+ );+ assert.match(+ credentialGuide("codeBuddyApiKey", { codeBuddyInternetEnvironment: "china" })+ .link,+ /国内站/,+ );const intl = credentialGuide("codeBuddyApiKey", {});assert.equal(intl.url, "https://www.codebuddy.ai/profile/keys");diff --git a/chatbot/tests/hooks.test.jsx b/chatbot/tests/hooks.test.jsxindex de21399b..b4bd1ae6 100644--- a/chatbot/tests/hooks.test.jsx+++ b/chatbot/tests/hooks.test.jsx@@ -98,6 +98,35 @@ describe("conversation hooks", () => {localStorage.removeItem("loopforge.assistant.executor");});+ test("without an own key chat is limited to the administrator's shared models", async () => {+ localStorage.removeItem("loopforge.assistant.executor");+ const original = apiMock.getMockImplementation();+ apiMock.mockImplementation(async (path, options) => {+ if (path === "/api/auth/current") return { user: { id: 1, loginName: "tester", codeBuddyApiKeyConfigured: false } };+ if (path === "/api/users") return [{ id: 1, loginName: "tester", codeBuddyApiKeyConfigured: false }];+ if (path === "/api/assistant/models")+ return { default: "glm-5.1", sponsoredModel: "glm-5.1", sponsoredModels: ["glm-5.1", "kimi-k2.6"], models: [{ id: "glm-5.1", name: "GLM" }, { id: "kimi-k2.6", name: "Kimi" }] };+ return original(path, options);+ });+ try {+ const { result } = renderHook(() => useChat());+ await waitFor(() => expect(result.current.ready).toBe(true));+ expect(result.current.sponsored).toBe(true);+ expect(result.current.sponsoredModels).toEqual(["glm-5.1", "kimi-k2.6"]);+ expect(result.current.model).toBe("glm-5.1");+ let accepted;+ act(() => { accepted = result.current.setModel("kimi-k2.6"); });+ expect(accepted).toBe(true);+ expect(result.current.model).toBe("kimi-k2.6");+ act(() => { accepted = result.current.setModel("claude-opus-5"); });+ expect(accepted).toBe(false);+ expect(result.current.model).toBe("kimi-k2.6");+ expect(result.current.error).toContain("glm-5.1、kimi-k2.6");+ } finally {+ apiMock.mockImplementation(original);+ }+ });+test("persists the draft sandbox selection when creating a conversation", async () => {history.replaceState({}, "", "/?projectId=p1");const { result } = renderHook(() => useChat());diff --git a/chatbot/tests/quick-access-wizard.test.jsx b/chatbot/tests/quick-access-wizard.test.jsxindex 0ebc4360..de391508 100644--- a/chatbot/tests/quick-access-wizard.test.jsx+++ b/chatbot/tests/quick-access-wizard.test.jsx@@ -13,6 +13,7 @@ const { project, user, apiMock, writeMock, mockState } = vi.hoisted(() => {gitTokenConfigured: true, codeBuddyApiKeyConfigured: true,};const apiMock = vi.fn(async (path) => {+ if (path === "/api/users" && mockState.users) return mockState.users();if (path === "/api/users")return [mockState.unconfigured ? {id: 1, loginName: "tester", chineseName: "测试",@@ -34,7 +35,7 @@ const { project, user, apiMock, writeMock, mockState } = vi.hoisted(() => {if (path.includes("/verify")) return { valid: true };return [];});- const mockState = { failClone: false, unconfigured: false };+ const mockState = { failClone: false, unconfigured: false, users: null };const writeMock = vi.fn(async (path, body) => {if (path.includes("/git-token/verify")) return { valid: true };if (path === "/api/projects") return { ...project, ...body };@@ -59,9 +60,16 @@ import QuickAccessWizard, {HarnessSelect,HarnessSwitch,parseGongfengRepo,+ sharedModelNames,} from "../src/QuickAccessWizard.jsx";describe("QuickAccessWizard", () => {+ test("names the shared models an administrator allowed", () => {+ expect(sharedModelNames(["glm-5.1", "deepseek-v4.1-flash"])).toBe("glm-5.1、Deepseek-V4.1-Flash");+ expect(sharedModelNames([], "deepseek-v4.1-flash")).toBe("Deepseek-V4.1-Flash");+ expect(sharedModelNames(undefined)).toBe("");+ });+test("parses supported repository addresses", () => {expect(parseGongfengRepo("https://github.com/acme/widgets")).toEqual({project: "github:acme/widgets",@@ -224,6 +232,83 @@ describe("QuickAccessWizard", () => {mockState.unconfigured = false;});+ test("rewrites an old china environment to internal when moving past the credential step", async () => {+ mockState.users = () => [{ ...user, codeBuddyInternetEnvironment: "china" }];+ writeMock.mockClear();+ const userAction = userEvent.setup();+ try {+ render(+ <QuickAccessWizard+ open+ user={user}+ projects={[project]}+ projectId="p1"+ onClose={vi.fn()}+ onCompleted={vi.fn()}+ onOpenView={vi.fn()}+ />,+ );+ await screen.findByRole("dialog");+ expect(await screen.findByText(/「china」无法识别/)).toBeInTheDocument();+ expect(screen.getByRole("link", { name: /获取 API Key/ })).toHaveAttribute(+ "href",+ "https://copilot.tencent.com/profile/",+ );+ await userAction.click(screen.getByRole("button", { name: "下一步" }));+ await screen.findByText("项目与仓库", { selector: "h3" });+ expect(writeMock).toHaveBeenCalledWith(+ "/api/users/1/credentials",+ { codeBuddyInternetEnvironment: "internal" },+ "PUT",+ );+ } finally {+ mockState.users = null;+ }+ });++ test("a refresh after switching to 国际站 elsewhere drops the omitted environment", async () => {+ let environment = "internal";+ mockState.users = () => [+ { ...user, ...(environment ? { codeBuddyInternetEnvironment: environment } : {}) },+ ];+ writeMock.mockClear();+ const userAction = userEvent.setup();+ try {+ render(+ <QuickAccessWizard+ open+ user={user}+ projects={[project]}+ projectId="p1"+ onClose={vi.fn()}+ onCompleted={vi.fn()}+ onOpenView={vi.fn()}+ />,+ );+ await screen.findByRole("dialog");+ const keyLink = screen.getByRole("link", { name: /获取 API Key/ });+ await waitFor(() =>+ expect(keyLink).toHaveAttribute("href", "https://copilot.tencent.com/profile/"),+ );+ // 个人配置 switched the environment to 国际站; the users API omits it now.+ environment = "";+ window.dispatchEvent(new Event("focus"));+ await waitFor(() =>+ expect(keyLink).toHaveAttribute("href", "https://www.codebuddy.ai/profile/keys"),+ );+ await userAction.type(screen.getByLabelText("CodeBuddy API Key"), "ck_new");+ await userAction.click(screen.getByRole("button", { name: "下一步" }));+ await screen.findByText("项目与仓库", { selector: "h3" });+ expect(writeMock).toHaveBeenCalledWith(+ "/api/users/1/credentials",+ { codeBuddyApiKey: "ck_new", codeBuddyInternetEnvironment: "" },+ "PUT",+ );+ } finally {+ mockState.users = null;+ }+ });+test("a sponsored model lets new users skip credentials", async () => {mockState.unconfigured = true;const userAction = userEvent.setup();diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex 043ef4fd..84075364 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -659,6 +659,132 @@ paths:$ref: "#/components/schemas/User""403":$ref: "#/components/responses/Unauthorized"+ /api/platform/accounts:+ get:+ tags: [Users]+ operationId: listPlatformAccounts+ summary: List accounts for platform administrators+ responses:+ "200":+ description: Accounts, oldest first, and whether self sign-up is enabled+ content:+ application/json:+ schema:+ type: object+ properties:+ accounts: {type: array, items: {$ref: "#/components/schemas/PlatformAccount"}}+ signupEnabled: {type: boolean}+ "403": {description: Platform administrator access required}+ post:+ tags: [Users]+ operationId: createPlatformAccount+ summary: Create a password account+ description: Platform administrators only. Browser requests must be same-origin; API tokens are accepted. The account joins the welcome project.+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ required: [loginName, password]+ properties:+ loginName: {type: string, pattern: "^[A-Za-z0-9][A-Za-z0-9_.-]{1,63}$"}+ password: {type: string, writeOnly: true, minLength: 6, maxLength: 72}+ admin: {type: boolean, description: Also grant platform administration}+ responses:+ "201":+ description: Created account+ content:+ application/json:+ schema: {$ref: "#/components/schemas/PlatformAccount"}+ "400": {description: Invalid login name or password}+ "403": {description: Platform administrator access or same-origin request required}+ "409": {description: Login name already taken}+ /api/platform/accounts/{id}/password:+ put:+ tags: [Users]+ operationId: resetPlatformAccountPassword+ summary: Set a new password for a password account+ description: Platform administrators only. Accounts that sign in through GitHub or a gateway are refused with 400, so this never adds a password login to them.+ parameters:+ - name: id+ in: path+ required: true+ schema: {type: integer, format: int64}+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ required: [password]+ properties:+ password: {type: string, writeOnly: true, minLength: 6, maxLength: 72}+ responses:+ "200":+ description: Account+ content:+ application/json:+ schema: {$ref: "#/components/schemas/PlatformAccount"}+ "400": {description: Invalid password or not a password account}+ "403": {description: Platform administrator access or same-origin request required}+ "404": {description: Unknown account}+ /api/platform/codebuddy-key:+ get:+ tags: [Users]+ operationId: getPlatformCodeBuddyKey+ summary: Show the shared CodeBuddy API Key settings+ description: Platform administrators only. The key itself is never returned.+ parameters:+ - name: environment+ in: query+ description: Network environment whose models to list in catalog; defaults to the saved one.+ schema: {type: string, enum: ["", internal, ioa]}+ responses:+ "200":+ description: Shared key status and the models offered in the environment+ content:+ application/json:+ schema: {$ref: "#/components/schemas/PlatformCodeBuddyKey"}+ "403": {description: Platform administrator access required}+ put:+ tags: [Users]+ operationId: savePlatformCodeBuddyKey+ summary: Share a CodeBuddy API Key with users who have none+ description: >-+ Platform administrators only; browser requests must be same-origin. Users without their own key+ chat and run SOPs on this key, limited to models (the first is the default). It replaces the+ AGENTFLOW_ASSISTANT_SPONSOR_LOGIN account while configured.+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ required: [models]+ properties:+ apiKey: {type: string, writeOnly: true, description: Blank keeps the stored key.}+ internetEnvironment: {type: string, description: "Empty for International, \"internal\" for China, \"ioa\" for iOA."}+ models: {type: array, minItems: 1, maxItems: 32, items: {type: string}}+ responses:+ "200":+ description: Saved settings+ content:+ application/json:+ schema: {$ref: "#/components/schemas/PlatformCodeBuddyKey"}+ "400": {description: Missing key or models, or an invalid environment or model ID}+ "403": {description: Platform administrator access or same-origin request required}+ delete:+ tags: [Users]+ operationId: clearPlatformCodeBuddyKey+ summary: Stop sharing the CodeBuddy API Key+ responses:+ "200":+ description: Settings after clearing+ content:+ application/json:+ schema: {$ref: "#/components/schemas/PlatformCodeBuddyKey"}+ "403": {description: Platform administrator access or same-origin request required}/api/business-domains:get:tags: [BusinessDomains]@@ -3974,6 +4100,36 @@ components:role:type: stringenum: [maintainer, member, viewer]+ PlatformAccount:+ type: object+ properties:+ userId: {type: integer, format: int64}+ loginName: {type: string}+ chineseName: {type: string}+ admin: {type: boolean}+ password: {type: boolean, description: False for accounts that sign in through GitHub or a gateway}+ codeBuddyApiKeyConfigured: {type: boolean}+ createdAt: {type: string, format: date-time}+ PlatformCodeBuddyKey:+ type: object+ properties:+ configured: {type: boolean}+ internetEnvironment: {type: string}+ models: {type: array, items: {type: string}, description: Allowed models, the default first}+ updatedAt: {type: string, format: date-time}+ updatedBy: {type: string}+ legacySponsor: {type: string, description: Account named by AGENTFLOW_ASSISTANT_SPONSOR_LOGIN, used while no key is configured here}+ legacySponsorModel: {type: string}+ catalog:+ type: array+ description: Models offered in the requested network environment (GET only)+ items:+ type: object+ properties:+ id: {type: string}+ name: {type: string}+ family: {type: string}+ credits: {type: string}User:type: objectrequired: [id, loginName]diff --git a/docs/deployment.md b/docs/deployment.mdindex 8e054e26..70189487 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -59,9 +59,11 @@ Access to the Docker socket is equivalent to root on the host. Two safeguards foThe first account created in the browser becomes the platform administrator. After that, anyone who can reach the login page may sign up as a regular user while `AGENTFLOW_ALLOW_SIGNUP` is `true` (the default). Registered users can create requirements and run SOPs on your workers, so set `AGENTFLOW_ALLOW_SIGNUP=false` for any installation reachable from untrusted networks and create accounts explicitly instead.+Platform administrators create accounts under **Platform administration → Member accounts** (平台管理 → 成员账号): enter a login name and an initial password, optionally grant administration, and hand the password to the teammate. The same page lists every account and resets the password of a password account; accounts that sign in through GitHub or a gateway cannot be given a password there. New accounts join the welcome project, like self sign-ups.+LoopForge assumes a trusted team. Every signed-in account can list all projects, requirements and runs. Project settings and repositories can be changed only by the project owner or a platform administrator, and personal credentials only by their owner. Do not use one installation to separate untrusted tenants.-For a native installation, export the `.env` values before running the explicit account command:+Without a browser, export the `.env` values for a native installation and run the explicit account command:```bashset -a; source .env; set +a@@ -78,6 +80,8 @@ The upstream process roles remain `-role api`, `-role worker` and `-role all`. APersonal runners are connected from the execution-machine page with a short-lived binding code. The installer is served at `/runners/install.sh`. `AGENTFLOW_RUNNER_BINARY` can point to binaries with `{os}` and `{arch}` substitutions. Container images bundle Linux/macOS amd64/arm64 runner and gate binaries. Native source installations can build on demand with Go.+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 SOPs 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. Scheduled tasks, clarification, reports, bots and run evaluation still need a personal key. 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.+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 SOP roles support CodeBuddy, Codex and Claude Code 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. Requirement clarification, scheduled assistant tasks and notifications continue to use CodeBuddy. Live model tests are opt-in; set `AGENTFLOW_LIVE_TESTS=1` only for the acceptance suites that need to load local credentials.## Observability schemadiff --git a/internal/engine/codebuddy_auth.go b/internal/engine/codebuddy_auth.goindex aace6060..4ceddf2c 100644--- a/internal/engine/codebuddy_auth.go+++ b/internal/engine/codebuddy_auth.go@@ -14,7 +14,7 @@ const ()// resolveCodeBuddyCredential returns the responsible user's own key, or the-// platform sponsor's key when the user has none (see repo.CodeBuddySponsor).+// 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{}@@ -26,29 +26,38 @@ func resolveCodeBuddyCredential(s *repo.Store, userID int64) runtime.CodeBuddyCrif strings.TrimSpace(user.CodeBuddyAPIKey) != "" {return runtime.CodeBuddyCredential{APIKey: user.CodeBuddyAPIKey, InternetEnvironment: user.CodeBuddyInternetEnvironment}}- sponsor, ok := s.CodeBuddySponsor()- if !ok || sponsor.ID == user.ID {+ shared, ok := s.SharedCodeBuddyKey()+ if !ok || (shared.SponsorID != 0 && shared.SponsorID == user.ID) {return runtime.CodeBuddyCredential{InternetEnvironment: user.CodeBuddyInternetEnvironment}}- return runtime.CodeBuddyCredential{APIKey: sponsor.CodeBuddyAPIKey, InternetEnvironment: sponsor.CodeBuddyInternetEnvironment, Sponsored: true}+ return runtime.CodeBuddyCredential{APIKey: shared.APIKey, InternetEnvironment: shared.InternetEnvironment, Sponsored: true, SponsoredModels: shared.Models}}const sponsoredRunEvent = "model.sponsored"-// sponsoredExecutor pins a CodeBuddy node running on the sponsor's key to the-// sponsored model, and tells the user why the role's own model is not used.-func (e *Engine) sponsoredExecutor(runID string, ex domain.ExecutorDefinition, sink func(domain.TelemetryEvent)) domain.ExecutorDefinition {+// 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)- ex.Model = repo.SponsoredCodeBuddyModel- message := "责任人未配置个人 CodeBuddy API Key,本节点使用平台共享模型 Deepseek-V4.1-Flash"- if configured != "" && configured != ex.Model {- message += "(角色配置的 " + configured + " 本次不生效)"+ 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,本次运行使用平台共享模型 Deepseek-V4.1-Flash。在个人配置中配置自己的 Key 后,可使用角色配置的模型")+ e.event(r, "", sponsoredRunEvent, "责任人未配置个人 CodeBuddy API Key,本次运行使用平台共享 Key,只能使用平台管理员允许的模型("+strings.Join(models, "、")+")。在个人配置中配置自己的 Key 后,可使用角色配置的任意模型")}})}diff --git a/internal/engine/codebuddy_auth_test.go b/internal/engine/codebuddy_auth_test.goindex a778c07b..a703c7a5 100644--- a/internal/engine/codebuddy_auth_test.go+++ b/internal/engine/codebuddy_auth_test.go@@ -68,13 +68,73 @@ func TestResolveCodeBuddyCredentialFallsBackToSponsor(t *testing.T) {if got := resolveCodeBuddyCredential(s, 999); got.APIKey != "" {t.Fatalf("unknown user must not borrow the sponsor key, got %+v", got)}+ if got := resolveCodeBuddyCredential(s, 22); len(got.SponsoredModels) != 1 || got.SponsoredModels[0] != repo.SponsoredCodeBuddyModel {+ t.Fatalf("legacy sponsor models = %+v", got)+ }t.Setenv(repo.CodeBuddySponsorLoginEnv, "nobody")if got := resolveCodeBuddyCredential(s, 22); got.APIKey != "" || got.Sponsored {t.Fatalf("missing sponsor account = %+v", got)}}-// A sponsored CodeBuddy node runs the sponsored model whatever its role+// The key configured under 平台管理 wins over the legacy sponsor account and+// carries the administrator's model list.+func TestResolveCodeBuddyCredentialUsesPlatformSharedKey(t *testing.T) {+ s, err := repo.OpenTest()+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { s.Close() })+ for _, user := range []domain.User{+ {ID: 21, LoginName: "owner", CodeBuddyAPIKey: "ck_user"},+ {ID: 22, LoginName: "newcomer"},+ {ID: 23, LoginName: "sponsor", CodeBuddyAPIKey: "ck_sponsor"},+ } {+ if err := s.PutUser(user); err != nil {+ t.Fatal(err)+ }+ }+ t.Setenv(repo.CodeBuddySponsorLoginEnv, "sponsor")+ if err := s.SetPlatformCodeBuddyKey(repo.PlatformCodeBuddyKeyUpdate{APIKey: "ck_platform", InternetEnvironment: "internal", Models: []string{"glm-5.1", "kimi-k2.6"}}, 21); err != nil {+ t.Fatal(err)+ }+ got := resolveCodeBuddyCredential(s, 22)+ if got.APIKey != "ck_platform" || got.InternetEnvironment != "internal" || !got.Sponsored || strings.Join(got.SponsoredModels, ",") != "glm-5.1,kimi-k2.6" {+ t.Fatalf("platform shared credential = %+v", got)+ }+ if got := resolveCodeBuddyCredential(s, 23); got.APIKey != "ck_sponsor" || got.Sponsored {+ t.Fatalf("a user with a key keeps it, got %+v", got)+ }+ if err := s.ClearPlatformCodeBuddyKey(); err != nil {+ t.Fatal(err)+ }+ if got := resolveCodeBuddyCredential(s, 22); got.APIKey != "ck_sponsor" || !got.Sponsored {+ t.Fatalf("clearing the platform key falls back to the legacy sponsor, got %+v", got)+ }+}++// A shared-key CodeBuddy node keeps the role's model when the administrator+// allowed it.+func TestSponsoredExecutorKeepsAllowedRoleModel(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: "codebuddy", Model: "kimi-k2.6"}, []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)+ if got.Model != "glm-5.1" {+ t.Fatalf("role without a model uses the shared default, got %+v", got)+ }+}++// A sponsored CodeBuddy node runs an allowed model whatever its role// configures, says so on the node, and notes it once on the run.func TestSponsoredExecutorPinsModelAndExplains(t *testing.T) {st, err := repo.OpenTest()@@ -96,12 +156,12 @@ func TestSponsoredExecutorPinsModelAndExplains(t *testing.T) {var observed []domain.TelemetryEventsink := 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"}, sink)+ got := e.sponsoredExecutor(run.ID, domain.ExecutorDefinition{ID: "codebuddy", Kind: "codebuddy", Model: "claude-opus-5", Effort: "high"}, []string{repo.SponsoredCodeBuddyModel}, sink)if got.Model != repo.SponsoredCodeBuddyModel || got.Effort != "high" || got.Kind != "codebuddy" {t.Fatalf("executor = %+v", got)}}- if len(observed) != 2 || observed[0].Model != repo.SponsoredCodeBuddyModel || !strings.Contains(observed[0].Message, "共享模型") || !strings.Contains(observed[0].Message, "claude-opus-5") {+ if len(observed) != 2 || observed[0].Model != repo.SponsoredCodeBuddyModel || !strings.Contains(observed[0].Message, "共享 Key") || !strings.Contains(observed[0].Message, "claude-opus-5") || !strings.Contains(observed[0].Message, "不生效") {t.Fatalf("node notice = %+v", observed)}current, _ := st.RunState(run.ID)diff --git a/internal/engine/node_execute.go b/internal/engine/node_execute.goindex 18813a51..660ac152 100644--- a/internal/engine/node_execute.go+++ b/internal/engine/node_execute.go@@ -662,8 +662,8 @@ func (e *Engine) executeNode(ctx context.Context, runID string, wf domain.Workfloptions.GateResultPath = gateResultPath(node.ID, attempt)}ex := ex- if ex.Kind == "codebuddy" && sb.credentialSnapshot().CodeBuddy.Sponsored {- ex = e.sponsoredExecutor(runID, ex, sink)+ if cb := sb.credentialSnapshot().CodeBuddy; ex.Kind == "codebuddy" && cb.Sponsored {+ ex = e.sponsoredExecutor(runID, ex, cb.SponsoredModels, sink)}if execMachine := e.defaultExecutionRunner(current); execMachine != "" {// 执行机器 mode (bind-cli): the responsible user selected a defaultdiff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.goindex cc478cac..e4c537e1 100644--- a/internal/httpapi/assistant.go+++ b/internal/httpapi/assistant.go@@ -95,9 +95,9 @@ func (h *assistantHandlers) chat(c *gin.Context) {return}req.Executor = assistantExecutor(req.Executor)- user, sponsored := stored, false+ user, sharedModels := stored, []string(nil)if req.Executor == "codebuddy" {- if user, sponsored, ok = h.assistantChatUser(stored); !ok {+ if user, sharedModels, ok = h.assistantChatUser(stored); !ok {c.JSON(400, gin.H{"error": "请先在个人配置中配置自己的 CodeBuddy API Key"})return}@@ -105,10 +105,10 @@ func (h *assistantHandlers) chat(c *gin.Context) {c.JSON(400, gin.H{"error": err.Error()})return}- if sponsored {- model, allowed := assistantSponsoredModelFor(req.Model)+ if sharedModels != nil {+ model, allowed := assistantSponsoredModelFor(sharedModels, req.Model)if !allowed {- c.JSON(400, gin.H{"error": errAssistantSponsoredModel()})+ c.JSON(400, gin.H{"error": errAssistantSponsoredModel(sharedModels)})return}req.Model = model@@ -177,7 +177,7 @@ func (h *assistantHandlers) chat(c *gin.Context) {return}if req.Executor == "codebuddy" {- catalog := assistantChatCatalog(c.Request.Context(), user.CodeBuddyInternetEnvironment)+ catalog := h.chatCatalog(c.Request.Context(), user)req.Model = assistantAllowedModel(req.Model, catalog)if err := validateAssistantEffort(req.Model, req.Effort); err != nil {c.JSON(400, gin.H{"error": err.Error()})diff --git a/internal/httpapi/assistant_approval_review.go b/internal/httpapi/assistant_approval_review.goindex 96b4291a..81ee1370 100644--- a/internal/httpapi/assistant_approval_review.go+++ b/internal/httpapi/assistant_approval_review.go@@ -128,7 +128,7 @@ func (h *assistantHandlers) approvalReviewer(req assistantRequest, user domain.Uif h.reviewCatalog != nil {catalog = h.reviewCatalog(user.CodeBuddyInternetEnvironment)} else {- catalog = assistantChatCatalog(context.Background(), user.CodeBuddyInternetEnvironment)+ catalog = h.chatCatalog(context.Background(), user)}models := assistantApprovalReviewModels(catalog)var modelMu sync.Mutexdiff --git a/internal/httpapi/assistant_approval_review_test.go b/internal/httpapi/assistant_approval_review_test.goindex 81f8f8be..0b9f34b9 100644--- a/internal/httpapi/assistant_approval_review_test.go+++ b/internal/httpapi/assistant_approval_review_test.go@@ -46,8 +46,7 @@ func TestAssistantApprovalReviewUsesConfiguredDefaultWithoutPrices(t *testing.T)func TestAssistantChatCatalogPreselectsSponsoredModelOnlyWithSponsor(t *testing.T) {t.Setenv("AGENTFLOW_ASSISTANT_MODEL", "team-model")- t.Setenv(assistantSponsorLoginEnv, "")- catalog := assistantChatCatalog(context.Background(), "")+ catalog := assistantChatCatalog(context.Background(), "", nil)if catalog.Default != "team-model" {t.Fatal("chat default without sponsor", catalog)}@@ -56,15 +55,20 @@ func TestAssistantChatCatalogPreselectsSponsoredModelOnlyWithSponsor(t *testing.t.Fatal("sponsored model listed without sponsor", catalog)}}- t.Setenv(assistantSponsorLoginEnv, "sponsor")- catalog = assistantChatCatalog(context.Background(), "")- listed := false+ catalog = assistantChatCatalog(context.Background(), "", []string{assistantSponsoredModel, "shared-extra"})+ listed := 0for _, model := range catalog.Models {- listed = listed || model.ID == assistantSponsoredModel+ if model.ID == assistantSponsoredModel || model.ID == "shared-extra" {+ listed+++ }}- if catalog.Default != assistantSponsoredModel || !listed {+ if catalog.Default != assistantSponsoredModel || listed != 2 {t.Fatal("chat default with sponsor", catalog)}+ restricted := restrictAssistantCatalog(catalog, []string{"shared-extra", assistantSponsoredModel})+ if restricted.Default != "shared-extra" || len(restricted.Models) != 2 || restricted.Models[0].ID != "shared-extra" {+ t.Fatal("restricted catalog", restricted)+ }}func pricedReviewCatalog(string) assistantModelCatalog {diff --git a/internal/httpapi/assistant_generation.go b/internal/httpapi/assistant_generation.goindex 74478849..8024a8a4 100644--- a/internal/httpapi/assistant_generation.go+++ b/internal/httpapi/assistant_generation.go@@ -36,9 +36,9 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) {return}req.Executor = assistantExecutor(req.Executor)- user, sponsored := stored, false+ user, sharedModels := stored, []string(nil)if req.Executor == "codebuddy" {- if user, sponsored, ok = h.assistantChatUser(stored); !ok {+ if user, sharedModels, ok = h.assistantChatUser(stored); !ok {c.JSON(400, gin.H{"error": "请先配置个人 CodeBuddy API Key"})return}@@ -46,10 +46,10 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) {c.JSON(400, gin.H{"error": err.Error()})return}- if sponsored {- model, allowed := assistantSponsoredModelFor(req.Model)+ if sharedModels != nil {+ model, allowed := assistantSponsoredModelFor(sharedModels, req.Model)if !allowed {- c.JSON(400, gin.H{"error": errAssistantSponsoredModel()})+ c.JSON(400, gin.H{"error": errAssistantSponsoredModel(sharedModels)})return}req.Model = model@@ -105,7 +105,7 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) {return}if req.Executor == "codebuddy" {- req.Model = assistantAllowedModel(req.Model, assistantChatCatalog(c.Request.Context(), user.CodeBuddyInternetEnvironment))+ req.Model = assistantAllowedModel(req.Model, h.chatCatalog(c.Request.Context(), user))if err := validateAssistantEffort(req.Model, req.Effort); err != nil {c.JSON(400, gin.H{"error": err.Error()})return@@ -177,7 +177,7 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) {// Keep the authenticated identity, but disconnect model execution from the// lifetime of the browser request. Only explicit cancellation stops a turn.parent := context.WithValue(context.WithoutCancel(c.Request.Context()), assistantFreshCLIKey{}, freshCLI)- h.scheduleAssistantTitle(parent, ownerID, user, old, req.SessionID, req.Messages, sponsored)+ h.scheduleAssistantTitle(parent, ownerID, user, old, req.SessionID, req.Messages, sharedModels)done := inflightTasks.Add()go func() {defer done()@@ -427,7 +427,7 @@ func (h *assistantHandlers) steerGeneration(c *gin.Context) {c.JSON(400, gin.H{"error": "请先配置个人 CodeBuddy API Key"})return}- user, sponsored, ok := h.assistantChatUser(stored)+ user, sharedModels, ok := h.assistantChatUser(stored)if !ok {c.JSON(400, gin.H{"error": "请先配置个人 CodeBuddy API Key"})return@@ -464,15 +464,15 @@ func (h *assistantHandlers) steerGeneration(c *gin.Context) {return}model := body.Model- if sponsored {- forced, allowed := assistantSponsoredModelFor(model)+ if sharedModels != nil {+ forced, allowed := assistantSponsoredModelFor(sharedModels, model)if !allowed {- c.JSON(400, gin.H{"error": errAssistantSponsoredModel()})+ c.JSON(400, gin.H{"error": errAssistantSponsoredModel(sharedModels)})return}model = forced}- model = assistantAllowedModel(model, assistantChatCatalog(c.Request.Context(), user.CodeBuddyInternetEnvironment))+ model = assistantAllowedModel(model, h.chatCatalog(c.Request.Context(), user))if err := validateAssistantEffort(model, body.Effort); err != nil {c.JSON(400, gin.H{"error": err.Error()})returndiff --git a/internal/httpapi/assistant_models.go b/internal/httpapi/assistant_models.goindex 58a29453..01e675e0 100644--- a/internal/httpapi/assistant_models.go+++ b/internal/httpapi/assistant_models.go@@ -11,14 +11,17 @@ import ("sync""time"+ "agentflow/internal/domain"+"github.com/gin-gonic/gin")const assistantDefaultModel = "default"-// assistantChatDefaultModel is preselected for new chat conversations when a-// sponsor account is configured. Otherwise chat uses the operator's default,-// like clarification, scheduled prompts, reports and executors.+// assistantChatDefaultModel is the model the legacy sponsor account lends.+// New chat conversations preselect the shared key's default model when one is+// configured; otherwise chat uses the operator's default, like clarification,+// scheduled prompts, reports and executors.const assistantChatDefaultModel = assistantSponsoredModeltype assistantModel struct {@@ -32,9 +35,11 @@ type assistantModel struct {type assistantModelCatalog struct {Default string `json:"default"`Models []assistantModel `json:"models"`- // SponsoredModel is set when users without their own CodeBuddy API Key- // may still chat, limited to this model.- SponsoredModel string `json:"sponsoredModel,omitempty"`+ // SponsoredModels is set when users without their own CodeBuddy API Key+ // may still chat on the platform's shared key, limited to these models;+ // SponsoredModel is the first (the default).+ SponsoredModel string `json:"sponsoredModel,omitempty"`+ SponsoredModels []string `json:"sponsoredModels,omitempty"`}func prefetchAssistantModels() {}@@ -186,35 +191,54 @@ func (h *assistantHandlers) models(c *gin.Context) {return}- environment := ""+ var catalog assistantModelCatalog+ key, shared := h.assistantSharedKey()+ user, signedIn := domain.User{}, falseif current, ok := h.requestUser(c.Request, true); ok {- if user, ok := h.repo.User(current.ID); ok {- environment = user.CodeBuddyInternetEnvironment- refreshCLIModels(c.Request.Context(), environment, user.CodeBuddyAPIKey)- }+ user, signedIn = h.repo.User(current.ID)}- catalog := assistantChatCatalog(c.Request.Context(), environment)- if _, ok := h.assistantSponsor(); ok {- catalog.SponsoredModel = assistantSponsoredModel+ switch {+ case signedIn && shared && strings.TrimSpace(user.CodeBuddyAPIKey) == "":+ // Chat runs on the shared key, so list what that key's environment offers.+ refreshCLIModels(c.Request.Context(), key.InternetEnvironment, key.APIKey)+ catalog = restrictAssistantCatalog(assistantChatCatalog(c.Request.Context(), key.InternetEnvironment, key.Models), key.Models)+ case signedIn:+ // A user's own key keeps their environment's models and default: the+ // shared key's default may not exist in that environment.+ refreshCLIModels(c.Request.Context(), user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey)+ catalog = assistantChatCatalog(c.Request.Context(), user.CodeBuddyInternetEnvironment, nil)+ default:+ catalog = assistantChatCatalog(c.Request.Context(), "", nil)+ }+ if shared {+ catalog.SponsoredModel, catalog.SponsoredModels = key.Models[0], key.Models}c.JSON(200, catalog)}// assistantChatCatalog is the catalog used by chat conversations: the same-// models, with the chat default listed and preselected.-func assistantChatCatalog(ctx context.Context, env string) assistantModelCatalog {+// models, with the shared key's models listed and its default preselected.+// Pass shared only for turns that run on the shared key (see chatCatalog).+func assistantChatCatalog(ctx context.Context, env string, shared []string) assistantModelCatalog {catalog := loadAssistantModels(ctx, env)- if strings.TrimSpace(os.Getenv(assistantSponsorLoginEnv)) == "" {+ if len(shared) == 0 {return catalog}- listed := false+ listed := map[string]bool{}for _, model := range catalog.Models {- listed = listed || model.ID == assistantChatDefaultModel+ listed[model.ID] = true}- if !listed {- catalog.Models = append(catalog.Models, assistantListedModel(assistantChatDefaultModel, "Deepseek-V4.1-Flash", ""))+ for _, id := range shared {+ if !listed[id] {+ name := id+ if id == assistantChatDefaultModel {+ name = "Deepseek-V4.1-Flash"+ }+ catalog.Models = append(catalog.Models, assistantListedModel(id, name, ""))+ listed[id] = true+ }}- catalog.Default = assistantChatDefaultModel+ catalog.Default = shared[0]return catalog}diff --git a/internal/httpapi/assistant_sponsor.go b/internal/httpapi/assistant_sponsor.goindex 55ac0ddc..725140af 100644--- a/internal/httpapi/assistant_sponsor.go+++ b/internal/httpapi/assistant_sponsor.go@@ -1,6 +1,7 @@package httpapiimport (+ "context""strings""agentflow/internal/domain"@@ -8,51 +9,89 @@ import ()// Users who have not configured their own CodeBuddy API Key can still chat-// with the sponsor's key (see repo.CodeBuddySponsor), limited to-// assistantSponsoredModel. SOP runs are sponsored by the engine the same way;-// scheduled tasks, clarification, reports and bots keep requiring the user's-// own key.+// with the platform's shared key (see repo.SharedCodeBuddyKey), limited to+// the models a platform administrator allowed. SOP runs use it the same way+// through the engine; scheduled tasks, clarification, reports and bots keep+// requiring the user's own key.const (assistantSponsorLoginEnv = repo.CodeBuddySponsorLoginEnvassistantSponsoredModel = repo.SponsoredCodeBuddyModel)-func errAssistantSponsoredModel() string {- return "未配置个人 CodeBuddy API Key 时只能使用 Deepseek-V4.1-Flash。要使用其他模型,请先在个人配置中配置自己的 CodeBuddy API Key"+func errAssistantSponsoredModel(models []string) string {+ return "未配置个人 CodeBuddy API Key 时只能使用平台管理员允许的模型(" + strings.Join(models, "、") + ")。要使用其他模型,请先在个人配置中配置自己的 CodeBuddy API Key"}-// assistantSponsor returns the account whose key is lent, if one is-// configured and has a key.-func (h *assistantHandlers) assistantSponsor() (domain.User, bool) {+// assistantSharedKey returns the key users without their own borrow.+func (h *assistantHandlers) assistantSharedKey() (repo.SharedCodeBuddyKey, bool) {if h == nil || h.deps == nil || h.repo == nil {- return domain.User{}, false+ return repo.SharedCodeBuddyKey{}, false}- return h.repo.CodeBuddySponsor()+ return h.repo.SharedCodeBuddyKey()}// assistantChatUser returns the identity a chat turn runs as. Users with-// their own key are returned unchanged. Otherwise the sponsor's key and-// network environment are substituted and sponsored is true; everything else-// (ID, permissions, Git credentials) stays the caller's own.-func (h *assistantHandlers) assistantChatUser(user domain.User) (chatUser domain.User, sponsored, ok bool) {+// their own key are returned unchanged. Otherwise the shared key and its+// network environment are substituted and shared lists the models the turn+// may use; everything else (ID, permissions, Git credentials) stays the+// caller's own.+func (h *assistantHandlers) assistantChatUser(user domain.User) (chatUser domain.User, shared []string, ok bool) {if strings.TrimSpace(user.CodeBuddyAPIKey) != "" {- return user, false, true+ return user, nil, true}- sponsor, found := h.assistantSponsor()- if !found || sponsor.ID == user.ID {- return user, false, false+ key, found := h.assistantSharedKey()+ if !found || (key.SponsorID != 0 && key.SponsorID == user.ID) {+ return user, nil, false}- user.CodeBuddyAPIKey = sponsor.CodeBuddyAPIKey- user.CodeBuddyInternetEnvironment = sponsor.CodeBuddyInternetEnvironment- return user, true, true+ user.CodeBuddyAPIKey = key.APIKey+ user.CodeBuddyInternetEnvironment = key.InternetEnvironment+ return user, key.Models, true}-// assistantSponsoredModelFor pins sponsored turns to the sponsored model. An-// empty request picks it; any other explicit model is refused.-func assistantSponsoredModelFor(requested string) (string, bool) {- requested = strings.TrimSpace(requested)- if requested == "" || requested == assistantSponsoredModel {- return assistantSponsoredModel, true+// 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)+}++// usesSharedKey reports whether a 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+ }+ stored, ok := h.repo.User(user.ID)+ return ok && strings.TrimSpace(stored.CodeBuddyAPIKey) == ""+}++// chatCatalog is the chat catalog for a chat user (see assistantChatUser). A+// turn on the shared key only sees the allowed models, defaulting to the+// first; a user with their own key keeps their environment's catalog and+// default, which the shared key's models must not replace.+func (h *assistantHandlers) chatCatalog(ctx context.Context, user domain.User) assistantModelCatalog {+ key, shared := h.assistantSharedKey()+ if !shared || !h.usesSharedKey(user) {+ return assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, nil)+ }+ return restrictAssistantCatalog(assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, key.Models), key.Models)+}++// restrictAssistantCatalog keeps the allowed models, in the allowed order.+func restrictAssistantCatalog(catalog assistantModelCatalog, allowed []string) assistantModelCatalog {+ byID := map[string]assistantModel{}+ for _, model := range catalog.Models {+ byID[model.ID] = model+ }+ restricted := assistantModelCatalog{SponsoredModel: catalog.SponsoredModel, SponsoredModels: catalog.SponsoredModels}+ for _, id := range allowed {+ model, ok := byID[id]+ if !ok {+ model = assistantListedModel(id, id, "")+ }+ restricted.Models = append(restricted.Models, model)+ }+ if len(allowed) > 0 {+ restricted.Default = allowed[0]}- return "", false+ return restricted}diff --git a/internal/httpapi/assistant_sponsor_test.go b/internal/httpapi/assistant_sponsor_test.goindex 1984e1e9..e92b923a 100644--- a/internal/httpapi/assistant_sponsor_test.go+++ b/internal/httpapi/assistant_sponsor_test.go@@ -55,6 +55,7 @@ func sponsoredChat(h *assistantHandlers, user domain.User, model string) *httptefunc TestUsersWithoutKeyChatOnSponsoredModel(t *testing.T) {st, newcomer := sponsorFixture(t)+ stubCLIModelDiscovery(t)t.Setenv(assistantSponsorLoginEnv, "sponsor")var used domain.Userh := &assistantHandlers{deps: &deps{repo: st}, generate: func(_ context.Context, _ string, u domain.User) (string, error) {@@ -81,16 +82,91 @@ func TestUsersWithoutKeyChatOnSponsoredModel(t *testing.T) {t.Fatal("sponsor key must never be persisted on the newcomer")}+ for _, viewer := range []*domain.User{&newcomer, nil} {+ var catalog assistantModelCatalog+ mrec := httptest.NewRecorder()+ c, _ := gin.CreateTestContext(mrec)+ c.Request = httptest.NewRequest("GET", "/api/assistant/models", nil)+ want := assistantFixedCatalog().Default+ if viewer != nil {+ c.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), requestUserContextKey{}, domainUserToAuth(*viewer)))+ want = assistantChatDefaultModel+ }+ h.models(c)+ // Everyone learns that a shared model exists; only the newcomer, who+ // would chat on it, gets it preselected.+ if json.Unmarshal(mrec.Body.Bytes(), &catalog) != nil || catalog.SponsoredModel != assistantSponsoredModel || catalog.Default != want {+ t.Fatalf("signed in %v: catalog = %s", viewer != nil, mrec.Body.String())+ }+ if strings.Contains(mrec.Body.String(), `"sponsor"`) || strings.Contains(mrec.Body.String(), "sponsor-secret") {+ t.Fatal("catalog must not reveal the sponsor account or key")+ }+ }+}++// A user with their own key may be on another network environment than the+// shared key, where the shared models do not exist: their catalog and default+// must stay their own, for /api/assistant/models and for the chat turn.+func TestOwnKeyKeepsItsEnvironmentDefaultWhileAKeyIsShared(t *testing.T) {+ st, member := sponsorFixture(t)+ stubCLIModelDiscovery(t)+ discoverCLIModels = func(_ context.Context, environment, _ string) []string {+ if environment == "ioa" {+ return []string{"glm-5.1", "kimi-k2.6", "hy3-ioa"}+ }+ return []string{"claude-opus-5", "gpt-5.5"}+ }+ if err := st.SetPlatformCodeBuddyKey(repo.PlatformCodeBuddyKeyUpdate{APIKey: "platform-secret", InternetEnvironment: "ioa", Models: []string{"glm-5.1", "kimi-k2.6"}}, 0); err != nil {+ t.Fatal(err)+ }+ international := ""+ if _, err := st.UpdateUserCredentials(member.ID, repo.UserCredentialUpdate{CodeBuddyAPIKey: "own-secret", CodeBuddyInternetEnvironment: &international}); err != nil {+ t.Fatal(err)+ }+ stored, _ := st.User(member.ID)+ 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+ }}+ operatorDefault := assistantFixedCatalog().Default+var catalog assistantModelCatalogmrec := 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(stored)))h.models(c)- if json.Unmarshal(mrec.Body.Bytes(), &catalog) != nil || catalog.SponsoredModel != assistantSponsoredModel || catalog.Default != assistantChatDefaultModel {- t.Fatalf("catalog = %s", mrec.Body.String())+ if json.Unmarshal(mrec.Body.Bytes(), &catalog) != nil || catalog.Default != operatorDefault {+ t.Fatalf("own-key catalog default must not be the shared default: %s", mrec.Body.String())+ }+ ids := map[string]bool{}+ for _, model := range catalog.Models {+ ids[model.ID] = true+ }+ if !ids["claude-opus-5"] || ids["glm-5.1"] || ids["kimi-k2.6"] {+ t.Fatalf("own-key catalog must list the user's environment only: %s", mrec.Body.String())+ }++ chat := h.chatCatalog(context.Background(), stored)+ if got := assistantAllowedModel("", chat); got != operatorDefault {+ t.Fatalf("a new own-key conversation resolves to %q, want %q", got, operatorDefault)}- if strings.Contains(mrec.Body.String(), `"sponsor"`) || strings.Contains(mrec.Body.String(), "sponsor-secret") {- t.Fatal("catalog must not reveal the sponsor account or key")+ if got := assistantAllowedModel("claude-opus-5", chat); got != "claude-opus-5" {+ t.Fatalf("own-key user picking claude-opus-5 got %q", got)+ }+ if rec := sponsoredChat(h, stored, ""); rec.Code != 200 || used.CodeBuddyAPIKey != "own-secret" || used.CodeBuddyInternetEnvironment != "" {+ t.Fatalf("own-key turn: %d %s used=%+v", rec.Code, rec.Body.String(), used)+ }++ // Clearing the key moves the member onto the shared key and its models.+ if _, err := st.UpdateUserCredentials(member.ID, repo.UserCredentialUpdate{CodeBuddyAPIKeyClear: true}); err != nil {+ t.Fatal(err)+ }+ stored, _ = st.User(member.ID)+ borrowed, _, _ := h.assistantChatUser(stored)+ if got := assistantAllowedModel("", h.chatCatalog(context.Background(), borrowed)); got != "glm-5.1" {+ t.Fatalf("a shared-key conversation resolves to %q, want glm-5.1", got)}}@@ -120,6 +196,16 @@ func TestBootstrapAdvertisesSponsoredModel(t *testing.T) {if boot["sponsoredModel"] != assistantSponsoredModel {t.Fatalf("sponsoredModel = %v", boot["sponsoredModel"])}+ if err := st.SetPlatformCodeBuddyKey(repo.PlatformCodeBuddyKeyUpdate{APIKey: "platform-secret", Models: []string{"glm-5.1", "kimi-k2.6"}}, 0); err != nil {+ t.Fatal(err)+ }+ boot = requestEmptyJSON[map[string]any](t, h, http.MethodGet, "/api/bootstrap", http.StatusOK)+ if models, _ := boot["sponsoredModels"].([]any); boot["sponsoredModel"] != "glm-5.1" || len(models) != 2 {+ t.Fatalf("platform shared key = %v %v", boot["sponsoredModel"], boot["sponsoredModels"])+ }+ if err := st.ClearPlatformCodeBuddyKey(); err != nil {+ t.Fatal(err)+ }t.Setenv(assistantSponsorLoginEnv, "")boot = requestEmptyJSON[map[string]any](t, h, http.MethodGet, "/api/bootstrap", http.StatusOK)if boot["sponsoredModel"] != "" {@@ -138,12 +224,57 @@ func TestNoSponsorKeepsRequiringOwnKey(t *testing.T) {if rec := sponsoredChat(h, newcomer, ""); rec.Code != 400 || !strings.Contains(rec.Body.String(), "CodeBuddy API Key") {t.Fatalf("sponsor %q: %d %s", login, rec.Code, rec.Body.String())}- if _, ok := h.assistantSponsor(); ok {+ if _, ok := h.assistantSharedKey(); ok {t.Fatalf("sponsor %q without a key must not be available", login)}}}+// The key an administrator configures under 平台管理 replaces the legacy+// sponsor account, and limits shared turns to the models they allowed.+func TestPlatformSharedKeyLimitsChatToAllowedModels(t *testing.T) {+ st, newcomer := sponsorFixture(t)+ stubCLIModelDiscovery(t)+ t.Setenv(assistantSponsorLoginEnv, "sponsor")+ if err := st.SetPlatformCodeBuddyKey(repo.PlatformCodeBuddyKeyUpdate{APIKey: "platform-secret", InternetEnvironment: "ioa", Models: []string{"glm-5.1", "kimi-k2.6"}}, 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+ }}+ for model, want := range map[string]string{"": "glm-5.1", "kimi-k2.6": "kimi-k2.6"} {+ used = domain.User{}+ rec := sponsoredChat(h, newcomer, model)+ if rec.Code != 200 || used.CodeBuddyAPIKey != "platform-secret" || used.CodeBuddyInternetEnvironment != "ioa" {+ t.Fatalf("model %q: %d %s used=%+v", model, rec.Code, rec.Body.String(), used)+ }+ if got := assistantAllowedModel(model, h.chatCatalog(context.Background(), used)); got != want {+ t.Fatalf("model %q resolves to %q, want %q", model, got, want)+ }+ }+ for _, model := range []string{assistantSponsoredModel, "claude-opus-5"} {+ rec := sponsoredChat(h, newcomer, model)+ if rec.Code != 400 || !strings.Contains(rec.Body.String(), "glm-5.1、kimi-k2.6") {+ t.Fatalf("model %q outside the allow list: %d %s", model, rec.Code, rec.Body.String())+ }+ }++ var catalog assistantModelCatalog+ 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)+ if json.Unmarshal(mrec.Body.Bytes(), &catalog) != nil || catalog.Default != "glm-5.1" || strings.Join(catalog.SponsoredModels, ",") != "glm-5.1,kimi-k2.6" || len(catalog.Models) != 2 {+ t.Fatalf("shared-key catalog = %s", mrec.Body.String())+ }+ if strings.Contains(mrec.Body.String(), "platform-secret") {+ t.Fatal("catalog must not reveal the shared key")+ }+}+func TestAssistantModelsPerExecutor(t *testing.T) {h := &assistantHandlers{deps: &deps{}}get := func(executor string) (*httptest.ResponseRecorder, assistantModelCatalog) {diff --git a/internal/httpapi/assistant_title.go b/internal/httpapi/assistant_title.goindex 517b5f59..9e0cc8b9 100644--- a/internal/httpapi/assistant_title.go+++ b/internal/httpapi/assistant_title.go@@ -75,7 +75,8 @@ func assistantPromptTitleMatches(session domain.AssistantSession, title string)return false}-func (h *assistantHandlers) scheduleAssistantTitle(ctx context.Context, ownerID int64, user domain.User, old domain.AssistantSession, sessionID string, messages []domain.AssistantMessage, sponsored bool) {+// shared lists the allowed models when the turn runs on the shared key.+func (h *assistantHandlers) scheduleAssistantTitle(ctx context.Context, ownerID int64, user domain.User, old domain.AssistantSession, sessionID string, messages []domain.AssistantMessage, shared []string) {if h == nil || h.repo == nil {return}@@ -94,7 +95,7 @@ func (h *assistantHandlers) scheduleAssistantTitle(ctx context.Context, ownerIDif h.titleSummary != nil {title, err = h.titleSummary(runCtx, user, prompt)} else {- title, err = summarizeAssistantTitle(runCtx, user, prompt, sponsored)+ title, err = summarizeAssistantTitle(runCtx, user, prompt, shared)}if err != nil || strings.TrimSpace(title) == "" {log.Printf("assistant title summary skipped session=%s: %v", sessionID, err)@@ -106,10 +107,14 @@ func (h *assistantHandlers) scheduleAssistantTitle(ctx context.Context, ownerID}()}-func summarizeAssistantTitle(ctx context.Context, user domain.User, prompt string, sponsored bool) (string, error) {- model := assistantSponsoredModel- if !sponsored {- model = assistantApprovalReviewModel(assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment))+// A shared-key title uses the cheapest allowed model, or the shared default.+func summarizeAssistantTitle(ctx context.Context, user domain.User, prompt string, shared []string) (string, error) {+ if len(shared) == 0 {+ return runAssistantTitleSummary(ctx, user, assistantApprovalReviewModel(assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, nil)), prompt)+ }+ model := assistantApprovalReviewModel(restrictAssistantCatalog(assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, shared), shared))+ if model == "" {+ model = shared[0]}return runAssistantTitleSummary(ctx, user, model, prompt)}diff --git a/internal/httpapi/assistant_title_test.go b/internal/httpapi/assistant_title_test.goindex 6f24c446..c41faca8 100644--- a/internal/httpapi/assistant_title_test.go+++ b/internal/httpapi/assistant_title_test.go@@ -85,7 +85,7 @@ func TestScheduleAssistantTitleWritesSummary(t *testing.T) {t.Fatal(err)}old, _ := st.AssistantSession(1, id)- h.scheduleAssistantTitle(context.Background(), 1, domain.User{ID: 1}, old, id, []domain.AssistantMessage{{Role: "user", Content: prompt + ",请按模块列出缺口"}}, false)+ h.scheduleAssistantTitle(context.Background(), 1, domain.User{ID: 1}, old, id, []domain.AssistantMessage{{Role: "user", Content: prompt + ",请按模块列出缺口"}}, nil)deadline := time.Now().Add(2 * time.Second)var got domain.AssistantSessionfor time.Now().Before(deadline) {diff --git a/internal/httpapi/auth_register.go b/internal/httpapi/auth_register.goindex 13fb1f16..6f6edc64 100644--- a/internal/httpapi/auth_register.go+++ b/internal/httpapi/auth_register.go@@ -40,8 +40,10 @@ const welcomeProjectID = "welcome"// joinWelcomeProject makes the seeded demo project usable by new accounts so// the onboarding path works before they create a project of their own.-func (h *authHandlers) joinWelcomeProject(userID int64) {- project, ok := h.repo.Project(welcomeProjectID)+func (h *authHandlers) joinWelcomeProject(userID int64) { joinWelcomeProject(h.repo, userID) }++func joinWelcomeProject(store *repo.Store, userID int64) {+ project, ok := store.Project(welcomeProjectID)if !ok {return}@@ -51,7 +53,7 @@ func (h *authHandlers) joinWelcomeProject(userID int64) {}}project.Members = append(project.Members, domain.ProjectMember{UserID: userID, Role: "member"})- if err := h.repo.PutProject(project); err != nil {+ if err := store.PutProject(project); err != nil {log.Printf("join welcome project: %v", err)}}diff --git a/internal/httpapi/platform_settings.go b/internal/httpapi/platform_settings.gonew file mode 100644index 00000000..76519a74--- /dev/null+++ b/internal/httpapi/platform_settings.go@@ -0,0 +1,262 @@+package httpapi++import (+ "errors"+ "fmt"+ "net/http"+ "net/url"+ "regexp"+ "strconv"+ "strings"++ "agentflow/internal/domain"+ "agentflow/internal/repo"++ "github.com/gin-gonic/gin"+)++// 平台管理 → 成员账号 and 平台共享 CodeBuddy 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).+func (h *usersHandlers) platformAdminWrite(c *gin.Context) bool {+ if !h.isPlatformAdmin(c.Request) {+ c.JSON(http.StatusForbidden, gin.H{"error": "只有平台管理员可以执行该操作"})+ return false+ }+ if _, bearer := bearerToken(c.Request); bearer {+ return true+ }+ origin, err := url.Parse(c.GetHeader("Origin"))+ if err != nil || origin.Host != c.Request.Host || (origin.Scheme != "http" && origin.Scheme != "https") {+ c.JSON(http.StatusForbidden, gin.H{"error": "invalid request origin"})+ return false+ }+ return true+}++func (h *usersHandlers) platformAccounts(c *gin.Context) {+ if c.Request.Method != http.MethodGet {+ h.createPlatformAccount(c)+ return+ }+ if !h.isPlatformAdmin(c.Request) {+ c.JSON(http.StatusForbidden, gin.H{"error": "只有平台管理员可以查看成员账号"})+ return+ }+ accounts, err := h.repo.ListPlatformAccounts()+ if err != nil {+ respond(c, err)+ return+ }+ c.JSON(http.StatusOK, gin.H{"accounts": accounts, "signupEnabled": signupEnabled()})+}++func validAccountPassword(c *gin.Context, password string) bool {+ if len(password) < repo.MinPasswordLength || len(password) > repo.MaxPasswordLength {+ c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("密码需 %d–%d 个字符", repo.MinPasswordLength, repo.MaxPasswordLength)})+ return false+ }+ return true+}++func (h *usersHandlers) createPlatformAccount(c *gin.Context) {+ if !h.platformAdminWrite(c) {+ return+ }+ c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4096)+ var input struct {+ LoginName string `json:"loginName"`+ Password string `json:"password"`+ Admin bool `json:"admin"`+ }+ if c.ShouldBindJSON(&input) != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": "invalid account request"})+ return+ }+ input.LoginName = strings.TrimSpace(input.LoginName)+ if !loginPattern.MatchString(input.LoginName) {+ c.JSON(http.StatusBadRequest, gin.H{"error": "用户名需 2–64 位,以字母或数字开头,只能包含字母、数字、_ . -"})+ return+ }+ if !validAccountPassword(c, input.Password) {+ return+ }+ registerMu.Lock()+ u, err := h.repo.CreateLocalAccount(input.LoginName, input.Password, input.Admin)+ if err == nil {+ joinWelcomeProject(h.repo, u.ID)+ }+ registerMu.Unlock()+ if errors.Is(err, repo.ErrLoginTaken) {+ c.JSON(http.StatusConflict, gin.H{"error": "该用户名已被使用"})+ return+ }+ if err != nil {+ respond(c, err)+ return+ }+ c.JSON(http.StatusCreated, h.platformAccount(u.ID))+}++func (h *usersHandlers) platformAccount(userID int64) repo.PlatformAccount {+ accounts, _ := h.repo.ListPlatformAccounts()+ for _, account := range accounts {+ if account.UserID == userID {+ return account+ }+ }+ return repo.PlatformAccount{UserID: userID}+}++// resetPlatformAccountPassword sets a new password for a password account.+// Accounts that sign in through GitHub or a gateway are left alone, so this+// cannot add a password login to them.+func (h *usersHandlers) resetPlatformAccountPassword(c *gin.Context) {+ if !h.platformAdminWrite(c) {+ return+ }+ id, err := strconv.ParseInt(c.Param("id"), 10, 64)+ if err != nil || id <= 0 {+ c.JSON(http.StatusBadRequest, gin.H{"error": "valid user id is required"})+ return+ }+ c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4096)+ var input struct {+ Password string `json:"password"`+ }+ if c.ShouldBindJSON(&input) != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": "invalid password request"})+ return+ }+ if !validAccountPassword(c, input.Password) {+ return+ }+ account := h.platformAccount(id)+ if account.LoginName == "" {+ c.JSON(http.StatusNotFound, gin.H{"error": "账号不存在"})+ return+ }+ if !account.Password {+ c.JSON(http.StatusBadRequest, gin.H{"error": "该账号不是用户名密码账号(例如通过 GitHub 登录),不能在这里设置密码"})+ return+ }+ if err := h.repo.SetLocalPassword(id, input.Password); err != nil {+ respond(c, err)+ return+ }+ c.JSON(http.StatusOK, account)+}++var sharedModelPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$`)++type platformCodeBuddyKeyResponse struct {+ repo.PlatformCodeBuddyKeyStatus+ // Catalog lists the models offered in the requested network environment.+ Catalog []assistantModel `json:"catalog"`+}++// platformCodeBuddyKey shows and edits the shared CodeBuddy API Key. The key+// itself is write-only: responses only say whether one is configured.+func (h *usersHandlers) platformCodeBuddyKey(c *gin.Context) {+ 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()+ environment := status.InternetEnvironment+ if raw, ok := c.GetQuery("environment"); ok {+ normalized, valid := domain.NormalizeCodeBuddyInternetEnvironment(raw)+ if !valid {+ c.JSON(http.StatusBadRequest, gin.H{"error": "CodeBuddy 网络环境只能是国际站(留空)、国内站(internal)或 iOA(ioa)"})+ return+ }+ environment = normalized+ }+ apiKey := ""+ if key, ok := h.repo.SharedCodeBuddyKey(); ok && key.SponsorID == 0 && key.InternetEnvironment == environment {+ apiKey = key.APIKey+ }+ refreshCLIModels(c.Request.Context(), environment, apiKey)+ catalog := loadAssistantModels(c.Request.Context(), environment).Models+ c.JSON(http.StatusOK, platformCodeBuddyKeyResponse{PlatformCodeBuddyKeyStatus: status, Catalog: catalog})+ case http.MethodPut:+ h.savePlatformCodeBuddyKey(c)+ case http.MethodDelete:+ if !h.platformAdminWrite(c) {+ return+ }+ if err := h.repo.ClearPlatformCodeBuddyKey(); err != nil {+ respond(c, err)+ return+ }+ c.JSON(http.StatusOK, h.repo.PlatformCodeBuddyKeyStatus())+ default:+ c.JSON(http.StatusMethodNotAllowed, gin.H{"error": "method not allowed"})+ }+}++func (h *usersHandlers) savePlatformCodeBuddyKey(c *gin.Context) {+ if !h.platformAdminWrite(c) {+ return+ }+ c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 16<<10)+ var input struct {+ APIKey string `json:"apiKey"`+ InternetEnvironment string `json:"internetEnvironment"`+ Models []string `json:"models"`+ }+ if c.ShouldBindJSON(&input) != nil {+ 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+ }+ 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+ }+ var models []string+ seen := map[string]bool{}+ for _, raw := range input.Models {+ id := strings.TrimSpace(raw)+ if id == "" || seen[id] {+ continue+ }+ if !sharedModelPattern.MatchString(id) {+ c.JSON(http.StatusBadRequest, gin.H{"error": "模型 ID 格式不正确:" + id})+ return+ }+ seen[id] = true+ models = append(models, id)+ }+ if len(models) == 0 {+ c.JSON(http.StatusBadRequest, gin.H{"error": "请至少选择一个允许使用的模型"})+ return+ }+ if len(models) > repo.MaxSharedCodeBuddyModels {+ c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("最多选择 %d 个模型", repo.MaxSharedCodeBuddyModels)})+ return+ }+ var actorID int64+ 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"})+ return+ }+ if err != nil {+ respond(c, err)+ return+ }+ c.JSON(http.StatusOK, h.repo.PlatformCodeBuddyKeyStatus())+}diff --git a/internal/httpapi/platform_settings_test.go b/internal/httpapi/platform_settings_test.gonew file mode 100644index 00000000..0501519e--- /dev/null+++ b/internal/httpapi/platform_settings_test.go@@ -0,0 +1,249 @@+package httpapi++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync/atomic"+ "testing"++ "agentflow/internal/domain"+ "agentflow/internal/engine"+ "agentflow/internal/repo"+ "agentflow/internal/runtime"+)++type platformSettingsClient struct {+ t *testing.T+ h http.Handler+}++func (p platformSettingsClient) call(cookie *http.Cookie, method, path, origin, body string) *httptest.ResponseRecorder {+ r := httptest.NewRequest(method, "http://localhost"+path, bytes.NewBufferString(body))+ r.Header.Set("Content-Type", "application/json")+ if origin != "" {+ r.Header.Set("Origin", origin)+ }+ if cookie != nil {+ r.AddCookie(cookie)+ }+ w := httptest.NewRecorder()+ p.h.ServeHTTP(w, r)+ return w+}++// platformSettingsSignIns gives every sign-in its own client address, so these+// tests never use up the per-IP password budget other tests share.+var platformSettingsSignIns atomic.Int32++func (p platformSettingsClient) signIn(login, password string) *http.Cookie {+ p.t.Helper()+ r := httptest.NewRequest("POST", "http://localhost/api/auth/password", bytes.NewBufferString(`{"login":"`+login+`","password":"`+password+`"}`))+ r.Header.Set("Content-Type", "application/json")+ r.Header.Set("Origin", "http://localhost")+ r.RemoteAddr = fmt.Sprintf("198.51.100.%d:1234", platformSettingsSignIns.Add(1)%250+1)+ w := httptest.NewRecorder()+ p.h.ServeHTTP(w, r)+ if w.Code != 200 || len(w.Result().Cookies()) == 0 {+ p.t.Fatalf("sign in %s: %d %s", login, w.Code, w.Body.String())+ }+ return w.Result().Cookies()[0]+}++func platformSettingsFixture(t *testing.T) (*repo.Store, platformSettingsClient, *http.Cookie, *http.Cookie) {+ t.Helper()+ t.Setenv("AGENTFLOW_AUTH_REQUIRED", "true")+ t.Setenv("AGENTFLOW_SCHEDULER_ENABLED", "false")+ t.Setenv("AGENTFLOW_ALLOW_SIGNUP", "false")+ t.Setenv(assistantSponsorLoginEnv, "")+ s, err := repo.OpenTest()+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(s.Close)+ if _, err := s.CreateLocalAccount("owner", "owner-password", true); err != nil {+ t.Fatal(err)+ }+ if _, err := s.CreateLocalAccount("member", "member-password", false); err != nil {+ t.Fatal(err)+ }+ client := platformSettingsClient{t: t, h: New(s, engine.New(s, runtime.NewManager(t.TempDir())), nil, "", "")}+ return s, client, client.signIn("owner", "owner-password"), client.signIn("member", "member-password")+}++// With self-service signup closed, administrators create accounts and reset+// passwords from 平台管理 instead of the command line.+func TestPlatformAdminsManageAccounts(t *testing.T) {+ s, client, owner, member := platformSettingsFixture(t)+ if err := s.PutProject(domain.Project{ID: welcomeProjectID, Name: "Welcome"}); err != nil {+ t.Fatal(err)+ }+ const origin = "http://localhost"+ create := `{"loginName":"alice","password":"alice-initial","admin":false}`++ if w := client.call(member, "GET", "/api/platform/accounts", "", ""); w.Code != 403 {+ t.Fatalf("member list: %d", w.Code)+ }+ if w := client.call(member, "POST", "/api/platform/accounts", origin, create); w.Code != 403 {+ t.Fatalf("member create: %d", w.Code)+ }+ if w := client.call(owner, "POST", "/api/platform/accounts", "https://attacker.invalid", create); w.Code != 403 {+ t.Fatalf("cross-origin create: %d", w.Code)+ }+ if w := client.call(owner, "POST", "/api/platform/accounts", "", create); w.Code != 403 {+ t.Fatalf("create without origin: %d", w.Code)+ }+ for _, bad := range []string{`{"loginName":"a","password":"alice-initial"}`, `{"loginName":"bad name","password":"alice-initial"}`, `{"loginName":"alice","password":"short"}`} {+ if w := client.call(owner, "POST", "/api/platform/accounts", origin, bad); w.Code != 400 {+ t.Fatalf("invalid %s: %d %s", bad, w.Code, w.Body.String())+ }+ }+ w := client.call(owner, "POST", "/api/platform/accounts", origin, create)+ var created repo.PlatformAccount+ if w.Code != 201 || json.Unmarshal(w.Body.Bytes(), &created) != nil || created.LoginName != "alice" || !created.Password || created.Admin {+ t.Fatalf("create: %d %s", w.Code, w.Body.String())+ }+ if strings.Contains(w.Body.String(), "alice-initial") {+ t.Fatal("responses must not echo the password")+ }+ if w := client.call(owner, "POST", "/api/platform/accounts", origin, create); w.Code != 409 {+ t.Fatalf("duplicate: %d", w.Code)+ }+ if !s.CheckLocalPassword(created.UserID, "alice-initial") {+ t.Fatal("the new account signs in with the initial password")+ }+ welcome, _ := s.Project(welcomeProjectID)+ if len(welcome.Members) != 1 || welcome.Members[0].UserID != created.UserID {+ t.Fatalf("new account joins the welcome project: %+v", welcome.Members)+ }++ w = client.call(owner, "GET", "/api/platform/accounts", "", "")+ var listed struct {+ Accounts []repo.PlatformAccount+ SignupEnabled bool+ }+ if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &listed) != nil || listed.SignupEnabled {+ t.Fatalf("list: %d %s", w.Code, w.Body.String())+ }+ byLogin := map[string]repo.PlatformAccount{}+ for _, account := range listed.Accounts {+ byLogin[account.LoginName] = account+ }+ if !byLogin["owner"].Admin || byLogin["member"].Admin || !byLogin["alice"].Password || listed.Accounts[len(listed.Accounts)-1].LoginName != "alice" {+ t.Fatalf("accounts = %+v", listed.Accounts)+ }++ reset := `{"password":"alice-second"}`+ path := "/api/platform/accounts/" + itoa(created.UserID) + "/password"+ if w := client.call(member, "PUT", path, origin, reset); w.Code != 403 {+ t.Fatalf("member reset: %d", w.Code)+ }+ if w := client.call(owner, "PUT", path, origin, `{"password":"short"}`); w.Code != 400 {+ t.Fatalf("short reset: %d", w.Code)+ }+ if w := client.call(owner, "PUT", path, origin, reset); w.Code != 200 {+ t.Fatalf("reset: %d %s", w.Code, w.Body.String())+ }+ if s.CheckLocalPassword(created.UserID, "alice-initial") || !s.CheckLocalPassword(created.UserID, "alice-second") {+ t.Fatal("reset replaces the password")+ }+ if w := client.call(owner, "PUT", "/api/platform/accounts/999999/password", origin, reset); w.Code != 404 {+ t.Fatalf("missing account: %d", w.Code)+ }+ if err := s.PutUser(domain.User{LoginName: "octocat", ChineseName: "octocat"}); err != nil {+ t.Fatal(err)+ }+ octocat, _ := s.UserByLoginName("octocat")+ if w := client.call(owner, "PUT", "/api/platform/accounts/"+itoa(octocat.ID)+"/password", origin, reset); w.Code != 400 {+ t.Fatalf("a GitHub account must not gain a password login: %d", w.Code)+ }+}++// The shared key is write-only: administrators see whether one is+// configured, its network environment and models, never the key.+func TestPlatformAdminsConfigureSharedCodeBuddyKey(t *testing.T) {+ s, client, owner, member := platformSettingsFixture(t)+ stubCLIModelDiscovery(t)+ const origin = "http://localhost"+ save := `{"apiKey":"ck_platform_secret","internetEnvironment":"internal","models":["glm-5.1"," kimi-k2.6 ","glm-5.1"]}`++ if w := client.call(member, "GET", "/api/platform/codebuddy-key", "", ""); w.Code != 403 {+ t.Fatalf("member read: %d", w.Code)+ }+ if w := client.call(member, "PUT", "/api/platform/codebuddy-key", origin, save); w.Code != 403 {+ t.Fatalf("member save: %d", w.Code)+ }+ if w := client.call(owner, "PUT", "/api/platform/codebuddy-key", "https://attacker.invalid", save); w.Code != 403 {+ t.Fatalf("cross-origin save: %d", w.Code)+ }+ for body, want := range map[string]string{+ `{"apiKey":"","internetEnvironment":"","models":["glm-5.1"]}`: "API Key",+ `{"apiKey":"ck_x","internetEnvironment":"","models":[]}`: "至少选择",+ `{"apiKey":"ck_x","internetEnvironment":"private-net","models":["glm-5.1"]}`: "网络环境",+ `{"apiKey":"ck_x","internetEnvironment":"","models":["bad model"]}`: "模型 ID",+ `{"apiKey":"ck x","internetEnvironment":"","models":["glm-5.1"]}`: "API Key",+ } {+ if w := client.call(owner, "PUT", "/api/platform/codebuddy-key", origin, body); w.Code != 400 || !strings.Contains(w.Body.String(), want) {+ t.Fatalf("invalid %s: %d %s", body, w.Code, w.Body.String())+ }+ }+ w := client.call(owner, "PUT", "/api/platform/codebuddy-key", origin, save)+ if w.Code != 200 || strings.Contains(w.Body.String(), "ck_platform_secret") {+ t.Fatalf("save: %d %s", w.Code, w.Body.String())+ }+ key, ok := s.SharedCodeBuddyKey()+ if !ok || key.APIKey != "ck_platform_secret" || key.InternetEnvironment != "internal" || strings.Join(key.Models, ",") != "glm-5.1,kimi-k2.6" {+ t.Fatalf("stored key = %+v", key)+ }++ // Changing the models keeps the stored key when none is typed.+ if w := client.call(owner, "PUT", "/api/platform/codebuddy-key", origin, `{"internetEnvironment":"internal","models":["kimi-k2.6"]}`); w.Code != 200 {+ t.Fatalf("update models: %d %s", w.Code, w.Body.String())+ }+ w = client.call(owner, "GET", "/api/platform/codebuddy-key", "", "")+ var status platformCodeBuddyKeyResponse+ 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())+ }+ if strings.Contains(w.Body.String(), "ck_platform_secret") {+ t.Fatal("status must not reveal the key")+ }+ if w := client.call(owner, "GET", "/api/platform/codebuddy-key?environment=bogus", "", ""); w.Code != 400 {+ t.Fatalf("bogus environment: %d", w.Code)+ }+ if key, _ := s.SharedCodeBuddyKey(); key.APIKey != "ck_platform_secret" || strings.Join(key.Models, ",") != "kimi-k2.6" {+ t.Fatalf("models-only update = %+v", key)+ }++ if w := client.call(owner, "DELETE", "/api/platform/codebuddy-key", origin, ""); w.Code != 200 || strings.Contains(w.Body.String(), `"configured":true`) {+ t.Fatalf("clear: %d %s", w.Code, w.Body.String())+ }+ if _, ok := s.SharedCodeBuddyKey(); ok {+ t.Fatal("cleared key must not be lent")+ }+ if w := client.call(owner, "PUT", "/api/platform/codebuddy-key", origin, `{"internetEnvironment":"","models":["glm-5.1"]}`); w.Code != 400 {+ t.Fatalf("a cleared key needs a new one: %d", w.Code)+ }+}++func itoa(v int64) string {+ b, _ := json.Marshal(v)+ return string(b)+}++// stubCLIModelDiscovery keeps tests from running the CodeBuddy CLI.+func stubCLIModelDiscovery(t *testing.T) {+ t.Helper()+ old := discoverCLIModels+ discoverCLIModels = func(context.Context, string, string) []string { return nil }+ t.Cleanup(func() {+ discoverCLIModels = old+ cliModelMu.Lock()+ cliModelCache = map[string]cliModelEntry{}+ cliModelMu.Unlock()+ })+}diff --git a/internal/httpapi/server.go b/internal/httpapi/server.goindex 0cc8f2e7..14eaee71 100644--- a/internal/httpapi/server.go+++ b/internal/httpapi/server.go@@ -255,6 +255,12 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Servg.GET("/api/users", api.users.users)g.GET("/api/platform/admins", api.users.platformAdmins)g.PUT("/api/platform/admins", api.users.platformAdmins)+ 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/codebuddy-key", api.users.platformCodeBuddyKey)+ g.PUT("/api/platform/codebuddy-key", api.users.platformCodeBuddyKey)+ g.DELETE("/api/platform/codebuddy-key", api.users.platformCodeBuddyKey)// master(net/http) 的 /api/users/ 子树只接受 PUT /api/users/<id>/credentials// 一种形态,其余任何方法/子路径都走 method(w) → 405 JSON。g.Any("/api/users/:id/credentials", func(c *gin.Context) {@@ -728,6 +734,11 @@ func (s *Server) bootstrap(c *gin.Context) {currentUserID = current.ID}mcpServers = domain.PublicMCPServers(withMarketIcons(visibleMCPServersForUser(mcpServers, currentUserID)))+ sharedModels := s.repo.SharedCodeBuddyModels()+ sponsoredModel := ""+ if len(sharedModels) > 0 {+ sponsoredModel = sharedModels[0]+ }c.JSON(200, map[string]any{"businessDomains": businessDomains, "projects": domain.PublicProjects(projects), "repositories": domain.PublicRepositories(repositories),"agents": catalogAgents(agents), "rules": rules, "skills": skills, "mcpServers": mcpServers,@@ -737,8 +748,10 @@ func (s *Server) bootstrap(c *gin.Context) {"storage": s.repo.StorageInfo(),"capabilities": map[string]bool{"docker": runtime.DockerReady()},// Set when users without their own CodeBuddy API Key can still chat- // and run SOPs on the platform's shared model.- "sponsoredModel": s.repo.SponsoredCodeBuddyModelAvailable(),+ // and run SOPs on the platform's shared key, limited to these models+ // (sponsoredModel is the default).+ "sponsoredModel": sponsoredModel,+ "sponsoredModels": sharedModels,})}diff --git a/internal/repo/codebuddy_sponsor.go b/internal/repo/codebuddy_sponsor.goindex bdb13267..c9dc2359 100644--- a/internal/repo/codebuddy_sponsor.go+++ b/internal/repo/codebuddy_sponsor.go@@ -1,41 +1,213 @@package repoimport (+ "encoding/json"+ "errors""os""strings"+ "time""agentflow/internal/domain"++ "gorm.io/gorm/clause")-// Users who have not configured their own CodeBuddy API Key borrow the key of-// the account named by AGENTFLOW_ASSISTANT_SPONSOR_LOGIN, limited to-// SponsoredCodeBuddyModel. It covers chat conversations and SOP 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.+// 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 SOP+// 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"))-// CodeBuddySponsor returns the account whose key is lent, if one is configured-// and has a key.-func (s *Store) CodeBuddySponsor() (domain.User, bool) {+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 == "" || s == nil {+ if login == "" || r == nil {return domain.User{}, false}- sponsor, ok := s.UserByLoginName(login)+ sponsor, ok := r.UserByLoginName(login)if !ok || strings.TrimSpace(sponsor.CodeBuddyAPIKey) == "" {return domain.User{}, false}return sponsor, true}-// SponsoredCodeBuddyModelAvailable returns the sponsored model when a sponsor-// is configured, or "" otherwise.-func (s *Store) SponsoredCodeBuddyModelAvailable() string {- if _, ok := s.CodeBuddySponsor(); ok {- return SponsoredCodeBuddyModel+// 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}- return ""+ 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/local_accounts.go b/internal/repo/local_accounts.goindex ab892b26..11e7747a 100644--- a/internal/repo/local_accounts.go+++ b/internal/repo/local_accounts.go@@ -4,6 +4,8 @@ import ("agentflow/internal/domain""errors""fmt"+ "time"+"golang.org/x/crypto/bcrypt")@@ -46,6 +48,50 @@ func (r *UsersRepo) LocalAccountCount() int64 {return n}+// PlatformAccount is one user as listed under 平台管理 → 成员账号.+type PlatformAccount struct {+ UserID int64 `json:"userId"`+ LoginName string `json:"loginName"`+ ChineseName string `json:"chineseName,omitempty"`+ Admin bool `json:"admin"`+ // Password is false for users who sign in through GitHub or a gateway.+ Password bool `json:"password"`+ CodeBuddyAPIKey bool `json:"codeBuddyApiKeyConfigured"`+ CreatedAt *time.Time `json:"createdAt,omitempty"`+}++// ListPlatformAccounts lists every user, oldest first.+func (r *UsersRepo) ListPlatformAccounts() ([]PlatformAccount, error) {+ var rows []struct {+ ID int64+ LoginName string+ ChineseName string+ PlatformRole string+ CreatedAt *time.Time+ HasPassword bool+ HasKey bool+ }+ err := r.DB.Raw(`SELECT u.id, u.login_name, u.chinese_name, u.platform_role, u.created_at,+ (l.user_id IS NOT NULL) AS has_password,+ (c.codebuddy_api_key IS NOT NULL AND c.codebuddy_api_key <> '') AS has_key+ FROM users u+ LEFT JOIN local_accounts l ON l.user_id = u.id+ LEFT JOIN user_configs c ON c.user_id = u.id+ ORDER BY u.id ASC`).Scan(&rows).Error+ if err != nil {+ return nil, err+ }+ out := make([]PlatformAccount, 0, len(rows))+ for _, row := range rows {+ out = append(out, PlatformAccount{+ UserID: row.ID, LoginName: row.LoginName, ChineseName: row.ChineseName,+ Admin: IsAllowlistedPlatformAdmin(row.LoginName) || domain.IsPlatformAdmin(domain.User{PlatformRole: row.PlatformRole}),+ Password: row.HasPassword, CodeBuddyAPIKey: row.HasKey, CreatedAt: row.CreatedAt,+ })+ }+ return out, nil+}+// CreateLocalAccount registers a new password account; it never takes over an// existing user row.func (r *UsersRepo) CreateLocalAccount(login, password string, admin bool) (domain.User, error) {diff --git a/internal/repo/models.go b/internal/repo/models.goindex 9ee035c5..23931235 100644--- a/internal/repo/models.go+++ b/internal/repo/models.go@@ -675,7 +675,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{}, domain.NotificationDelivery{},- userRow{}, localAccountRow{}, userConfigRow{}, authIntegrationRow{}, apiTokenRow{}, genericTemplateRow{},+ userRow{}, localAccountRow{}, userConfigRow{}, authIntegrationRow{}, platformCodeBuddyKeyRow{}, apiTokenRow{}, genericTemplateRow{},insightSourceRow{}, insightExecutionRow{},projectRow{}, projectMemberRow{}, repositoryRow{}, businessDomainRow{}, businessDomainAssignmentRow{},agentRow{}, ruleRow{}, skillRow{}, skillFileRow{}, mcpServerRow{}, mcpFileRow{}, executorRow{},diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.goindex 493484a9..88e377f1 100644--- a/internal/runtime/runtime.go+++ b/internal/runtime/runtime.go@@ -26,9 +26,10 @@ type CodeBuddyCredential struct {APIKey stringInternetEnvironment string// Sponsored is set when the responsible user has no key of their own and- // the platform sponsor's key is used; such runs are pinned to the- // sponsored model.- Sponsored bool+ // the platform's shared key is used; such runs are limited to+ // SponsoredModels (the default first).+ Sponsored bool+ SponsoredModels []string}// RunCredentials lives only on the in-memory run sandbox handle. It is neverdiff --git a/migrations/024_platform_codebuddy_key.sql b/migrations/024_platform_codebuddy_key.sqlnew file mode 100644index 00000000..dd50a477--- /dev/null+++ b/migrations/024_platform_codebuddy_key.sql@@ -0,0 +1,13 @@+-- Manual, idempotent MySQL migration. The platform also creates this table+-- on startup; the script documents it for operators who manage DDL by hand.+-- Holds at most one row (id = 1): the CodeBuddy API Key a platform+-- administrator shares with users who have no key of their own, and the+-- models (a JSON array, default first) it may run.+CREATE TABLE IF NOT EXISTS platform_codebuddy_keys (+ id BIGINT NOT NULL PRIMARY KEY,+ api_key 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+);diff --git a/web/app/access.js b/web/app/access.jsindex 1addf851..e8b98ece 100644--- a/web/app/access.js+++ b/web/app/access.js@@ -175,7 +175,7 @@ function renderGuideSetupBody(body,user,isGuest){const credCard=`<div class="setup-card ${credReady?'is-ready':''}"><div class="setup-card-head"><b>① 配个人凭据</b><small>个人配置 · 一次配齐</small>${badge(credReady)}</div><p>${lfT('在<b>个人配置</b>中配置 CodeBuddy API Key 与 GitHub Token,或绑定本机 CLI。Main Bot 和内置 SOP 默认都使用 CodeBuddy。','Configure your CodeBuddy API key and GitHub token in <b>Settings</b>, or connect a local CLI. Main Bot and the built-in SOPs use CodeBuddy by default.')}</p><div class="setup-steps">- ${subItem('codeBuddyApiKey','CodeBuddy API Key',cbOwn,codeBuddyKeyURL(stored.codeBuddyInternetEnvironment),cbShared?'未配置时对话和 SOP 都用平台共享模型 Deepseek-V4.1-Flash;配置后可使用其他模型':'Agent 调模型执行任务')}+ ${subItem('codeBuddyApiKey','CodeBuddy API Key',cbOwn,codeBuddyKeyURL(stored.codeBuddyInternetEnvironment),cbShared?`未配置时对话和 SOP 都用平台共享 Key,可用模型:${escapeHTML(sharedModelSummary())};配置后可使用其他模型`:'Agent 调模型执行任务')}${subItem('codexApiKey','Codex API Key',!!stored.codexApiKeyConfigured,'https://platform.openai.com/api-keys','公共 SOP 默认执行器')}${subItem('claudeCodeApiKey','Claude Code API Key',!!stored.claudeCodeApiKeyConfigured,'https://console.anthropic.com/','可按角色选择的执行器')}${subItem('gitToken','GitHub Git Token',gfReady,'/#/settings','用 GitHub 设备码授权后选择仓库,也支持手动配置 PAT')}diff --git a/web/app/workbench.js b/web/app/workbench.jsindex 6c21d9c7..3b725ac7 100644--- a/web/app/workbench.js+++ b/web/app/workbench.js@@ -40,14 +40,21 @@ const CODEBUDDY_ENVIRONMENTS=[{value:'ioa',label:'iOA',site:'tencent.sso.copilot.tencent.com',keyUrl:'https://tencent.sso.copilot.tencent.com/profile/keys'},];const CODEBUDDY_ENVIRONMENT_ALIASES={public:'',intl:'',international:'','国际站':'',china:'internal',cn:'internal','国内站':'internal'};-// Returns null for a value the CLI would not recognize.+// The CLI receives the stored text as-is, so only the exact values count; returns null for anything else.function codeBuddyEnvironment(value){+ const key=String(value||'').trim();+ return CODEBUDDY_ENVIRONMENTS.find(env=>env.value===key)||null;+}+// What an old free-text value most likely meant (china → 国内站), used to preselect the fix.+function codeBuddyEnvironmentIntent(value){const key=String(value||'').trim().toLowerCase();const normalized=Object.prototype.hasOwnProperty.call(CODEBUDDY_ENVIRONMENT_ALIASES,key)?CODEBUDDY_ENVIRONMENT_ALIASES[key]:key;return CODEBUDDY_ENVIRONMENTS.find(env=>env.value===normalized)||null;}-function codeBuddyKeyURL(value){return (codeBuddyEnvironment(value)||CODEBUDDY_ENVIRONMENTS[0]).keyUrl}-function codeBuddyKeyLinkLabel(value){return `前往${(codeBuddyEnvironment(value)||CODEBUDDY_ENVIRONMENTS[0]).label}获取 API Key`}+// A stored value the CLI does not take as written; it connects to 国际站 until it is saved again.+function codeBuddyEnvironmentLegacy(value){const raw=String(value||'').trim();return !!raw&&!codeBuddyEnvironment(raw)}+function codeBuddyKeyURL(value){return (codeBuddyEnvironmentIntent(value)||CODEBUDDY_ENVIRONMENTS[0]).keyUrl}+function codeBuddyKeyLinkLabel(value){return `前往${(codeBuddyEnvironmentIntent(value)||CODEBUDDY_ENVIRONMENTS[0]).label}获取 API Key`}const CREDENTIAL_KINDS=[{key:'gitToken',group:'platform',name:'GitHub',short:'仓库授权',logo:'github',monochrome:true,use:'克隆私有仓库、创建任务分支、推送交付产物',@@ -100,9 +107,10 @@ function credentialSecretWarning(kind,value){?'这像是 DeepSeek、OpenAI 等第三方模型的 Key,CodeBuddy 会拒绝;第三方 Key 请改填到 Claude Code 或 Codex 凭证并设置 Base URL':'CodeBuddy API Key 通常以 ck_ 开头,请确认复制的是 CodeBuddy 的 Key';}-// The value an extra field starts from. An unrecognized network environment shows as 国际站, which is what the CLI uses.+// The value an extra field starts from. An old network environment preselects what it meant (china → 国内站),+// and one that cannot be guessed shows as 国际站, which is what the CLI uses.function credentialExtraValue(kind,value){- if(kind?.extra?.options)return codeBuddyEnvironment(value)?.value??'';+ if(kind?.extra?.options)return codeBuddyEnvironmentIntent(value)?.value??'';return value||kind?.extra?.fallback||'';}function credentialExtraLabel(kind,value){@@ -110,7 +118,7 @@ function credentialExtraLabel(kind,value){return String(value||'').trim()||(kind.extra.url?'官方地址':kind.extra.fallback||'');}function codeBuddyEnvironmentHintHTML(selected,stored=''){- const raw=String(stored||'').trim(),legacy=raw&&!codeBuddyEnvironment(raw)?`原来填写的「${raw}」无法识别,CodeBuddy 实际按国际站连接。`:'';+ const raw=String(stored||'').trim(),legacy=codeBuddyEnvironmentLegacy(raw)?`原来填写的「${raw}」无法识别,CodeBuddy 实际按国际站连接,点保存改为上面选择的环境。`:'';return `${escapeHTML(legacy)}Key 只能在创建它的站点使用 · <a href="${escapeHTML(codeBuddyKeyURL(selected))}" target="_blank" rel="noopener noreferrer" data-credential-key-link>${escapeHTML(codeBuddyKeyLinkLabel(selected))} ↗</a>`;}function credentialSelectFieldHTML(kind,stored,note=''){@@ -229,8 +237,8 @@ function credentialEditorHTML(kind,user){const extraField=!kind.extra?'':kind.extra.options?credentialSelectFieldHTML(kind,user[kind.extra.name],'与 Key 所在站点一致'):credentialFieldHTML({label:kind.extra.label,note:kind.extra.url?'留空使用官方地址':'',name:'extra',type:kind.extra.url?'url':'text',value:extraValue,placeholder:kind.extra.placeholder,hint:null});- // An unrecognized stored environment can be saved as shown without retyping the key.- const legacy=!!(kind.extra?.options&&String(user[kind.extra.name]||'').trim()&&!codeBuddyEnvironment(user[kind.extra.name]));+ // A stored environment the CLI does not take as written (china, private-net…) can be saved as shown without retyping the key.+ const legacy=!!(kind.extra?.options&&codeBuddyEnvironmentLegacy(user[kind.extra.name]));return `<div class="credential-editor-form"${kind.extra?` data-original="${escapeHTML(extraValue)}"`:''}${legacy?' data-legacy="true"':''}>${credentialFieldHTML({label:kind.short,note:'已配置 · 留空则不改',name:'secret',placeholder:'输入新值以替换',hint:kind.hint||''})}${extraField}@@ -836,10 +844,50 @@ function renderPlatformNav(){const platformItem=group.querySelector('[data-view="platform"]');if(platformItem)platformItem.hidden=!isPlatformAdmin();}+// 平台管理分成三个 tab:成员账号、平台管理员、共享 CodeBuddy Key。+const PLATFORM_TABS=[+ {id:'accounts',zh:'成员账号',en:'Accounts'},+ {id:'admins',zh:'平台管理员',en:'Admins'},+ {id:'sharedKey',zh:'共享 CodeBuddy Key',en:'Shared CodeBuddy Key'},+];+function platformTabsHTML(active){+ return `<div class="pa-tabs-wrap platform-tabs-wrap"><div class="pa-tabs platform-tabs" id="platformTabs" role="tablist" aria-label="平台管理分区">${PLATFORM_TABS.map(t=>{+ const on=t.id===active;+ const extra=t.id==='sharedKey'?'<span class="platform-tab-state" data-platform-tab-state hidden></span>':'<span class="pa-tab-n" data-platform-tab-count hidden></span>';+ return `<button type="button" role="tab" class="pa-tab${on?' on':''}" id="platformTab-${t.id}" data-platform-tab="${t.id}" aria-controls="platformPanel-${t.id}" aria-selected="${on}" tabindex="${on?0:-1}">${lfT(t.zh,t.en)}${extra}</button>`;+ }).join('')}</div></div>`;+}+function platformTabPanel(id,active,body){+ return `<section class="platform-tab-panel" id="platformPanel-${id}" role="tabpanel" aria-labelledby="platformTab-${id}" data-platform-panel="${id}"${id===active?'':' hidden'}>${body}</section>`;+}+function setPlatformTab(host,tab){+ if(!PLATFORM_TABS.some(t=>t.id===tab))tab=PLATFORM_TABS[0].id;+ state.platformTab=tab;+ host.querySelectorAll('[data-platform-tab]').forEach(b=>{const on=b.dataset.platformTab===tab;b.classList.toggle('on',on);b.setAttribute('aria-selected',String(on));b.tabIndex=on?0:-1});+ host.querySelectorAll('[data-platform-panel]').forEach(p=>{p.hidden=p.dataset.platformPanel!==tab});+}+function bindPlatformTabs(host){+ const bar=host.querySelector('#platformTabs');if(!bar)return;+ bar.querySelectorAll('[data-platform-tab]').forEach(b=>b.onclick=()=>setPlatformTab(host,b.dataset.platformTab));+ bar.onkeydown=e=>{+ if(!['ArrowLeft','ArrowRight'].includes(e.key))return;+ const ids=PLATFORM_TABS.map(t=>t.id),i=ids.indexOf(state.platformTab),next=ids[(i+(e.key==='ArrowRight'?1:ids.length-1))%ids.length];+ setPlatformTab(host,next);bar.querySelector(`[data-platform-tab="${next}"]`)?.focus();+ };+}+function setPlatformTabCount(host,tab,n){+ const el=host.querySelector(`[data-platform-tab="${tab}"] [data-platform-tab-count]`);+ if(el){el.textContent=String(n);el.hidden=false}+}function renderPlatformAdminPanel(){const host=$('#platformAdminPanel');if(!host)return;if(!isPlatformAdmin()){host.innerHTML='';return}+ const tab=PLATFORM_TABS.some(t=>t.id===state.platformTab)?state.platformTab:PLATFORM_TABS[0].id;+ state.platformTab=tab;host.innerHTML=`+ ${platformTabsHTML(tab)}+ ${platformTabPanel('accounts',tab,platformAccountsHTML())}+ ${platformTabPanel('admins',tab,`<div class="platform-metric-grid"><div class="platform-metric-card"><div class="platform-metric-icon blue">@@ -887,7 +935,6 @@ function renderPlatformAdminPanel(){<div class="platform-admin-main-card"><div class="platform-admin-head"><div class="platform-admin-head-meta">- <span class="credential-eyebrow">平台权限</span><h2>谁可以改通用模板</h2><p>平台管理员能直接编辑通用模板和它打包的角色,改完所有项目下次运行生效。系统内置名单不能在这里撤销。</p></div>@@ -968,9 +1015,275 @@ function renderPlatformAdminPanel(){</div></div></div>+ `)}+ ${platformTabPanel('sharedKey',tab,platformSharedKeyHTML())}`;+ bindPlatformTabs(host);+ loadPlatformAccounts(host);+ loadPlatformSharedKey(host);loadPlatformAdmins(host);}++// 平台管理 → 成员账号 / 平台共享 CodeBuddy Key.+const PLATFORM_ACCOUNT_PASSWORD_MIN=6;+function platformRandomPassword(){+ const alphabet='ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789';+ const bytes=new Uint32Array(14);window.crypto.getRandomValues(bytes);+ return Array.from(bytes,b=>alphabet[b%alphabet.length]).join('');+}+function sharedModelLabel(id){return id==='deepseek-v4.1-flash'?'Deepseek-V4.1-Flash':String(id||'')}+// The models users without their own CodeBuddy key may use, as announced by bootstrap.+function sharedModelSummary(){+ const models=Array.isArray(state.data?.sponsoredModels)&&state.data.sponsoredModels.length?state.data.sponsoredModels:(state.data?.sponsoredModel?[state.data.sponsoredModel]:[]);+ return models.map(sharedModelLabel).join('、');+}+const PLATFORM_ICON_USER='<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>';+const PLATFORM_ICON_LOCK='<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>';+const PLATFORM_ICON_SEARCH='<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>';+function platformAccountsHTML(){+ return `+ <section class="platform-admin-main-card" id="platformAccountsCard">+ <div class="platform-admin-head">+ <div class="platform-admin-head-meta">+ <h2>给同事开账号</h2>+ <p data-account-intro>填好用户名和初始密码,点创建,再把登录信息发给同事。同事忘记密码时可以在下面重置。</p>+ </div>+ <span class="platform-admin-count-pill" id="platformAccountCountBadge">${lfT('-- 个账号','-- accounts')}</span>+ </div>+ <div class="platform-account-create">+ <form id="platformAccountForm" class="platform-account-form" autocomplete="off">+ <div class="platform-input-wrap"><span class="platform-input-icon">${PLATFORM_ICON_USER}</span><input name="loginName" placeholder="用户名,如 alice" aria-label="用户名" maxlength="64" autocomplete="off" spellcheck="false"></div>+ <div class="platform-input-wrap"><span class="platform-input-icon">${PLATFORM_ICON_LOCK}</span><input name="password" placeholder="初始密码,至少 6 位" aria-label="初始密码" maxlength="72" autocomplete="new-password" spellcheck="false"><button type="button" class="button ghost small" data-account-generate>随机生成</button></div>+ <label class="platform-check"><input type="checkbox" name="admin"><span>同时设为平台管理员</span></label>+ <button class="button primary platform-add-btn" type="submit">创建账号</button>+ </form>+ <div class="platform-account-created" data-account-created hidden></div>+ </div>+ <div class="platform-list-toolbar">+ <div class="platform-search-wrap platform-account-search">${PLATFORM_ICON_SEARCH}<input data-account-search placeholder="搜索用户名..." autocomplete="off"></div>+ </div>+ <div id="platformAccountList" class="platform-admin-list platform-account-list"></div>+ </section>`;+}+function platformSharedKeyHTML(){+ const envOptions=CODEBUDDY_ENVIRONMENTS.map(env=>`<option value="${escapeHTML(env.value)}">${escapeHTML(env.label)} · ${escapeHTML(env.site)}</option>`).join('');+ return `+ <section class="platform-admin-main-card" id="platformSharedKeyCard">+ <div class="platform-admin-head">+ <div class="platform-admin-head-meta">+ <h2>给没配 Key 的成员用</h2>+ <p>成员没配自己的 CodeBuddy API Key 时,对话和 SOP 会用这里的 Key,并且只能用下面勾选的模型。成员配了自己的 Key 就用自己的,不受限制。</p>+ </div>+ <span class="platform-admin-count-pill platform-status-pill" data-shared-key-badge>${lfT('加载中','Loading')}</span>+ </div>+ <form id="platformSharedKeyForm" class="platform-shared-key-form" autocomplete="off">+ <div class="platform-shared-key-grid">+ <div class="platform-shared-key-col">+ <label class="platform-field"><span>网络环境</span><select name="internetEnvironment">${envOptions}</select></label>+ <div class="platform-field-group">+ <label class="platform-field"><span>API Key</span><input name="apiKey" type="password" autocomplete="new-password" spellcheck="false" placeholder="ck_ 开头的 CodeBuddy API Key"></label>+ <a class="platform-shared-key-link" data-shared-key-link target="_blank" rel="noopener noreferrer"></a>+ </div>+ <div class="platform-note is-warn" data-shared-key-warning hidden></div>+ <label class="platform-field"><span>默认模型</span><select name="defaultModel"></select><small class="platform-field-hint">没指定模型时用它;SOP 角色的模型不在允许范围内时也改用它。</small></label>+ </div>+ <div class="platform-shared-key-col">+ <div class="platform-field">+ <div class="platform-field-head"><span>允许使用的模型</span><small data-shared-models-count></small></div>+ <div class="platform-model-list" data-shared-models><p class="prop-hint">正在读取可用模型…</p></div>+ </div>+ <label class="platform-field"><span>列表里没有的模型</span><input name="extraModels" placeholder="模型 ID,多个用逗号分隔" autocomplete="off" spellcheck="false"></label>+ </div>+ </div>+ <div class="platform-shared-key-footer">+ <p class="platform-add-hint" data-shared-key-meta></p>+ <div class="platform-shared-key-actions">+ <button class="button ghost danger" type="button" data-shared-key-clear hidden>停用共享 Key</button>+ <button class="button primary" type="submit">保存</button>+ </div>+ </div>+ </form>+ </section>`;+}+function platformAccountCreatedHTML(action,login,password){+ const who=`<b data-i18n-skip>${escapeHTML(login)}</b>`,secret=`<code>${escapeHTML(password)}</code>`;+ const text=action==='reset'+ ?lfT(`已重置账号 ${who},新密码 ${secret}。密码只显示这一次,请现在发给对方。`,`Password of ${who} reset to ${secret}. It is shown only once; send it now.`)+ :lfT(`已创建账号 ${who},初始密码 ${secret}。密码只显示这一次,请现在发给对方。`,`Created ${who} with the initial password ${secret}. It is shown only once; send it now.`);+ return `<div class="platform-note is-ok"><span>${text}</span><button type="button" class="button ghost small" data-copy-login>复制登录信息</button></div>`;+}+const platformPasswordTooShort=()=>lfT(`密码至少 ${PLATFORM_ACCOUNT_PASSWORD_MIN} 位`,`The password needs at least ${PLATFORM_ACCOUNT_PASSWORD_MIN} characters`);+async function loadPlatformAccounts(host){+ const card=host.querySelector('#platformAccountsCard');if(!card)return;+ const list=card.querySelector('#platformAccountList'),form=card.querySelector('#platformAccountForm'),created=card.querySelector('[data-account-created]'),search=card.querySelector('[data-account-search]');+ let accounts=[],query='',resetting=null;+ const showCreated=(action,login,password)=>{+ created.innerHTML=platformAccountCreatedHTML(action,login,password);created.hidden=false;+ created.querySelector('[data-copy-login]').onclick=()=>copyText(lfT(`登录地址:${location.origin}\n用户名:${login}\n密码:${password}`,`Sign in at: ${location.origin}\nLogin: ${login}\nPassword: ${password}`),'已复制登录信息');+ };+ const render=()=>{+ const n=accounts.length,badge=card.querySelector('#platformAccountCountBadge');if(badge)badge.textContent=lfT(`共 ${n} 个账号`,`${n} account${n===1?'':'s'}`);+ setPlatformTabCount(host,'accounts',n);+ const q=query.toLowerCase();+ const rows=accounts.filter(a=>!q||String(a.loginName||'').toLowerCase().includes(q)||String(a.chineseName||'').toLowerCase().includes(q));+ if(!rows.length){list.innerHTML=`<div class="platform-empty-state"><b>${accounts.length?'没有匹配的账号':'还没有账号'}</b></div>`;return}+ list.innerHTML=rows.map(a=>{+ const name=a.chineseName&&a.chineseName.toLowerCase()!==String(a.loginName).toLowerCase()?`${a.loginName}(${a.chineseName})`:a.loginName;+ const badges=[a.admin?'<span class="platform-source-badge source-builtin">平台管理员</span>':'',a.password?'<span class="platform-source-badge source-default">用户名密码</span>':'<span class="platform-source-badge source-default">GitHub / 网关登录</span>',a.codeBuddyApiKeyConfigured?'<span class="platform-source-badge source-env">已配 CodeBuddy Key</span>':'<span class="platform-source-badge source-default">未配 CodeBuddy Key</span>'].join('');+ const editing=resetting===a.userId;+ return `<div class="platform-admin-row platform-account-row" data-account-row="${Number(a.userId)}">+ <div class="platform-admin-user">+ <div class="platform-admin-avatar">${userAvatarHTML(a.loginName,100)}</div>+ <div class="platform-admin-info"><span class="platform-admin-name" data-i18n-skip>${escapeHTML(name)}</span><div class="platform-admin-meta">${badges}</div></div>+ </div>+ <div class="platform-admin-actions">${a.password?(editing?`<form class="platform-account-reset" data-reset-form="${Number(a.userId)}"><input name="password" placeholder="新密码,至少 6 位" aria-label="新密码" maxlength="72" autocomplete="new-password" spellcheck="false"><button type="button" class="button ghost small" data-reset-generate>随机</button><button type="submit" class="button primary small">确认重置</button><button type="button" class="button ghost small" data-reset-cancel>取消</button></form>`:`<button type="button" class="button ghost small" data-reset-account="${Number(a.userId)}">重置密码</button>`):'<span class="platform-locked-tag" title="通过 GitHub 或网关登录的账号没有平台密码">无平台密码</span>'}</div>+ </div>`;+ }).join('');+ list.querySelectorAll('[data-reset-account]').forEach(btn=>btn.onclick=()=>{resetting=Number(btn.dataset.resetAccount);render();list.querySelector('[data-reset-form] input')?.focus()});+ const resetForm=list.querySelector('[data-reset-form]');+ if(resetForm){+ resetForm.querySelector('[data-reset-cancel]').onclick=()=>{resetting=null;render()};+ resetForm.querySelector('[data-reset-generate]').onclick=()=>{resetForm.elements.password.value=platformRandomPassword()};+ resetForm.onsubmit=async e=>{+ e.preventDefault();+ const password=resetForm.elements.password.value;+ if(password.length<PLATFORM_ACCOUNT_PASSWORD_MIN)return toast(platformPasswordTooShort(),'err');+ const account=accounts.find(a=>a.userId===resetting);+ resetForm.querySelectorAll('button').forEach(b=>b.disabled=true);+ try{+ await api(`/api/platform/accounts/${encodeURIComponent(resetting)}/password`,{method:'PUT',body:JSON.stringify({password})});+ resetting=null;render();showCreated('reset',account?.loginName||'',password);toast('密码已重置','ok');+ }catch(err){toast(err.message,'err');resetForm.querySelectorAll('button').forEach(b=>b.disabled=false)}+ };+ }+ };+ const load=async()=>{+ try{+ const result=await api('/api/platform/accounts');+ accounts=Array.isArray(result?.accounts)?result.accounts:[];+ const intro=card.querySelector('[data-account-intro]');+ if(intro)intro.textContent=result?.signupEnabled+ ?'登录页目前允许自助注册。也可以在这里直接创建账号,再把登录信息发给同事;同事忘记密码时可以在下面重置。'+ :'登录页的自助注册已关闭,同事的账号要在这里创建:填好用户名和初始密码,点创建,再把登录信息发给对方。忘记密码时可以在下面重置。';+ render();+ }catch(e){list.innerHTML=`<p class="prop-hint">${escapeHTML(e.message||'加载账号失败')}</p>`}+ };+ if(search)search.oninput=()=>{query=search.value.trim();render()};+ form.querySelector('[data-account-generate]').onclick=()=>{form.elements.password.value=platformRandomPassword()};+ form.onsubmit=async e=>{+ e.preventDefault();+ const loginName=form.elements.loginName.value.trim(),password=form.elements.password.value,admin=form.elements.admin.checked;+ if(!/^[A-Za-z0-9][A-Za-z0-9_.-]{1,63}$/.test(loginName))return toast('用户名需 2–64 位,以字母或数字开头,只能包含字母、数字、_ . -','err');+ if(password.length<PLATFORM_ACCOUNT_PASSWORD_MIN)return toast(platformPasswordTooShort(),'err');+ const submit=form.querySelector('button[type="submit"]');if(submit)submit.disabled=true;+ try{+ const account=await api('/api/platform/accounts',{method:'POST',body:JSON.stringify({loginName,password,admin})});+ form.reset();+ accounts=[...accounts.filter(a=>a.userId!==account?.userId),account].filter(Boolean);+ render();showCreated('create',loginName,password);toast('账号已创建','ok');+ if(admin)loadPlatformAdmins(host);+ }catch(err){toast(err.message,'err')}+ finally{if(submit)submit.disabled=false}+ };+ await load();+}+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 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 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=>`<option value="${escapeHTML(id)}">${escapeHTML(sharedModelLabel(id))}</option>`).join(''):'<option value="">请先勾选模型</option>';+ 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=>`<label class="platform-check platform-model-option"><input type="checkbox" value="${escapeHTML(m.id)}"${selected.includes(m.id)?' checked':''}><span>${escapeHTML(m.name&&m.name!==m.id?`${m.name}(${m.id})`:sharedModelLabel(m.id))}</span>${m.credits?`<small>${escapeHTML(m.credits)}</small>`:''}</label>`).join(''):'<p class="prop-hint">这个网络环境暂时没有读到模型列表,可以在下面直接填模型 ID。</p>';+ 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();+ });+ renderDefault();+ };+ const renderLink=()=>{link.href=codeBuddyKeyURL(env.value);link.textContent=`${codeBuddyKeyLinkLabel(env.value)} ↗`};+ 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?'使用旧配置':'未启用';+ 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}`:''}.`));+ }+ else parts.push(lfT('还没有配置共享 Key,没配 Key 的成员需要先配自己的 Key 才能对话和跑 SOP。','No shared key yet; members without their own key must add one before chatting or running SOPs.'));+ 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 syncBootstrap=()=>{+ if(!state.data)return;+ const models=status?.configured?(status.models||[]):(status?.legacySponsor?[status.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:[];+ return result;+ };+ try{+ status=await fetchStatus();+ env.value=status?.internetEnvironment||'';+ selected=status?.configured?[...(status.models||[])]:(status?.legacySponsorModel?[status.legacySponsorModel]:[]);+ renderStatus();renderLink();renderModels();+ }catch(e){+ badge.textContent='加载失败';modelsHost.innerHTML=`<p class="prop-hint">${escapeHTML(e.message||'加载共享 Key 失败')}</p>`;+ return;+ }+ env.onchange=async()=>{+ renderLink();+ modelsHost.innerHTML='<p class="prop-hint">正在读取可用模型…</p>';+ try{await fetchStatus(env.value)}catch(e){catalog=[]}+ renderModels();+ };+ extra.oninput=renderDefault;+ key.oninput=()=>{const text=credentialSecretWarning(credentialKind('codeBuddyApiKey'),key.value);warning.textContent=text;warning.hidden=!text};+ form.onsubmit=async e=>{+ e.preventDefault();+ const models=chosen();+ if(!models.length)return toast('请至少勾选一个允许使用的模型','err');+ if(!status?.configured&&!key.value.trim())return toast('请填写 CodeBuddy API Key','err');+ const first=defaultSelect.value&&models.includes(defaultSelect.value)?defaultSelect.value:models[0];+ const ordered=[first,...models.filter(id=>id!==first)];+ 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})});+ key.value='';warning.hidden=true;extra.value='';selected=[...(status.models||ordered)];+ 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 对话和跑 SOP。确定停用?',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')}+ };+}async function loadPlatformAdmins(host){const list=host.querySelector('#platformAdminList');const form=host.querySelector('#platformAdminForm');@@ -1009,6 +1322,7 @@ async function loadPlatformAdmins(host){if(elLocked)elLocked.textContent=locked;if(elGranted)elGranted.textContent=granted;if(elBadge)elBadge.textContent=`共 ${total} 位管理员`;+ setPlatformTabCount(host,'admins',total);};const render=()=>{diff --git a/web/i18n-en.js b/web/i18n-en.jsindex f38277d4..9005446d 100644--- a/web/i18n-en.js+++ b/web/i18n-en.js@@ -41,3 +41,5 @@ Object.assign(window.LF_I18N_EN,{"了解 LoopForge 能做什么":"Discover whatObject.assign(window.LF_I18N_EN,{"AI 聊天和 Agent 任务需要模型 API Key;下面的脚本体验无需 Key。":"AI chat and Agent tasks need a model API key; the script demo below does not.","项目用来归集需求、SOP 和运行记录。可以直接用体验项目,也可以新建项目,不要求绑定仓库。":"Projects organize requirements, SOPs and runs. Use the demo project or create your own; a repository is not required.","接入 GitHub 代码仓库":"Connect a GitHub repository","分析或修改仓库代码、提交 PR 时再配置仓库和 GitHub Token;聊天、文档生成及无仓库 SOP 可以跳过。":"Configure a repository and GitHub token when analyzing or changing repository code or submitting PRs. Chat, document generation and SOPs without a repository can skip this.","可选":"Optional"});Object.assign(window.LF_I18N_EN,{"按":"Pulls issues from ","当前项目已绑定的 GitHub 仓库":"GitHub repositories bound to this project","拉取 Issue,使用个人设置里的 GitHub 访问令牌。自动同步间隔是平台级配置。":", using the GitHub access token from personal settings. The auto-sync interval is a platform-wide setting.","当前项目还没有绑定 GitHub 仓库,去「项目配置」添加。":"No GitHub repository is bound to this project yet. Add one in Project settings.","建单后按所选 SOP 启动。":"After creation, the selected SOP starts.","保存只改本平台记录,不会回写外部系统。":"Saving only updates this platform record; nothing is written back to external systems.","开启自动同步后,外部同步仍会按间隔把所有已配置来源拉进项目列表。":"With auto-sync on, every configured source is still pulled into the project list at the configured interval.","所有已配置来源":"All configured sources","需求交付明细":"Requirement delivery details","帮我梳理当前项目的待办需求":"Help me review the open requirements in this project","尚未同步。绑定 GitHub 仓库后,可在「需求列表」里点击「同步 GitHub」。":"Not synced yet. After binding a GitHub repository, click \"Sync GitHub\" in Requirements.","请在代码托管平台补充勾选":"; add the missing scopes on your code hosting platform","仓库路径":"Repository path","GitHub 令牌认证":"GitHub token auth","建单后会启动 SOP。":"The SOP starts after creation.","请选择建单方式":"Choose how to create the requirement","点下方「平台需求」":"Click \"Platform requirement\" below","你已确认可以建单。点下方按钮建单并启动 SOP。":"You confirmed it is ready. Use the button below to create it and start the SOP."});+Object.assign(window.LF_I18N_EN,{"给同事开账号":"Create accounts for teammates","填好用户名和初始密码,点创建,再把登录信息发给同事。同事忘记密码时可以在下面重置。":"Enter a login name and an initial password, create the account, then send the sign-in details to your teammate. Reset the password below if they forget it.","登录页目前允许自助注册。也可以在这里直接创建账号,再把登录信息发给同事;同事忘记密码时可以在下面重置。":"Self sign-up is open on the login page. You can also create accounts here and send the sign-in details to your teammate; reset the password below if they forget it.","登录页的自助注册已关闭,同事的账号要在这里创建:填好用户名和初始密码,点创建,再把登录信息发给对方。忘记密码时可以在下面重置。":"Self sign-up is closed, so create teammates' accounts here: enter a login name and an initial password, create the account, then send them the sign-in details. Reset the password below if they forget it.","用户名,如 alice":"Login name, e.g. alice","初始密码,至少 6 位":"Initial password, at least 6 characters","新密码,至少 6 位":"New password, at least 6 characters","随机生成":"Generate","随机":"Generate","创建账号":"Create account","搜索用户名...":"Search login names...","用户名密码":"Password sign-in","GitHub / 网关登录":"GitHub / gateway sign-in","已配 CodeBuddy Key":"Has a CodeBuddy key","未配 CodeBuddy Key":"No CodeBuddy key","无平台密码":"No platform password","通过 GitHub 或网关登录的账号没有平台密码":"Accounts that sign in through GitHub or a gateway have no platform password","重置密码":"Reset password","确认重置":"Reset","没有匹配的账号":"No matching accounts","还没有账号":"No accounts yet","复制登录信息":"Copy sign-in details","已复制登录信息":"Sign-in details copied","账号已创建":"Account created","密码已重置":"Password reset","密码只显示这一次,请现在发给对方。":"The password is shown only once; send it now.","共享 CodeBuddy Key":"Shared CodeBuddy Key","给没配 Key 的成员用":"For members without their own key","成员没配自己的 CodeBuddy API Key 时,对话和 SOP 会用这里的 Key,并且只能用下面勾选的模型。成员配了自己的 Key 就用自己的,不受限制。":"Members without their own CodeBuddy API Key chat and run SOPs on this key, limited to the models checked below. Members with their own key keep using it without limits.","允许使用的模型":"Allowed models","列表里没有的模型":"Models not in the list","模型 ID,多个用逗号分隔":"Model IDs, separated by commas","默认模型":"Default model","请先勾选模型":"Check a model first","正在读取可用模型…":"Loading available models…","这个网络环境暂时没有读到模型列表,可以在下面直接填模型 ID。":"No model list was found for this network environment yet; enter model IDs below.","ck_ 开头的 CodeBuddy API Key":"CodeBuddy API Key starting with ck_","已配置,留空保持不变":"Configured; leave blank to keep it","停用共享 Key":"Stop sharing the key","使用旧配置":"Legacy setting","共享 Key 已保存":"Shared key saved","共享 Key 已停用":"Shared key turned off","还没有配置共享 Key,没配 Key 的成员需要先配自己的 Key 才能对话和跑 SOP。":"No shared key yet; members without their own key must add one before chatting or running SOPs.","停用后,没配自己 Key 的成员将不能再用共享 Key 对话和跑 SOP。确定停用?":"Members without their own key will no longer chat or run SOPs on the shared key. Turn it off?","请至少勾选一个允许使用的模型":"Check at least one allowed model","请填写 CodeBuddy API Key":"Enter the CodeBuddy API Key","平台管理分区":"Platform admin sections","没指定模型时用它;SOP 角色的模型不在允许范围内时也改用它。":"Used when no model is chosen, and for SOP roles whose model is not allowed."});+Object.assign(window.LF_I18N_EN,{"统计":"Usage","切换项目":"Switch project","/ Agent 原生研发协作平台":"/ Agent-native delivery platform","全局导航":"Main navigation","展开导航":"Expand navigation","收起导航":"Collapse navigation","返回首页":"Back to home","展开设置导航":"Expand settings navigation","收起设置导航":"Collapse settings navigation","个人配置":"Personal settings","个人配置与模型":"Personal settings & models","个人信息与操作":"Profile & actions","点击查看个人信息":"Click to view your profile","认证换票未通过":"Sign-in token exchange failed","当前为访客身份":"Browsing as a guest","搜索任务…":"Search tasks…","搜索任务":"Search tasks","任务状态筛选":"Filter tasks by status","任务责任人筛选":"Filter tasks by assignee","我负责的":"Assigned to me","待处理 / 暂停":"Pending / paused","拖动调整侧栏宽度,双击恢复默认":"Drag to resize the sidebar; double-click to reset","调整侧栏宽度":"Resize sidebar","平台集成":"Platform integrations","代码仓库与统一认证":"Code repositories & sign-in","AI 对话与编码 CLI":"AI chat & coding CLIs","仓库授权":"Repository access","推荐凭证已全部就绪":"All recommended credentials are ready","克隆私有仓库、创建任务分支、推送交付产物":"Clone private repositories, create task branches, push deliverables","AI 对话与 SOP 的 CodeBuddy 执行器":"AI chat and the CodeBuddy executor in SOPs","AI 对话(含 Claude、GPT 等模型)和 SOP 的 CodeBuddy 执行器都使用它;网络环境按账号所在环境配置。":"Used by AI chat (including Claude, GPT and other models) and by the CodeBuddy executor in SOPs. Pick the network environment your account belongs to.","AI 对话选择 Codex 执行器,以及以 Codex 运行的 SOP 节点":"AI chat with the Codex executor, and SOP steps that run on Codex","AI 对话选择 Claude 执行器,以及以 Claude Code 运行的 SOP 节点":"AI chat with the Claude executor, and SOP steps that run on Claude Code","筛选凭证":"Filter credentials","添加凭证":"Add credential","SOP 使用需求责任人(未指定时为项目 Owner)的个人凭证,保存后对下一次任务生效。":"SOPs use the personal credentials of the requirement owner (the project owner when none is set). Changes apply from the next task.","GitHub 仓库(已绑定)":"GitHub repository (bound)","需由责任人本人在个人配置中配置":"The owner has to set this in their own Personal settings","最小接入配置需要绑定到你的账号:执行器 API Key 和 GitHub Git Token 保存在个人配置里;也可以绑定本机 CLI。":"The minimal setup is tied to your account: the executor API key and GitHub Git token are stored in Personal settings. You can also connect a local CLI.","个人配置 · 一次配齐":"Personal settings · all in one place","打开个人配置 →":"Open Personal settings →","CodeBuddy 使用个人配置中保存的 API Key":"CodeBuddy uses the API key saved in Personal settings","到个人配置补充 CodeBuddy API Key":"Add a CodeBuddy API key in Personal settings","到个人配置补充 Codex API Key":"Add a Codex API key in Personal settings","到个人配置补充 Claude Code API Key":"Add a Claude Code API key in Personal settings","将使用个人配置中的 API 凭证":"The API credentials in Personal settings will be used","已切换;请先到个人配置补充该 CLI 的 API Key":"Switched. Add this CLI's API key in Personal settings first","当前以访客身份访问平台。登录后可在左侧「个人配置」配置 GitHub Git Token 和 CodeBuddy API Key。":"You are browsing as a guest. After signing in, set your GitHub Git token and CodeBuddy API key under “Personal settings” on the left.","连接后可选择自己的仓库;公开仓库也可直接填写地址。访问令牌可在个人配置中设置。":"Once connected you can pick your own repositories; public repositories can also be entered by URL. The access token is set in Personal settings.","去个人配置配置":"Set it in Personal settings","使用项目已绑定的仓库。访问私有仓库或推送代码时需要在个人配置中配置 GitHub Token;未绑定仓库时可在任务工作区直接运行。":"Uses the repositories bound to the project. Private repositories and pushing code need a GitHub token in Personal settings; without a bound repository the run works directly in the task workspace.","请检查个人配置中的 CodeBuddy API Key 配置或网络状态后重新评测。":"Check the CodeBuddy API key in Personal settings and your network, then run the evaluation again.","请先在个人配置中配置自己的 CodeBuddy API Key":"Set your own CodeBuddy API key in Personal settings first","请先配置个人 CodeBuddy API Key":"Set your personal CodeBuddy API key first","未配置个人 CodeBuddy API Key 时只能使用平台管理员允许的模型":"Without a personal CodeBuddy API key you can only use the models a platform admin allowed","要使用其他模型,请先在个人配置中配置自己的 CodeBuddy API Key":"To use other models, set your own CodeBuddy API key in Personal settings first"});diff --git a/web/platform.css b/web/platform.cssindex 22116ce4..8584f123 100644--- a/web/platform.css+++ b/web/platform.css@@ -1511,14 +1511,81 @@ textarea.pa-input{height:auto;min-height:76px;padding:9px 11px;resize:vertical;l}.platform-audit-note svg{flex-shrink:0}+/* 平台管理 tab:成员账号 / 平台管理员 / 共享 CodeBuddy Key */+.platform-tabs-wrap{margin-top:0}+.platform-tabs .pa-tab{font-size:14px}+.platform-tabs .pa-tab.on{font-weight:650}+.platform-tabs .pa-tab.on::after{content:'';position:absolute;left:8px;right:8px;bottom:0;height:2px;border-radius:2px;background:var(--blue)}+.platform-tabs .pa-tab-n[hidden],.platform-tab-state[hidden]{display:none}+.platform-tab-state{width:7px;height:7px;border-radius:50%;background:var(--muted-2)}+.platform-tab-state.is-on{background:var(--hui-success,var(--green))}+.platform-tab-state.is-legacy{background:var(--hui-warn,var(--amber))}+.platform-tab-panel{display:flex;flex-direction:column;gap:22px;min-width:0}+.platform-tab-panel[hidden]{display:none}+.platform-status-pill.is-on{background:color-mix(in srgb,var(--hui-success,var(--green)) 10%,transparent);color:var(--hui-success,var(--green));border-color:color-mix(in srgb,var(--hui-success,var(--green)) 28%,transparent)}+.platform-status-pill.is-legacy{background:color-mix(in srgb,var(--hui-warn,var(--amber)) 10%,transparent);color:var(--hui-warn,var(--amber));border-color:color-mix(in srgb,var(--hui-warn,var(--amber)) 28%,transparent)}+.platform-status-pill.is-off{background:var(--bg-soft);color:var(--muted);border-color:var(--line)}++.platform-account-create{display:flex;flex-direction:column;gap:12px;padding:14px;border:1px solid var(--line);border-radius:12px;background:var(--bg-soft)}+.platform-account-form{display:flex;flex-wrap:wrap;gap:10px 14px;align-items:center}+.platform-account-form .platform-input-wrap{flex:1 1 160px;min-width:0}+.platform-account-form .platform-input-wrap+.platform-input-wrap{flex:1.4 1 240px}+.platform-account-form .platform-input-wrap input{min-width:0}+.platform-account-form .platform-check{flex:none}+.platform-account-form .platform-add-btn{flex:none;margin-left:auto}+.platform-input-wrap .button.small{flex:none;padding:4px 9px;font-size:12px}+.platform-check{display:inline-flex;align-items:center;gap:7px;font-size:13px;color:var(--text);cursor:pointer;white-space:nowrap}+.platform-check input{margin:0;accent-color:var(--blue)}+.platform-account-search{max-width:320px}+.platform-account-list{max-height:560px;overflow:auto;padding-right:2px}+.platform-account-row .platform-admin-meta{flex-wrap:wrap;gap:6px}+.platform-account-row:hover{transform:none}+.platform-account-reset{display:flex;gap:6px;align-items:center}+.platform-account-reset input{width:170px;padding:6px 10px;border:1px solid var(--line-strong);border-radius:8px;background:var(--panel);color:var(--text);font-size:12.5px}+.platform-note{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:10px 12px;border:1px solid var(--line);border-radius:10px;background:var(--bg-soft);color:var(--muted);font-size:12.5px;line-height:1.6}+.platform-note[hidden]{display:none}+.platform-note code{font-family:var(--mono);padding:1px 6px;border-radius:5px;background:var(--panel);border:1px solid var(--line);color:var(--text);user-select:all}+.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-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}+.platform-field-group{display:flex;flex-direction:column;gap:6px}+.platform-field{display:flex;flex-direction:column;gap:6px;margin:0;font-size:12.5px;color:var(--muted)}+.platform-field>span,.platform-field-head>span{font-weight:650;color:var(--text)}+.platform-field-head{display:flex;align-items:baseline;justify-content:space-between;gap:12px}+.platform-field-head small{color:var(--muted-2);font-size:12px}+.platform-field-hint{color:var(--muted-2);font-size:12px;line-height:1.5}+.platform-field input,.platform-field select{width:100%;box-sizing:border-box;padding:9px 12px;border:1px solid var(--line-strong);border-radius:10px;background:var(--panel);color:var(--text);font-size:13px}+.platform-field input:focus,.platform-field select:focus{outline:none;border-color:var(--blue);box-shadow:0 0 0 3px color-mix(in srgb,var(--blue) 18%,transparent)}+.platform-shared-key-link{align-self:flex-start;font-size:12px;color:var(--blue);text-decoration:none}+.platform-shared-key-link:hover{text-decoration:underline}+.platform-model-list{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:2px 12px;max-height:288px;overflow:auto;padding:8px;border:1px solid var(--line);border-radius:10px;background:var(--bg-soft)}+.platform-model-list .prop-hint{grid-column:1/-1;margin:4px;padding:0}+.platform-model-option{white-space:normal;align-items:flex-start;padding:6px 8px;border-radius:7px;font-size:12.5px;transition:background .15s}+.platform-model-option:hover{background:var(--panel)}+.platform-model-option input{margin-top:2px}+.platform-model-option span{min-width:0;overflow-wrap:anywhere}+.platform-model-option small{margin-left:auto;color:var(--muted-2);font-size:11px;white-space:nowrap}+.platform-shared-key-footer{display:flex;align-items:center;justify-content:space-between;gap:16px;padding-top:16px;border-top:1px solid var(--line)}+.platform-shared-key-actions{display:flex;gap:10px;align-items:center;flex:none}+.platform-shared-key-form .platform-add-hint{margin:0;font-size:12.5px;line-height:1.55}+@media(max-width:1280px){.platform-metric-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(max-width:1080px){.platform-admin-layout{grid-template-columns:1fr}+ .platform-shared-key-grid{grid-template-columns:1fr}}@media(max-width:640px){.platform-metric-grid{grid-template-columns:1fr}+ .platform-account-form .platform-input-wrap{flex-basis:100%}+ .platform-shared-key-footer{flex-direction:column;align-items:stretch}+ .platform-shared-key-actions{justify-content:flex-end}+ .platform-account-row{flex-direction:column;align-items:stretch}+ .platform-account-reset{flex-wrap:wrap}.platform-admin-head{flex-direction:column;align-items:stretch}.platform-admin-form{flex-direction:column;align-items:stretch}.platform-list-toolbar{flex-direction:column;align-items:stretch}diff --git a/web/syntax_test.go b/web/syntax_test.goindex b8ad216c..1d035b5b 100644--- a/web/syntax_test.go+++ b/web/syntax_test.go@@ -833,8 +833,12 @@ assert.ok(credentialExtraError(cred.kind('codexApiKey'), 'ftp://proxy'));assert.equal(credentialExtraError(cred.kind('codexApiKey'), ''), '');// CodeBuddy: the network environment is a fixed choice and the key link follows it.-assert.deepEqual(['', 'public', 'INTL', ' iOA ', 'internal', '国内站', 'china'].map(v => codeBuddyEnvironment(v)?.value), ['', '', '', 'ioa', 'internal', 'internal', 'internal']);-assert.equal(codeBuddyEnvironment('private-net'), null);+// The CLI gets the stored text as-is, so only exact values are recognized; aliases only guess what an old value meant.+assert.deepEqual(['', ' internal ', 'ioa'].map(v => codeBuddyEnvironment(v)?.value), ['', 'internal', 'ioa']);+assert.deepEqual(['public', 'INTL', 'iOA', '国内站', 'china', 'cn', 'private-net'].map(v => codeBuddyEnvironment(v)), [null, null, null, null, null, null, null]);+assert.deepEqual(['', 'public', 'INTL', ' iOA ', 'internal', '国内站', 'china'].map(v => codeBuddyEnvironmentIntent(v)?.value), ['', '', '', 'ioa', 'internal', 'internal', 'internal']);+assert.equal(codeBuddyEnvironmentIntent('private-net'), null);+assert.deepEqual(['', 'internal', 'china', 'iOA', 'private-net'].map(codeBuddyEnvironmentLegacy), [false, false, true, true, true]);assert.equal(codeBuddyKeyURL(''), 'https://www.codebuddy.ai/profile/keys');assert.equal(codeBuddyKeyURL('internal'), 'https://copilot.tencent.com/profile/');assert.equal(codeBuddyKeyURL('ioa'), 'https://tencent.sso.copilot.tencent.com/profile/keys');@@ -851,6 +855,11 @@ const legacyEditor = credentialEditorHTML(cbKind, {codeBuddyApiKeyConfigured: trassert.ok(legacyEditor.includes('data-original=""') && legacyEditor.includes('<option value="" selected>') && legacyEditor.includes('「private-net」无法识别'));assert.ok(legacyEditor.includes('data-legacy="true"') && !legacyEditor.includes('data-credential-act="save" disabled'), 'a legacy value can be saved as 国际站 without retyping the key');assert.ok(!cbEditor.includes('data-legacy') && cbEditor.includes('data-credential-act="save" disabled'));+// An old alias preselects what it meant and stays savable: the CLI would otherwise keep connecting to 国际站.+const chinaEditor = credentialEditorHTML(cbKind, {codeBuddyApiKeyConfigured: true, codeBuddyInternetEnvironment: 'china'});+assert.ok(chinaEditor.includes('data-original="internal"') && chinaEditor.includes('<option value="internal" selected>') && chinaEditor.includes('「china」无法识别'));+assert.ok(chinaEditor.includes('data-legacy="true"') && !chinaEditor.includes('data-credential-act="save" disabled'));+assert.ok(credentialSubline(cbKind, {codeBuddyApiKeyConfigured: true, codeBuddyInternetEnvironment: 'china'}).includes('「china」无法识别'));assert.ok(credentialSubline(cbKind, {codeBuddyApiKeyConfigured: true, codeBuddyInternetEnvironment: 'ioa'}).includes('>iOA<'));assert.ok(credentialSubline(cbKind, {codeBuddyApiKeyConfigured: true}).includes('>国际站<'));assert.ok(credentialSubline(cbKind, {codeBuddyApiKeyConfigured: true, codeBuddyInternetEnvironment: 'private-net'}).includes('无法识别'));diff --git a/webtest/tests/i18n-navigation.test.mjs b/webtest/tests/i18n-navigation.test.mjsnew file mode 100644index 00000000..a731dd2e--- /dev/null+++ b/webtest/tests/i18n-navigation.test.mjs@@ -0,0 +1,80 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { readFile } from 'node:fs/promises';+import path from 'node:path';+import vm from 'node:vm';+import { JSDOM } from 'jsdom';+import { loadApp, WEB_ROOT } from '../lib/load-app.mjs';++const HAN = /[\u3400-\u9fff]/;+const ATTRS = ['placeholder', 'title', 'aria-label', 'data-tip', 'data-tooltip'];++// A page in English mode: i18n.js rewrites the Chinese copy with i18n-en.js.+async function englishPage(html) {+ const dom = new JSDOM(html.replace('<html', '<html data-lang="en"'), { runScripts: 'outside-only', url: 'http://127.0.0.1/' });+ for (const file of ['i18n-en.js', 'i18n.js']) {+ new vm.Script(await readFile(path.join(WEB_ROOT, file), 'utf8'), { filename: file }).runInContext(dom.getInternalVMContext());+ }+ return dom.window;+}++function leftoverChinese(roots) {+ const left = [];+ for (const root of roots) {+ for (const el of [root, ...root.querySelectorAll('*')]) {+ if (el.closest('[data-i18n-skip]')) continue;+ for (const node of el.childNodes) if (node.nodeType === 3 && HAN.test(node.nodeValue)) left.push(node.nodeValue.trim());+ for (const name of ATTRS) {+ const value = el.getAttribute(name);+ if (value && HAN.test(value)) left.push(`${name}="${value}"`);+ }+ }+ }+ return left;+}++test('English mode leaves no Chinese in the navigation, the top bar or the 个人配置 heading', async () => {+ const window = await englishPage(await readFile(path.join(WEB_ROOT, 'index.html'), 'utf8'));+ const { document } = window;+ const roots = [...document.querySelectorAll('#platformRail, #settingsSidebar, .topbar, #settingsView .page-heading')];+ assert.equal(roots.length, 4);+ assert.deepEqual(leftoverChinese(roots), []);+ assert.equal(document.querySelector('#settingsSidebar [data-view="settings"] .nav-label').textContent, 'Personal settings');+ assert.equal(document.querySelector('#platformRail [data-view="observability"]').dataset.tooltip, 'Usage');+ window.close();+});++test('English mode translates every page title and the copy the app renders into the navigation', async (t) => {+ const app = await loadApp({ dispatchReady: false });+ t.after(app.close);+ const window = await englishPage('<html><body></body></html>');+ const titles = app.evaluate('viewTitles()');+ const untranslated = Object.entries(titles).filter(([, zh]) => HAN.test(window.lfTranslate(zh)));+ assert.deepEqual(untranslated, []);+ for (const text of ['收起设置导航', '展开设置导航', '收起导航', '展开导航', '返回首页', '拖动调整侧栏宽度,双击恢复默认', '调整侧栏宽度',+ 'alice (alice) · 点击查看个人信息', '当前为访客身份 · 点击查看个人信息', '认证换票未通过 · 点击查看个人信息']) {+ assert.doesNotMatch(window.lfTranslate(text), HAN, text);+ }+ window.close();+});++test('English mode translates the 个人配置 credential panel and the hints that point to it', async (t) => {+ const app = await loadApp({ dispatchReady: false });+ t.after(app.close);+ const window = await englishPage('<html><body></body></html>');+ const panel = window.document.createElement('div');+ panel.innerHTML = app.evaluate('credentialPanelHTML({})');+ window.document.body.append(panel);+ await new Promise((resolve) => window.setTimeout(resolve, 0));+ assert.deepEqual(leftoverChinese([panel]), []);+ for (const text of ['需由责任人本人在个人配置中配置', '个人配置 · 一次配齐', '打开个人配置 →', 'CodeBuddy 使用个人配置中保存的 API Key',+ '到个人配置补充 Codex API Key', '将使用个人配置中的 API 凭证', '已切换;请先到个人配置补充该 CLI 的 API Key', '去个人配置配置',+ '请先在个人配置中配置自己的 CodeBuddy API Key', '请先配置个人 CodeBuddy API Key',+ // The shared-key refusal lists the allowed models, so only its two sentences are in the dictionary.+ '未配置个人 CodeBuddy API Key 时只能使用平台管理员允许的模型(glm-5.1、kimi-k2.6)。要使用其他模型,请先在个人配置中配置自己的 CodeBuddy API Key']) {+ assert.doesNotMatch(window.lfTranslate(text), HAN, text);+ }+ assert.equal(window.lfTranslate('未配置个人 CodeBuddy API Key 时只能使用平台管理员允许的模型(glm-5.1、kimi-k2.6)。要使用其他模型,请先在个人配置中配置自己的 CodeBuddy API Key'),+ 'Without a personal CodeBuddy API key you can only use the models a platform admin allowed (glm-5.1, kimi-k2.6). To use other models, set your own CodeBuddy API key in Personal settings first');+ window.close();+});diff --git a/webtest/tests/platform-admin.test.mjs b/webtest/tests/platform-admin.test.mjsindex 38abaac4..2d4e85e7 100644--- a/webtest/tests/platform-admin.test.mjs+++ b/webtest/tests/platform-admin.test.mjs@@ -42,3 +42,175 @@ test('platform admin panel loads metrics, searches, filters, grants, revokes, anhost.querySelector('[data-platform-nav="agents"]')?.click();assert.equal(app.evaluate(`state.currentView`), 'agents');});++test('platform admin page splits accounts, admins and the shared key into tabs', async (t) => {+ const app = await loadApp();+ t.after(app.close);+ 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.evaluate(`renderPlatformAdminPanel()`);+ await settle(8);+ const host = app.document.querySelector('#platformAdminPanel');+ const panel = (id) => host.querySelector(`[data-platform-panel="${id}"]`);+ const tab = (id) => host.querySelector(`[data-platform-tab="${id}"]`);+ const shown = () => ['accounts', 'admins', 'sharedKey'].filter((id) => !panel(id).hidden);++ assert.deepEqual(shown(), ['accounts'], 'accounts open first');+ assert.equal(tab('accounts').getAttribute('aria-selected'), 'true');+ assert.equal(tab('accounts').querySelector('[data-platform-tab-count]').textContent, '3');+ assert.equal(tab('admins').querySelector('[data-platform-tab-count]').textContent, '1');+ assert.match(tab('sharedKey').querySelector('[data-platform-tab-state]').className, /is-on/);+ assert.ok(host.querySelector('[data-shared-key-badge]').classList.contains('is-on'));+ assert.match(host.querySelector('[data-shared-models-count]').textContent, /已选 1 个/);++ tab('sharedKey').click();+ assert.deepEqual(shown(), ['sharedKey']);+ assert.equal(tab('accounts').getAttribute('aria-selected'), 'false');+ host.querySelector('#platformTabs').dispatchEvent(new app.window.KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true }));+ assert.deepEqual(shown(), ['accounts'], 'arrow keys wrap around');+ host.querySelector('#platformTabs').dispatchEvent(new app.window.KeyboardEvent('keydown', { key: 'ArrowRight', bubbles: true }));+ assert.deepEqual(shown(), ['admins']);+ assert.ok(panel('admins').querySelector('.platform-metric-grid'), 'admin metrics live in the admins tab');++ app.evaluate(`renderPlatformAdminPanel()`);+ await settle(6);+ assert.deepEqual(shown(), ['admins'], 'the open tab survives a re-render');+});++test('platform admins create accounts and reset passwords from the page', async (t) => {+ const app = await loadApp();+ t.after(app.close);+ app.evaluate(`state.currentUser={...state.data.users[0],isGuest:false,isPlatformAdmin:true}`);+ const accounts = [+ { userId: 1, loginName: 'owner', admin: true, password: true, codeBuddyApiKeyConfigured: true },+ { userId: 2, loginName: 'octocat', admin: false, password: false, codeBuddyApiKeyConfigured: false },+ ];+ app.router.get('/api/platform/admins', []);+ app.router.get('/api/platform/accounts', { accounts, signupEnabled: false });+ app.router.post('/api/platform/accounts', (call) => ({ status: 201, body: { userId: 3, loginName: call.body.loginName, admin: call.body.admin, password: true, codeBuddyApiKeyConfigured: false } }));+ app.router.put('/api/platform/accounts/3/password', { userId: 3, loginName: 'alice', password: true });+ app.evaluate(`renderPlatformAdminPanel()`);+ await settle(8);+ const card = app.document.querySelector('#platformAccountsCard');+ assert.match(card.textContent, /自助注册已关闭/);+ assert.match(card.textContent, /共 2 个账号/);+ assert.ok(card.querySelector('[data-reset-account="1"]'), 'password accounts can be reset');+ assert.ok(!card.querySelector('[data-reset-account="2"]'), 'GitHub accounts have no platform password');+ assert.match(card.querySelector('[data-account-row="2"]').textContent, /无平台密码/);++ const form = card.querySelector('#platformAccountForm');+ form.elements.loginName.value = 'x';+ form.elements.password.value = 'secret-123';+ form.dispatchEvent(new app.window.Event('submit', { bubbles: true, cancelable: true }));+ await settle(4);+ assert.equal(app.router.calls.filter((call) => call.method === 'POST').length, 0, 'an invalid login is rejected before sending');++ form.elements.loginName.value = 'alice';+ card.querySelector('[data-account-generate]').click();+ const generated = form.elements.password.value;+ assert.match(generated, /^[A-Za-z0-9]{14}$/);+ form.dispatchEvent(new app.window.Event('submit', { bubbles: true, cancelable: true }));+ await settle(6);+ const created = app.router.calls.find((call) => call.method === 'POST' && call.path === '/api/platform/accounts');+ assert.deepEqual(created.body, { loginName: 'alice', password: generated, admin: false });+ assert.match(card.textContent, /共 3 个账号/);+ const note = card.querySelector('[data-account-created]');+ assert.equal(note.hidden, false);+ assert.match(note.textContent, /已创建账号 alice/);+ assert.equal(note.querySelector('code').textContent, generated);+ assert.equal(form.elements.loginName.value, '', 'the form clears after creating');++ card.querySelector('[data-reset-account="3"]').click();+ const reset = card.querySelector('[data-reset-form="3"]');+ reset.elements.password.value = 'second-pass';+ reset.dispatchEvent(new app.window.Event('submit', { bubbles: true, cancelable: true }));+ await settle(6);+ const resetCall = app.router.calls.find((call) => call.path === '/api/platform/accounts/3/password');+ assert.deepEqual(resetCall.body, { password: 'second-pass' });+ assert.match(note.textContent, /已重置账号 alice/);+ assert.ok(!card.querySelector('[data-reset-form]'), 'the inline reset closes');++ const search = card.querySelector('[data-account-search]');+ search.value = 'octo';+ search.dispatchEvent(new app.window.Event('input', { bubbles: true }));+ assert.equal(card.querySelectorAll('[data-account-row]').length, 1);+});++test('platform admins share a CodeBuddy key 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}`);+ const catalogs = {+ '': [{ 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' };+ 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.put('/api/platform/codebuddy-key', (call) => {+ saved = { ...saved, configured: true, internetEnvironment: call.body.internetEnvironment, models: call.body.models, updatedBy: 'owner' };+ return saved;+ });+ app.router.delete('/api/platform/codebuddy-key', () => {+ saved = { ...saved, configured: false, models: [] };+ return saved;+ });+ app.evaluate(`renderPlatformAdminPanel()`);+ await settle(8);+ const card = app.document.querySelector('#platformSharedKeyCard');+ const form = card.querySelector('#platformSharedKeyForm');+ assert.match(card.querySelector('[data-shared-key-badge]').textContent, /使用旧配置/);+ assert.match(card.querySelector('[data-shared-key-meta]').textContent, /AGENTFLOW_ASSISTANT_SPONSOR_LOGIN.*sponsor/);+ 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);++ 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 }));+ 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']);+ form.elements.defaultModel.value = 'glm-5.1';++ 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, 0, 'a first save needs the key');++ form.elements.apiKey.value = 'sk-third-party';+ form.elements.apiKey.dispatchEvent(new app.window.Event('input', { bubbles: true }));+ assert.equal(card.querySelector('[data-shared-key-warning]').hidden, false);+ form.elements.apiKey.value = 'ck_shared';+ form.elements.apiKey.dispatchEvent(new app.window.Event('input', { bubbles: true }));+ 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'] });+ 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');++ 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.match(card.querySelector('[data-shared-key-badge]').textContent, /使用旧配置/);+ assert.equal(app.evaluate(`state.data.sponsoredModel`), 'deepseek-v4.1-flash');+});diff --git a/webtest/tests/workbench-credentials.test.mjs b/webtest/tests/workbench-credentials.test.mjsindex c0c13550..eefdbb57 100644--- a/webtest/tests/workbench-credentials.test.mjs+++ b/webtest/tests/workbench-credentials.test.mjs@@ -122,6 +122,31 @@ test('CodeBuddy inline editor changes only the network environment and keeps theassert.deepEqual(saved.body, { codeBuddyApiKey: '', codeBuddyInternetEnvironment: '' });});+test('CodeBuddy inline editor rewrites an old china value to internal without retyping the key', async (t) => {+ const app = await loadApp();+ t.after(app.close);+ app.evaluate(`+ state.data.users[0].id=1;+ state.currentUser={...state.data.users[0],id:1,isGuest:false,codeBuddyApiKeyConfigured:true,codeBuddyInternetEnvironment:'china'};+ state.data.users[0]=state.currentUser;+ `);+ app.router.put('/api/users/1/credentials', { id: 1, username: 'tester', codeBuddyApiKeyConfigured: true, codeBuddyInternetEnvironment: 'internal' });+ await app.evaluate(`renderPersonalSettings()`);+ const row = () => app.document.querySelector('[data-credential-row="codeBuddyApiKey"]');+ assert.match(row().querySelector('.credential-row-who small').textContent, /「china」无法识别/);+ row().querySelector('.credential-row-main').click();+ const select = row().querySelector('select[name="extra"]');+ const save = row().querySelector('[data-credential-act="save"]');+ assert.equal(select.value, 'internal', 'the old value preselects what it meant');+ assert.equal(save.disabled, false, 'the stored text still needs rewriting, so saving is allowed as shown');+ assert.match(row().querySelector('[data-credential-env-hint]').textContent, /「china」无法识别/);+ save.click();+ await settle(6);+ const saved = app.router.calls.find((call) => call.path === '/api/users/1/credentials');+ assert.deepEqual(saved.body, { codeBuddyApiKey: '', codeBuddyInternetEnvironment: 'internal' });+ assert.match(row().querySelector('.credential-row-who small').textContent, /网络环境国内站/);+});+test('credential panel filters, expands, validates, reveals secrets, and confirms deletion', async (t) => {const app = await loadApp();t.after(app.close);