Skip to content

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.

fix: pick the CodeBuddy network environment from a list and link to its key page (#108)

Robert0622ce0116d0cfe4
diff --git a/chatbot/src/QuickAccessWizard.jsx b/chatbot/src/QuickAccessWizard.jsx
index 5065a113..a693740f 100644
--- a/chatbot/src/QuickAccessWizard.jsx
+++ b/chatbot/src/QuickAccessWizard.jsx
@@ -12,7 +12,13 @@ import HarnessIcon from "./HarnessIcon";
import SlidingTabs from "./SlidingTabs";
import { api, canChatInProject, write } from "./api";
import { usePanelPresence } from "./usePanelPresence";
-import { openCredentialSettings } from "./credentials";
+import {
+ CODEBUDDY_ENVIRONMENTS,
+ codeBuddyEnvironment,
+ codeBuddyKeyURL,
+ codeBuddyKeyWarning,
+ openCredentialSettings,
+} from "./credentials";
import "./quick-access-wizard.css";
const DEFAULT_SOP_ID = "generic-backend-delivery";
@@ -759,6 +765,8 @@ export default function QuickAccessWizard({
const [error, setError] = useState("");
const [gitToken, setGitToken] = useState("");
const [codeBuddyApiKey, setCodeBuddyApiKey] = useState("");
+ // null follows the saved setting until the user picks an environment here.
+ const [codeBuddyEnvChoice, setCodeBuddyEnvChoice] = useState(null);
const [verifyingGit, setVerifyingGit] = useState(false);
const [gitVerify, setGitVerify] = useState(null);
const [projectMode, setProjectMode] = useState("existing");
@@ -904,6 +912,7 @@ export default function QuickAccessWizard({
setError("");
setGitToken("");
setCodeBuddyApiKey("");
+ setCodeBuddyEnvChoice(null);
setGitVerify(null);
setCompletedSummary(null);
setBindRepoNow(true);
@@ -1117,6 +1126,12 @@ export default function QuickAccessWizard({
const codeBuddyReady = Boolean(
storedUser?.codeBuddyApiKeyConfigured || codeBuddyApiKey.trim(),
);
+ const storedCodeBuddyEnv =
+ codeBuddyEnvironment(storedUser?.codeBuddyInternetEnvironment)?.value ?? "";
+ const codeBuddyEnv = codeBuddyEnvChoice ?? storedCodeBuddyEnv;
+ const codeBuddyEnvInfo =
+ codeBuddyEnvironment(codeBuddyEnv) || CODEBUDDY_ENVIRONMENTS[0];
+ const codeBuddyWarning = codeBuddyKeyWarning(codeBuddyApiKey);
const nodes =
activeWorkflow?.nodes?.filter((node) => node.type === "agent") ||
FALLBACK_NODES;
@@ -1133,6 +1148,9 @@ export default function QuickAccessWizard({
if (gitToken.trim()) payload.gitToken = gitToken.trim();
if (codeBuddyApiKey.trim())
payload.codeBuddyApiKey = codeBuddyApiKey.trim();
+ // A key is always saved with the environment it was issued for.
+ if (codeBuddyApiKey.trim() || codeBuddyEnv !== storedCodeBuddyEnv)
+ payload.codeBuddyInternetEnvironment = codeBuddyEnv;
if (!Object.keys(payload).length) return storedUser;
const saved = await write(
`/api/users/${encodeURIComponent(user.id)}/credentials`,
@@ -1140,9 +1158,14 @@ export default function QuickAccessWizard({
"PUT",
);
const merged = { ...storedUser, ...saved };
+ // The server omits an empty environment, so 国际站 must overwrite the old value here.
+ if ("codeBuddyInternetEnvironment" in payload)
+ merged.codeBuddyInternetEnvironment =
+ saved?.codeBuddyInternetEnvironment || "";
setStoredUser(merged);
setGitToken("");
setCodeBuddyApiKey("");
+ setCodeBuddyEnvChoice(null);
window.parent !== window &&
window.parent.postMessage(
{ type: "agentflow-credentials-changed" },
@@ -1788,6 +1811,19 @@ export default function QuickAccessWizard({
<StatusPill ok={codeBuddyReady} />
</header>
<div className="qa-cred-body">
+ <div className="qa-field">
+ <span className="qa-label">网络环境</span>
+ <HarnessSelect
+ value={codeBuddyEnv}
+ options={CODEBUDDY_ENVIRONMENTS.map((env) => ({
+ value: env.value,
+ label: env.label,
+ hint: env.site,
+ }))}
+ onChange={setCodeBuddyEnvChoice}
+ ariaLabel="CodeBuddy 网络环境"
+ />
+ </div>
<div className="qa-input-row">
<input
type="password"
@@ -1801,18 +1837,26 @@ export default function QuickAccessWizard({
? "已配置,留空保持不变"
: "粘贴 CodeBuddy API Key"
}
+ aria-label="CodeBuddy API Key"
autoComplete="new-password"
/>
<a
className="qa-link"
data-hover-ink-control=""
- href="https://www.codebuddy.ai/"
+ href={codeBuddyKeyURL(codeBuddyEnv)}
target="_blank"
rel="noopener noreferrer"
>
获取 API Key ↗
</a>
</div>
+ <p
+ className={`qa-hint${codeBuddyWarning ? " is-warn" : ""}`}
+ role="status"
+ >
+ {codeBuddyWarning ||
+ `Key 只能在创建它的站点使用:当前选择${codeBuddyEnvInfo.label}(${codeBuddyEnvInfo.site}),「获取 API Key」会打开该站点的密钥页。`}
+ </p>
</div>
</section>
</div>
diff --git a/chatbot/src/RunAlerts.jsx b/chatbot/src/RunAlerts.jsx
index 50461c4c..e9f9c9b0 100644
--- a/chatbot/src/RunAlerts.jsx
+++ b/chatbot/src/RunAlerts.jsx
@@ -9,7 +9,7 @@ import React, {
import { api } from "./api";
import HarnessIcon from "./HarnessIcon";
import {
- CREDENTIAL_GUIDES,
+ credentialGuide,
credentialHint,
openCredentialSettings,
} from "./credentials";
@@ -160,10 +160,15 @@ function RunAlert({
const { run } = item;
const failed = item.kind === "failed";
const hint = credentialHint(item.reason);
- const guide = hint ? CREDENTIAL_GUIDES[hint.field] : null;
const ownerId = run.executionContext?.responsibleUserId;
const mine = !ownerId || ownerId === user?.id;
const owner = users.find((u) => u.id === ownerId);
+ const guide = hint
+ ? credentialGuide(
+ hint.field,
+ mine ? users.find((u) => u.id === user?.id) || user : owner,
+ )
+ : null;
const ownerName =
owner?.chineseName || owner?.name || owner?.loginName || "运行责任人";
const flag = hint ? `${hint.field}Configured` : "";
diff --git a/chatbot/src/credentials.js b/chatbot/src/credentials.js
index aa97c0c0..57d185f8 100644
--- a/chatbot/src/credentials.js
+++ b/chatbot/src/credentials.js
@@ -8,6 +8,64 @@ export const CREDENTIALS = {
gitToken: "GitHub Git Token",
};
+// A CodeBuddy key only works on the edition that issued it, and the CLI
+// treats an unrecognized environment as 国际站. Keep in sync with
+// CODEBUDDY_ENVIRONMENTS in web/app/workbench.js and
+// domain.NormalizeCodeBuddyInternetEnvironment.
+export const CODEBUDDY_ENVIRONMENTS = [
+ {
+ value: "",
+ label: "国际站",
+ site: "codebuddy.ai",
+ keyUrl: "https://www.codebuddy.ai/profile/keys",
+ },
+ {
+ value: "internal",
+ label: "国内站",
+ site: "copilot.tencent.com",
+ keyUrl: "https://copilot.tencent.com/profile/",
+ },
+ {
+ value: "ioa",
+ label: "iOA",
+ site: "tencent.sso.copilot.tencent.com",
+ keyUrl: "https://tencent.sso.copilot.tencent.com/profile/keys",
+ },
+];
+
+const CODEBUDDY_ENVIRONMENT_ALIASES = new Map([
+ ["public", ""],
+ ["intl", ""],
+ ["international", ""],
+ ["国际站", ""],
+ ["china", "internal"],
+ ["cn", "internal"],
+ ["国内站", "internal"],
+]);
+
+// codeBuddyEnvironment returns null for a value the CLI would not recognize.
+export function codeBuddyEnvironment(value) {
+ const key = String(value || "").trim().toLowerCase();
+ const normalized = CODEBUDDY_ENVIRONMENT_ALIASES.has(key)
+ ? CODEBUDDY_ENVIRONMENT_ALIASES.get(key)
+ : key;
+ return CODEBUDDY_ENVIRONMENTS.find((env) => env.value === normalized) || null;
+}
+
+export function codeBuddyKeyURL(value) {
+ return (codeBuddyEnvironment(value) || CODEBUDDY_ENVIRONMENTS[0]).keyUrl;
+}
+
+// Advisory only: a third-party model key is accepted but CodeBuddy answers it
+// with 401.
+export function codeBuddyKeyWarning(key) {
+ const text = String(key || "").trim();
+ if (!text || text.startsWith("ck_")) return "";
+ return /^sk-/i.test(text)
+ ? "这像是 DeepSeek、OpenAI 等第三方模型的 Key,CodeBuddy 会拒绝;第三方 Key 请在个人配置中改填到 Claude Code 或 Codex 凭证并设置 Base URL"
+ : "CodeBuddy API Key 通常以 ck_ 开头,请确认复制的是 CodeBuddy 的 Key";
+}
+
// Where and how to get each credential. Keep in sync with
// assistantCredentialRules in internal/httpapi/assistant_run_view.go.
export const CREDENTIAL_GUIDES = {
@@ -22,11 +80,11 @@ export const CREDENTIAL_GUIDES = {
],
},
codeBuddyApiKey: {
- url: "https://www.codebuddy.ai/",
+ url: CODEBUDDY_ENVIRONMENTS[0].keyUrl,
link: "打开 CodeBuddy 创建 Key",
steps: [
- "打开 CodeBuddy 个人中心创建 API Key 并复制",
- "到「个人配置 → CodeBuddy API Key」粘贴并保存",
+ "在 CodeBuddy 账号所在站点(国际站、国内站或 iOA)创建 API Key 并复制",
+ "到「个人配置 → CodeBuddy API Key」选择同一网络环境,粘贴 Key 并保存;DeepSeek 等第三方模型的 Key 不能用在这里",
"回到这里点「重试节点」",
],
},
@@ -44,6 +102,17 @@ export const CREDENTIAL_GUIDES = {
},
};
+// credentialGuide points the CodeBuddy link at the key page of the edition
+// the credential owner has selected.
+export function credentialGuide(field, owner) {
+ const guide = CREDENTIAL_GUIDES[field];
+ if (!guide || field !== "codeBuddyApiKey") return guide || null;
+ const env =
+ codeBuddyEnvironment(owner?.codeBuddyInternetEnvironment) ||
+ CODEBUDDY_ENVIRONMENTS[0];
+ return { ...guide, url: env.keyUrl, link: `打开 CodeBuddy ${env.label}创建 Key` };
+}
+
const RULES = [
["codexApiKey", /Codex[^。\n]{0,16}API Key/i],
["claudeCodeApiKey", /Claude Code[^。\n]{0,16}API Key/i],
diff --git a/chatbot/src/quick-access-wizard.css b/chatbot/src/quick-access-wizard.css
index 1a1ef7e1..7762ea5f 100644
--- a/chatbot/src/quick-access-wizard.css
+++ b/chatbot/src/quick-access-wizard.css
@@ -1014,6 +1014,10 @@
color: var(--qa-ok-text);
}
+.qa-hint.is-warn {
+ color: var(--qa-warn-text);
+}
+
.qa-hint code,
.qa-repo-default-row code {
padding: 1px 5px;
diff --git a/chatbot/tests/components.test.jsx b/chatbot/tests/components.test.jsx
index bd05b6b1..9ce8ae11 100644
--- a/chatbot/tests/components.test.jsx
+++ b/chatbot/tests/components.test.jsx
@@ -592,6 +592,40 @@ describe("content and panels", () => {
expect(onAsk).toHaveBeenCalled();
});
+ test("a CodeBuddy key alert links to the key page of the owner's network environment", () => {
+ const { unmount } = render(
+ <RunAlerts
+ runs={[run]}
+ user={{ id: 1 }}
+ users={[{ id: 1, codeBuddyInternetEnvironment: "internal" }]}
+ readOnly={false}
+ onOpenNode={vi.fn()}
+ onAsk={vi.fn()}
+ onChanged={vi.fn()}
+ />,
+ );
+ expect(screen.getByRole("link", { name: /国内站创建 Key/ })).toHaveAttribute(
+ "href",
+ "https://copilot.tencent.com/profile/",
+ );
+ unmount();
+ render(
+ <RunAlerts
+ runs={[{ ...run, executionContext: { responsibleUserId: 2 } }]}
+ user={{ id: 1, codeBuddyInternetEnvironment: "internal" }}
+ users={[{ id: 2, loginName: "owner", codeBuddyInternetEnvironment: "ioa" }]}
+ readOnly={false}
+ onOpenNode={vi.fn()}
+ onAsk={vi.fn()}
+ onChanged={vi.fn()}
+ />,
+ );
+ expect(screen.getByRole("link", { name: /iOA创建 Key/ })).toHaveAttribute(
+ "href",
+ "https://tencent.sso.copilot.tencent.com/profile/keys",
+ );
+ });
+
test("renders a waiting approval alert", () => {
render(
<RunAlerts
diff --git a/chatbot/tests/credentials.test.mjs b/chatbot/tests/credentials.test.mjs
index a3bd4593..21a623b6 100644
--- a/chatbot/tests/credentials.test.mjs
+++ b/chatbot/tests/credentials.test.mjs
@@ -1,13 +1,51 @@
import { test } from "vitest";
import assert from "node:assert/strict";
-import { CREDENTIAL_GUIDES, credentialHint } from "../src/credentials.js";
+import {
+ CREDENTIAL_GUIDES,
+ codeBuddyEnvironment,
+ codeBuddyKeyURL,
+ codeBuddyKeyWarning,
+ credentialGuide,
+ credentialHint,
+} from "../src/credentials.js";
+
+test("CodeBuddy key links follow the selected network environment", () => {
+ 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",
+ );
+ 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);
+
+ const intl = credentialGuide("codeBuddyApiKey", {});
+ assert.equal(intl.url, "https://www.codebuddy.ai/profile/keys");
+ const china = credentialGuide("codeBuddyApiKey", {
+ codeBuddyInternetEnvironment: "internal",
+ });
+ assert.equal(china.url, "https://copilot.tencent.com/profile/");
+ assert.match(china.link, /国内站/);
+ assert.deepEqual(china.steps, CREDENTIAL_GUIDES.codeBuddyApiKey.steps);
+ assert.equal(credentialGuide("gitToken", {}), CREDENTIAL_GUIDES.gitToken);
+ assert.equal(credentialGuide("unknown", {}), null);
+});
+
+test("third-party model keys are flagged before CodeBuddy rejects them", () => {
+ assert.equal(codeBuddyKeyWarning(""), "");
+ assert.equal(codeBuddyKeyWarning("ck_abc"), "");
+ assert.match(codeBuddyKeyWarning("sk-abc"), /第三方/);
+ assert.match(codeBuddyKeyWarning("abc"), /ck_/);
+});
test("credential errors from the platform link to the right setting", () => {
const cases = [
["请先在个人配置中配置自己的 CodeBuddy API Key", "codeBuddyApiKey", false],
["请先配置个人 CodeBuddy API Key", "codeBuddyApiKey", false],
[
- "CodeBuddy 拒绝了你的 API Key(401/403),请在「设置」里检查 CodeBuddy API Key 和网络环境",
+ "CodeBuddy 拒绝了你的 API Key(401/403):请在「个人配置 → CodeBuddy API Key」确认网络环境与创建 Key 的站点一致,且填的是 CodeBuddy 的 Key,而不是 DeepSeek、OpenAI 等第三方模型的 Key",
"codeBuddyApiKey",
false,
],
diff --git a/chatbot/tests/quick-access-wizard.test.jsx b/chatbot/tests/quick-access-wizard.test.jsx
index aeb05521..0ebc4360 100644
--- a/chatbot/tests/quick-access-wizard.test.jsx
+++ b/chatbot/tests/quick-access-wizard.test.jsx
@@ -185,7 +185,40 @@ describe("QuickAccessWizard", () => {
await screen.findByText("项目与仓库", { selector: "h3" });
expect(writeMock).toHaveBeenCalledWith(
"/api/users/1/credentials",
- { codeBuddyApiKey: "cb-key" },
+ { codeBuddyApiKey: "cb-key", codeBuddyInternetEnvironment: "" },
+ "PUT",
+ );
+ mockState.unconfigured = false;
+ });
+
+ test("saves the CodeBuddy key with the chosen network environment and links to its key page", async () => {
+ mockState.unconfigured = true;
+ writeMock.mockClear();
+ const userAction = userEvent.setup();
+ render(
+ <QuickAccessWizard
+ open
+ user={{ id: 1, loginName: "tester", chineseName: "测试" }}
+ 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/ });
+ expect(keyLink).toHaveAttribute("href", "https://www.codebuddy.ai/profile/keys");
+ await userAction.click(screen.getByLabelText("CodeBuddy 网络环境"));
+ await userAction.click(screen.getByRole("option", { name: /国内站/ }));
+ expect(keyLink).toHaveAttribute("href", "https://copilot.tencent.com/profile/");
+ await userAction.type(screen.getByPlaceholderText("粘贴 CodeBuddy API Key"), "sk-deepseek");
+ expect(screen.getByText(/第三方模型的 Key/)).toBeInTheDocument();
+ await userAction.click(screen.getByRole("button", { name: "下一步" }));
+ await screen.findByText("项目与仓库", { selector: "h3" });
+ expect(writeMock).toHaveBeenCalledWith(
+ "/api/users/1/credentials",
+ { codeBuddyApiKey: "sk-deepseek", codeBuddyInternetEnvironment: "internal" },
"PUT",
);
mockState.unconfigured = false;
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml
index 1f700c6c..043ef4fd 100644
--- a/docs/api/openapi.yaml
+++ b/docs/api/openapi.yaml
@@ -643,7 +643,7 @@ paths:
gitTokenClear: {type: boolean}
codeBuddyApiKey: {type: string, writeOnly: true}
codeBuddyApiKeyClear: {type: boolean}
- codeBuddyInternetEnvironment: {type: string}
+ codeBuddyInternetEnvironment: {type: string, description: "Edition that issued the CodeBuddy key: empty for International, \"internal\" for China, \"ioa\" for iOA (\"public\" and \"China\" are also accepted). Any other value is rejected with 400."}
codexApiKey: {type: string, writeOnly: true, description: "Blank preserves the stored key."}
codexApiKeyClear: {type: boolean}
codexBaseUrl: {type: string, description: "HTTP(S) Responses API base URL. Omitted preserves the value; empty uses the official endpoint."}
diff --git a/docs/deployment.md b/docs/deployment.md
index 3071069b..8e054e26 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -112,13 +112,15 @@ Git commits created by the platform use the responsible local account name and a
## CodeBuddy authentication environment
-In personal settings, choose the network environment belonging to the API key. A key from one edition may return HTTP 401 when sent to another edition. The setting is per user; public installations do not assume an enterprise environment.
+In personal settings, choose the network environment belonging to the API key; the "get API key" link opens that edition's key page. A key from one edition returns HTTP 401 when sent to another edition, and keys from third-party model providers (DeepSeek, OpenAI and similar) are not CodeBuddy keys. The setting is per user; public installations do not assume an enterprise environment.
-| Edition | CodeBuddy network environment |
-| --- | --- |
-| International | Leave empty |
-| China | `internal` |
-| iOA | `ioa` |
+| Edition | Stored value | Key page |
+| --- | --- | --- |
+| International | empty | https://www.codebuddy.ai/profile/keys |
+| China | `internal` | https://copilot.tencent.com/profile/ |
+| iOA | `ioa` | https://tencent.sso.copilot.tencent.com/profile/keys |
+
+`PUT /api/users/:id/credentials` accepts only these values (`public` and `China` are also understood) and rejects anything else with HTTP 400, because the CLI silently falls back to the international edition for values it does not recognize.
Other dedicated/self-hosted configurations are described in the [official CodeBuddy identity documentation](https://www.codebuddy.ai/docs/cli/iam). Configure the model catalog with `AGENTFLOW_ASSISTANT_MODEL` and `AGENTFLOW_ASSISTANT_MODELS`; ordinary roles can select a model independently.
diff --git a/internal/domain/user.go b/internal/domain/user.go
index ff9584e1..d1a1b96c 100644
--- a/internal/domain/user.go
+++ b/internal/domain/user.go
@@ -36,6 +36,23 @@ type User struct {
const PlatformRoleAdmin = "admin"
+// NormalizeCodeBuddyInternetEnvironment maps a network environment chosen in
+// personal settings to the CODEBUDDY_INTERNET_ENVIRONMENT value: "" for the
+// international edition, "internal" for the China edition and "ioa" for iOA.
+// The CLI silently falls back to the international edition for any value it
+// does not recognize, so unknown values report ok=false instead of being saved.
+func NormalizeCodeBuddyInternetEnvironment(raw string) (value string, ok bool) {
+ switch strings.ToLower(strings.TrimSpace(raw)) {
+ case "", "public", "intl", "international", "国际站":
+ return "", true
+ case "internal", "china", "cn", "国内站":
+ return "internal", true
+ case "ioa":
+ return "ioa", true
+ }
+ return "", false
+}
+
// IsPlatformAdmin reports whether the user holds the platform-admin role.
func IsPlatformAdmin(u User) bool {
return strings.EqualFold(strings.TrimSpace(u.PlatformRole), PlatformRoleAdmin)
diff --git a/internal/domain/user_test.go b/internal/domain/user_test.go
new file mode 100644
index 00000000..a38af8f5
--- /dev/null
+++ b/internal/domain/user_test.go
@@ -0,0 +1,30 @@
+package domain
+
+import "testing"
+
+func TestNormalizeCodeBuddyInternetEnvironment(t *testing.T) {
+ for raw, want := range map[string]string{
+ "": "",
+ " ": "",
+ "public": "",
+ "INTL": "",
+ "international": "",
+ "国际站": "",
+ "internal": "internal",
+ " China ": "internal",
+ "cn": "internal",
+ "国内站": "internal",
+ "ioa": "ioa",
+ "iOA": "ioa",
+ } {
+ if got, ok := NormalizeCodeBuddyInternetEnvironment(raw); !ok || got != want {
+ t.Fatalf("NormalizeCodeBuddyInternetEnvironment(%q) = %q, %v; want %q", raw, got, ok, want)
+ }
+ }
+ // The CLI would silently use the international edition for these.
+ for _, raw := range []string{"intranet", "selfhosted", "cloudhosted", "国内", "io a"} {
+ if got, ok := NormalizeCodeBuddyInternetEnvironment(raw); ok || got != "" {
+ t.Fatalf("NormalizeCodeBuddyInternetEnvironment(%q) = %q, %v; want rejection", raw, got, ok)
+ }
+ }
+}
diff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.go
index 2f86ce98..cc478cac 100644
--- a/internal/httpapi/assistant.go
+++ b/internal/httpapi/assistant.go
@@ -1366,7 +1366,7 @@ func (t *assistantTurnUsage) snapshot() *domain.TokenUsage {
// errAssistantCredentialRejected means CodeBuddy answered the turn with an
// authorization failure instead of model output; retrying cannot help.
-var errAssistantCredentialRejected = errors.New("CodeBuddy 拒绝了你的 API Key(401/403),请在「设置」里检查 CodeBuddy API Key 和网络环境")
+var errAssistantCredentialRejected = errors.New("CodeBuddy 拒绝了你的 API Key(401/403):请在「个人配置 → CodeBuddy API Key」确认网络环境与创建 Key 的站点一致,且填的是 CodeBuddy 的 Key,而不是 DeepSeek、OpenAI 等第三方模型的 Key")
// isCredentialRejection reports whether an assistant text block is the bare
// HTTP auth failure CodeBuddy emits in place of a reply.
diff --git a/internal/httpapi/assistant_run_view.go b/internal/httpapi/assistant_run_view.go
index 69db392b..af6a970e 100644
--- a/internal/httpapi/assistant_run_view.go
+++ b/internal/httpapi/assistant_run_view.go
@@ -112,9 +112,9 @@ var assistantCredentialRules = []struct {
"到 LoopForge「个人配置 → Claude Code API Key」填写 Key(及 Base URL)并保存,或把执行机器的认证方式切回本机登录",
"回到运行重试失败节点",
}},
- {"codeBuddyApiKey", "CodeBuddy API Key", regexp.MustCompile(`(?i)CodeBuddy[^。\n]{0,20}(API Key|Key|凭据)|拒绝了你的 API Key`), "https://www.codebuddy.ai/", []string{
- "打开 https://www.codebuddy.ai/ 创建 API Key 并复制",
- "到 LoopForge「个人配置 → CodeBuddy API Key」粘贴并保存",
+ {"codeBuddyApiKey", "CodeBuddy API Key", regexp.MustCompile(`(?i)CodeBuddy[^。\n]{0,20}(API Key|Key|凭据)|拒绝了你的 API Key`), "https://www.codebuddy.ai/profile/keys", []string{
+ "确认 CodeBuddy 账号所在站点并在该站点创建 API Key:国际站 https://www.codebuddy.ai/profile/keys ,国内站 https://copilot.tencent.com/profile/ ,iOA https://tencent.sso.copilot.tencent.com/profile/keys",
+ "到 LoopForge「个人配置 → CodeBuddy API Key」选择同一网络环境,粘贴 Key 并保存;DeepSeek、OpenAI 等第三方模型的 Key 不能用作 CodeBuddy Key",
"回到运行重试失败节点",
}},
{"gitToken", "GitHub Git Token", regexp.MustCompile(`(?i)Git Token|工蜂[^。\n]{0,12}令牌|could not read Username|Authentication failed|HTTP Basic: Access denied|terminal prompts disabled|requested URL returned error: 40[13]`), "https://github.com/settings/tokens", []string{
diff --git a/internal/httpapi/assistant_run_view_test.go b/internal/httpapi/assistant_run_view_test.go
index 2f5c6575..ca5fa52c 100644
--- a/internal/httpapi/assistant_run_view_test.go
+++ b/internal/httpapi/assistant_run_view_test.go
@@ -118,3 +118,16 @@ func TestAssistantCredentialProblemMatchesGitToken(t *testing.T) {
t.Fatal("ordinary failures must not suggest credentials")
}
}
+
+func TestAssistantCredentialProblemPointsCodeBuddyAtEveryKeyPage(t *testing.T) {
+ fix := assistantCredentialProblem(errAssistantCredentialRejected.Error(), "")
+ if fix == nil || fix.Field != "codeBuddyApiKey" || fix.HelpURL != "https://www.codebuddy.ai/profile/keys" {
+ t.Fatalf("fix = %+v", fix)
+ }
+ steps := strings.Join(fix.Steps, "\n")
+ for _, want := range []string{"https://www.codebuddy.ai/profile/keys", "https://copilot.tencent.com/profile/", "https://tencent.sso.copilot.tencent.com/profile/keys", "网络环境", "第三方"} {
+ if !strings.Contains(steps, want) {
+ t.Fatalf("CodeBuddy steps miss %q: %s", want, steps)
+ }
+ }
+}
diff --git a/internal/httpapi/issues_test.go b/internal/httpapi/issues_test.go
index 84462ddc..a3aa36ff 100644
--- a/internal/httpapi/issues_test.go
+++ b/internal/httpapi/issues_test.go
@@ -2195,6 +2195,55 @@ func TestUserCredentialsAreStoredAndRedacted(t *testing.T) {
}
}
+func TestCodeBuddyInternetEnvironmentIsNormalizedOrRejected(t *testing.T) {
+ t.Setenv("AGENTFLOW_SESSION_SECRET", "credential-test-session-secret")
+ root := t.TempDir()
+ s, err := repo.OpenTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { s.Close() })
+ h := New(s, engine.New(s, runtime.NewManager(filepath.Join(root, "workspaces"))), tracker.NewService(), "", "")
+ if err := s.PutUser(domain.User{StaffID: 2003, LoginName: "bob", ChineseName: "鲍勃"}); err != nil {
+ t.Fatal(err)
+ }
+ bob, _ := s.UserByLoginName("bob")
+ token, err := auth.NewClientFromEnv().SignUser(&auth.User{ID: bob.ID, LoginName: bob.LoginName, AuthTime: time.Now().UTC()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ put := func(environment string) *httptest.ResponseRecorder {
+ body, _ := json.Marshal(map[string]any{"codeBuddyApiKey": "ck_bob", "codeBuddyInternetEnvironment": environment})
+ req := httptest.NewRequest(http.MethodPut, fmt.Sprintf("/api/users/%d/credentials", bob.ID), bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ req.AddCookie(&http.Cookie{Name: authCookieName, Value: token})
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ return rec
+ }
+ for raw, want := range map[string]string{" iOA ": "ioa", "国内站": "internal", "China": "internal", "public": "", "": ""} {
+ if rec := put(raw); rec.Code != http.StatusOK {
+ t.Fatalf("environment %q status=%d body=%s", raw, rec.Code, rec.Body.String())
+ }
+ if stored, _ := s.User(bob.ID); stored.CodeBuddyInternetEnvironment != want {
+ t.Fatalf("environment %q stored as %q, want %q", raw, stored.CodeBuddyInternetEnvironment, want)
+ }
+ }
+ if rec := put("internal"); rec.Code != http.StatusOK {
+ t.Fatalf("internal status=%d", rec.Code)
+ }
+ // A typo would make the CLI quietly call the international edition, so nothing is saved.
+ for _, raw := range []string{"intranet", "selfhosted", "国内"} {
+ rec := put(raw)
+ if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "网络环境") {
+ t.Fatalf("environment %q status=%d body=%s", raw, rec.Code, rec.Body.String())
+ }
+ }
+ if stored, _ := s.User(bob.ID); stored.CodeBuddyInternetEnvironment != "internal" || stored.CodeBuddyAPIKey != "ck_bob" {
+ t.Fatalf("rejected environment changed the stored credential: %+v", stored)
+ }
+}
+
func requestJSON[T any](t *testing.T, h http.Handler, method, path string, body any, wantStatus int) T {
t.Helper()
raw, err := json.Marshal(body)
diff --git a/internal/httpapi/users.go b/internal/httpapi/users.go
index 760b798c..cf54eb99 100644
--- a/internal/httpapi/users.go
+++ b/internal/httpapi/users.go
@@ -39,6 +39,14 @@ func (h *usersHandlers) user(c *gin.Context) {
if !decode(c, &body) {
return
}
+ if raw := body.CodeBuddyInternetEnvironment; raw != nil {
+ environment, ok := domain.NormalizeCodeBuddyInternetEnvironment(*raw)
+ if !ok {
+ c.JSON(http.StatusBadRequest, map[string]string{"error": "CodeBuddy 网络环境只能是国际站(留空)、国内站(internal)或 iOA(ioa)"})
+ return
+ }
+ body.CodeBuddyInternetEnvironment = &environment
+ }
for _, raw := range []*string{body.CodexBaseURL, body.ClaudeCodeBaseURL} {
if raw == nil || strings.TrimSpace(*raw) == "" {
continue
diff --git a/web/app/access.js b/web/app/access.js
index fa4494a0..1addf851 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,'https://www.codebuddy.ai/',cbShared?'未配置时对话和 SOP 都用平台共享模型 Deepseek-V4.1-Flash;配置后可使用其他模型':'Agent 调模型执行任务')}
+ ${subItem('codeBuddyApiKey','CodeBuddy API Key',cbOwn,codeBuddyKeyURL(stored.codeBuddyInternetEnvironment),cbShared?'未配置时对话和 SOP 都用平台共享模型 Deepseek-V4.1-Flash;配置后可使用其他模型':'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.js
index 4b11bdf2..6c21d9c7 100644
--- a/web/app/workbench.js
+++ b/web/app/workbench.js
@@ -32,6 +32,22 @@ const CREDENTIAL_GROUPS=[
{id:'platform',name:'平台集成',sub:'代码仓库与统一认证',icon:'key'},
{id:'model',name:'模型与执行',sub:'AI 对话与编码 CLI',icon:'sparkles'},
];
+// A CodeBuddy key only works on the edition that issued it; the CLI treats unknown values as 国际站.
+// Keep in sync with chatbot/src/credentials.js and domain.NormalizeCodeBuddyInternetEnvironment.
+const CODEBUDDY_ENVIRONMENTS=[
+ {value:'',label:'国际站',site:'codebuddy.ai',keyUrl:'https://www.codebuddy.ai/profile/keys'},
+ {value:'internal',label:'国内站',site:'copilot.tencent.com',keyUrl:'https://copilot.tencent.com/profile/'},
+ {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.
+function codeBuddyEnvironment(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`}
const CREDENTIAL_KINDS=[
{key:'gitToken',group:'platform',name:'GitHub',short:'仓库授权',logo:'github',monochrome:true,
use:'克隆私有仓库、创建任务分支、推送交付产物',
@@ -42,9 +58,9 @@ const CREDENTIAL_KINDS=[
{key:'codeBuddyApiKey',group:'model',name:'CodeBuddy',short:'CodeBuddy API Key',logo:'codebuddy',
use:'AI 对话与 SOP 的 CodeBuddy 执行器',
description:'AI 对话(含 Claude、GPT 等模型)和 SOP 的 CodeBuddy 执行器都使用它;网络环境按账号所在环境配置。',
- guide:[['登录 CodeBuddy 个人密钥页','https://www.codebuddy.ai/','前往 CodeBuddy 获取 API Key'],['新建 API Key,复制以 <code>ck_</code> 开头的密钥'],['粘贴到下方;网络环境国际站留空,国内站填 internal,iOA 填 ioa']],
+ guide:[['先在下方选择 CodeBuddy 账号所在的网络环境:国际站、国内站或 iOA'],['登录该站点的 API Key 页面,新建 API Key',codeBuddyKeyURL,codeBuddyKeyLinkLabel],['复制以 <code>ck_</code> 开头的密钥粘贴到下方;DeepSeek、OpenAI 等第三方模型的 Key 不能填在这里']],
placeholder:'请输入个人 ck_ key',
- extra:{name:'codeBuddyInternetEnvironment',label:'网络环境',placeholder:'国际站留空,国内站 internal,iOA 填 ioa'},
+ extra:{name:'codeBuddyInternetEnvironment',label:'网络环境',options:CODEBUDDY_ENVIRONMENTS},
impact:'AI 对话将只能使用默认模型,CodeBuddy 执行器节点会失败。'},
{key:'codexApiKey',group:'model',name:'Codex',short:'Codex API Key',logo:'codex',monochrome:true,
use:'AI 对话选择 Codex 执行器,以及以 Codex 运行的 SOP 节点',
@@ -76,6 +92,37 @@ function credentialNextKind(user){return CREDENTIAL_RECOMMENDED.map(credentialKi
function credentialSecretError(kind,value){
return '';
}
+// Advisory only: a third-party model key is accepted here but CodeBuddy answers it with 401.
+function credentialSecretWarning(kind,value){
+ const text=String(value||'').trim();
+ if(kind?.key!=='codeBuddyApiKey'||!text||text.startsWith('ck_'))return '';
+ return /^sk-/i.test(text)
+ ?'这像是 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.
+function credentialExtraValue(kind,value){
+ if(kind?.extra?.options)return codeBuddyEnvironment(value)?.value??'';
+ return value||kind?.extra?.fallback||'';
+}
+function credentialExtraLabel(kind,value){
+ if(kind.extra.options){const env=codeBuddyEnvironment(value)||CODEBUDDY_ENVIRONMENTS[0];return `${env.label} · ${env.site}`}
+ 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 实际按国际站连接。`:'';
+ 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=''){
+ const selected=credentialExtraValue(kind,stored);
+ const options=kind.extra.options.map(option=>`<option value="${escapeHTML(option.value)}"${option.value===selected?' selected':''}>${escapeHTML(option.label)} · ${escapeHTML(option.site)}</option>`).join('');
+ return `<label class="credential-field"><span>${escapeHTML(kind.extra.label)}${note?`<em>${escapeHTML(note)}</em>`:''}</span><div class="credential-input is-plain is-select"><select name="extra">${options}</select></div><small class="credential-env-hint" data-credential-env-hint>${codeBuddyEnvironmentHintHTML(selected,stored)}</small></label>`;
+}
+// Keeps the 获取 API Key links pointed at the edition that is selected now.
+function refreshCredentialEnvironmentLinks(scope,value){
+ const hint=scope?.querySelector('[data-credential-env-hint]');if(hint)hint.innerHTML=codeBuddyEnvironmentHintHTML(value);
+ scope?.querySelectorAll('[data-wizard-link][data-environment-link]').forEach(link=>{link.href=codeBuddyKeyURL(value);link.textContent=`${codeBuddyKeyLinkLabel(value)} ↗`});
+}
function credentialExtraError(kind,value){
const text=String(value||'').trim();
if(!kind.extra?.url||!text)return '';
@@ -124,14 +171,17 @@ function credentialSubline(kind,user){
if(!result.valid)return source+dot+`<span class="is-err">缺少权限 ${escapeHTML((result.missing||[]).join('、'))}</span>`;
return source+dot+'<span class="is-ok">令牌有效</span>'+(result.scopes?.length?dot+`<span class="credential-mono">${escapeHTML(result.scopes.join(' · '))}</span>`:'');
}
- if(kind.key==='codeBuddyApiKey')return `<span>网络环境</span><span class="credential-mono">${escapeHTML(user.codeBuddyInternetEnvironment||'国际站')}</span>${dot}${use}`;
+ if(kind.key==='codeBuddyApiKey'){
+ const raw=String(user.codeBuddyInternetEnvironment||'').trim(),env=codeBuddyEnvironment(raw);
+ return `<span>网络环境</span>${env?`<span class="credential-mono">${escapeHTML(env.label)}</span>`:`<span class="is-err">「${escapeHTML(raw)}」无法识别,按国际站连接</span>`}${dot}${use}`;
+ }
if(kind.extra)return (user[kind.extra.name]?`<span class="credential-mono">${escapeHTML(user[kind.extra.name])}</span>`:'<span>官方地址</span>')+dot+use;
return use;
}
-function credentialFieldHTML({label,note='',name,type='password',value='',placeholder='',hint='',id=''}){
+function credentialFieldHTML({label,note='',name,type='password',value='',placeholder='',hint='',hintTone='',id=''}){
const secret=type==='password';
// Secrets are never serialized into markup; callers assign input.value after rendering.
- return `<label class="credential-field"><span>${escapeHTML(label)}${note?`<em>${escapeHTML(note)}</em>`:''}</span><div class="credential-input${secret?'':' is-plain'}"><input${id?` id="${id}"`:''} name="${name}" type="${type}" ${secret?'autocomplete="new-password"':'autocomplete="off" spellcheck="false"'}${secret?'':` value="${escapeHTML(value)}"`} placeholder="${escapeHTML(placeholder)}">${secret?`<button type="button" class="credential-eye" data-credential-eye aria-label="显示">${credentialGlyph('eye',15)}</button>`:''}</div>${hint!==null?`<small data-credential-hint="${name}">${escapeHTML(hint)}</small>`:''}</label>`;
+ return `<label class="credential-field"><span>${escapeHTML(label)}${note?`<em>${escapeHTML(note)}</em>`:''}</span><div class="credential-input${secret?'':' is-plain'}${hintTone?' is-'+(hintTone==='err'?'bad':hintTone==='ok'?'good':hintTone):''}"><input${id?` id="${id}"`:''} name="${name}" type="${type}" ${secret?'autocomplete="new-password"':'autocomplete="off" spellcheck="false"'}${secret?'':` value="${escapeHTML(value)}"`} placeholder="${escapeHTML(placeholder)}">${secret?`<button type="button" class="credential-eye" data-credential-eye aria-label="显示">${credentialGlyph('eye',15)}</button>`:''}</div>${hint!==null?`<small data-credential-hint="${name}"${hintTone?` class="is-${hintTone}"`:''}>${escapeHTML(hint)}</small>`:''}</label>`;
}
function credentialOAuthHTML(label,note){
return (typeof githubConnectHTML==='function'?githubConnectHTML():'')+`<div class="credential-oauth" data-gongfeng-oauth${state.gongfengOAuthEnabled?'':' hidden'}><a class="credential-btn secondary credential-ink" href="/api/auth/gongfeng/start" target="_blank" rel="noopener noreferrer">${credentialLogo(credentialKind('gitToken'),'is-mini')}<span>${label}</span></a><small>${note}</small></div>`;
@@ -175,12 +225,17 @@ function gitTokenEditorHTML(kind,user){
}
function credentialEditorHTML(kind,user){
if(kind.key==='gitToken')return gitTokenEditorHTML(kind,user);
- const extraValue=kind.extra?(user[kind.extra.name]||kind.extra.fallback||''):'';
- return `<div class="credential-editor-form"${kind.extra?` data-original="${escapeHTML(extraValue)}"`:''}>
+ const extraValue=kind.extra?credentialExtraValue(kind,user[kind.extra.name]):'';
+ 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]));
+ 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||''})}
- ${kind.extra?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}):''}
+ ${extraField}
<div class="credential-swap">
- <div class="credential-editor-foot" data-credential-pane="foot"><button type="button" class="credential-btn ghost danger credential-ink" data-credential-act="delete">${credentialGlyph('trash',14)}<span>删除</span></button><div><button type="button" class="credential-btn ghost credential-ink" data-credential-act="cancel">取消</button><button type="button" class="credential-btn primary credential-ink" data-credential-act="save" disabled>保存</button></div></div>
+ <div class="credential-editor-foot" data-credential-pane="foot"><button type="button" class="credential-btn ghost danger credential-ink" data-credential-act="delete">${credentialGlyph('trash',14)}<span>删除</span></button><div><button type="button" class="credential-btn ghost credential-ink" data-credential-act="cancel">取消</button><button type="button" class="credential-btn primary credential-ink" data-credential-act="save"${legacy?'':' disabled'}>保存</button></div></div>
<div class="credential-confirm is-off" data-credential-pane="confirm" role="alert"><div>删除 <b>${escapeHTML(kind.short)}</b>?${escapeHTML(kind.impact)}</div><button type="button" class="credential-btn ghost credential-ink" data-credential-act="undelete">取消</button><button type="button" class="credential-btn danger-solid credential-ink" data-credential-act="confirm-delete">删除</button></div>
</div>
</div>`;
@@ -267,11 +322,12 @@ function setCredentialRowOpen(key,open){
function resetCredentialEditor(row){
row.querySelectorAll('input[name="secret"]').forEach(input=>{input.value='';input.type='password'});
const form=row.querySelector('.credential-editor-form');if(!form)return;
- const extra=form.querySelector('input[name="extra"]');if(extra)extra.value=form.dataset.original||'';
+ const extra=form.querySelector('[name="extra"]');if(extra)extra.value=form.dataset.original||'';
+ if(extra?.tagName==='SELECT')refreshCredentialEnvironmentLinks(form,extra.value);
if(row.dataset.credentialRow==='gitToken'){
const line=form.querySelector('[data-git-verify-line]');if(line){line.classList.remove('is-err');line.innerHTML=''}
setCredentialHint(form,'secret',GIT_TOKEN_REPLACE_HINT);
- }
+ }else setCredentialHint(form,'secret',credentialKind(row.dataset.credentialRow)?.hint||'');
updateCredentialEditorDirty(form);
}
function toggleCredentialRow(key,open){
@@ -291,13 +347,13 @@ function showCredentialPane(row,name,focus=CREDENTIAL_PANE_FOCUS[name]){
if(focus)setTimeout(()=>target.querySelector(focus)?.focus({preventScroll:true}),60);
}
function updateCredentialEditorDirty(form){
- const secret=form.querySelector('input[name="secret"]')?.value.trim()||'',extra=form.querySelector('input[name="extra"]'),save=form.querySelector('[data-credential-act="save"]');
- if(save&&!save.dataset.busy)save.disabled=!secret&&!(extra&&extra.value.trim()!==(form.dataset.original||''));
+ const secret=form.querySelector('input[name="secret"]')?.value.trim()||'',extra=form.querySelector('[name="extra"]'),save=form.querySelector('[data-credential-act="save"]');
+ if(save&&!save.dataset.busy)save.disabled=!secret&&!form.dataset.legacy&&!(extra&&extra.value.trim()!==(form.dataset.original||''));
}
function setCredentialHint(scope,name,text,tone=''){
const hint=scope.querySelector(`[data-credential-hint="${name}"]`),box=scope.querySelector(`input[name="${name}"]`)?.closest('.credential-input');
if(hint){hint.textContent=text;hint.className=tone?'is-'+tone:''}
- if(box){box.classList.toggle('is-bad',tone==='err');box.classList.toggle('is-good',tone==='ok');if(tone==='err'){box.classList.remove('is-shake');void box.offsetWidth;box.classList.add('is-shake')}}
+ if(box){box.classList.toggle('is-bad',tone==='err');box.classList.toggle('is-good',tone==='ok');box.classList.toggle('is-warn',tone==='warn');if(tone==='err'){box.classList.remove('is-shake');void box.offsetWidth;box.classList.add('is-shake')}}
}
function setCredentialButtonBusy(button,label){
if(!button)return;
@@ -359,7 +415,7 @@ function credentialSaved(key,message){
}
async function submitCredentialEditor(row,button){
const key=row.dataset.credentialRow,kind=credentialKind(key),form=row.querySelector('.credential-editor-form');
- const secret=form.querySelector('input[name="secret"]').value.trim(),extra=form.querySelector('input[name="extra"]');
+ const secret=form.querySelector('input[name="secret"]').value.trim(),extra=form.querySelector('[name="extra"]');
const secretError=credentialSecretError(kind,secret),extraError=extra?credentialExtraError(kind,extra.value):'';
if(secretError){setCredentialHint(form,'secret',secretError,'err');return}
if(extraError){toast(extraError,'err');extra.focus();return}
@@ -447,7 +503,11 @@ function bindCredentialPanel(panel){
};
panel.oninput=event=>{
const form=event.target.closest?.('.credential-editor-form');if(!form)return;
- if(event.target.name==='secret'){const kind=credentialKind(form.closest('[data-credential-row]').dataset.credentialRow),error=credentialSecretError(kind,event.target.value);setCredentialHint(form,'secret',error||(kind.key==='gitToken'?GIT_TOKEN_REPLACE_HINT:kind.hint||''),error?'err':'')}
+ if(event.target.name==='secret'){
+ const kind=credentialKind(form.closest('[data-credential-row]').dataset.credentialRow),error=credentialSecretError(kind,event.target.value),warning=credentialSecretWarning(kind,event.target.value);
+ setCredentialHint(form,'secret',error||warning||(kind.key==='gitToken'?GIT_TOKEN_REPLACE_HINT:kind.hint||''),error?'err':warning?'warn':'');
+ }
+ if(event.target.name==='extra'&&event.target.tagName==='SELECT')refreshCredentialEnvironmentLinks(form,event.target.value);
updateCredentialEditorDirty(form);
};
}
@@ -466,7 +526,7 @@ function revealCredentialRow(key){
// ---- 添加凭证向导 ----
let credentialWizard=null;
-function credentialWizardDefaults(kind,user){return kind?.extra?(user[kind.extra.name]||kind.extra.fallback||''):''}
+function credentialWizardDefaults(kind,user){return kind?.extra?credentialExtraValue(kind,user[kind.extra.name]):''}
function openCredentialWizard(key){
const user=credentialUser();
if(!state.currentUser||state.currentUser.isGuest||!$('#credentialPanel'))return;
@@ -516,6 +576,11 @@ function credentialWizardValid(wizard=credentialWizard){
const secret=String(wizard.secret||'').trim(),error=credentialSecretError(kind,secret)||(kind.extra?credentialExtraError(kind,wizard.extra):'');
return {ok:!!secret&&!error,error};
}
+function credentialWizardSecretHint(kind,wizard,validity=credentialWizardValid(wizard)){
+ const error=credentialSecretError(kind,wizard.secret);if(error)return {text:error,tone:'err'};
+ const warning=credentialSecretWarning(kind,wizard.secret);if(warning)return {text:warning,tone:'warn'};
+ return validity.ok?{text:'格式正确',tone:'ok'}:{text:kind.hint||'只在你负责的任务运行时注入,保存后不再明文展示',tone:''};
+}
function credentialWizardStepOneHTML(user){
const wizard=credentialWizard,all=CREDENTIAL_KINDS.every(kind=>credentialConfigured(kind,user));
const groups=CREDENTIAL_GROUPS.map(group=>`<p class="credential-opt-label">${escapeHTML(group.name)}</p><div class="credential-opts" role="radiogroup" aria-label="${escapeHTML(group.name)}">${CREDENTIAL_KINDS.filter(kind=>kind.group===group.id).map((kind,index)=>{
@@ -526,25 +591,35 @@ function credentialWizardStepOneHTML(user){
}
function credentialWizardStepTwoHTML(kind){
const wizard=credentialWizard;
- const guide=kind.guide.map(([text,href,label],index)=>`<li class="${wizard.guide[index]?'is-done':''}" data-wizard-guide="${index}"><span class="credential-guide-no">${wizard.guide[index]?credentialGlyph('check-draw',10):index+1}</span><span>${text}${href?`<a href="${href}" target="_blank" rel="noopener noreferrer" data-wizard-link="${index}">${escapeHTML(label)} ↗</a>`:''}</span></li>`).join('');
+ // A guide link given as functions follows the selected network environment.
+ const guide=kind.guide.map(([text,href,label],index)=>{
+ const dynamic=typeof href==='function',url=dynamic?href(wizard.extra):href,name=typeof label==='function'?label(wizard.extra):label;
+ return `<li class="${wizard.guide[index]?'is-done':''}" data-wizard-guide="${index}"><span class="credential-guide-no">${wizard.guide[index]?credentialGlyph('check-draw',10):index+1}</span><span>${text}${url?`<a href="${escapeHTML(url)}" target="_blank" rel="noopener noreferrer" data-wizard-link="${index}"${dynamic?' data-environment-link':''}>${escapeHTML(name)} ↗</a>`:''}</span></li>`;
+ }).join('');
const github=kind.key==='gitToken';
const manual=wizard.githubMethod==='manual';
const methods=github?`<div class="github-methods" role="tablist" aria-label="GitHub 连接方式"><button type="button" role="tab" data-github-method="oauth" aria-selected="${!manual}">GitHub 授权</button><button type="button" role="tab" data-github-method="manual" aria-selected="${manual}">访问令牌</button></div>`:'';
if(github&&!manual)return `<div class="credential-question">${credentialLogo(kind,'is-mini')}<span>连接 GitHub</span><small class="credential-description">连接后可选择仓库,用于克隆代码、创建分支和推送交付产物。</small></div>${methods}${credentialOAuthHTML('用工蜂授权','')}`;
const validity=credentialWizardValid();
- const secretHint=validity.error&&credentialSecretError(kind,wizard.secret)?validity.error:validity.ok?'格式正确':(kind.hint||'只在你负责的任务运行时注入,保存后不再明文展示');
+ const {text:secretHint,tone:secretTone}=credentialWizardSecretHint(kind,wizard,validity);
+ const secretField=credentialFieldHTML({label:github?'个人访问令牌(PAT)':kind.short,name:'secret',id:'credentialWizardSecret',placeholder:kind.placeholder,hint:secretHint,hintTone:secretTone});
+ const extraField=!kind.extra?''
+ :kind.extra.options?credentialSelectFieldHTML(kind,wizard.extra)
+ :credentialFieldHTML({label:kind.extra.label,note:kind.extra.url?'可选 · 留空使用官方地址':'',name:'extra',type:kind.extra.url?'url':'text',value:wizard.extra,placeholder:kind.extra.placeholder,hint:''});
+ // The network environment decides where the key comes from, so it is chosen first.
return `<div class="credential-question">${credentialLogo(kind,'is-mini')}<span>${github?'使用访问令牌':'配置 '+escapeHTML(kind.short)}</span><small class="credential-description">${escapeHTML(kind.description)}</small></div>${methods}<ol class="credential-guide">${guide}</ol><div class="credential-fields">
- ${credentialFieldHTML({label:github?'个人访问令牌(PAT)':kind.short,name:'secret',id:'credentialWizardSecret',placeholder:kind.placeholder,hint:secretHint})}
- ${kind.extra?credentialFieldHTML({label:kind.extra.label,note:kind.extra.url?'可选 · 留空使用官方地址':'',name:'extra',type:kind.extra.url?'url':'text',value:wizard.extra,placeholder:kind.extra.placeholder,hint:''}):''}
+ ${kind.extra?.options?extraField+secretField:secretField+extraField}
</div>`;
}
function credentialWizardStepThreeHTML(kind){
const wizard=credentialWizard;
if(wizard.done)return `<div class="credential-saved"><span class="credential-check-big"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12.5l4.2 4.2L19 7"/></svg></span><h4>${escapeHTML(kind.short)} 已保存</h4><p>下一次运行你负责的任务时生效,可随时在列表中展开编辑。</p></div>`;
- const extra=kind.extra?`<dt>${escapeHTML(kind.extra.label)}</dt><dd${kind.extra.url?' class="credential-mono"':''}>${escapeHTML(String(wizard.extra||'').trim()||(kind.extra.url?'官方地址':kind.extra.fallback))}</dd>`:'';
+ const extra=kind.extra?`<dt>${escapeHTML(kind.extra.label)}</dt><dd${kind.extra.url?' class="credential-mono"':''}>${escapeHTML(credentialExtraLabel(kind,wizard.extra))}</dd>`:'';
+ const warning=credentialSecretWarning(kind,wizard.secret);
const line=wizard.error?`<p class="credential-vline is-err" role="alert">${credentialGlyph('alert',13)}${escapeHTML(wizard.error)}</p>`
:wizard.saving&&kind.key==='gitToken'?`<p class="credential-vline is-info" role="status">${credentialSpinner(13)}正在校验令牌有效性与权限…</p>`
- :kind.key==='gitToken'?`<p class="credential-vline git-token-verify-status">${credentialGlyph('lock',13)}保存前会先校验令牌有效性与权限</p>`:'';
+ :kind.key==='gitToken'?`<p class="credential-vline git-token-verify-status">${credentialGlyph('lock',13)}保存前会先校验令牌有效性与权限</p>`
+ :warning?`<p class="credential-vline is-warn" role="status">${credentialGlyph('alert',13)}${escapeHTML(warning)}</p>`:'';
return `<div class="credential-question">${credentialGlyph('check',16)}<span>确认并保存</span><small>密钥只在任务运行时注入,不写入 Agent 资产</small></div><div class="credential-summary"><div>${credentialGlyph('key',14)}${escapeHTML(kind.name)}</div><dl><dt>凭证</dt><dd>${escapeHTML(kind.short)}</dd><dt>密钥</dt><dd class="credential-mask">已填写 ••••••••</dd>${extra}<dt>生效</dt><dd>下一次任务</dd></dl></div>${line}`;
}
function credentialWizardFootHTML(){
@@ -602,7 +677,7 @@ function focusCredentialWizard(){
}
function credentialWizardFocusables(){
const dialog=$('#credentialWizard .credential-dialog');if(!dialog)return [];
- return [...dialog.querySelectorAll('button, a[href], input')].filter(el=>!el.disabled&&!el.closest('.credential-pane.is-leaving, [hidden]')&&el.getClientRects().length);
+ return [...dialog.querySelectorAll('button, a[href], input, select')].filter(el=>!el.disabled&&!el.closest('.credential-pane.is-leaving, [hidden]')&&el.getClientRects().length);
}
function markCredentialGuide(index){
const wizard=credentialWizard;if(!wizard||wizard.guide[index])return;
@@ -617,9 +692,10 @@ function credentialWizardInput(event){
const kind=credentialKind(wizard.kind),pane=input.closest('.credential-pane');
if(input.name==='extra')wizard.extra=input.value;
if(input.name==='secret')wizard.secret=input.value;
- const secretError=credentialSecretError(kind,wizard.secret),valid=credentialWizardValid();
- setCredentialHint(pane,'secret',secretError||(valid.ok?'格式正确':kind.hint||'只在你负责的任务运行时注入,保存后不再明文展示'),secretError?'err':valid.ok?'ok':'');
- if(kind.extra){const extraError=credentialExtraError(kind,wizard.extra);setCredentialHint(pane,'extra',extraError,extraError?'err':'')}
+ const valid=credentialWizardValid(),hint=credentialWizardSecretHint(kind,wizard,valid);
+ setCredentialHint(pane,'secret',hint.text,hint.tone);
+ if(kind.extra?.options){if(input.name==='extra')refreshCredentialEnvironmentLinks(pane,wizard.extra)}
+ else if(kind.extra){const extraError=credentialExtraError(kind,wizard.extra);setCredentialHint(pane,'extra',extraError,extraError?'err':'')}
if(valid.ok)kind.guide.forEach((_,index)=>markCredentialGuide(index));
const next=$('#credentialWizard [data-wizard-next]');if(next)next.disabled=!valid.ok;
}
diff --git a/web/i18n-en.js b/web/i18n-en.js
index 6c40cdcb..f38277d4 100644
--- a/web/i18n-en.js
+++ b/web/i18n-en.js
@@ -18,7 +18,7 @@ Object.assign(window.LF_I18N_EN,{"日常工作": "Daily work", "会话": "Conver
Object.assign(window.LF_I18N_EN, {"发送前需要配置模型凭据":"Configure model credentials before sending", "配置 API Key":"Configure API Key", "先写下需求,配置 API Key 后即可发送":"Draft your request, then configure an API key to send"});
-Object.assign(window.LF_I18N_EN, {"国际站留空,国内站 internal,iOA 填 ioa":"International: leave empty; China: internal; iOA: ioa"});
+Object.assign(window.LF_I18N_EN, {"国际站":"International","国内站":"China","与 Key 所在站点一致":"same site as the key","Key 只能在创建它的站点使用":"A key only works on the site that issued it","前往国际站获取 API Key":"Get an API key on International","前往国内站获取 API Key":"Get an API key on China","前往iOA获取 API Key":"Get an API key on iOA","先在下方选择 CodeBuddy 账号所在的网络环境:国际站、国内站或 iOA":"First choose the network your CodeBuddy account belongs to below: International, China or iOA","登录该站点的 API Key 页面,新建 API Key":"Sign in to that site's API key page and create a key","复制以":"Copy the key starting with","开头的密钥粘贴到下方;DeepSeek、OpenAI 等第三方模型的 Key 不能填在这里":"and paste it below; keys for third-party models such as DeepSeek or OpenAI do not work here","这像是 DeepSeek、OpenAI 等第三方模型的 Key,CodeBuddy 会拒绝;第三方 Key 请改填到 Claude Code 或 Codex 凭证并设置 Base URL":"This looks like a key for a third-party model such as DeepSeek or OpenAI, which CodeBuddy rejects; put third-party keys in the Claude Code or Codex credential with a Base URL","CodeBuddy API Key 通常以 ck_ 开头,请确认复制的是 CodeBuddy 的 Key":"CodeBuddy API keys usually start with ck_; make sure you copied a CodeBuddy key"});
Object.assign(window.LF_I18N_EN,{"这是首次启动。创建的第一个账号将成为平台管理员。":"This is the first start. The first account you create becomes the platform administrator.","确认密码":"Confirm password","密码至少 6 个字符":"Use at least 6 characters","还没有账号?":"No account yet?","注册":"Sign up","已有账号?":"Already have an account?"});
Object.assign(window.LF_I18N_EN,{"未配置 API Key,暂时无法发送":"Add an API key to send messages","快速上手":"Get started","已完成":"done","关闭引导":"Dismiss guide","新手引导":"Getting started","配置模型 API Key":"Configure a model API key","在个人设置里填入 CodeBuddy API Key,Agent 才能开始工作。":"Add your CodeBuddy API key in personal settings so agents can work.","去配置":"Configure","准备一个项目":"Pick a project","项目用来归集需求、SOP 和运行记录。可以直接用体验项目,也可以新建项目并绑定 GitHub 仓库。":"Projects group requirements, SOPs and runs. Use the sample project or create one linked to a GitHub repository.","新建项目":"New project","和 Main Bot 聊一句":"Say hi to Main Bot","描述一个想法,Main Bot 会帮你拆解需求、推荐 SOP。":"Describe an idea; Main Bot breaks it down and suggests an SOP.","试一试":"Try it","跑通第一条 SOP":"Run your first SOP","在需求列表里新建需求并选择 SOP,观察执行、产物和人工审批。":"Create a requirement, pick an SOP, and follow execution, artifacts and approval.","去需求列表":"Open requirements","我想做一个待办清单小工具,帮我梳理需求并推荐合适的 SOP。":"I want to build a small to-do list app. Help me clarify the requirements and suggest an SOP."});
Object.assign(window.LF_I18N_EN,{"接入你的代码仓库":"Connect your code repository","在个人设置里配置 GitHub Token,Agent 才能拉取代码并提交 PR。":"Add a GitHub token in personal settings so agents can clone code and open pull requests.","为当前项目添加 GitHub 仓库,并配置 Git Token,SOP 才能改你的代码、提交 PR。":"Add a GitHub repository to this project and configure a Git token so SOPs can change your code and open pull requests.","配置 Token":"Add token","添加仓库":"Add repository"});
diff --git a/web/platform.css b/web/platform.css
index 3e2f415f..22116ce4 100644
--- a/web/platform.css
+++ b/web/platform.css
@@ -2302,7 +2302,12 @@ html[data-theme="dark"] .credential-logo.monochrome img{filter:invert(1)}
.credential-field>span em{color:var(--cr-tertiary);font-size:11.5px;font-style:normal;font-weight:400}
.credential-field small{color:var(--cr-tertiary);font-size:11.5px;transition:color .2s}
.credential-field small:empty{display:none}
-.credential-field small.is-err{color:var(--cr-err)}.credential-field small.is-ok{color:var(--cr-ok)}
+.credential-field small.is-err{color:var(--cr-err)}.credential-field small.is-ok{color:var(--cr-ok)}.credential-field small.is-warn{color:var(--cr-warn)}
+.credential-env-hint a{color:var(--cr-accent);text-decoration:none;white-space:nowrap}
+.credential-env-hint a:hover{text-decoration:underline}
+.credential-input select{width:100%;height:36px;margin:0;padding:0 32px 0 11px;border:1px solid var(--cr-line);border-radius:8px;background:var(--cr-surface) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23888' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E") no-repeat right 11px center;color:var(--cr-text);font:inherit;font-size:13px;outline:none;appearance:none;-webkit-appearance:none;cursor:pointer;transition:border-color .16s,box-shadow .25s var(--cr-flow)}
+.credential-input select:hover{border-color:var(--cr-line-strong)}
+.credential-input select:focus{border-color:color-mix(in srgb,var(--cr-accent) 55%,transparent);box-shadow:0 0 0 3px color-mix(in srgb,var(--cr-accent) 12%,transparent)}
.credential-input{position:relative;display:flex;align-items:center}
.credential-input input{width:100%;height:36px;margin:0;padding:0 36px 0 11px;border:1px solid var(--cr-line);border-radius:8px;background:var(--cr-surface);color:var(--cr-text);font:inherit;font-size:13px;outline:none;box-shadow:none;transition:border-color .16s,box-shadow .25s var(--cr-flow)}
.credential-input.is-plain input{padding-right:11px}
@@ -2311,6 +2316,7 @@ html[data-theme="dark"] .credential-logo.monochrome img{filter:invert(1)}
.credential-input input:focus{border-color:color-mix(in srgb,var(--cr-accent) 55%,transparent);box-shadow:0 0 0 3px color-mix(in srgb,var(--cr-accent) 12%,transparent)}
.credential-input.is-bad input{border-color:color-mix(in srgb,var(--cr-err) 60%,transparent);box-shadow:0 0 0 3px color-mix(in srgb,var(--cr-err) 10%,transparent)}
.credential-input.is-good input{border-color:color-mix(in srgb,var(--cr-ok) 50%,var(--cr-line))}
+.credential-input.is-warn input{border-color:color-mix(in srgb,var(--cr-warn) 55%,var(--cr-line))}
.credential-input.is-shake{animation:credentialShake .32s}
@keyframes credentialShake{25%{transform:translateX(-3px)}75%{transform:translateX(3px)}}
.credential-eye{position:absolute;right:4px;display:grid;place-items:center;width:28px;height:28px;margin:0;padding:0;border:0;border-radius:6px;background:transparent;color:var(--cr-tertiary);cursor:pointer}
@@ -2335,7 +2341,7 @@ html[data-theme="dark"] .credential-logo.monochrome img{filter:invert(1)}
.credential-note b{font-weight:600}
.credential-vline{display:flex;align-items:center;gap:7px;margin:0;color:var(--cr-muted);font-size:12px}
.credential-vline:empty{display:none}
-.credential-vline.is-err{color:var(--cr-err)}.credential-vline.is-info{color:var(--cr-info)}
+.credential-vline.is-err{color:var(--cr-err)}.credential-vline.is-info{color:var(--cr-info)}.credential-vline.is-warn{color:var(--cr-warn)}
.credential-vline>svg{flex:none}
.credential-swap{display:grid}
.credential-swap>*{grid-area:1/1;transition:opacity .2s,transform .3s var(--cr-fold)}
diff --git a/web/syntax_test.go b/web/syntax_test.go
index 13f505f9..b8ad216c 100644
--- a/web/syntax_test.go
+++ b/web/syntax_test.go
@@ -23,7 +23,7 @@ func TestCredentialBrandAssetsEmbedded(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- for _, want := range []string{"https://github.com/settings/tokens", "https://www.codebuddy.ai/", "credential-description", "git-token-verify"} {
+ for _, want := range []string{"https://github.com/settings/tokens", "https://www.codebuddy.ai/profile/keys", "https://copilot.tencent.com/profile/", "credential-description", "git-token-verify"} {
if !strings.Contains(string(app), want) {
t.Fatalf("credential UI is missing %q", want)
}
@@ -832,6 +832,35 @@ assert.equal(credentialSecretError(cred.kind('gitToken'), 'github_pat_1'), '');
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);
+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');
+assert.equal(codeBuddyKeyURL('typo'), 'https://www.codebuddy.ai/profile/keys');
+const cbKind = cred.kind('codeBuddyApiKey');
+assert.equal(credentialExtraValue(cbKind, 'iOA'), 'ioa');
+assert.equal(credentialExtraValue(cbKind, 'private-net'), '', 'an unknown value shows as 国际站, which is what the CLI uses');
+assert.equal(credentialExtraValue(cred.kind('codexApiKey'), 'https://p.example'), 'https://p.example');
+const cbEditor = credentialEditorHTML(cbKind, {codeBuddyApiKeyConfigured: true, codeBuddyInternetEnvironment: 'internal'});
+assert.ok(cbEditor.includes('<select name="extra">') && !cbEditor.includes('<input name="extra"'));
+assert.ok(cbEditor.includes('data-original="internal"') && cbEditor.includes('<option value="internal" selected>'));
+assert.ok(cbEditor.includes('href="https://copilot.tencent.com/profile/"') && cbEditor.includes('前往国内站获取 API Key'));
+const legacyEditor = credentialEditorHTML(cbKind, {codeBuddyApiKeyConfigured: true, codeBuddyInternetEnvironment: 'private-net'});
+assert.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'));
+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('无法识别'));
+// Third-party keys are flagged but never blocked.
+assert.equal(credentialSecretWarning(cbKind, 'ck_abc'), '');
+assert.match(credentialSecretWarning(cbKind, 'sk-abc'), /第三方/);
+assert.match(credentialSecretWarning(cbKind, 'abc'), /ck_/);
+assert.equal(credentialSecretWarning(cred.kind('codexApiKey'), 'sk-abc'), '');
+assert.equal(credentialSecretError(cbKind, 'sk-abc'), '');
+
// Delete swaps the action bar for the confirm bar without sending anything.
const pane = () => ({classList: {on: new Set(), toggle(name, on) { on ? this.on.add(name) : this.on.delete(name) }}});
const foot = pane(), confirm = pane();
@@ -862,12 +891,21 @@ assert.equal(calls.length, 0);
assert.ok(!credentialFieldHTML({label: 'k', name: 'secret', value: 'sk-LEAK'}).includes('sk-LEAK'), 'secrets are never written into markup');
assert.ok(credentialFieldHTML({label: 'u', name: 'extra', type: 'url', value: 'https://p.example'}).includes('value="https://p.example"'));
// 去配置 jumps straight to step 2 with no back button.
- cred.wizard = {step: 2, kind: 'codeBuddyApiKey', direct: true, secret: '', extra: '', guide: {}, error: ''};
+ cred.wizard = {step: 2, kind: 'codeBuddyApiKey', direct: true, secret: '', extra: 'ioa', guide: {}, error: ''};
+ const cbStepTwo = credentialWizardStepTwoHTML(cred.kind('codeBuddyApiKey'));
+ assert.ok(cbStepTwo.indexOf('<select name="extra">') < cbStepTwo.indexOf('name="secret"'), 'the network environment is picked before the key');
+ assert.ok(cbStepTwo.includes('href="https://tencent.sso.copilot.tencent.com/profile/keys" target="_blank" rel="noopener noreferrer" data-wizard-link="1" data-environment-link>前往iOA获取 API Key'));
+ assert.ok(!cbStepTwo.includes('https://www.codebuddy.ai/"'));
+ cred.wizard.extra = '';
assert.ok(credentialWizardStepTwoHTML(cred.kind('codeBuddyApiKey')).includes('credential-description'));
assert.ok(!credentialWizardFootHTML().includes('data-wizard-back'));
assert.ok(credentialWizardFootHTML().includes('data-wizard-next disabled'), 'an empty key blocks next');
cred.wizard.direct = false;
assert.ok(credentialWizardFootHTML().includes('data-wizard-back'));
+ // Step 3 names the environment and repeats the third-party key warning without echoing the key.
+ cred.wizard = {step: 3, kind: 'codeBuddyApiKey', direct: true, secret: 'sk-third', extra: 'internal', guide: {}, error: ''};
+ const cbStepThree = credentialWizardStepThreeHTML(cred.kind('codeBuddyApiKey'));
+ assert.ok(cbStepThree.includes('国内站 · copilot.tencent.com') && cbStepThree.includes('credential-vline is-warn') && !cbStepThree.includes('sk-third'));
// Step 3 never echoes the secret.
cred.wizard = {step: 3, kind: 'codeBuddyApiKey', direct: true, secret: 'cb_SECRET', extra: '', guide: {}, error: ''};
assert.ok(!credentialWizardStepThreeHTML(cred.kind('codeBuddyApiKey')).includes('SECRET'));
diff --git a/webtest/tests/workbench-credentials.test.mjs b/webtest/tests/workbench-credentials.test.mjs
index 7519d44f..c0c13550 100644
--- a/webtest/tests/workbench-credentials.test.mjs
+++ b/webtest/tests/workbench-credentials.test.mjs
@@ -54,6 +54,74 @@ test('credential wizard focuses the first field on its own but never pulls focus
assert.equal(pane().querySelector('input[name="secret"]').value, '');
});
+test('CodeBuddy wizard picks the network environment from a list and its key link follows the choice', 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};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()`);
+ app.evaluate(`openCredentialWizard('codeBuddyApiKey')`);
+ const pane = () => app.document.querySelector('#credentialWizard .credential-pane:not(.is-leaving)');
+ const select = pane().querySelector('select[name="extra"]');
+ assert.ok(select, 'network environment is a list, not free text');
+ assert.equal(pane().querySelector('input[name="extra"]'), null);
+ assert.deepEqual([...select.options].map((option) => option.value), ['', 'internal', 'ioa']);
+ const guideLink = () => pane().querySelector('[data-environment-link]');
+ const hintLink = () => pane().querySelector('[data-credential-key-link]');
+ assert.equal(guideLink().getAttribute('href'), 'https://www.codebuddy.ai/profile/keys');
+ select.value = 'internal';
+ select.dispatchEvent(new app.window.Event('input', { bubbles: true }));
+ assert.equal(guideLink().getAttribute('href'), 'https://copilot.tencent.com/profile/');
+ assert.match(guideLink().textContent, /国内站/);
+ assert.equal(hintLink().getAttribute('href'), 'https://copilot.tencent.com/profile/');
+
+ const secret = pane().querySelector('input[name="secret"]');
+ secret.value = 'sk-third-party';
+ secret.dispatchEvent(new app.window.Event('input', { bubbles: true }));
+ const hint = pane().querySelector('[data-credential-hint="secret"]');
+ assert.equal(hint.className, 'is-warn');
+ assert.match(hint.textContent, /第三方/);
+ const next = app.document.querySelector('#credentialWizard [data-wizard-next]');
+ assert.equal(next.disabled, false, 'the warning never blocks saving');
+ secret.value = 'ck_placeholder';
+ secret.dispatchEvent(new app.window.Event('input', { bubbles: true }));
+ assert.equal(pane().querySelector('[data-credential-hint="secret"]').className, 'is-ok');
+ next.click();
+ await settle(3);
+ assert.match(pane().textContent, /国内站 · copilot\.tencent\.com/);
+ app.document.querySelector('#credentialWizard [data-wizard-next]').click();
+ await settle(6);
+ const saved = app.router.calls.find((call) => call.path === '/api/users/1/credentials');
+ assert.deepEqual(saved.body, { codeBuddyApiKey: 'ck_placeholder', codeBuddyInternetEnvironment: 'internal' });
+});
+
+test('CodeBuddy inline editor changes only the network environment and keeps the key link in step', 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:'ioa'};
+ state.data.users[0]=state.currentUser;
+ `);
+ app.router.put('/api/users/1/credentials', { id: 1, username: 'tester', codeBuddyApiKeyConfigured: true });
+ await app.evaluate(`renderPersonalSettings()`);
+ const row = app.document.querySelector('[data-credential-row="codeBuddyApiKey"]');
+ assert.match(row.querySelector('.credential-row-who small').textContent, /网络环境iOA/);
+ 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, 'ioa');
+ assert.equal(save.disabled, true);
+ select.value = '';
+ select.dispatchEvent(new app.window.Event('input', { bubbles: true }));
+ assert.equal(save.disabled, false);
+ assert.equal(row.querySelector('[data-credential-key-link]').getAttribute('href'), 'https://www.codebuddy.ai/profile/keys');
+ save.click();
+ await settle(6);
+ const saved = app.router.calls.find((call) => call.path === '/api/users/1/credentials');
+ assert.deepEqual(saved.body, { codeBuddyApiKey: '', codeBuddyInternetEnvironment: '' });
+});
+
test('credential panel filters, expands, validates, reveals secrets, and confirms deletion', async (t) => {
const app = await loadApp();
t.after(app.close);