diff --git a/.env.example b/.env.example index 348ab82a..d417f354 100644 --- a/.env.example +++ b/.env.example @@ -13,6 +13,11 @@ LOOPFORGE_DB_ROOT_PASSWORD=REPLACE_ME LOOPFORGE_MYSQL_PORT=33315 # Optional public address reachable from execution containers/runners: AGENTFLOW_PLATFORM_MCP_URL= +# Optional managed Git and TAPD web hosts, with a port if required. +AGENTFLOW_GONGFENG_HOST= +AGENTFLOW_TAPD_HOST= +# Optional deployment-level credential for a configured tracker MCP. +AGENTFLOW_MCP_TOKEN= # Optional model IDs available to your CodeBuddy account (comma-separated): AGENTFLOW_ASSISTANT_MODELS= AGENTFLOW_ASSISTANT_MODEL= diff --git a/.github/workflows/platform.yml b/.github/workflows/platform.yml index 50f32ca5..61259075 100644 --- a/.github/workflows/platform.yml +++ b/.github/workflows/platform.yml @@ -55,7 +55,7 @@ jobs: - name: Check real CLI credentials, MCP, stream parsing and native-tool restrictions env: AGENTFLOW_TEST_NATIVE_PROVIDERS: '1' - run: go test -p=2 ./internal/httpapi ./internal/runtime -run 'TestAssistantNativeProviderGateway|TestNativeProviderCustomGateway' -count=1 -v + run: go test -p=2 ./internal/httpapi ./internal/runtime -run 'TestAssistantNativeProviderGateway|TestNativeProviderCustomGateway|TestFeatureModelsWithoutCodeBuddy' -count=1 -v - run: go vet ./... - run: go run golang.org/x/vuln/cmd/govulncheck@v1.9.0 ./... - run: python3 scripts/collect-go-notices.py diff --git a/Dockerfile b/Dockerfile index 43b66605..c445ad52 100644 --- a/Dockerfile +++ b/Dockerfile @@ -28,10 +28,12 @@ RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache COPY --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 GOOS=${TARGETOS} GOARCH=${TARGETARCH} bash scripts/build-binaries.sh --platform /out FROM node:22-bookworm +ARG CODEBUDDY_PACKAGE=@tencent-ai/codebuddy-code@2.167.0 RUN --mount=type=cache,target=/root/.npm apt-get update && apt-get install -y --no-install-recommends ca-certificates git openssh-client bash curl python3 ripgrep \ && rm -rf /var/lib/apt/lists/* \ - && npm install -g @openai/codex@0.162.1 @tencent-ai/codebuddy-code@2.167.0 @deepseek-ai/dsh@0.2.2-rc.1 @wecom/cli@1.3.4 \ - && wecom-cli --version + && npm install -g @openai/codex@0.162.1 @deepseek-ai/dsh@0.2.2-rc.1 @wecom/cli@1.3.4 \ + && wecom-cli --version \ + && if [ -n "$CODEBUDDY_PACKAGE" ]; then npm install -g "$CODEBUDDY_PACKAGE"; fi # A relocatable Python that sandboxes of images without python3 mount for the # native CLI hooks (internal/runtime/toolchain.go). Its terminfo database has # names differing only in case, which a case-insensitive data directory (macOS) diff --git a/README.md b/README.md index 4d25faf4..d465ff9e 100644 --- a/README.md +++ b/README.md @@ -113,11 +113,11 @@ New accounts join the **LoopForge demo project**, which includes an SOP made onl
-- **Executors.** Pick one of ten CLIs beside the home composer, then a model. Every SOP role can choose its executor independently (built-in roles default to CodeBuddy). Requirement clarification, AI notification summaries, Bot replies and run evals currently use CodeBuddy, so their model pickers list CodeBuddy models only and the server refuses a model of another CLI instead of switching it to CodeBuddy; scheduled assistant tasks run on the CLI the task selects. +- **Executors.** Choose a CLI and model for chat, requirement clarification, Bot replies, notification reports, run evaluation, or static preview. Each SOP role can select its own CLI, and built-in templates still default to CodeBuddy. Scheduled prompts use the CLI selected on the schedule. The platform can run without a CodeBuddy installation or key once its workflows use other CLIs. [Deployment and upgrade](docs/deployment.md#choosing-an-executor) | Executor | Credentials | Installation | | --- | --- | --- | - | **CodeBuddy** | Personal key, or a shared key an administrator configures for chat and SOP runs | In the Docker image | + | **CodeBuddy** | Personal key, or a shared key an administrator configures for chat and SOP runs | Bundled by default, optional on source builds | | **Codex** | Personal key; a connected execution machine can use its local login | In the Docker image | | **Claude Code** | Personal key; a connected execution machine can use its local login | Installed from npm on first use, then cached | | **OpenCode · Kimi Code · Pi** | Personal key only | Installed from npm on first use, then cached | diff --git a/README.zh-CN.md b/README.zh-CN.md index d6fc67db..dcc0113f 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -113,11 +113,11 @@ GitLab、Gitea、Gogs 等托管可[配置 Git SSH](docs/deployment.md#git-reposi
-- **执行器。** 在首页输入框旁从 10 种 CLI 中选择一种,再选择模型。每个 SOP 角色都可以独立选择执行器(内置角色默认 CodeBuddy)。需求澄清、通知 AI 汇总、Bot 回复和运行评测目前使用 CodeBuddy,这些入口的模型列表只列 CodeBuddy 模型,服务端收到其他 CLI 的模型会直接拒绝并说明原因,不会悄悄换成 CodeBuddy;定时助手任务使用任务所选的执行器。 +- **执行器。** 首页对话、需求澄清、Bot 回复、通知汇报、运行评测和静态预览均可选择 CLI 与模型。每个 SOP 角色可以独立选择 CLI,内置模板仍默认使用 CodeBuddy。定时提示词使用任务所选的 CLI。将使用中的流程配置为其他 CLI 后,平台可在未安装 CodeBuddy、未配置其 Key 的环境中运行。[部署与升级说明](docs/deployment.md#choosing-an-executor) | 执行器 | 凭据 | 安装方式 | | --- | --- | --- | - | **CodeBuddy** | 个人 Key,或管理员配置的平台共享 Key(覆盖对话和 SOP 运行) | Docker 镜像内置 | + | **CodeBuddy** | 个人 Key,或管理员配置的平台共享 Key(覆盖对话和 SOP 运行) | 默认内置,源码构建时可省略 | | **Codex** | 个人 Key;已连接的执行机器可使用本机登录 | Docker 镜像内置 | | **Claude Code** | 个人 Key;已连接的执行机器可使用本机登录 | 首次使用时从 npm 安装并缓存 | | **OpenCode · Kimi Code · Pi** | 仅个人 Key | 首次使用时从 npm 安装并缓存 | diff --git a/chatbot/src/App.jsx b/chatbot/src/App.jsx index 53dcd3c2..d636c380 100644 --- a/chatbot/src/App.jsx +++ b/chatbot/src/App.jsx @@ -51,7 +51,7 @@ import { reconcileOperation, visibleSidebarArtifact } from "./platform.js"; import { isGeneratedArtifact, shouldRevealArtifactPanel } from "./artifact-autoreveal.js"; import { IconButton, Dialog, Menu, SelectMenu, CredentialAction } from "./ui"; import { CLIInstallAction } from "./cli-install.jsx"; -import { credentialHint, openCredentialSettings } from "./credentials"; +import { openCredentialSettings } from "./credentials"; import { groupSessionHistory, scheduledSession, sessionProjectName } from "./session-history.js"; import { runSessionState, sessionReplyStatus, sessionTooltip, sidebarReplyStatus } from "./session-status.js"; import { unreadReply, useReadReplies } from "./session-unread.js"; @@ -78,7 +78,7 @@ import ModelPicker from "./ModelPicker"; import ModelProviderIcon, { hasProviderLogo } from "./ModelProviderIcon"; import PermissionPicker, { normalizeApprovalMode } from "./PermissionPicker"; import { useComposerOptions } from "./composer-preferences.js"; -import { conversationEngine, engineBrand } from "./engines.js"; +import { EXECUTORS, conversationEngine, engineBrand } from "./engines.js"; import { effortOptions } from "./effort.js"; import QuickAccessWizard from "./QuickAccessWizard"; import HarnessSelect from "./HarnessSelect"; @@ -392,7 +392,7 @@ export default function App() { const approvalScope = chat.activeId ? chat.session?.id === chat.activeId && sessionApprovalScope(chat.session) : draftApprovalScope(newDraftSlot, chat.projectId); - const approval = normalizeApprovalMode(approvalScope && readApproval(approvalScope).mode); + const approval = normalizeApprovalMode((approvalScope && readApproval(approvalScope).mode) || (!chat.activeId && chat.defaultApproval)); function setApproval(value) { if (!approvalScope) return; const mode = normalizeApprovalMode(value); @@ -511,9 +511,12 @@ export default function App() { "个人对话"; const sessionLoading = !!chat.activeId && chat.session?.id !== chat.activeId; const composerLoading = sessionLoading || chat.replyStatePending; + const hasComposerExecutor = !!chat.executor || chat.local; + const needsExecutor = chat.ready && chat.user && !chat.user.isGuest && !chat.readOnly && + !hasComposerExecutor && !composerLoading && (chat.machinesReady || chat.machineError); const selectedModel = chat.models.find((m) => m.id === chat.model) || (!chat.local ? chat.modelDetails : null); const modelLabel = - (selectedModel?.name || chat.model)?.replace(/^Claude-/, "").replace(/^GPT-/, "") || "模型"; + (hasComposerExecutor && (selectedModel?.name || chat.model)?.replace(/^Claude-/, "").replace(/^GPT-/, "")) || "模型"; // The CLI switch is only for a conversation that has not started. A reply // in flight, or one already saved, keeps that CLI; another CLI needs a new chat. const lockedExecutorId = chat.session @@ -521,7 +524,7 @@ export default function App() { (chat.busy ? chat.executor : "") : ""; const pinnedExecutor = lockedExecutorId - ? (chat.executors || []).find((item) => item.id === lockedExecutorId) + ? EXECUTORS.find((item) => item.id === lockedExecutorId) : undefined; const projectOptions = projectPickerOptions( chat.projects, @@ -568,6 +571,14 @@ export default function App() { } if (starter.prompt) useStarter(starter.prompt); } + function closeQuickAccess() { + setQuickAccessOpen(false); + if (window.parent !== window) return; + const url = new URL(location.href); + if (!url.searchParams.has("quickAccess")) return; + url.searchParams.delete("quickAccess"); + history.replaceState(history.state, "", url); + } useEffect(() => { const wide = sidebarViewport().matchMedia("(min-width:1001px)"); const apply = () => setSidebarWidth(readSidebarWidth()); @@ -631,9 +642,13 @@ export default function App() { const listener = (event) => { if ( event.source !== window.parent || - event.origin !== location.origin || - event.data?.type !== "agentflow-chat-mention-issue" + event.origin !== location.origin ) return; + if (event.data?.type === "agentflow-chat-resume-quick-access") { + setQuickAccessOpen(true); + return; + } + if (event.data?.type !== "agentflow-chat-mention-issue") return; const issueId = String(event.data.issueId || ""); const projectId = String(event.data.projectId || ""); if (!issueId || !projectId) return; @@ -817,7 +832,7 @@ export default function App() { closeMenu(); } async function submit() { - if (uploading || composerLoading || draftReady.current !== draftKey || + if (!hasComposerExecutor || uploading || composerLoading || draftReady.current !== draftKey || (!chat.activeId && savingDraftApproval.current)) return; follow.current = true; const snapshot = draftSnapshot({ text, attachments, references }); @@ -1882,29 +1897,15 @@ export default function App() { ) : null} - {chat.ready && - !chat.local && - chat.user && - !chat.user.isGuest && - !chat.user.codeBuddyApiKeyConfigured && - !chat.sponsoredModel && - chat.executor === "codebuddy" && - !chat.readOnly && - credentialHint(chat.error)?.field !== "codeBuddyApiKey" ? ( + {needsExecutor ? (
-
) : null} @@ -2216,7 +2217,7 @@ export default function App() { e.target.value = ""; }} /> - {chat.executors.length > 1 && !pinnedExecutor && !chat.submitting ? ( + {hasComposerExecutor && chat.executors.length > 0 && !pinnedExecutor && !chat.submitting ? ( ) : null} setQuickAccessOpen(false)} + onClose={closeQuickAccess} onOpenView={(view) => navigate(view)} - onCredentialsSaved={chat.refreshUser} + onCredentialsSaved={chat.refreshCredentials} onCompleted={async (nextProjectId) => { await chat.refresh(); if (nextProjectId) await chat.selectProject(nextProjectId); diff --git a/chatbot/src/QuickAccessWizard.jsx b/chatbot/src/QuickAccessWizard.jsx index e4570b35..f53265ba 100644 --- a/chatbot/src/QuickAccessWizard.jsx +++ b/chatbot/src/QuickAccessWizard.jsx @@ -13,18 +13,12 @@ import HarnessIcon from "./HarnessIcon"; import SlidingTabs from "./SlidingTabs"; import { api, canChatInProject, canManageProjectRepos, write } from "./api"; import { usePanelPresence } from "./usePanelPresence"; -import { - CODEBUDDY_ENVIRONMENTS, - codeBuddyEnvironment, - codeBuddyEnvironmentIntent, - codeBuddyEnvironmentLegacy, - codeBuddyKeyURL, - codeBuddyKeyWarning, - openCredentialSettings, -} from "./credentials"; +import { EXECUTORS, personalEngineConfigured } from "./engines.js"; +import { openCredentialSettings } from "./credentials"; import "./quick-access-wizard.css"; const DEFAULT_SOP_ID = "generic-backend-delivery"; +const CREDENTIALS_REQUIRED = "请先添加一个 Git 凭据或执行器。"; // Display names for the models users without their own key may use. export function sharedModelNames(models, fallback = "") { @@ -34,26 +28,16 @@ export function sharedModelNames(models, fallback = "") { .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", title: "凭据与授权", - desc: "GitHub 访问与模型密钥", + desc: "仓库访问与执行器", }, { id: "project", title: "项目与仓库", - desc: "选择或新建项目,绑定 GitHub 仓库", + desc: "选择或新建项目,绑定 Git 仓库", }, { id: "workflow", @@ -578,84 +562,12 @@ function parseGitHubRepo(raw) { }; } -// SSH preview first (it leaves github.com to the GitHub parser, matching the -// server); self-hosted legacy repositories keep the git.example.com form. -export function parseGongfengRepo(raw) { - const httpsInfo = globalThis.LoopForgeGitHTTPS(raw); - if (httpsInfo) return httpsInfo; - const sshInfo = globalThis.LoopForgeGitSSH(raw); - if (sshInfo) return sshInfo; - const github = parseGitHubRepo(raw); - if (github) return github; - const original = String(raw || "") - .trim() - .replace(/^['"]+|['"]+$/g, ""); - if (!original) return null; - const strippedClone = /^git\s+clone\s+/i.test(original); - let value = original - .replace(/^git\s+clone\s+/i, "") - .trim() - .replace(/^['"]+|['"]+$/g, ""); - if (strippedClone && /\s/.test(value)) value = value.split(/\s+/)[0]; - if (!value || /[\s"'<>()\\]/.test(value)) return null; - const ssh = /^(git@|ssh:\/\/)/i.test(value); - value = value.replace(/\/+$/, ""); - const hadScheme = value.includes("://"); - const hadAt = value.includes("@"); - let rest = value; - if (hadScheme) rest = rest.slice(rest.indexOf("://") + 3); - if (rest.includes("@")) rest = rest.slice(rest.lastIndexOf("@") + 1); - let path = ""; - if (!hadScheme && !hadAt && !rest.includes(":")) { - path = rest; - } else if (rest.includes("/")) { - const cut = rest.search(/[:/]/); - const host = rest.slice(0, cut); - if (host.toLowerCase() !== "git.example.com") return null; - path = rest.slice(cut + 1); - if (rest[cut] === ":") { - const slash = path.indexOf("/"); - if (slash >= 0 && /^\d+$/.test(path.slice(0, slash))) - path = path.slice(slash + 1); - } - } else { - return null; - } - path = path.replace(/^git\.example\.com\//i, "").replace(/\.git$/i, ""); - for (const marker of [ - "/-/", - "/tree/", - "/blob/", - "/commit/", - "/commits/", - "/merge_requests/", - "/issues/", - "/snippets/", - "/wikis/", - "/releases/", - "/tags/", - ]) { - const index = path.indexOf(marker); - if (index >= 0) path = path.slice(0, index); - } - path = path.replace(/^\/+|\/+$/g, ""); - const parts = path.split("/"); - if ( - parts.length < 2 || - path.includes("..") || - parts.some((seg) => !seg || /[\s\\?#]/.test(seg)) - ) - return null; - const name = parts[parts.length - 1]; - return { - project: path, - provider: "gongfeng", - name, - webUrl: `https://git.example.com/${path}`, - cloneUrl: ssh - ? `git@git.example.com:${path}.git` - : `https://git.example.com/${path}.git`, - }; +// Explicit SSH keeps its transport. Managed HTTPS links use the configured host. +export function parseGongfengRepo(raw, host = "") { + return globalThis.LoopForgeGitSSH(raw) || + globalThis.LoopForgeGongfengRepository(raw, host) || + globalThis.LoopForgeGitHTTPS(raw) || + parseGitHubRepo(raw); } function slugifyProjectId(value) { @@ -782,7 +694,12 @@ export default function QuickAccessWizard({ }) { const [step, setStep] = useState(0); const [phase, setPhase] = useState("wizard"); - const [storedUser, setStoredUser] = useState(user); + const [credentialUser, setCredentialUser] = useState(null); + const storedUser = credentialUser?.id === user?.id ? credentialUser || user : user; + const { id: userId, loginName, chineseName, isPlatformAdmin, platformRole, isGuest } = user || {}; + const [credentialsPending, setCredentialsPending] = useState(false); + const [gitHttpHosts, setGitHttpHosts] = useState([]); + const [gongfengHost, setGongfengHost] = useState(""); const [sshCredentials, setSSHCredentials] = useState({ userId: null, keys: null, error: false }); const [catalogProjects, setCatalogProjects] = useState(projects); const [repositories, setRepositories] = useState([]); @@ -793,9 +710,6 @@ export default function QuickAccessWizard({ const [saving, setSaving] = useState(false); 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"); @@ -936,7 +850,15 @@ export default function QuickAccessWizard({ [availableWorkflows, selectedWorkflowId], ); - const parsedRepo = useMemo(() => parseGongfengRepo(repoUrl), [repoUrl]); + const parsedRepo = useMemo(() => parseGongfengRepo(repoUrl, gongfengHost), [repoUrl, gongfengHost]); + useEffect(() => { + if (!open) return; + let current = true; + api("/api/auth/gongfeng").then(status => { + if (current) setGongfengHost(status?.host || ""); + }).catch(() => {}); + return () => { current = false; }; + }, [open]); // Reopening during the exit transition reverses it onto the same content. useEffect(() => { @@ -947,9 +869,10 @@ export default function QuickAccessWizard({ setPhase("wizard"); setError(""); setGitToken(""); - setCodeBuddyApiKey(""); - setCodeBuddyEnvChoice(null); setGitVerify(null); + setCredentialUser(null); + setCredentialsPending(false); + setGitHttpHosts([]); setCompletedSummary(null); setBindRepoNow(true); setPreviewTab("stages"); @@ -957,50 +880,20 @@ export default function QuickAccessWizard({ setKeyTouched(false); }, [open]); - const verifyStoredGitToken = useCallback( - async (uid = user?.id) => { - if (!uid) return null; - setVerifyingGit(true); - try { - const result = await api( - `/api/users/${encodeURIComponent(uid)}/git-token/verify`, - ); - setGitVerify(result); - return result; - } catch (err) { - const fallback = { valid: false, error: err.message }; - setGitVerify(fallback); - return fallback; - } finally { - setVerifyingGit(false); - } - }, - [user?.id], - ); - useEffect(() => { if (!open) return undefined; let active = true; async function load() { setLoading(true); try { - const [usersRes, projectsRes, reposRes, workflowsRes, agentsRes] = + const [projectsRes, reposRes, workflowsRes, agentsRes] = await Promise.all([ - api("/api/users").catch(() => []), api("/api/projects").catch(() => projects), api("/api/repositories").catch(() => []), api("/api/workflows").catch(() => []), api("/api/agents").catch(() => []), ]); if (!active) return; - const freshUser = - (usersRes || []).find( - (item) => Number(item.id) === Number(user?.id), - ) || user; - setStoredUser(mergeFreshUser(user, freshUser)); - if (freshUser?.gitHubCredentialConfigured && freshUser?.id) { - void verifyStoredGitToken(freshUser.id); - } const nextProjects = Array.isArray(projectsRes) ? projectsRes : projects; @@ -1009,9 +902,8 @@ export default function QuickAccessWizard({ const nextWorkflows = Array.isArray(workflowsRes) ? workflowsRes : []; setWorkflows(nextWorkflows); setProjectAgents(Array.isArray(agentsRes) ? agentsRes : []); - const mine = nextProjects.filter((project) => - canChatInProject(project, freshUser), - ); + const actor = userId == null ? null : { id: userId, isPlatformAdmin, platformRole }; + const mine = nextProjects.filter((project) => canChatInProject(project, actor)); const preferred = mine.find((project) => project.id === projectId) || mine[0] || null; if (preferred) { @@ -1028,8 +920,8 @@ export default function QuickAccessWizard({ setSelectedWorkflowId(preferred.workflowId); } else { setProjectMode("create"); - const login = freshUser?.loginName || "team"; - const suggestedName = `${freshUser?.chineseName || login} 的项目`; + const login = loginName || "team"; + const suggestedName = `${chineseName || login} 的项目`; setNewProjectName(suggestedName); setNewProjectId(slugifyProjectId(`${login}-project`) || "my-project"); setNewProjectKey(deriveProjectKey(login)); @@ -1042,24 +934,46 @@ export default function QuickAccessWizard({ return () => { active = false; }; - }, [open, projectId, projects, user]); + }, [open, projectId, projects, userId, loginName, chineseName, isPlatformAdmin, platformRole]); useEffect(() => { - if (!open || !user?.id || user.isGuest) return undefined; + if (!open || !userId || isGuest) return undefined; let active = true; let generation = 0; const refresh = () => { const version = ++generation; - api(`/api/users/${encodeURIComponent(user.id)}/git-ssh-keys`) + const current = () => active && version === generation; + api("/api/users") + .then(async rows => { + const fresh = rows?.find(item => Number(item.id) === Number(userId)); + if (!current() || !fresh) return; + setCredentialUser(fresh); + const http = fresh.gitHttpCredentialsConfigured + ? await api(`/api/users/${encodeURIComponent(userId)}/git-http-credentials`).catch(() => []) + : []; + if (current()) setGitHttpHosts(http.map(item => item.host)); + }) + .catch(() => {}) + .finally(() => { if (current()) setCredentialsPending(false); }); + api(`/api/users/${encodeURIComponent(userId)}/git-ssh-keys`) .then((keys) => { - if (active && version === generation) setSSHCredentials({ userId: user.id, keys: Array.isArray(keys) ? keys : [], error: false }); + if (current()) setSSHCredentials({ userId, keys: Array.isArray(keys) ? keys : [], error: false }); }) .catch(() => { - if (active && version === generation) setSSHCredentials({ userId: user.id, keys: [], error: true }); + if (current()) setSSHCredentials({ userId, keys: [], error: true }); }); }; const credentialsChanged = (event) => { - if (event.origin === location.origin && event.source === window.parent && event.data?.type === "agentflow-credentials-changed") refresh(); + if (event.source !== window.parent || event.origin !== location.origin) return; + if (event.data?.type === "agentflow-chat-resume-quick-access") { + headingRef.current?.focus({ preventScroll: true }); + refresh(); + return; + } + if (event.data?.type !== "agentflow-credentials-changed") return; + setCredentialsPending(true); + setError(previous => previous === CREDENTIALS_REQUIRED ? "" : previous); + refresh(); }; refresh(); window.addEventListener("focus", refresh); @@ -1069,7 +983,7 @@ export default function QuickAccessWizard({ window.removeEventListener("focus", refresh); window.removeEventListener("message", credentialsChanged); }; - }, [open, user?.id, user?.isGuest]); + }, [open, userId, isGuest]); useEffect(() => { if (!open || !selectedWorkflowId) return undefined; @@ -1099,42 +1013,14 @@ export default function QuickAccessWizard({ headingRef.current?.focus({ preventScroll: true }); }, [open, step, phase]); - useEffect(() => { - if (!open) return undefined; - const refreshUser = () => { - api("/api/users") - .then((usersRes) => { - const fresh = (usersRes || []).find( - (item) => Number(item.id) === Number(user?.id), - ); - if (fresh) { - setStoredUser((prev) => mergeFreshUser(prev, fresh)); - if (fresh.gitHubCredentialConfigured) { - void verifyStoredGitToken(fresh.id); - } - } - }) - .catch(() => {}); - }; - window.addEventListener("focus", refreshUser); - const credentialsChanged = (event) => { - if (event.origin === location.origin && event.source === window.parent && event.data?.type === "agentflow-credentials-changed") refreshUser(); - }; - window.addEventListener("message", credentialsChanged); - return () => { - window.removeEventListener("focus", refreshUser); - window.removeEventListener("message", credentialsChanged); - }; - }, [open, user?.id, verifyStoredGitToken]); - useEffect(() => { if (!open) return undefined; const onKeyDown = (event) => { - if (event.key === "Escape" && !saving && !closeActiveSelect) onClose?.(); + if (event.key === "Escape" && !saving && !verifyingGit && !closeActiveSelect) onClose?.(); }; window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); - }, [open, saving, onClose]); + }, [open, saving, verifyingGit, onClose]); useEffect(() => { if (projectMode !== "create" || !parsedRepo) return; @@ -1185,30 +1071,24 @@ export default function QuickAccessWizard({ const activeStepIndex = phase === "success" ? STEPS.length - 1 : step; const activeStep = STEPS[activeStepIndex] || STEPS[0]; const wizardStepCount = STEPS.length - 1; - const gitReady = Boolean(storedUser?.gitHubCredentialConfigured || gitToken.trim()); - const hasSSHKeys = Boolean(storedUser?.gitSshKeyConfigured); - const selectedSSHRepo = parsedRepo || parseGongfengRepo(defaultRepo?.cloneUrl); + const gitHubReady = Boolean(storedUser?.gitHubCredentialConfigured); + const gongfengReady = Boolean(storedUser?.gitTokenOAuth); + const hasGit = gitHubReady || gongfengReady || Boolean(storedUser?.gitSshKeyConfigured || storedUser?.gitHttpCredentialsConfigured); const sshKeysLoaded = sshCredentials.userId === user?.id && sshCredentials.keys !== null; const hasSSHKey = (remote) => sshKeysLoaded && !sshCredentials.error && sshCredentials.keys.some( (key) => globalThis.LoopForgeGitSSHHost(key.host) === remote?.host, ); - const sshReady = hasSSHKey(selectedSSHRepo); - const sshRepository = (parsedRepo || defaultRepo)?.provider === "ssh"; - 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 = - codeBuddyEnvironmentIntent(storedCodeBuddyEnvRaw)?.value ?? ""; - const codeBuddyEnvLegacy = codeBuddyEnvironmentLegacy(storedCodeBuddyEnvRaw); - const codeBuddyEnv = codeBuddyEnvChoice ?? storedCodeBuddyEnv; - const codeBuddyEnvInfo = - codeBuddyEnvironment(codeBuddyEnv) || CODEBUDDY_ENVIRONMENTS[0]; - const codeBuddyWarning = codeBuddyKeyWarning(codeBuddyApiKey); + const gitAccess = (repo) => { + if (repo?.provider === "ssh") return { label: "Git SSH", ready: hasSSHKey(repo) }; + if (repo?.provider === "https") return { label: "Git HTTPS", ready: gitHttpHosts.includes(repo.host) }; + if (repo?.provider === "github") return { label: "GitHub", ready: gitHubReady }; + if (repo?.provider === "gongfeng") return { label: "工蜂", ready: gongfengReady }; + return { label: "Git", ready: hasGit }; + }; + const selectedRepo = (bindRepoNow && parsedRepo) || parseGongfengRepo(defaultRepo?.cloneUrl, gongfengHost); + const repoAccess = gitAccess(selectedRepo); + const readyCLIs = EXECUTORS.filter(cli => personalEngineConfigured(storedUser, cli.id)); + const cliReady = readyCLIs.length > 0 || Boolean(sponsoredModel); const nodes = activeWorkflow?.nodes?.filter((node) => node.type === "agent") || FALLBACK_NODES; @@ -1219,87 +1099,56 @@ export default function QuickAccessWizard({ setStep(next); } - async function saveTypedCredentials() { - if (!user?.id) return storedUser; - const payload = {}; - let savedGit = false; - if (gitToken.trim()) { - const endpoint = `/api/users/${encodeURIComponent(user.id)}/git-http-credentials`; - const credentials = await api(endpoint); - const existing = credentials.find(credential => credential.host === "github.com"); - await write(endpoint, { ...(existing ? {id:existing.id} : {}), host:"github.com", platform:"github", name:"GitHub", username:"x-access-token", token:gitToken.trim() }, "PUT"); - savedGit = true; - } - if (codeBuddyApiKey.trim()) - payload.codeBuddyApiKey = codeBuddyApiKey.trim(); - // A key is always saved with the environment it was issued for. - if (codeBuddyApiKey.trim() || codeBuddyEnv !== storedCodeBuddyEnvRaw) - payload.codeBuddyInternetEnvironment = codeBuddyEnv; - if (!Object.keys(payload).length && !savedGit) return storedUser; - const saved = await write( - `/api/users/${encodeURIComponent(user.id)}/credentials`, - payload, - "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); - void onCredentialsSaved?.(); - window.parent !== window && - window.parent.postMessage( - { type: "agentflow-credentials-changed" }, - location.origin, - ); - return merged; - } - async function verifyGit() { - if (!user?.id || verifyingGit) return; + if (!userId || verifyingGit) return false; + const secret = gitToken.trim(); + const userPath = `/api/users/${encodeURIComponent(userId)}`; setVerifyingGit(true); setGitVerify(null); setError(""); try { - const typed = gitToken.trim(); - const result = typed - ? await write( - `/api/users/${encodeURIComponent(user.id)}/git-token/verify`, - { token: typed }, - ) - : await api( - `/api/users/${encodeURIComponent(user.id)}/git-token/verify`, - ); + const result = secret + ? await write(`${userPath}/git-token/verify`, { token: secret }) + : await api(`${userPath}/git-token/verify`); + if (result.valid && secret) { + const endpoint = `${userPath}/git-http-credentials`; + const credentials = await api(endpoint); + const existing = credentials.find(credential => credential.host === "github.com"); + await write(endpoint, { + ...(existing ? { id: existing.id } : {}), + host: "github.com", platform: "github", name: "GitHub", username: "x-access-token", token: secret, + }, "PUT"); + setCredentialUser({ ...storedUser, id: userId, gitHubCredentialConfigured: true, gitHttpCredentialsConfigured: true }); + setGitToken(""); + onCredentialsSaved?.(); + if (window.parent !== window) { + window.parent.postMessage({ type: "agentflow-credentials-changed" }, location.origin); + } + } setGitVerify(result); - if (result?.valid && typed) await saveTypedCredentials(); - } catch (err) { - setGitVerify({ valid: false, error: err.message }); + return result.valid; + } catch (failure) { + setGitVerify({ valid: false, error: failure.message }); + return false; } finally { setVerifyingGit(false); } } async function nextStep() { - if (saving) return; + if (saving || verifyingGit) return; setError(""); if (activeStep.id === "auth") { - if (!gitReady && !hasSSHKeys && !codeBuddyReady && !sponsoredModel) { - setError("请先配置 GitHub Git Token、Git SSH 密钥或 CodeBuddy API Key。"); + if (gitToken.trim()) { + if (!(await verifyGit())) { + setError("GitHub 令牌未保存,请检查校验结果。"); + return; + } + } else if (!hasGit && !cliReady) { + setError(CREDENTIALS_REQUIRED); return; } - setSaving(true); - try { - await saveTypedCredentials(); - goToStep(1); - } catch (err) { - setError(err.message); - } finally { - setSaving(false); - } + goToStep(1); return; } if (activeStep.id === "project") { @@ -1345,7 +1194,6 @@ export default function QuickAccessWizard({ setSaving(true); setError(""); try { - const latestUser = await saveTypedCredentials(); let targetProject = currentProject; // Save the SOP the page shows; a stale id hidden by the current // filter must never be bound to the project. @@ -1518,11 +1366,8 @@ export default function QuickAccessWizard({ repository: boundRepo, workflow: provisionedWorkflow || activeWorkflow, rolesCount: roles.length, - gitReady: Boolean(boundRepo?.provider === "ssh" ? hasSSHKey(parseGongfengRepo(boundRepo.cloneUrl)) : latestUser?.gitHubCredentialConfigured), - codeBuddyReady: Boolean( - latestUser?.codeBuddyApiKeyConfigured || - storedUser?.codeBuddyApiKeyConfigured, - ), + gitAccess: gitAccess(parseGongfengRepo(boundRepo?.cloneUrl, gongfengHost)), + cliNames: EXECUTORS.filter(cli => personalEngineConfigured(storedUser, cli.id)).map(cli => cli.label), }); setPhase("success"); await onCompleted?.(targetProject?.id || ""); @@ -1541,7 +1386,7 @@ export default function QuickAccessWizard({ inert={closing} aria-hidden={closing || undefined} onClick={(event) => { - if (event.target === event.currentTarget && !saving && !closing) + if (event.target === event.currentTarget && !saving && !verifyingGit && !closing) onClose?.(); }} > @@ -1606,7 +1451,7 @@ export default function QuickAccessWizard({ type="button" className="qa-close" aria-label="关闭快速接入" - disabled={saving} + disabled={saving || verifyingGit} onClick={onClose} > @@ -1685,42 +1530,27 @@ export default function QuickAccessWizard({
  • - {completedSummary?.repository?.provider === "ssh" ? "Git SSH 访问:" : "GitHub 访问:"} - {completedSummary?.gitReady + {completedSummary?.gitAccess.label || "Git"} 访问: + {completedSummary?.gitAccess.ready ? "已就绪" : "未配置,克隆/推送私有仓库前可在个人配置补齐"}
  • -
  • - +
  • + - CodeBuddy API Key: - {completedSummary?.codeBuddyReady - ? "已配置" - : sponsoredModel - ? `未配置。对话和 SOP 都会使用平台共享 Key(可用模型:${sharedModelNames(sponsoredModels, sponsoredModel)}),可以直接开始;配置自己的 Key 后可选用任意模型` - : "未配置。对话可用平台默认模型,但运行 SOP 时节点需要它调模型,请先在个人配置补齐"} + 模型 CLI · {completedSummary?.cliNames?.join("、") || + (sponsoredModel + ? `平台共享模型(${sharedModelNames(sponsoredModels, sponsoredModel)})` + : "可在个人配置或执行机器设置中准备")}
  • @@ -1807,12 +1637,24 @@ export default function QuickAccessWizard({ className={`qa-stage ${stepAnimated ? "is-entering" : ""}`} data-direction={direction} > -
    - 第 {activeStepIndex + 1} 步,共 {wizardStepCount} 步 -
    -

    - {activeStep.title} -

    +
    +
    + + 第 {activeStepIndex + 1} 步,共 {wizardStepCount} 步 +
    +

    + {activeStep.title} +

    + {activeStep.id === "auth" ? ( +

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

    + ) : null} +
    {error ? (

    @@ -1823,136 +1665,54 @@ export default function QuickAccessWizard({ {activeStep.id === "auth" ? (

    -
    +
    - GitHub 代码仓库授权 - - 用于克隆私有仓库、创建分支、推送代码与发起 PR - + GitHub 代码仓库授权 + 用于克隆私有仓库、创建分支、推送代码与发起 PR
    - +
    - -

    在个人配置中完成授权,返回后继续;无需手动复制令牌。

    -

    GitLab 等 SSH 仓库:

    -

    工作区访问 GitLab、GitHub Enterprise 等 HTTPS 主机:

    +

    在个人配置中完成授权,返回后继续。

    +

    GitLab 等 SSH 仓库:

    +

    GitLab、GitHub Enterprise 等 HTTPS 主机:

    使用访问令牌(高级) -
    - setGitToken(e.target.value)} - placeholder={ - storedUser?.gitHubCredentialConfigured - ? "已配置,留空保持不变" - : "GitHub personal access token(授予 Contents 与 Pull requests 读写权限)" - } - autoComplete="new-password" - /> - - - 申请令牌 ↗ - -
    - {gitVerify ? ( - - ) : null} +
    + { setGitToken(event.target.value); setGitVerify(null); }} + placeholder={gitHubReady ? "已配置,留空保持不变" : "GitHub 个人访问令牌(PAT)"} + aria-label="GitHub 个人访问令牌" + autoComplete="new-password" + disabled={verifyingGit} + /> + + 申请令牌 ↗ +
    + {gitVerify ? : null}
    - -
    +
    - CodeBuddy API Key - - {sponsoredModel - ? "可选:未配置时对话和 SOP 使用平台共享模型,配置后可选用其他模型" - : "AI 对话与 SOP 节点调用模型时使用"} - + 执行器 + {readyCLIs.length ? readyCLIs.map(cli => cli.label).join("、") : sponsoredModel ? "可使用平台共享模型" : "尚未配置执行器"}
    - +
    -
    - 网络环境 - ({ - value: env.value, - label: env.label, - hint: env.site, - }))} - onChange={setCodeBuddyEnvChoice} - ariaLabel="CodeBuddy 网络环境" - /> -
    -
    - - setCodeBuddyApiKey(e.target.value) - } - placeholder={ - storedUser?.codeBuddyApiKeyConfigured - ? "已配置,留空保持不变" - : "粘贴 CodeBuddy API Key" - } - aria-label="CodeBuddy API Key" - autoComplete="new-password" - /> - - 获取 API Key ↗ - -
    -

    - {codeBuddyWarning || - `${codeBuddyEnvLegacy && codeBuddyEnvChoice === null ? `原来填写的「${storedCodeBuddyEnvRaw}」无法识别,CodeBuddy 实际按国际站连接,点下一步改为当前选择。` : ""}Key 只能在创建它的站点使用:当前选择${codeBuddyEnvInfo.label}(${codeBuddyEnvInfo.site}),「获取 API Key」会打开该站点的密钥页。`} -

    + +

    在个人配置中保存后,点击「返回快速接入」继续。

    @@ -2217,9 +1977,9 @@ export default function QuickAccessWizard({ 支持 Git HTTPS 链接或 Git SSH 地址,例如 git@gitlab.com:group/repo.git。

    )} - {selectedSSHRepo?.provider === "ssh" && sshKeysLoaded && !sshReady ? ( + {selectedRepo?.provider === "ssh" && sshKeysLoaded && !repoAccess.ready ? (

    - {sshCredentials.error ? "无法读取 SSH 密钥配置,请稍后重试。" : `尚未配置 ${selectedSSHRepo.host} 的 SSH 密钥,可稍后在「个人配置 → Git SSH 密钥」添加。`} + {sshCredentials.error ? "无法读取 SSH 密钥配置,请稍后重试。" : `尚未配置 ${selectedRepo.host} 的 SSH 密钥,可返回上一步添加,也可稍后在个人配置中添加。`}

    ) : null} @@ -2346,16 +2106,12 @@ export default function QuickAccessWizard({
    凭据
    - {sshRepository ? "Git SSH" : "GitHub"} {(sshRepository ? sshReady : gitReady) ? "已配置" : "未配置"} · - CodeBuddy{" "} - {codeBuddyReady - ? "已配置" - : sponsoredModel - ? "使用平台共享模型" - : "未配置"} + {repoAccess.label} {repoAccess.ready ? "已配置" : "未配置"} · + CLI · {readyCLIs.length ? readyCLIs.map(cli => cli.label).join("、") : + sponsoredModel ? "使用平台共享模型" : "未配置"}
    @@ -2421,7 +2177,7 @@ export default function QuickAccessWizard({ type="button" className="qa-btn qa-btn-primary" aria-busy={saving || undefined} - disabled={loading && !saving} + disabled={verifyingGit || ((loading || (activeStep.id === "auth" && credentialsPending)) && !saving)} onClick={nextStep} > diff --git a/chatbot/src/SopDesigner.jsx b/chatbot/src/SopDesigner.jsx index 6452bcb7..5a4c87e4 100644 --- a/chatbot/src/SopDesigner.jsx +++ b/chatbot/src/SopDesigner.jsx @@ -142,7 +142,12 @@ export default function SopDesigner({ search = location.search, canvas = window. // Fall back to the catalog default once it loads. useEffect(() => { if (!catalog.models?.length || catalog.models.some((m) => m.id === model)) return; - setModel(catalog.default || catalog.models[0]?.id || ""); + const preferredEngine = catalog.preferences?.executor; + const preferredModel = catalog.preferences?.model; + const preferred = modelsFor(catalog, preferredEngine).find((m) => + m.id === preferredModel || m.id === preferredEngine + ":" + preferredModel); + const configured = new Set(enginesOf(catalog).filter((item) => item.configured !== false).map((item) => item.id)); + setModel(preferred?.id || catalog.models.find((m) => configured.has(m.engine || defaultEngine))?.id || catalog.models[0].id); }, [catalog, model]); useEffect(() => { @@ -323,6 +328,7 @@ export default function SopDesigner({ search = location.search, canvas = window. sessionId: id, model, approvalMode: "confirm", + requireExactModel: !!model, workflowId: begun.workflowId ?? context.workflowId, canvas: begun.canvas ?? null, messages: [message], diff --git a/chatbot/src/api.js b/chatbot/src/api.js index 7d92c1d8..90678e16 100644 --- a/chatbot/src/api.js +++ b/chatbot/src/api.js @@ -148,7 +148,7 @@ export function collectArtifacts(session) { // links. const reviewLinks = [ [/https:\/\/github\.com\/([A-Za-z0-9._-]+\/[A-Za-z0-9._-]+)\/pull\/(\d+)/g, "#", "PR"], - [/https?:\/\/git\.example\.com\/([A-Za-z0-9._\-\/]+?)(?:\/-)?\/merge_requests\/(\d+)/g, "!", "MR"], + [/https?:\/\/[A-Za-z0-9.-]+(?::\d+)?\/([A-Za-z0-9._\-\/]+?)(?:\/-)?\/merge_requests\/(\d+)/g, "!", "MR"], ]; for (const [pattern, marker, label] of reviewLinks) for (const match of (reply.message || "").matchAll(pattern)) { diff --git a/chatbot/src/changes.js b/chatbot/src/changes.js index 57337107..4f65bbd9 100644 --- a/chatbot/src/changes.js +++ b/chatbot/src/changes.js @@ -6,6 +6,8 @@ // that payload into file rows and line-by-line hunks so the panel can render // the same changes the agent made without re-reading tool arguments. +import "../../web/app/git-ssh.js"; + const HUNK = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@ ?(.*)$/; const STATUS = { @@ -252,15 +254,18 @@ export function branchCompareUrl(repository) { return same ? `https://github.com/${github}/tree/${refPath(work)}` : `https://github.com/${github}/compare/${refPath(base)}...${refPath(work)}`; - const path = gongfengProjectPath(repository?.cloneUrl); - if (!path) return ""; - if (same) return `https://git.example.com/${path}/-/tree/${refPath(work)}`; - return `https://git.example.com/${path}/-/compare/${refPath(base)}...${refPath(work)}`; + const address = repository?.webUrl || repository?.cloneUrl; + let host = ""; + if (repository?.provider === "gongfeng") { + const raw = String(address || ""); + try { host = new URL(raw).host; } catch { host = /^git@([^:]+):/.exec(raw)?.[1] || ""; } + } + const managed = globalThis.LoopForgeGongfengRepository(address, host); + if (!managed) return ""; + if (same) return `${managed.webUrl}/-/tree/${refPath(work)}`; + return `${managed.webUrl}/-/compare/${refPath(base)}...${refPath(work)}`; } -// Only github.com and the legacy git.example.com remotes get a link: the -// token rules in the platform are scoped to those hosts, and other hosts may -// not render the same URL shape. export function githubRepoPath(remote) { const raw = String(remote || "").trim(); const match = @@ -270,10 +275,5 @@ export function githubRepoPath(remote) { } export function gongfengProjectPath(remote) { - const raw = String(remote || "").trim(); - const match = - /^(?:git@|ssh:\/\/git@)git\.example\.com[:/](.+)$/.exec(raw) || - /^https?:\/\/git\.example\.com\/(.+)$/.exec(raw); - if (!match) return ""; - return match[1].replace(/\.git$/, "").replace(/^\/+|\/+$/g, ""); + return globalThis.LoopForgeGongfengRepository(remote)?.project || ""; } diff --git a/chatbot/src/credentials.js b/chatbot/src/credentials.js index eef30323..d05c1d67 100644 --- a/chatbot/src/credentials.js +++ b/chatbot/src/credentials.js @@ -178,12 +178,30 @@ export function credentialHint(text) { return null; } -export function openCredentialSettings(field, sshRemote) { - const credential = CREDENTIALS[field] ? field : ""; - if (window.parent !== window) +export function openCredentialSettings(field, sshRemote, { returnToQuickAccess = false } = {}) { + const credential = field === "executors" || Object.hasOwn(CREDENTIALS, field) ? field : ""; + const resume = credential === "executors" && returnToQuickAccess; + if (window.parent !== window) { window.parent.postMessage( - { type: "agentflow-chat-open-view", view: "settings", credential, ...(credential === "gitSshKey" && sshRemote ? { sshRemote } : {}) }, + { + type: "agentflow-chat-open-view", view: "settings", credential, + ...(credential === "gitSshKey" && sshRemote ? { sshRemote } : {}), + ...(resume ? { returnToQuickAccess: true } : {}), + }, location.origin, ); - else location.href = "/#/settings"; + } else if (resume) { + const current = new URL(location.href); + current.searchParams.set("quickAccess", "1"); + history.replaceState(history.state, "", current); + const settings = new URL("/", location.origin); + for (const [key, source] of [["projectId", "projectId"], ["chatSession", "session"]]) { + const value = current.searchParams.get(source); + if (value) settings.searchParams.set(key, value); + } + settings.hash = "/settings/executors/quick-access"; + location.assign(settings); + } else { + location.href = credential === "executors" ? "/#/settings/executors" : "/#/settings"; + } } diff --git a/chatbot/src/engines.js b/chatbot/src/engines.js index a54a2c00..25315041 100644 --- a/chatbot/src/engines.js +++ b/chatbot/src/engines.js @@ -2,7 +2,7 @@ // (`engines`); models without `engine` run on CodeBuddy. export const defaultEngine = "codebuddy"; -// Main Bot can run on any configured agent CLI; CodeBuddy stays the default. +// Main Bot can run on any configured agent CLI. export const EXECUTORS = [ { id: "codebuddy", icon: "sparkles", label: "CodeBuddy", detail: "使用 CodeBuddy 模型与个人 API Key。" }, { id: "codex", icon: "terminal", label: "Codex", detail: "使用 Codex CLI 与个人 Codex API Key。" }, @@ -23,6 +23,15 @@ const brands = { }; export const engineBrand = (id) => Object.hasOwn(brands, id) ? brands[id] : ""; +export function personalEngineConfigured(user, engine) { + switch (engine) { + case "codebuddy": return Boolean(user?.codeBuddyApiKeyConfigured); + case "codex": return Boolean(user?.codexApiKeyConfigured); + case "claude-code": return Boolean(user?.claudeCodeApiKeyConfigured); + default: return Boolean(user?.agentCliCredentials?.[engine]?.apiKeyConfigured); + } +} + export const modelEngine = (model) => model?.engine || defaultEngine; const modelEnginePrefix = (id) => /^([a-z][a-z0-9-]*):./.exec(id || "")?.[1]; diff --git a/chatbot/src/quick-access-wizard.css b/chatbot/src/quick-access-wizard.css index db914734..22f1b31b 100644 --- a/chatbot/src/quick-access-wizard.css +++ b/chatbot/src/quick-access-wizard.css @@ -320,6 +320,10 @@ height: 0; } +.qa-stage-heading { + padding-right: 34px; +} + .qa-stage.is-entering[data-direction="forward"] { animation: qa-step-forward 320ms var(--qa-ease) backwards; } @@ -329,12 +333,19 @@ } .qa-kicker { + display: flex; + align-items: center; + gap: 8px; font-size: 11.5px; font-weight: 600; color: var(--qa-accent-text); font-variant-numeric: tabular-nums; } +.qa-kicker-name { + display: none; +} + .qa-title { margin: 4px 0 0; font-size: 20px; @@ -1686,11 +1697,20 @@ } } -@media (max-width: 820px) { +@media (max-width: 820px), (max-height: 580px) { .qa-rail { display: none; } + .qa-kicker-name { + display: inline; + padding-right: 8px; + border-right: 1px solid var(--qa-line-strong); + color: var(--qa-txt2); + } +} + +@media (max-width: 820px) { .qa-body { padding: 24px 20px; } @@ -1705,6 +1725,12 @@ } /* Universal selectors do not reach pseudo-elements, so they are listed explicitly. */ +@media (max-width: 520px) { + .qa-input-row { + flex-wrap: wrap; + } +} + @media (prefers-reduced-motion: reduce) { .qa-backdrop, .qa-backdrop *, diff --git a/chatbot/src/styles.css b/chatbot/src/styles.css index 73da01ce..1924a90f 100644 --- a/chatbot/src/styles.css +++ b/chatbot/src/styles.css @@ -1629,33 +1629,41 @@ small { .credential-notice { display: flex; align-items: center; - gap: 8px; + gap: 10px; margin-bottom: 10px; - padding: 9px 11px; + padding: 8px 10px 8px 12px; border: 1px solid #f3e2b8; border-radius: 10px; background: #fffbf0; color: #7a5a12; - font-size: 12px; + font-size: 13px; line-height: 1.5; } +[data-theme="dark"] .credential-notice { + border-color: #5a4a22; + background: #2b2513; + color: #e8cf8c; +} +.credential-notice > svg { + flex: none; +} .credential-notice > span { flex: 1; } .credential-notice button { - height: 26px; - padding: 0 12px; - border: 0; - border-radius: 999px; - background: var(--accent); - color: var(--surface); + flex: none; + height: 30px; + padding: 0 10px; + border: 1px solid var(--line); + border-radius: 7px; + background: var(--surface); + color: var(--text); font-size: 12px; + font-weight: 500; cursor: pointer; } -[data-theme="dark"] .credential-notice { - border-color: #5a4a22; - background: #2b2513; - color: #e8cf8c; +.credential-notice button:hover { + background: var(--hover); } .info-card { position: absolute; diff --git a/chatbot/src/useChat.js b/chatbot/src/useChat.js index 9ecc016b..6ea2efc0 100644 --- a/chatbot/src/useChat.js +++ b/chatbot/src/useChat.js @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { api, write, @@ -16,7 +16,7 @@ import { cliFailureSettles } from "./cli-install.jsx"; import { useExecutionMachines } from "./useExecutionMachines.js"; import { executionLocked } from "./execution-target.js"; import { knownEffort, modelEffort } from "./effort.js"; -import { EXECUTORS, concreteModel, conversationEngine, engineModels, engineOfModel } from "./engines.js"; +import { EXECUTORS, concreteModel, conversationEngine, engineModels, engineOfModel, personalEngineConfigured } from "./engines.js"; import { readComposerPreference, useComposerOptions, writeComposerPreference } from "./composer-preferences.js"; import { enqueue, @@ -90,7 +90,10 @@ class ComposerModelError extends Error {} export function useChat() { const stopRequestRef = useRef(null); - const [user, setUser] = useState(null), + const accountDefaultsRef = useRef(null); + const draftExecutorPicked = useRef(false); + const userRead = useRef(0); + const [identity, setIdentity] = useState(null), [projects, setProjects] = useState([]), [sandboxes, setSandboxes] = useState([]), [sandboxProfileId, setSandboxProfileId] = useState(""), @@ -103,6 +106,8 @@ export function useChat() { new URLSearchParams(location.search).get("issueId") || "", ), [models, setModels] = useState([]), + [catalogEngines, setCatalogEngines] = useState([]), + [accountDefaults, setAccountDefaults] = useState(null), [modelCatalogRefresh, requestModelCatalogRefresh] = useState(0), [sessions, setSessions] = useState([]), [session, setSession] = useState(null), @@ -114,8 +119,7 @@ export function useChat() { [revealId, setRevealId] = useState(activeId), [projectId, setProjectId] = useState(initialProject), [selection, setSelection] = useState(() => ({ executor: storedExecutor(), model: null, effort: null })), - [accountDefaults, setAccountDefaults] = useState(null), - [codeBuddyCatalogDefault, setCodeBuddyCatalogDefault] = useState(""), + [codeBuddyDefault, setCodeBuddyDefault] = useState({ id: "default", name: "默认" }), [sponsoredModels, setSponsoredModels] = useState([]), [providerCatalogs, setProviderCatalogs] = useState({}), [generation, setGeneration] = useState(null), @@ -137,7 +141,9 @@ export function useChat() { // A queued message sent with "send now": it interrupts the running reply // and stays on screen until the server's follow-up turn has started. [steering, setSteering] = useState(null); - const { executor, model, effort } = selection; + // The users endpoint returns a complete snapshot. Credentials omitted + // after deletion must not survive in the authenticated user's profile. + const user = useMemo(() => identity && { ...identity, ...users.find(row => row.id === identity.id) }, [identity, users]); const generationKnownRef = useRef(null); const generationRevision = useRef(0); const setGenerationKnown = useCallback((id) => { @@ -213,7 +219,8 @@ export function useChat() { sessionRef.current = null; setSession(null); executionMachines.resetMachine(); - setSelection((options) => ({ executor: id ? options.executor : storedExecutor(), model: null, effort: null })); + draftExecutorPicked.current = false; + setSelection((options) => ({ executor: id ? options.executor : accountDefaultsRef.current?.executor || storedExecutor(), model: null, effort: null })); setSandboxProfileId(""); currentId.current = id; setActiveId(id); @@ -254,9 +261,11 @@ export function useChat() { setSession(stored); } const applyModelCatalog = useCallback((catalog) => { + accountDefaultsRef.current = catalog.preferences || null; + setAccountDefaults(accountDefaultsRef.current); setModels(catalog.models || []); - setAccountDefaults(catalog.preferences || null); - setCodeBuddyCatalogDefault(catalog.default || ""); + setCatalogEngines(catalog.engines || []); + setCodeBuddyDefault({ id: catalog.default || "default", name: "默认", efforts: catalog.defaultEfforts }); setSponsoredModels(sponsoredModelList(catalog)); }, []); useEffect(() => { @@ -304,7 +313,7 @@ export function useChat() { api("/api/sandboxes"), ]); if (!current) return; - setUser({ ...auth.user, ...users.find((u) => u.id === auth.user.id) }); + setIdentity(auth.user); setUsers(users || []); setProjects(projectRows || []); setSandboxes(sandboxRows || []); @@ -635,13 +644,35 @@ export function useChat() { // 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] || ""; + function composerRunnerId(conversation) { + if (!executionLocked(conversation)) return executionMachines.defaultRunnerId; + return conversation.executionTarget?.pool === "runner" ? conversation.executionTarget.runnerId : ""; + } + const runnerId = composerRunnerId(session); + const runner = executionMachines.machines.find(machine => machine.id === runnerId && machine.ownerUserId === user?.id); + const availableExecutors = EXECUTORS.flatMap(item => { + const local = ["codex", "claude-code", "agy"].includes(item.id) && + runner?.runtimes?.some(runtime => runtime.provider === item.id && runtime.authMode !== "personal"); + if (local) return [{ ...item, detail: "使用执行机器上的本机登录态。" }]; + const configured = catalogEngines.find(engine => engine.id === item.id)?.configured ?? + personalEngineConfigured(user, item.id); + return configured || (item.id === "codebuddy" && sponsoredModel) ? [item] : []; + }); + // Drafts can use any available executor. A recorded conversation keeps its + // executor even if its authentication changes. + const availableExecutor = id => availableExecutors.find(item => item.id === id); + const preferred = !activeId && !draftExecutorPicked.current && availableExecutor(accountDefaults?.executor); + const keepSessionExecutor = activeId && (session?.id !== activeId || submitting || + generation?.status === "running" || conversationEngine(session?.messages, models, session?.executor) || + (session?.executionTarget?.pool === "runner" && !executionMachines.machinesReady)); + const executor = keepSessionExecutor || !user || user.isGuest ? selection.executor : + (preferred || availableExecutor(selection.executor) || availableExecutors[0])?.id || ""; + const { model, effort } = executor === selection.executor ? selection : { model: null, effort: null }; function resolveComposerModel( { executor, model, effort }, conversation, draft, catalogs = providerCatalogs, machines = executionMachines.machines, ) { - const personalMachineId = executionLocked(conversation) - ? (conversation.executionTarget?.pool === "runner" ? conversation.executionTarget.runnerId : "") - : executionMachines.defaultRunnerId; + const personalMachineId = composerRunnerId(conversation); const personalMachine = machines.find( (machine) => machine.id === personalMachineId && machine.ownerUserId === user?.id, ); @@ -651,7 +682,7 @@ export function useChat() { const providerCatalog = catalogs[agyAccountKey || executor]; const codeBuddy = executor === "codebuddy"; const listed = engineModels(models, executor); - const usesProviderCatalog = !codeBuddy && (!!agyAccountKey || !listed.length); + const usesProviderCatalog = !!executor && !codeBuddy && (!!agyAccountKey || !listed.length); const catalogToLoad = usesProviderCatalog && !providerCatalog ? agyAccountKey || executor : ""; const executorModels = usesProviderCatalog ? (providerCatalog?.models || []).filter((model) => concreteModel(model, executor)) @@ -662,12 +693,13 @@ export function useChat() { const hasSelectedModel = concrete && !listedModel?.disabled && !listedModel?.unavailable && (conversation || !executorModels.length || listedModel); const inheritsDefault = !!conversation && !concrete; - const personalDefault = inheritsDefault && !sponsored && accountDefaults?.executor === executor ? accountDefaults : null; + const saved = (draft || inheritsDefault) && !sponsored && accountDefaults?.executor === executor ? accountDefaults : null; + const savedModel = saved ? findExecutorModel(executorModels, executor, saved.model) : null; const selectedModel = hasSelectedModel ? model : preferredModel( executorModels, executor, - personalDefault?.model, - inheritsDefault ? (codeBuddy ? codeBuddyCatalogDefault : providerCatalog?.default) : null, - draft ? readComposerPreference(`model.${executor}`) : null, + savedModel?.id, + inheritsDefault ? (codeBuddy ? codeBuddyDefault.id : providerCatalog?.default) : null, + draft && !saved ? readComposerPreference(`model.${executor}`) : null, ); const availableModel = sponsored && !sponsoredModels.includes(selectedModel) ? sponsoredModel : selectedModel; const catalogEntry = findExecutorModel(executorModels, executor, availableModel); @@ -680,10 +712,9 @@ export function useChat() { ? catalogEntry?.efforts?.find((level) => catalogEntry.effortModelIds?.[level] === requestedModelId) : undefined; // null follows the browser preference, while "" is the CLI's default level. - const defaultEffort = personalDefault && catalogEntry && catalogEntry === findExecutorModel(executorModels, executor, personalDefault.model) - ? personalDefault.effort : null; - const preferredEffort = (inheritsDefault ? defaultEffort : ((model === null || hasSelectedModel) ? effort : null)) ?? - (draft ? readComposerPreference(effortPreference(executor, availableModel)) : null); + const preferredEffort = (!inheritsDefault && (model === null || hasSelectedModel) ? effort : null) ?? + (savedModel?.id === availableModel && saved ? saved.effort ?? "" : + draft ? readComposerPreference(effortPreference(executor, availableModel)) : null); // Custom models can remain usable without a picker entry. Keep their // saved effort visible and let the server validate it on send. const historical = conversation && activeModel && !unavailableAgyVariant && availableModel === selectedModel; @@ -692,13 +723,13 @@ export function useChat() { : undefined); const activeEffort = modelEffort(activeModelEntry, preferredEffort || legacyEffort); return { - personalMachineId, personalMachine, agyAccountKey, catalogToLoad, codeBuddy, executorModels, + personalMachineId, agyAccountKey, catalogToLoad, codeBuddy, executorModels, sponsored, activeModelEntry, activeModel, activeEffort, unavailableAgyVariant, }; } const composerModel = resolveComposerModel({ executor, model, effort }, session, !activeId); const { - personalMachineId, personalMachine, agyAccountKey, catalogToLoad, codeBuddy, executorModels, + personalMachineId, agyAccountKey, catalogToLoad, codeBuddy, executorModels, sponsored, activeModelEntry, activeModel, activeEffort, } = composerModel; const loadProviderCatalog = useCallback((key, executor, runnerId) => { @@ -786,12 +817,13 @@ export function useChat() { function chooseExecutor(id) { if (id === "claude") id = "claude-code"; if (sessionLoading() || replyStatePending() || submittingRef.current || generation?.status === "running" || - !EXECUTORS.some((item) => item.id === id) || id === executor) return; + !availableExecutor(id) || id === executor) return; const current = sessionRef.current; const locked = conversationEngine(current?.messages, models, current?.executor); writeComposerPreference("executor", id); if (locked && locked !== id) open(null); else if (current?.id === activeId) saveOptions(`model.${activeId}`, { executor: id }); + draftExecutorPicked.current = true; setSelection({ executor: id, model: null, effort: null }); } @@ -834,31 +866,25 @@ export function useChat() { rememberModelChoice(activeModel, level); } } - // Credential flags are omitted when false, so drop the old ones before - // merging; otherwise a cleared key would still look configured. - const refreshUser = useCallback( - () => - api("/api/users") - .then((rows) => { - setUsers(rows || []); - let fresh = null; - setUser((old) => { - fresh = old && (rows || []).find((u) => u.id === old.id); - if (!fresh) return old; - const base = Object.fromEntries( - Object.entries(old).filter(([k]) => !k.endsWith("Configured")), - ); - return { ...base, ...fresh }; - }); - // Drop a "please configure X" error once X is configured. - setError((old) => { - const hint = credentialHint(old); - return hint && fresh?.[`${hint.field}Configured`] ? "" : old; - }); - }) - .catch(() => {}), - [], - ); + const refreshUser = useCallback(async () => { + const read = ++userRead.current; + try { + const rows = await api("/api/users"); + if (read !== userRead.current) return; + setUsers(rows || []); + const fresh = rows?.find(row => row.id === identity?.id); + // Drop a "please configure X" error once X is configured. + setError(old => { + const hint = credentialHint(old); + return hint && fresh?.[`${hint.field}Configured`] ? "" : old; + }); + } catch {} + }, [identity?.id]); + const refreshCredentials = useCallback(() => { + catalogRequests.current.clear(); + setProviderCatalogs({}); + requestModelCatalogRefresh((revision) => revision + 1); + }, []); useEffect(() => { const onMessage = (e) => { if ( @@ -866,18 +892,17 @@ export function useChat() { e.origin === location.origin && e.data?.type === "agentflow-credentials-changed" ) { - catalogRequests.current.clear(); - setProviderCatalogs({}); - requestModelCatalogRefresh((revision) => revision + 1); + refreshCredentials(); } }; + const onFocus = () => requestModelCatalogRefresh(revision => revision + 1); window.addEventListener("message", onMessage); - if (ready && missingKey) window.addEventListener("focus", refreshUser); + if (ready && !user?.isGuest) window.addEventListener("focus", onFocus); return () => { window.removeEventListener("message", onMessage); - window.removeEventListener("focus", refreshUser); + window.removeEventListener("focus", onFocus); }; - }, [ready, missingKey, refreshUser]); + }, [ready, user?.isGuest, refreshCredentials]); useEffect(() => { if (!ready || !modelCatalogRefresh) return; void refreshUser(); @@ -1035,6 +1060,7 @@ export function useChat() { setError("会话仍在加载,请稍候再发送。"); return false; } + if (!executor) return false; const currentProjectId = sessionRef.current?.projectId || ""; const approval = fromQueue ? queuedApproval({ approvalMode, approvalUserId, approvalProjectId }, user?.id, currentProjectId) @@ -1093,8 +1119,9 @@ export function useChat() { // configured a key elsewhere after this tab loaded. const account = users.find((u) => u.id === user?.id) ?? user; if (codeBuddy && user && !user.isGuest && !sponsoredModel && !account?.codeBuddyApiKeyConfigured) { + const read = userRead.current; const rows = await api("/api/users").catch(() => null); - if (rows) setUsers(rows); + if (rows && read === userRead.current) setUsers(rows); const fresh = rows?.find((u) => u.id === user.id) ?? account; if (!fresh?.codeBuddyApiKeyConfigured) { if (viewingTarget()) setError("请先在个人配置中配置自己的 CodeBuddy API Key"); @@ -1572,7 +1599,8 @@ export function useChat() { }, []); return { user, - refreshUser, + defaultApproval: accountDefaults?.approval, + refreshCredentials, users, issueId: session?.issueId || (!activeId ? draftIssueId : ""), linkIssue, @@ -1588,11 +1616,7 @@ export function useChat() { selectSandbox, models: executorModels, executor, - executors: EXECUTORS.map((item) => { - if (!personalMachine || !["codex", "claude-code", "agy"].includes(item.id)) return item; - const runtime = personalMachine.runtimes?.find((runtime) => runtime.provider === item.id); - return runtime?.authMode === "personal" ? item : { ...item, detail: "使用执行机器上的本机登录态。" }; - }), + executors: user ? availableExecutors : [], setExecutor: chooseExecutor, sessions, session, diff --git a/chatbot/tests/app-render.test.jsx b/chatbot/tests/app-render.test.jsx index c59d832b..873ae0b9 100644 --- a/chatbot/tests/app-render.test.jsx +++ b/chatbot/tests/app-render.test.jsx @@ -938,10 +938,13 @@ describe("App", () => { Object.assign(chat, previous); }); - test("covers credential, local upload, read-only, and interrupted states", async () => { + test("offers executor setup before the first chat, along with local upload and read-only states", async () => { const previous = { ...chat }; Object.assign(chat, { - user: { id: "u1", loginName: "tester", codexApiKeyConfigured: true }, + user: { id: "u1", loginName: "tester" }, + executor: "", + executors: [], + machinesReady: true, activeId: null, session: null, sessions: [], @@ -954,11 +957,14 @@ describe("App", () => { error: "", }); const view = render(); - expect(screen.getByText(/当前执行器 CodeBuddy 需要先配置 CodeBuddy API Key/)).toBeInTheDocument(); - expect(screen.getByText(/也可以在输入框下方把执行器切换过去/)).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "新增执行器" })).toBeInTheDocument(); + expect(screen.queryByText(/CodeBuddy API Key/)).toBeNull(); + expect(screen.getByRole("button", { name: "选择模型" })).toBeDisabled(); chat.executor = "codex"; + chat.executors = previous.executors.filter(item => item.id === "codex"); view.rerender(); - expect(screen.queryByText(/当前执行器 CodeBuddy/)).toBeNull(); + expect(screen.queryByRole("button", { name: "新增执行器" })).toBeNull(); + expect(screen.getByRole("button", { name: "CLI" })).toHaveTextContent("Codex"); chat.executor = "codebuddy"; chat.local = true; view.rerender(); diff --git a/chatbot/tests/hooks.test.jsx b/chatbot/tests/hooks.test.jsx index e4201d2a..f5221e17 100644 --- a/chatbot/tests/hooks.test.jsx +++ b/chatbot/tests/hooks.test.jsx @@ -18,7 +18,10 @@ const { apiMock, writeMock } = vi.hoisted(() => { if (path === "/api/auth/current") return { user: { id: 1, loginName: "tester", codeBuddyApiKeyConfigured: true } }; if (path === "/api/projects") return [{ id: "p1", name: "项目一", ownerId: 1, members: [1] }]; if (path === "/api/assistant/models?executor=codex") return { default: "default", models: [{ id: "default", name: "CLI default", family: "gpt" }, { id: "gpt-5", name: "GPT-5", family: "gpt", efforts: ["high", "xhigh"] }] }; - if (path === "/api/assistant/models") return { default: "m1", sponsoredModel: "m1", models: [{ id: "m1", name: "模型一", effort: true }] }; + if (path === "/api/assistant/models") return { + default: "m1", sponsoredModel: "m1", models: [{ id: "m1", name: "模型一", effort: true }], + engines: [{ id: "codebuddy", configured: true }, { id: "codex", configured: true }, { id: "claude-code", configured: false }], + }; if (path === "/api/users") return [{ id: 1, loginName: "tester", codeBuddyApiKeyConfigured: true }]; if (path === "/api/assistant/sessions") return [baseSession]; if (path.includes("/generation")) return { id: "g1", status: "completed", events: [] }; @@ -43,7 +46,6 @@ vi.mock("../src/api.js", async (original) => ({ newId: () => "new-session", })); -import { EXECUTORS } from "../src/engines.js"; import { useChat } from "../src/useChat.js"; import { writeComposerPreference } from "../src/composer-preferences.js"; import { @@ -81,7 +83,7 @@ describe("conversation hooks", () => { const { result } = renderHook(() => useChat()); await waitFor(() => expect(result.current.ready).toBe(true)); expect(result.current.executor).toBe("codebuddy"); - expect(result.current.executors.map((item) => item.id)).toEqual(EXECUTORS.map((item) => item.id)); + expect(result.current.executors.map((item) => item.id)).toEqual(["codebuddy", "codex"]); act(() => result.current.setExecutor("codex")); await waitFor(() => expect(result.current.models.map((m) => m.id)).toEqual(["gpt-5"])); expect(result.current.model).toBe("gpt-5"); @@ -108,6 +110,77 @@ describe("conversation hooks", () => { await waitFor(() => expect(result.current.model).toBe("gpt-5")); }); + test("requires an available executor for a new chat and recovers a stale CLI preference", async () => { + const original = apiMock.getMockImplementation(); + const user = { id: 1, loginName: "tester" }; + let engines = []; + apiMock.mockImplementation(async (path, options) => { + if (path === "/api/auth/current") return { user }; + if (path === "/api/users") return [user]; + if (path === "/api/assistant/models") return { default: "m1", models: [{ id: "m1" }], engines }; + return original(path, options); + }); + writeComposerPreference("executor", "codebuddy"); + try { + const { result, unmount } = renderHook(useChat); + await waitFor(() => expect(result.current.ready).toBe(true)); + expect(result.current).toMatchObject({ executor: "", executors: [], model: "" }); + await act(async () => expect(await result.current.send({ text: "第一条消息" })).toBe(false)); + expect(writeMock).not.toHaveBeenCalled(); + unmount(); + + engines = [{ id: "codebuddy", configured: false }, { id: "codex", configured: true }]; + const configured = renderHook(useChat); + await waitFor(() => expect(configured.result.current.ready).toBe(true)); + expect(configured.result.current.executor).toBe("codex"); + expect(configured.result.current.executors.map(item => item.id)).toEqual(["codex"]); + } finally { + apiMock.mockImplementation(original); + writeComposerPreference("executor", null); + } + }); + + test("removes a deleted CLI and selects the re-added executor without reloading the chat", async () => { + const original = apiMock.getMockImplementation(); + let zcode = true, codebuddy = true; + const identity = { id: 1, loginName: "tester", avatarUrl: "/avatar.png" }; + apiMock.mockImplementation(async (path, options) => { + if (path === "/api/auth/current") return { user: identity }; + if (path === "/api/users") return [{ + id: 1, loginName: "tester", + ...(zcode && { agentCliCredentials: { zcode: { apiKeyConfigured: true } } }), + ...(codebuddy && { codeBuddyApiKeyConfigured: true }), + }]; + if (path === "/api/assistant/models") return { + models: [], engines: [{ id: "zcode", configured: zcode }, { id: "codebuddy", configured: codebuddy }], + preferences: { executor: zcode ? "zcode" : codebuddy ? "codebuddy" : "" }, + }; + return original(path, options); + }); + const notifyChange = () => act(() => window.dispatchEvent(new MessageEvent("message", { + origin: location.origin, source: window.parent, data: { type: "agentflow-credentials-changed" }, + }))); + try { + const { result } = renderHook(useChat); + await waitFor(() => expect(result.current.ready).toBe(true)); + expect(result.current.executor).toBe("zcode"); + expect(result.current.executors.map(item => item.id)).toEqual(["codebuddy", "zcode"]); + + zcode = codebuddy = false; + notifyChange(); + await waitFor(() => expect(result.current.executors).toEqual([])); + await waitFor(() => expect(result.current.user.agentCliCredentials).toBeUndefined()); + + codebuddy = true; + notifyChange(); + await waitFor(() => expect(result.current.executor).toBe("codebuddy")); + expect(result.current.executors.map(item => item.id)).toEqual(["codebuddy"]); + expect(result.current.user.avatarUrl).toBe(identity.avatarUrl); + } finally { + apiMock.mockImplementation(original); + } + }); + test.each([ { status: "running", accepted: false }, { status: "running", accepted: true }, @@ -439,6 +512,10 @@ describe("conversation hooks", () => { }); test("does not create a chat without a concrete model on Pi", async () => { + const original = apiMock.getMockImplementation(); + apiMock.mockImplementation(async (path, options) => path === "/api/assistant/models" + ? { ...(await original(path, options)), engines: [{ id: "pi", configured: true }] } + : original(path, options)); const view = renderHook(() => useChat()); try { await waitFor(() => expect(view.result.current.ready).toBe(true)); @@ -449,6 +526,7 @@ describe("conversation hooks", () => { expect(writeMock).not.toHaveBeenCalled(); } finally { view.unmount(); + apiMock.mockImplementation(original); localStorage.removeItem("loopforge.assistant.executor"); } }); @@ -680,6 +758,7 @@ describe("conversation hooks", () => { return { default: "m1", cursorModelsPending: !discovered, + engines: [{ id: "cursor", configured: true }], models: [{ ...fallback, id: "cursor:widget", engine: "cursor", efforts: discovered ? ["low", "xhigh"] : [] }], }; } @@ -687,10 +766,7 @@ describe("conversation hooks", () => { }); try { const { result } = renderHook(() => useChat()); - await waitFor(() => expect(result.current.modelDetails?.name).toBe("Widget")); await waitFor(() => expect(result.current.ready).toBe(true)); - expect(result.current.modelDetails.efforts || []).toEqual([]); - act(() => { result.current.setModel(result.current.model); }); if (!configured) { configured = true; act(() => window.dispatchEvent(new MessageEvent("message", { @@ -700,6 +776,9 @@ describe("conversation hooks", () => { }))); } await waitFor(() => expect(pendingReads).toBeGreaterThan(0)); + await waitFor(() => expect(result.current.modelDetails?.name).toBe("Widget")); + expect(result.current.modelDetails.efforts || []).toEqual([]); + act(() => { result.current.setModel(result.current.model); }); discovered = true; await waitFor(() => expect(result.current.modelDetails.efforts).toEqual(["low", "xhigh"]), { timeout: 3500 }); act(() => result.current.setEffort("xhigh")); @@ -724,7 +803,7 @@ describe("conversation hooks", () => { if (path === "/api/auth/current") return Promise.resolve({ user }); if (path === "/api/users") return Promise.resolve([user]); if (path === "/api/assistant/models") return Promise.resolve({ - default: "default", models: [{ id: "default" }, { id: "default-model" }], + default: "default", engines: [{ id: "codebuddy", configured: true }], models: [{ id: "default" }, { id: "default-model" }], }); return original(path, options); }); @@ -750,7 +829,7 @@ describe("conversation hooks", () => { if (path === "/api/auth/current") return Promise.resolve({ user }); if (path === "/api/users") return Promise.resolve([{ ...user, codeBuddyApiKeyConfigured: configured }]); if (path === "/api/assistant/models") return Promise.resolve({ - default: "default", models: configured ? [{ id: "deepseek-v4.1-flash" }] : [], + default: "default", engines: [{ id: "codebuddy", configured: true }], models: configured ? [{ id: "deepseek-v4.1-flash" }] : [], }); return original(path, options); }); @@ -848,7 +927,7 @@ describe("conversation hooks", () => { ]; if (personalCodexCatalog) models.push({ id: "codex:gpt-5", engine: "codex", name: "GPT-5", efforts: ["high"] }); - return { default: "default", defaultEfforts: ["low"], models }; + return { default: "default", defaultEfforts: ["low"], models, engines: [{ id: "codex", configured: true }] }; } return original(path, options); }); @@ -937,7 +1016,7 @@ describe("conversation hooks", () => { }; apiMock.mockImplementation((path, options) => { if (path === "/api/assistant/models") return Promise.resolve({ - default: "m1", models: [ + default: "m1", engines: [{ id: "codebuddy", configured: true }, { id: "codex", configured: true }], models: [ { id: "m1" }, { id: "codex:gpt-main", engine: "codex" }, { id: "codex:gpt-alternate", engine: "codex", efforts: ["high"] }, diff --git a/chatbot/tests/quick-access-wizard.test.jsx b/chatbot/tests/quick-access-wizard.test.jsx index 5883ae00..2a8db7df 100644 --- a/chatbot/tests/quick-access-wizard.test.jsx +++ b/chatbot/tests/quick-access-wizard.test.jsx @@ -1,5 +1,5 @@ import React from "react"; -import { render, screen, waitFor } from "@testing-library/react"; +import { act, render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { describe, expect, test, vi } from "vitest"; @@ -13,11 +13,11 @@ const { project, user, apiMock, writeMock, mockState } = vi.hoisted(() => { gitHubCredentialConfigured: 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: "测试", gitHubCredentialConfigured: false, codeBuddyApiKeyConfigured: false, + ...mockState.savedCredentials, } : user]; if (path === "/api/projects") return [project]; if (path === "/api/repositories") return []; @@ -33,12 +33,11 @@ const { project, user, apiMock, writeMock, mockState } = vi.hoisted(() => { ]; if (path === "/api/agents") return []; if (path.includes("/agents")) return []; - if (path.includes("/verify")) return { valid: true }; return []; }); - const mockState = { failClone: false, unconfigured: false, users: null, sshKeys: null }; + const mockState = { failClone: false, unconfigured: false, sshKeys: null, savedCredentials: {}, gitVerification: null }; const writeMock = vi.fn(async (path, body) => { - if (path.includes("/git-token/verify")) return { valid: true }; + if (path === "/api/users/1/git-token/verify") return mockState.gitVerification; if (path === "/api/projects") return { ...project, ...body }; if (path.includes("/clone")) { if (mockState.failClone) throw new Error("clone unavailable"); @@ -72,6 +71,10 @@ describe("QuickAccessWizard", () => { }); test("parses supported repository addresses", () => { + expect(parseGongfengRepo("acme/widgets")).toBeNull(); + expect(parseGongfengRepo("https://git.review.test:8443/acme/widgets", "git.review.test:8443")).toMatchObject({ + provider: "gongfeng", project: "acme/widgets", cloneUrl: "https://git.review.test:8443/acme/widgets.git", + }); expect(parseGongfengRepo("https://github.com/acme/widgets")).toEqual({ project: "github:acme/widgets", provider: "github", @@ -187,175 +190,86 @@ describe("QuickAccessWizard", () => { } }); - test("validates and saves typed credentials", async () => { - mockState.unconfigured = true; - const userAction = userEvent.setup(); - render( - , - ); - await screen.findByRole("dialog"); - await userAction.click(screen.getByRole("button", { name: "下一步" })); - expect(screen.getByRole("alert")).toHaveTextContent("请先配置 GitHub Git Token、Git SSH 密钥或 CodeBuddy API Key"); - expect(screen.queryByText(/工蜂/)).toBeNull(); - await userAction.click(screen.getByText("使用访问令牌(高级)")); - await userAction.type( - screen.getByPlaceholderText(/GitHub personal access token/), - "token-value", - ); - await userAction.click(screen.getByRole("button", { name: "校验" })); - await waitFor(() => expect(writeMock).toHaveBeenCalledWith( - "/api/users/1/git-http-credentials", - expect.objectContaining({ host:"github.com", token: "token-value" }), - "PUT", - )); - mockState.unconfigured = false; - }); - - test("saves a typed CodeBuddy key when moving past the credential step", async () => { - mockState.unconfigured = true; - writeMock.mockClear(); - const userAction = userEvent.setup(); - const credentialsSaved = vi.fn(); - render( - , - ); - await screen.findByRole("dialog"); - await userAction.type(screen.getByPlaceholderText("粘贴 CodeBuddy API Key"), "cb-key"); - await userAction.click(screen.getByRole("button", { name: "下一步" })); - await screen.findByText("项目与仓库", { selector: "h3" }); - expect(writeMock).toHaveBeenCalledWith( - "/api/users/1/credentials", - { codeBuddyApiKey: "cb-key", codeBuddyInternetEnvironment: "" }, - "PUT", - ); - expect(credentialsSaved).toHaveBeenCalledTimes(1); - mockState.unconfigured = false; - }); - - test("saves the CodeBuddy key with the chosen network environment and links to its key page", async () => { + test("keeps the wizard open when configuring an executor and refreshes it on return", async () => { mockState.unconfigured = true; - writeMock.mockClear(); - const userAction = userEvent.setup(); - render( - , - ); - 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; - }); - - 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(); + const onClose = vi.fn(); + const parentFrame = document.createElement("iframe"); + document.body.append(parentFrame); + const parent = parentFrame.contentWindow; + const post = vi.spyOn(parent, "postMessage").mockImplementation(() => {}); + const parentWindow = vi.spyOn(window, "parent", "get").mockReturnValue(parent); try { render( , ); - 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", + expect(screen.getByRole("heading", { name: "凭据与授权", level: 3 })).toBeVisible(); + expect(screen.getByText("第 1 步,共 3 步")).toBeVisible(); + expect(screen.getByText("配置任意一项即可继续。下一步选择项目和仓库。")).toBeVisible(); + const next = screen.getByRole("button", { name: "下一步" }); + await waitFor(() => expect(next).toBeEnabled()); + await userAction.click(next); + expect(screen.getByRole("alert")).toHaveTextContent("请先添加一个 Git 凭据或执行器。"); + + await userAction.click(screen.getByRole("button", { name: "执行器配置", exact: true })); + expect(post).toHaveBeenCalledWith( + { type: "agentflow-chat-open-view", view: "settings", credential: "executors", returnToQuickAccess: true }, + location.origin, ); + expect(onClose).not.toHaveBeenCalled(); + mockState.savedCredentials = { codeBuddyApiKeyConfigured: true }; + const data = { type: "agentflow-credentials-changed" }; + await act(async () => { + window.dispatchEvent(new MessageEvent("message", { data, origin: location.origin, source: window })); + window.dispatchEvent(new MessageEvent("message", { data, origin: "https://other.example.org", source: parent })); + }); + expect(screen.getByText("尚未配置执行器")).toBeVisible(); + + await act(async () => { + window.dispatchEvent(new MessageEvent("message", { data, origin: location.origin, source: parent })); + window.dispatchEvent(new MessageEvent("message", { data: { type: "agentflow-chat-resume-quick-access" }, origin: location.origin, source: parent })); + }); + expect(screen.getByRole("heading", { name: "凭据与授权", level: 3 })).toHaveFocus(); + expect(screen.getByText(/可以继续选择项目和仓库/)).toBeVisible(); + await userAction.click(next); + expect(await screen.findByRole("heading", { name: "项目与仓库", level: 3 })).toBeInTheDocument(); + expect(onClose).not.toHaveBeenCalled(); } finally { - mockState.users = null; + parentWindow.mockRestore(); + post.mockRestore(); + parentFrame.remove(); + mockState.unconfigured = false; + mockState.savedCredentials = {}; } }); - 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(); + test("validates the optional GitHub token before advancing or saving it", async () => { + mockState.unconfigured = true; + const actions = userEvent.setup(); try { - render( - , - ); - 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" }); + render(); + await actions.click(screen.getByText("使用访问令牌(高级)")); + await actions.type(screen.getByLabelText("GitHub 个人访问令牌"), "token-value"); + mockState.gitVerification = { valid: false, error: "测试校验拒绝" }; + const next = screen.getByRole("button", { name: "下一步" }); + await actions.click(next); + expect(await screen.findByText("测试校验拒绝")).toBeVisible(); + expect(writeMock.mock.calls.some(([path]) => path === "/api/users/1/git-http-credentials")).toBe(false); + mockState.gitVerification = { valid: true }; + await actions.click(next); + expect(await screen.findByRole("heading", { name: "项目与仓库", level: 3 })).toBeVisible(); expect(writeMock).toHaveBeenCalledWith( - "/api/users/1/credentials", - { codeBuddyApiKey: "ck_new", codeBuddyInternetEnvironment: "" }, - "PUT", + "/api/users/1/git-http-credentials", expect.objectContaining({ host: "github.com", token: "token-value" }), "PUT", ); } finally { - mockState.users = null; + mockState.unconfigured = false; + mockState.gitVerification = null; } }); @@ -375,6 +289,8 @@ describe("QuickAccessWizard", () => { />, ); await screen.findByRole("dialog"); + expect(screen.getByText(/平台共享模型可用,可直接继续/)).toBeVisible(); + expect(screen.getByText("可使用平台共享模型")).toBeVisible(); await userAction.click(screen.getByRole("button", { name: "下一步" })); expect(await screen.findByText("项目与仓库", { selector: "h3" })).toBeInTheDocument(); mockState.unconfigured = false; diff --git a/compose.dev.yaml b/compose.dev.yaml index c26fff83..1345c2dc 100644 --- a/compose.dev.yaml +++ b/compose.dev.yaml @@ -9,5 +9,6 @@ services: args: LOOPFORGE_BUILD_JOBS: ${LOOPFORGE_BUILD_JOBS:-} LOOPFORGE_COMMIT: ${LOOPFORGE_COMMIT:-} + CODEBUDDY_PACKAGE: ${CODEBUDDY_PACKAGE-@tencent-ai/codebuddy-code@2.167.0} environment: AGENTFLOW_ISOLATED_IMAGE: loopforge-platform:local diff --git a/compose.yaml b/compose.yaml index 25e5535c..4710f3d2 100644 --- a/compose.yaml +++ b/compose.yaml @@ -32,10 +32,15 @@ services: AGENTFLOW_ALLOW_SIGNUP: ${AGENTFLOW_ALLOW_SIGNUP:-true} AGENTFLOW_SECURE_COOKIES: ${AGENTFLOW_SECURE_COOKIES:-false} AGENTFLOW_GITHUB_CLIENT_ID: ${AGENTFLOW_GITHUB_CLIENT_ID:-} + AGENTFLOW_GONGFENG_HOST: ${AGENTFLOW_GONGFENG_HOST:-} + AGENTFLOW_TAPD_HOST: ${AGENTFLOW_TAPD_HOST:-} + AGENTFLOW_MCP_TOKEN: ${AGENTFLOW_MCP_TOKEN:-} AGENTFLOW_GIT_SSH_KNOWN_HOSTS: ${AGENTFLOW_GIT_SSH_KNOWN_HOSTS:-} AGENTFLOW_ASSISTANT_SESSION_DIR: /data/assistant AGENTFLOW_CONVERSATION_DIR: ${LOOPFORGE_DATA_DIR}/conversations AGENTFLOW_CLARIFY_SESSION_DIR: /data/clarify + AGENTFLOW_BASELINE_ALIGN_EXECUTOR: ${AGENTFLOW_BASELINE_ALIGN_EXECUTOR:-} + AGENTFLOW_SKIP_CODEBUDDY_INSTALL: ${AGENTFLOW_SKIP_CODEBUDDY_INSTALL:-} AGENTFLOW_ASSISTANT_MODEL: ${AGENTFLOW_ASSISTANT_MODEL:-} AGENTFLOW_ASSISTANT_MODELS: ${AGENTFLOW_ASSISTANT_MODELS:-} AGENTFLOW_PREVIEW_PUBLIC_URL: ${AGENTFLOW_PREVIEW_PUBLIC_URL:-} diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml index fc2f6b61..fa516d44 100644 --- a/docs/api/openapi.yaml +++ b/docs/api/openapi.yaml @@ -104,7 +104,7 @@ paths: operationId: chatAssistant summary: Ask the Studio AI assistant or generate platform resource drafts description: | - Uses the signed-in user's personal CodeBuddy API key. The model can + Uses the signed-in user's credential for the selected CLI. The model can request bounded source lookups and project HTTP MCP calls (`mcpCalls`). The CLI itself cannot call MCP, modify the source snapshot, push, or deploy. The server invokes TAPD/Gongfeng-style HTTP MCP that the user @@ -247,6 +247,18 @@ paths: required: [default, models] properties: default: {type: string} + preferences: + $ref: "#/components/schemas/AssistantDefaults" + engines: + type: array + items: + type: object + properties: + id: {type: string} + name: {type: string} + configured: {type: boolean} + personal: {type: boolean} + credential: {type: string, description: Configuration field name} models: type: array items: @@ -256,6 +268,7 @@ paths: id: {type: string} name: {type: string} family: {type: string} + engine: {type: string} credits: {type: string, example: x0.79} "401": $ref: "#/components/responses/Unauthorized" @@ -479,7 +492,7 @@ paths: These tasks make the Studio assistant run a user-written prompt on an interval, scoped to one Studio project. They persist in MySQL `assistant_tasks` and are not TAPD/Gongfeng SOP schedule jobs. Each run - starts a fresh CodeBuddy session and does not resume the previous run. + starts a fresh session on the selected CLI. During execution the server may invoke that project's HTTP MCP servers (for example TAPD) on the model's `mcpCalls`. parameters: @@ -512,7 +525,7 @@ paths: intervalSec: {type: integer, minimum: 60, description: Used when cron is empty. Minimum 60 seconds.} cron: {type: string, description: Optional 5-field cron (minute hour day month weekday) in Asia/Shanghai. When set, intervalSec is ignored.} enabled: {type: boolean} - model: {type: string, description: CodeBuddy model id used when the task runs} + model: {type: string, description: Model ID on the selected CLI. Prefix non-CodeBuddy models with the CLI ID.} projectId: {type: string, description: Studio project that owns this assistant task} responses: "200": @@ -751,8 +764,11 @@ paths: schema: type: object properties: + assistantDefaults: + $ref: "#/components/schemas/AssistantDefaults" codeBuddyApiKey: {type: string, writeOnly: true} codeBuddyApiKeyClear: {type: boolean} + codeBuddyBaseUrl: {type: string, description: "HTTP(S) CodeBuddy gateway base URL. Omitted preserves the value; empty uses the official endpoint for the selected edition."} 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} @@ -1504,6 +1520,28 @@ paths: $ref: "#/components/responses/Unauthorized" "404": $ref: "#/components/responses/NotFound" + /api/issues/{issueId}/clarify-models: + parameters: + - $ref: "#/components/parameters/IssueId" + get: + tags: [Issues] + operationId: listIssueClarificationModels + description: List model choices for the issue assignee or project owner who runs the clarification. Requires project write access. + responses: + "200": + description: Executors and models available for issue clarification + content: + application/json: + schema: + $ref: "#/paths/~1api~1assistant~1models/get/responses/200/content/application~1json/schema" + "400": + $ref: "#/components/responses/BadRequest" + "401": + $ref: "#/components/responses/Unauthorized" + "403": + $ref: "#/components/responses/Forbidden" + "404": + $ref: "#/components/responses/NotFound" /api/issues/{issueId}/chat-clarify: parameters: - $ref: "#/components/parameters/IssueId" @@ -3124,6 +3162,7 @@ paths: post: tags: [Runs] operationId: startRunEval + description: Evaluates a finished run using the requesting account's personal CLI credentials. requestBody: required: false content: @@ -4048,6 +4087,13 @@ components: items: $ref: "#/components/schemas/ScheduleJob" schemas: + AssistantDefaults: + type: object + properties: + executor: {type: string, description: A configured personal executor.} + model: {type: string, description: Concrete model ID on the executor.} + effort: {type: string, description: The selected model's reasoning effort.} + approval: {type: string, enum: [confirm, assisted, auto], description: Initial confirmation mode for new conversations.} OpenObject: type: object additionalProperties: true @@ -4359,6 +4405,7 @@ components: avatarUrl: {type: string} gitHubCredentialConfigured: {type: boolean, readOnly: true} codeBuddyApiKeyConfigured: {type: boolean, readOnly: true} + codeBuddyBaseUrl: {type: string} codexApiKeyConfigured: {type: boolean, readOnly: true} codexBaseUrl: {type: string} claudeCodeApiKeyConfigured: {type: boolean, readOnly: true} diff --git a/docs/api/orchestration.md b/docs/api/orchestration.md index fc126c35..8ded2ca5 100644 --- a/docs/api/orchestration.md +++ b/docs/api/orchestration.md @@ -273,11 +273,11 @@ curl -u "$AGENTFLOW_USER:$AGENTFLOW_PASS" -X POST \ ## Run 评测 -只评测终态 run(`succeeded|failed|cancelled`)。使用当前登录用户的 CodeBuddy Key 和助手模型目录,不自动触发。 +只评测终态 run(`succeeded|failed|cancelled`)。手动触发,使用请求人的执行器凭据。 ### `POST /api/runs/{runId}/eval` -请求 `{ "model": "default" }`,`model` 可选。成功 `202` 返回评测记录(`status=running`)。进行中的 run 返回 `409`;未登录 `401`;未配置个人 CodeBuddy Key `400`。 +请求可选 `model`,例如 `{ "model": "codex:" }`。省略或使用 `default` 时,从请求人的个人配置中选择默认执行器和模型。成功返回 `202` 与评测记录(`status=running`)。进行中的 run 返回 `409`。未登录返回 `401`。缺少所选执行器的凭据时返回 `400`。 ### `GET /api/runs/{runId}/eval` diff --git a/docs/deployment.md b/docs/deployment.md index 14d98739..693cb9d6 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -4,16 +4,14 @@ `bash scripts/dev.sh` explicitly configures local secrets, starts only this checkout's MySQL service, builds the platform, provisions the `admin` account, installs the missing observability generated columns through an explicit script, applies `migrations/seed/*.sql`, and starts the server on port 8090. Existing catalog definitions are preserved by `INSERT IGNORE`. Keep `.env`, `.local/` and database volumes outside version control. -For a native installation, use Node.js 22+ on the API host and install the CLIs you choose. CodeBuddy is also used for requirement clarification; scheduled assistant tasks use whichever supported CLI the task selects: +For a native installation, use Node.js 22+ on the API host and install the CLI you plan to use. Example with Codex: ```bash -npm install --global @tencent-ai/codebuddy-code -codebuddy --version -# Optional executors for Main Bot and SOP roles: -npm install --global @openai/codex@0.162.1 @anthropic-ai/claude-code@2.1.326 +npm install --global @openai/codex@0.162.1 +codex --version ``` -Ensure the service can find `codebuddy` and Node.js on its PATH, or set `AGENTFLOW_CODEBUDDY_BIN` to the installed executable. Configure the model key and its network environment in personal settings. The no-key script demo does not need the CLI. The production Docker image includes CodeBuddy, Codex and DeepSeek Harness (`dsh`). Claude Code and the other agent CLIs are not bundled. When a conversation fails because one is missing, the error says it is not installed and offers an install button. That downloads the pinned `@anthropic-ai/claude-code` release, or the public package for OpenCode, Kimi Code and Pi, into `$LOOPFORGE_DATA_DIR/cli`; an installation outside the image gets the pinned `@deepseek-ai/dsh` release the same way. Cursor CLI and Antigravity use their providers' installers and land in the service user's `~/.local/bin`. Closing or reloading the browser does not stop an install that has already started, and the button stays on “自动安装” until it finishes. A finished install replaces the earlier generation failure with a prompt to send the message again. The next message reuses the installation. An SOP sandbox of the published image that selects Claude Code, OpenCode, Kimi Code or Pi installs the same package on first use and shares it with conversations. Cursor CLI and Antigravity are not installed into SOP sandboxes. Connected runners keep their own CLI requirements. +Configure the CLI's credential in personal settings. If you select CodeBuddy, use its network environment and put its binary on PATH or set `AGENTFLOW_CODEBUDDY_BIN`. The production image bundles Codex, DeepSeek Harness and, by default, CodeBuddy. If an on-demand CLI is missing, the conversation shows the installation action. SOP sandboxes that use the published image share the first-use installation for Claude Code, OpenCode, Kimi Code and Pi. Connected runners manage their own CLI installations. WeCom notifications require `wecom-cli` on the platform service's PATH. The platform image built from this Dockerfile includes `@wecom/cli@1.3.4`; published images gain it with the next release. For a native installation, install it separately with `npm install --global @wecom/cli@1.3.4`, ensure system CA certificates are installed, and verify `wecom-cli --version` as the service user. Configuring a WeCom bot is still required to send notifications. @@ -35,6 +33,18 @@ Stop the foreground service with Ctrl-C. Start it again with the same command. M Use `AGENTFLOW_MYSQL_DSN` for your own MySQL deployment. A fresh account command or server connection creates missing schema objects. Apply existing-installation data migrations individually after reviewing their prerequisites; do not blindly replay all historical migrations against a new database. +## Choosing an executor + +- The model pickers for requirement clarification, Bot replies, SOP notification reports, run evaluation, and scheduled AI tasks accept models from the supported CLIs. API clients can send `codex:`, `claude-code:` or another CLI-prefixed model ID. Legacy bare model IDs remain CodeBuddy IDs. An omitted model or bare `default` uses the execution account's personal default when available. The existing CodeBuddy default takes precedence in the fallback order. A concrete model is passed unchanged to its CLI. +- In **Personal configuration**, add Git credentials for each repository host and executor credentials for each CLI you use. Git selects credentials by the repository protocol, host, and port. The first configured executor becomes the personal default. You can change it and choose a default model, reasoning effort, and chat approval mode. CodeBuddy accepts an optional Base URL alongside its network environment. Leave the URL blank to use the environment's official endpoint. A custom CodeBuddy URL on a remote execution machine requires Runner 0.11.2 or later. +- Clarification uses the assignee's credentials, falling back to the project owner when unassigned. Bot replies use the bound sender, reports use the responsible account on the run, and evaluation uses the requesting account. Assisted approval uses the turn's CLI and selected model. +- SOP roles and static previews can each select a CLI. CodeBuddy remains the default for newly created roles and static previews. To use a built-in template with another CLI, copy it into a project and update its roles, or edit the template as a platform administrator. +- Set `AGENTFLOW_BASELINE_ALIGN_EXECUTOR=codex` on the platform to run the scheduled baseline conflict resolver with Codex. The setting takes a built-in executor ID, including `claude` for Claude Code. The resolver defaults to CodeBuddy when this setting is empty. New runs record the configured executor in their snapshot. +- To omit CodeBuddy from a source build, pass `--build-arg CODEBUDDY_PACKAGE=` to Docker or prefix the development Compose build with `CODEBUDDY_PACKAGE=`. Use that image as `AGENTFLOW_ISOLATED_IMAGE` for platform sandboxes. Without a shared image, set `AGENTFLOW_SKIP_CODEBUDDY_INSTALL=1` for the built-in fallback Dockerfile. Custom Dockerfiles manage their own packages. With that flag the default managed CLI list also omits CodeBuddy. Set `AGENTFLOW_MANAGED_CLIS` to manage an explicit list of providers. +- Tracker MCP authentication uses explicit catalog headers or the deployment's `AGENTFLOW_MCP_TOKEN`. Project-scoped trackers use their own MCP authorization headers. +- Set `AGENTFLOW_GONGFENG_HOST` to the managed Git host (hostname and optional HTTPS port) to enable its repository and merge request links and token checks. Gongfeng OAuth also needs its application credentials and callback. Existing OAuth endpoint overrides still take precedence. +- Set `AGENTFLOW_TAPD_HOST` to a deployment-specific TAPD web host when needed. Generated TAPD work item links use `www.tapd.cn` by default. + ## Container installation ```bash @@ -161,9 +171,9 @@ The installer checks the helper destinations against the staged macOS binary and When platform updates are enabled, macOS runners synchronize the helper in the background at startup. A failed version check is retried during rescans, including when an older helper remains usable. A readable, compatible local ELF or a locally configured script wrapper can be copied into a Docker workspace with executable permissions while the sync runs. Operations that need a missing helper for Git or MCP can wait up to five seconds for the initial sync. The background download continues within its own transfer timeout. -A platform administrator can share one CodeBuddy API Key under **Platform administration → Shared CodeBuddy Key** (平台共享 CodeBuddy Key): pick the network environment that issued it and the models members may use (the first is the default). Members without a key of their own then chat and run 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 the runner's own key. A scheduled task uses the key for its selected CLI and does not borrow the shared CodeBuddy 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. +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. Clarification, reports, bots and run evaluation use the personal credentials of the relevant account. Scheduled prompts follow the selected CLI's credential and sponsorship settings. The key is stored in the database like personal keys and is never shown again after saving. `AGENTFLOW_ASSISTANT_SPONSOR_LOGIN`, which lent one account's key limited to `deepseek-v4.1-flash`, still applies while no shared key is configured. -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 each choose a built-in CLI independently. Select the executor beside the home model selector; its API key (and optional Codex/Claude base URL) comes from your personal settings. Changing the executor preserves the draft; saved conversations record the executor used. Main Bot writes still pass through the platform tool gateway and its approval checks. Requirement clarification and notifications continue to use CodeBuddy. A scheduled assistant task can select any supported CLI and runs as an ordinary chat turn; Codex and Claude Code still need that account's own credential. Live model tests are opt-in; set `AGENTFLOW_LIVE_TESTS=1` only for the acceptance suites that need to load local credentials. +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 each choose a built-in CLI independently. Select the executor beside the home model selector; its API key (and optional Codex/Claude base URL) comes from your personal settings. Changing the executor preserves the draft; saved conversations record the executor used. Main Bot writes still pass through the platform tool gateway and its approval checks. A scheduled assistant task can select any supported CLI and runs as an ordinary chat turn; Codex and Claude Code still need that account's own credential. Live model tests are opt-in; set `AGENTFLOW_LIVE_TESTS=1` only for the acceptance suites that need to load local credentials. ## Observability schema diff --git a/e2e/README.md b/e2e/README.md index 765622b2..57f3eb81 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -34,6 +34,8 @@ AGENTFLOW_E2E_CODEBUDDY_API_KEY=ck_... ./local.sh api/40-model.test.mjs # 带 | `AGENTFLOW_E2E_BASE` | 验收环境,默认 localhost:8090 | | `AGENTFLOW_E2E_MODEL` | 显式设为 `1` 启用付费模型测试,默认关闭 | | `AGENTFLOW_E2E_MODEL_ID` | 真实 Agent 节点使用的模型 ID,例如 `deepseek-v4.1-flash` | +| `AGENTFLOW_E2E_CLI_KEY` | 本地实测时所选 CLI 的个人凭据 | +| `AGENTFLOW_E2E_CLI_BASE_URL` | 本地实测可选的自定义模型网关 | | `AGENTFLOW_E2E_EXECUTOR` | 执行器,默认 `codebuddy` | | `AGENTFLOW_E2E_SANDBOX` | 沙箱,默认 `local`,仅对可信的验收任务使用 | | `AGENTFLOW_E2E_MODEL_SANDBOX` | 真实模型用例使用的沙箱,镜像里要有执行器 CLI;默认同 `AGENTFLOW_E2E_SANDBOX` | diff --git a/e2e/api/30-runs.test.mjs b/e2e/api/30-runs.test.mjs index 78c58c9e..487e096f 100644 --- a/e2e/api/30-runs.test.mjs +++ b/e2e/api/30-runs.test.mjs @@ -258,9 +258,15 @@ test('starting a run validates its input', async () => { // A fresh database (local.sh) has no built-in templates to try this with. const template = await api('GET', '/api/workflows/generic-backend-delivery', undefined, { expect: [200, 404], raw: true }); if (!project.defaultRepositoryId && template.status === 200 && template.data?.generic) { + const requirements = await get(`/api/workflows/generic-backend-delivery/executor-requirements?projectId=${encodeURIComponent(cfg.projectId)}`); + assert.ok(Array.isArray(requirements)); const run = await startRun('generic-backend-delivery', 'Check repository-free admission'); assert.deepEqual(run.repositories || [], []); - await post(`/api/runs/${run.id}/cancel`, {}); + const cancel = await api('POST', `/api/runs/${run.id}/cancel`, {}, { expect: [200, 400], raw: true }); + if (cancel.status === 400) { + assert.equal(cancel.data?.error, 'run is not active'); + assert.match((await get(`/api/runs/${run.id}`)).status, /^(failed|succeeded|cancelled)$/); + } } }); diff --git a/e2e/local.sh b/e2e/local.sh index 2fa5660a..8244638d 100755 --- a/e2e/local.sh +++ b/e2e/local.sh @@ -11,7 +11,10 @@ # for the repository-bound scenarios, and removes all of it afterwards. # # Optional environment: -# AGENTFLOW_E2E_CODEBUDDY_API_KEY enables the real-model scenarios +# AGENTFLOW_E2E_EXECUTOR CLI executor ID (default codebuddy) +# AGENTFLOW_E2E_CLI_KEY enables real-model scenarios for that CLI +# AGENTFLOW_E2E_CLI_BASE_URL optional custom model gateway +# AGENTFLOW_E2E_CODEBUDDY_API_KEY legacy CodeBuddy credential input # AGENTFLOW_E2E_CODEBUDDY_INTERNET CodeBuddy network environment (default # empty: the international site) # AGENTFLOW_E2E_LOCAL_PORT platform port (default 18090) @@ -20,7 +23,7 @@ # agentflow-e2e-local-mysql); set it when # several checkouts run the suite at once # AGENTFLOW_E2E_MODEL_SANDBOX sandbox for model scenarios (default local: -# the seeded Docker image has no CodeBuddy CLI) +# the seeded Docker image has no model CLI) # AGENTFLOW_E2E_KEEP=1 keep the platform, database and files; the # exports needed to rerun single files against # it are written to $WORK/env (mode 600) @@ -109,11 +112,38 @@ INSERT INTO api_tokens (id, user_id, name, prefix, token_hash, expires_at, creat VALUES ('tok-e2e-local', 900001, 'e2e-local', '${TOKEN:0:12}', '$HASH', DATE_ADD(NOW(3), INTERVAL 1 DAY), NOW(3)), ('tok-e2e-local-b', 900002, 'e2e-local-b', '${TOKEN_B:0:12}', '$HASH_B', DATE_ADD(NOW(3), INTERVAL 1 DAY), NOW(3)); SQL -if [ -n "${AGENTFLOW_E2E_CODEBUDDY_API_KEY:-}" ]; then - # Passed through stdin so the key never shows up in a process listing. - printf "INSERT INTO user_configs (user_id, codebuddy_api_key, codebuddy_internet_environment, created_at, updated_at) VALUES (900001, '%s', '%s', NOW(3), NOW(3));\n" \ - "${AGENTFLOW_E2E_CODEBUDDY_API_KEY//\'/}" "${AGENTFLOW_E2E_CODEBUDDY_INTERNET:-}" | mysql_exec || exit 1 +export AGENTFLOW_E2E_EXECUTOR=${AGENTFLOW_E2E_EXECUTOR:-codebuddy} +if [ -n "${AGENTFLOW_E2E_CLI_KEY:-}" ] || { [ "$AGENTFLOW_E2E_EXECUTOR" = codebuddy ] && [ -n "${AGENTFLOW_E2E_CODEBUDDY_API_KEY:-}" ]; }; then + # Seed disposable credentials over stdin. Hex literals preserve the exact + # key and URL without passing either to the MySQL client as an argument. + if ! python3 - <<'PY_CLI' | mysql_exec >/dev/null 2>&1 +import json +import os + +executor = os.environ["AGENTFLOW_E2E_EXECUTOR"] +key = os.environ.get("AGENTFLOW_E2E_CLI_KEY", "") or os.environ.get("AGENTFLOW_E2E_CODEBUDDY_API_KEY", "") +base = os.environ.get("AGENTFLOW_E2E_CLI_BASE_URL", "") +if executor == "codebuddy": + fields = {"codebuddy_api_key": key, "codebuddy_internet_environment": os.environ.get("AGENTFLOW_E2E_CODEBUDDY_INTERNET", "")} +elif executor in ("codex", "claude"): + prefix = "codex" if executor == "codex" else "claude_code" + fields = {prefix + "_api_key": key, prefix + "_base_url": base} +elif executor in ("opencode", "cursor", "agy", "kimi", "pi", "dsh", "zcode"): + fields = {"agent_cli_credentials": json.dumps({executor: {"apiKey": key, "baseUrl": base}})} +else: + raise SystemExit("Unsupported model executor") +columns = ", ".join(fields) +values = ", ".join("X'" + value.encode().hex() + "'" for value in fields.values()) +print(f"INSERT INTO user_configs (user_id, {columns}, created_at, updated_at) VALUES (900001, {values}, NOW(3), NOW(3));") +PY_CLI + then + echo "Seeding the selected CLI credential failed." >&2 + exit 1 + fi +else + export AGENTFLOW_E2E_MODEL=0 fi +unset AGENTFLOW_E2E_CODEBUDDY_API_KEY AGENTFLOW_E2E_CLI_KEY api() { local code @@ -138,11 +168,9 @@ export AGENTFLOW_E2E_REPO_CLONE_URL="$REPO/remote.git" AGENTFLOW_E2E_REPO_BRANCH export AGENTFLOW_E2E_MODEL_SANDBOX=${AGENTFLOW_E2E_MODEL_SANDBOX:-local} # A fresh database has no data-rich project to tour; tour the e2e project. export AGENTFLOW_E2E_VIEW_PROJECT=${AGENTFLOW_E2E_VIEW_PROJECT:-e2e-auto} -[ -n "${AGENTFLOW_E2E_CODEBUDDY_API_KEY:-}" ] || export AGENTFLOW_E2E_MODEL=0 -unset AGENTFLOW_E2E_CODEBUDDY_API_KEY if [ "${AGENTFLOW_E2E_KEEP:-0}" = 1 ]; then - (umask 077 && printf 'export AGENTFLOW_E2E_BASE=%q AGENTFLOW_E2E_TOKEN=%q AGENTFLOW_E2E_TOKEN_B=%q AGENTFLOW_E2E_REPO_CLONE_URL=%q AGENTFLOW_E2E_REPO_BRANCH=main AGENTFLOW_E2E_MODEL_SANDBOX=%q AGENTFLOW_E2E_MODEL=%q AGENTFLOW_E2E_VIEW_PROJECT=%q\n' \ - "$BASE" "$TOKEN" "$TOKEN_B" "$AGENTFLOW_E2E_REPO_CLONE_URL" "$AGENTFLOW_E2E_MODEL_SANDBOX" "${AGENTFLOW_E2E_MODEL:-1}" "$AGENTFLOW_E2E_VIEW_PROJECT" >"$WORK/env") + (umask 077 && printf 'export AGENTFLOW_E2E_BASE=%q AGENTFLOW_E2E_TOKEN=%q AGENTFLOW_E2E_TOKEN_B=%q AGENTFLOW_E2E_REPO_CLONE_URL=%q AGENTFLOW_E2E_REPO_BRANCH=main AGENTFLOW_E2E_MODEL_SANDBOX=%q AGENTFLOW_E2E_MODEL=%q AGENTFLOW_E2E_VIEW_PROJECT=%q AGENTFLOW_E2E_EXECUTOR=%q AGENTFLOW_E2E_MODEL_ID=%q\n' \ + "$BASE" "$TOKEN" "$TOKEN_B" "$AGENTFLOW_E2E_REPO_CLONE_URL" "$AGENTFLOW_E2E_MODEL_SANDBOX" "${AGENTFLOW_E2E_MODEL:-1}" "$AGENTFLOW_E2E_VIEW_PROJECT" "$AGENTFLOW_E2E_EXECUTOR" "${AGENTFLOW_E2E_MODEL_ID:-}" >"$WORK/env") fi status=0 diff --git a/e2e/public/00-first-run.spec.mjs b/e2e/public/00-first-run.spec.mjs index 6bf5e144..69290614 100644 --- a/e2e/public/00-first-run.spec.mjs +++ b/e2e/public/00-first-run.spec.mjs @@ -1,6 +1,6 @@ import {test,expect} from '@playwright/test'; import fs from 'node:fs'; -import {password, appReady, chat, composer, openHome} from './helpers.mjs'; +import {password, appReady, chat, composer, openHome, openExecutorSetup} from './helpers.mjs'; // A brand-new installation, seen by someone who has never used LoopForge: // first visit creates the administrator, the home page explains what to do @@ -56,11 +56,8 @@ test('the home page guides a new account and explains the missing model key',asy const input=await openHome(page); const frame=chat(page); await expect(frame.locator('.home-starter')).toHaveCount(3); - const notice=frame.locator('.credential-notice'); - await expect(notice).toContainText('CodeBuddy API Key'); await input.fill('First question after installing'); - await notice.getByRole('button',{name:'去配置'}).click(); - await expect(page.locator('#credentialWizard .credential-pane:not(.is-leaving) input[name="secret"]')).toBeFocused(); + await openExecutorSetup(page); await page.keyboard.press('Escape'); await expect(await openHome(page)).toHaveValue('First question after installing'); await composer(page).fill(''); diff --git a/e2e/public/composer.spec.mjs b/e2e/public/composer.spec.mjs index 412d939a..8182141d 100644 --- a/e2e/public/composer.spec.mjs +++ b/e2e/public/composer.spec.mjs @@ -1,5 +1,5 @@ import {test,expect} from '@playwright/test'; -import {password as adminPassword, signInUnconfigured, appReady, switchProject, chat, openHome} from './helpers.mjs'; +import {password as adminPassword, signInUnconfigured, appReady, switchProject, chat, openHome, openExecutorSetup} from './helpers.mjs'; // Credential UI must never enter a Playwright trace or screenshot artifact. test.use({trace:'off',screenshot:'off'}); @@ -12,39 +12,44 @@ test('a user without model credentials can draft, configure credentials and retu // This is an inert value for a UI state transition. No model request is sent. const marker='e2e-placeholder-credential-not-for-model-use'; const draft='保留这份尚未发送的需求草稿'; + let clearCredential; try { let input=await openHome(page); await input.fill(draft); - const notice=chat(page).locator('.credential-notice'); - await expect(notice).toBeVisible(); - await expect(notice).toContainText('CodeBuddy API Key'); - await notice.getByRole('button',{name:'去配置'}).click(); - await expect(page).toHaveURL(/#\/settings/); + const chooser=await openExecutorSetup(page); + if(chooser)await page.getByRole('listbox',{name:'新增执行器',exact:true}).getByRole('option',{name:'ZCode',exact:true}).click(); const wizard=page.locator('#credentialWizard'); const pane=wizard.locator('.credential-pane:not(.is-leaving)'); const next=wizard.locator('[data-wizard-next]'); - await expect(wizard.locator('[data-wizard-step]')).toHaveText('2 / 3'); + if(!chooser)await expect(wizard.locator('[data-wizard-step]')).toHaveText('2 / 3'); await expect(pane.locator('input[name="secret"]')).toBeFocused(); await expect(next).toBeDisabled(); + clearCredential=chooser?{agentCliCredentials:{zcode:{apiKeyClear:true}}}:{codeBuddyApiKeyClear:true}; await pane.locator('input[name="secret"]').fill(marker); await expect(next).toBeEnabled(); await next.click(); - await expect(wizard.locator('[data-wizard-step]')).toHaveText('3 / 3'); - await expect(pane).not.toContainText(marker); - await next.click(); - await expect(wizard.locator('[data-wizard-done]')).toBeVisible({timeout:20_000}); + if(chooser){ + await expect(wizard).toBeHidden(); + }else{ + await expect(wizard.locator('[data-wizard-step]')).toHaveText('3 / 3'); + await expect(pane).not.toContainText(marker); + await next.click(); + await expect(wizard.locator('[data-wizard-done]')).toBeVisible({timeout:20_000}); + await wizard.locator('[data-wizard-done]').click(); + } const users=await page.request.get('/api/users').then(r=>r.json()); const saved=users.find(u=>u.id===current.user.id); - expect(saved.codeBuddyApiKeyConfigured).toBe(true); + expect(chooser?saved.agentCliCredentials?.zcode?.apiKeyConfigured:saved.codeBuddyApiKeyConfigured).toBe(true); expect(JSON.stringify(saved)).not.toContain(marker); - await wizard.locator('[data-wizard-done]').click(); input=await openHome(page); await expect(input).toHaveValue(draft); await expect(chat(page).locator('.credential-notice')).toHaveCount(0); expect(errors).toEqual([]); } finally { - const cleared=await page.request.put(path,{data:{codeBuddyApiKeyClear:true}}); - expect(cleared.ok()).toBe(true); + if(clearCredential){ + const cleared=await page.request.put(path,{data:clearCredential}); + expect(cleared.ok()).toBe(true); + } } }); diff --git a/e2e/public/executors.spec.mjs b/e2e/public/executors.spec.mjs index 23bb0d37..d0f4b1b2 100644 --- a/e2e/public/executors.spec.mjs +++ b/e2e/public/executors.spec.mjs @@ -3,9 +3,18 @@ import {signInUnconfigured, switchProject, chat, openHome, fitsFrame, openSettin test.use({trace:'off',screenshot:'off'}); -// first-run drives the published image, whose picker is still labeled 执行器 and -// lists three CLIs. The browser job builds this checkout, which labels it CLI. +// The published image labels the picker 执行器. The source build labels it CLI. const executorButton = (frame) => frame.getByRole('button', { name: /^(执行器|CLI)$/ }); +const testKey='e2e-inert-executor-key-for-menu-tests'; +const putCredentials=async(page,path,data)=>expect((await page.request.put(path,{data})).ok()).toBe(true); + +async function emptyCredentialsPath(page){ + const {user}=await page.request.get('/api/auth/current').then(r=>r.json()); + expect(!!user.codeBuddyApiKeyConfigured).toBe(false); + expect(!!user.codexApiKeyConfigured).toBe(false); + expect(!!user.claudeCodeApiKeyConfigured).toBe(false); + return `/api/users/${user.id}/credentials`; +} for(const viewport of [{width:1280,height:400},{width:390,height:600}]){ test(`the executor and model menus stay usable at ${viewport.width}x${viewport.height}`,async({page})=>{ @@ -14,61 +23,49 @@ for(const viewport of [{width:1280,height:400},{width:390,height:600}]){ page.on('request',r=>{if(r.isNavigationRequest()&&r.frame()===page.mainFrame())errors.length=0}); await page.setViewportSize(viewport); await signInUnconfigured(page); - await openHome(page); - const frame=chat(page); - const cli=executorButton(frame),cliMenu=frame.locator('.permission-menu[role="menu"]'); - const fits=async menu=>{ - await expect(menu).toBeVisible(); - await expect.poll(()=>fitsFrame(menu)).toBe(true); - }; - await cli.click(); - await fits(cliMenu); - await page.keyboard.press('Escape'); - await expect(cliMenu).toBeHidden(); - // Codex offers a built-in catalog on installations without any configured models. - await cli.click(); - await cliMenu.getByRole('menuitemradio',{name:'Codex',exact:true}).click(); - const model=frame.getByRole('button',{name:'选择模型',exact:true}),modelMenu=frame.locator('.grasp-model-menu'); - await model.click(); - await fits(modelMenu); - await page.keyboard.press('Escape'); - await expect(modelMenu).toBeHidden(); - // Long catalogs are searched inside the menu. - await model.click(); - const search=modelMenu.locator('input[aria-label="搜索模型"]'); - await expect(search).toBeVisible(); - const first=(await modelMenu.locator('[role^="menuitem"]').first().innerText()).split('\n')[0].trim(); - await search.fill('zz-no-such-model'); - await expect(modelMenu).not.toContainText(first); - await search.fill(first); - await expect(modelMenu).toContainText(first); - await page.keyboard.press('Escape'); - expect(errors).toEqual([]); + const path=await emptyCredentialsPath(page); + await putCredentials(page,path,{codexApiKey:testKey}); + try{ + await page.reload();await openHome(page); + const frame=chat(page); + const cli=executorButton(frame),cliMenu=frame.locator('.permission-menu[role="menu"]'); + const fits=async menu=>{ + await expect(menu).toBeVisible(); + await expect.poll(()=>fitsFrame(menu)).toBe(true); + }; + await cli.click(); + await fits(cliMenu); + await page.keyboard.press('Escape'); + await expect(cliMenu).toBeHidden(); + await cli.click(); + await cliMenu.getByRole('menuitemradio',{name:'Codex',exact:true}).click(); + const model=frame.getByRole('button',{name:'选择模型',exact:true}),modelMenu=frame.locator('.grasp-model-menu'); + await model.click(); + await fits(modelMenu); + await page.keyboard.press('Escape'); + await expect(modelMenu).toBeHidden(); + await model.click(); + const search=modelMenu.locator('input[aria-label="搜索模型"]'); + await expect(search).toBeVisible(); + const first=(await modelMenu.locator('[role^="menuitem"]').first().innerText()).split('\n')[0].trim(); + await search.fill('zz-no-such-model'); + await expect(modelMenu).not.toContainText(first); + await search.fill(first); + await expect(modelMenu).toContainText(first); + await page.keyboard.press('Escape'); + expect(errors).toEqual([]); + }finally{ + await putCredentials(page,path,{codexApiKeyClear:true}); + } }); } test('executor selection has independent models, credentials and a persistent choice',async({page})=>{ await signInUnconfigured(page); + const path=await emptyCredentialsPath(page); const draft='Keep this draft while choosing an executor'; - const input=await openHome(page); - const frame=chat(page); - const executor=executorButton(frame); - const choose=async label=>{ - await executor.click(); - await frame.locator('.permission-menu [role="menuitemradio"]').filter({hasText:label}).click(); - await expect(executor).toContainText(label); - }; - await executor.click(); - const options=frame.locator('.permission-menu [role="menuitemradio"]'); - for(const label of ['CodeBuddy','Codex','Claude Code'])await expect(options.filter({hasText:label})).toHaveCount(1); - await page.keyboard.press('Escape'); - await input.fill(draft); for(const [id,label] of [['codex','Codex'],['claude','Claude Code'],['codebuddy','CodeBuddy']]){ - await choose(label); - await expect(input).toHaveValue(draft); - // Only CodeBuddy has the inline key reminder; every executor is still checked server-side. - await expect(frame.locator('.credential-notice')).toHaveCount(id==='codebuddy'?1:0); - const response=await page.request.post('/api/assistant/generations',{data:{executor:id,model:'default',projectId:'welcome',messages:[{role:'user',content:'No key: reject before executing.'}]}}); + const response=await page.request.post('/api/assistant/generations',{data:{executor:id,model:'default',messages:[{role:'user',content:'No key: reject before executing.'}]}}); expect(response.status()).toBe(400);expect((await response.json()).error).toContain(label); const models=await page.request.get('/api/assistant/models?executor='+id); expect(models.ok()).toBe(true); @@ -77,13 +74,41 @@ test('executor selection has independent models, credentials and a persistent ch if(id==='codebuddy')expect(catalog.default).toBeTruthy(); else expect(catalog.models.length).toBeGreaterThan(0); } - await choose('Codex'); - await page.reload(); - await expect(composer()).toBeEditable(); - await expect(executorButton(chat(page))).toContainText('Codex'); - await choose('CodeBuddy'); - expect((await page.request.get('/api/assistant/models?executor=shell')).status()).toBe(400); - function composer(){return chat(page).locator('.composer-column textarea')} + await putCredentials(page,path,{codexApiKey:testKey}); + try{ + const catalog=await page.request.get('/api/assistant/models').then(r=>r.json()); + await page.reload(); + const initial=await openHome(page); + const frame=chat(page),executor=executorButton(frame); + const options=frame.locator('.permission-menu [role="menuitemradio"]'); + if(catalog.preferences){ + expect(catalog.preferences.executor).toBe('codex'); + await executor.click(); + await expect(options).toHaveCount(1); + await expect(options.first()).toContainText('Codex'); + await page.keyboard.press('Escape'); + } + await initial.fill(draft); + await putCredentials(page,path,{codeBuddyApiKey:testKey,claudeCodeApiKey:testKey}); + await page.reload(); + const input=await openHome(page); + const choose=async label=>{ + await executor.click(); + await options.filter({hasText:label}).click(); + await expect(executor).toContainText(label); + }; + for(const label of ['Codex','Claude Code','CodeBuddy']){ + await choose(label); + await expect(input).toHaveValue(draft); + await expect(frame.locator('.credential-notice')).toHaveCount(0); + } + await choose('Codex'); + await page.reload(); + await expect(executor).toContainText('Codex'); + expect((await page.request.get('/api/assistant/models?executor=shell')).status()).toBe(400); + }finally{ + await putCredentials(page,path,{codeBuddyApiKeyClear:true,codexApiKeyClear:true,claudeCodeApiKeyClear:true}); + } }); test('SOP readiness checks each role executor rather than always requiring CodeBuddy',async({page})=>{ diff --git a/e2e/public/github-setup.spec.mjs b/e2e/public/github-setup.spec.mjs index 7d818353..6a2f2beb 100644 --- a/e2e/public/github-setup.spec.mjs +++ b/e2e/public/github-setup.spec.mjs @@ -3,7 +3,7 @@ import {password,appReady} from './helpers.mjs'; test.use({trace:'off',screenshot:'off'}); -test('GitHub authorization stays in one credential row with a separate manual path',async({page},info)=>{ +test('GitHub authorization has a separate manual token path',async({page},info)=>{ const errors=[],failed=[]; page.on('pageerror',error=>errors.push(error.message)); page.on('response',response=>{if(response.status()>=500)failed.push(response.status()+' '+response.url())}); @@ -16,9 +16,18 @@ test('GitHub authorization stays in one credential row with a separate manual pa const capability=await page.request.get('/api/auth/github').then(response=>response.json()); await page.goto('/#/settings'); await expect(page.locator('#personalSettingsContent > .personal-settings-card')).toHaveCount(0); - await expect(page.locator('[data-credential-row="gitToken"]')).toContainText('GitHub'); + const panel=page.locator('#credentialPanel'); + await expect(panel).toBeVisible(); + const add=panel.getByRole('button',{name:'新增 Git 配置',exact:true}); + const chooser=await add.isVisible(); + const row=panel.locator('[data-credential-row="gitToken"]'); + if(chooser)await expect(row).toHaveCount(0); + else await expect(row).toContainText('GitHub'); await page.screenshot({path:info.outputPath('github-settings.png'),fullPage:true}); - await page.locator('[data-credential-row="gitToken"] [data-credential-act="setup"]').click(); + if(chooser){ + await add.click(); + await page.getByRole('listbox',{name:'新增 Git 配置',exact:true}).getByRole('option',{name:'GitHub',exact:true}).click(); + }else await row.locator('[data-credential-act="setup"]').click(); const wizard=page.locator('#credentialWizard'); if(capability.enabled){ await expect(wizard.locator('[data-github-start]')).toBeVisible(); diff --git a/e2e/public/helpers.mjs b/e2e/public/helpers.mjs index 3f751542..9a8630bb 100644 --- a/e2e/public/helpers.mjs +++ b/e2e/public/helpers.mjs @@ -52,6 +52,28 @@ export async function openHome(page){ await page.waitForLoadState('networkidle'); return composer(page); } + +// The first-run suite also tests the pinned release, which opens the +// CodeBuddy wizard directly before the executor picker was introduced. +export async function openExecutorSetup(page){ + const {expect}=await import('@playwright/test'); + const notice=chat(page).locator('.credential-notice'); + await expect(notice).toBeVisible(); + const add=notice.getByRole('button',{name:'新增执行器',exact:true}); + const chooser=await add.isVisible(); + if(chooser){ + await expect(notice).toContainText('添加一个执行器即可开始对话'); + await add.click(); + await expect(page.getByRole('listbox',{name:'新增执行器',exact:true})).toBeVisible(); + }else{ + await expect(notice).toContainText('CodeBuddy API Key'); + await notice.getByRole('button',{name:'去配置',exact:true}).click(); + await expect(page.locator('#credentialWizard .credential-pane:not(.is-leaving) input[name="secret"]')).toBeFocused(); + } + await expect(page).toHaveURL(/#\/settings/); + return chooser; +} + // A menu or dialog inside the chat frame must fit the frame's viewport. export const fitsFrame=locator=>locator.evaluate(el=>{ const r=el.getBoundingClientRect(); diff --git a/e2e/public/welcome.spec.mjs b/e2e/public/welcome.spec.mjs index b599e62a..5987afc5 100644 --- a/e2e/public/welcome.spec.mjs +++ b/e2e/public/welcome.spec.mjs @@ -1,5 +1,5 @@ import {test,expect} from '@playwright/test'; -import {signInUnconfigured, appReady, switchProject, chat, openHome, fitsFrame} from './helpers.mjs'; +import {signInUnconfigured, appReady, switchProject, chat, openHome, openExecutorSetup, fitsFrame} from './helpers.mjs'; // Default journeys use an account with no model key, joined to the welcome // project. New self-registered accounts join it automatically. The real-model @@ -78,14 +78,21 @@ test('sending without a model key is refused before any request, with a way to c const frame=chat(page); const text='No key yet: this must be refused before any model runs.'; await input.fill(text); - await frame.locator('.send-button').click(); - const configure=frame.getByRole('button',{name:'去配置 CodeBuddy API Key'}); - await expect(configure).toBeVisible(); + const send=frame.locator('.send-button'); + const notice=frame.locator('.credential-notice'); + await expect(notice).toBeVisible(); + const chooser=await notice.getByRole('button',{name:'新增执行器',exact:true}).isVisible(); + if(chooser)await expect(send).toBeDisabled(); + else await send.click(); await expect(input).toHaveValue(text); expect(writes).toBe(0); - await configure.click(); - await expect(page).toHaveURL(/#\/settings/); - await expect(page.locator('#credentialWizard .credential-pane:not(.is-leaving) input[name="secret"]')).toBeFocused(); + if(chooser){ + await openExecutorSetup(page); + }else{ + await frame.getByRole('button',{name:'去配置 CodeBuddy API Key',exact:true}).click(); + await expect(page).toHaveURL(/#\/settings/); + await expect(page.locator('#credentialWizard .credential-pane:not(.is-leaving) input[name="secret"]')).toBeFocused(); + } await page.keyboard.press('Escape'); }); diff --git a/e2e/ui/03-workbench-settings.spec.mjs b/e2e/ui/03-workbench-settings.spec.mjs index 5b23f964..a4322e5a 100644 --- a/e2e/ui/03-workbench-settings.spec.mjs +++ b/e2e/ui/03-workbench-settings.spec.mjs @@ -88,17 +88,12 @@ test('personal credentials: the add wizard validates, saves write-only, and the const errors = watchErrors(page); await openView(page, 'settings'); - await page.locator('[data-credential-add]').click(); + await page.locator('#credentialPanel').getByRole('button', { name: '新增执行器', exact: true }).click(); + await page.getByRole('listbox', { name: '新增执行器', exact: true }).getByRole('option', { name: 'Codex', exact: true }).click(); const wizard = page.locator('#credentialWizard'); const pane = wizard.locator('.credential-pane:not(.is-leaving)'); const next = wizard.locator('[data-wizard-next]'); - await expect(wizard.getByRole('dialog', { name: '添加凭证' })).toBeVisible(); - await expect(wizard.locator('[data-wizard-step]')).toHaveText('1 / 3'); - await wizard.locator('[data-wizard-kind="codexApiKey"]').click(); - await expect(wizard.locator('[data-wizard-kind="codexApiKey"]')).toHaveAttribute('aria-checked', 'true'); - await next.click(); - - await expect(wizard.locator('[data-wizard-step]')).toHaveText('2 / 3'); + await expect(wizard.getByRole('dialog')).toBeVisible(); await expect(next).toBeDisabled(); const key = `sk-e2e-${cfg.runTag}`; await pane.locator('input[name="secret"]').fill(key); @@ -106,19 +101,14 @@ test('personal credentials: the add wizard validates, saves write-only, and the await baseURL.fill('not-a-url'); await expect(pane.locator('[data-credential-hint="extra"]')).toContainText('http://'); await expect(next).toBeDisabled(); - await baseURL.fill('https://gateway.example.com/v1'); + await baseURL.fill('https://gateway.invalid/v1'); await expect(next).toBeEnabled(); await next.click(); - await expect(wizard.locator('[data-wizard-step]')).toHaveText('3 / 3'); - await expect(pane).not.toContainText(key); - await next.click(); - await expect(wizard.locator('[data-wizard-done]')).toBeVisible({ timeout: 20_000 }); + await expect(wizard).toBeHidden({ timeout: 20_000 }); const saved = await userById(me.id); expect(saved.codexApiKeyConfigured).toBe(true); expect(JSON.stringify(saved)).not.toContain(key); - await wizard.locator('[data-wizard-done]').click(); - await expect(wizard.getByRole('dialog')).toHaveCount(0); const row = page.locator('#credentialPanel [data-credential-row="codexApiKey"]'); await expect(row).toHaveClass(/is-configured/); @@ -126,7 +116,7 @@ test('personal credentials: the add wizard validates, saves write-only, and the await expect(row).toHaveClass(/is-open/); await row.locator('[data-credential-act="delete"]').click(); await row.locator('[data-credential-act="confirm-delete"]').click(); - await expect(row).not.toHaveClass(/is-configured/, { timeout: 20_000 }); + await expect(row).toHaveCount(0, { timeout: 20_000 }); expect((await userById(me.id)).codexApiKeyConfigured).toBeFalsy(); expect(errors).toEqual([]); }); diff --git a/internal/application/operations.go b/internal/application/operations.go index 3f690262..cd770c18 100644 --- a/internal/application/operations.go +++ b/internal/application/operations.go @@ -96,7 +96,7 @@ func PublicOperations() []Operation { {Name: "runs_get", Description: "Get one Run", Method: "GET", Path: "/api/runs/{id}", ReadOnly: true}, {Name: "runs_wait", Description: "Wait for the SOP with path.id to succeed, fail, be cancelled, or need human action (waiting/paused). One call waits up to 25 seconds. If timedOut is true, the SOP is still active or queued; keep waiting on the same run ID if needed.", Method: "GET", Path: "/api/runs/{id}/wait", ReadOnly: true}, {Name: "runs_delete", Description: "Delete a finished Run", Method: "DELETE", Path: "/api/runs/{id}"}, - {Name: "runs_eval_start", Description: "Manually start an LLM quality evaluation of a finished SOP run. Body: {model}. Uses the current user's CodeBuddy key and assistant model catalog.", Method: "POST", Path: "/api/runs/{id}/eval"}, + {Name: "runs_eval_start", Description: "Manually start an LLM quality evaluation of a finished SOP run. Body: {model}. Uses the current user's credentials for the selected CLI. Use a CLI-prefixed model ID, or omit model to use a configured CLI default.", Method: "POST", Path: "/api/runs/{id}/eval"}, {Name: "runs_eval_get", Description: "Get the latest SOP run evaluation", Method: "GET", Path: "/api/runs/{id}/eval", ReadOnly: true}, {Name: "runs_eval_apply", Description: "Apply selected evaluation recommendations to the current SOP or agent after user confirmation. Body: {evalId, recommendationIds}", Method: "POST", Path: "/api/runs/{id}/eval/apply"}, {Name: "runs_telemetry_list", Description: "Page through Run telemetry", Method: "GET", Path: "/api/runs/{id}/telemetry", ReadOnly: true}, @@ -124,7 +124,7 @@ func PublicOperations() []Operation { {Name: "schedule_jobs_publish", Description: "Publish a credential-free shared AI task version from an independent task. baseVersion is required for optimistic concurrency.", Method: "POST", Path: "/api/schedule-jobs/{id}/publish"}, {Name: "schedule_jobs_list", Description: "List scheduled SOP jobs", Method: "GET", Path: "/api/schedule-jobs", ReadOnly: true}, {Name: "schedule_job_executions_list", Description: "List schedule job executions newest first: status, error, durationMs, AI reply summary and the runs[] (issueId, runId) each execution dispatched. Look up a Trace ID copied from the schedule execution panel or a scheduler log line (trace=...) with query.traceId; filter by jobId or status (running/success/failed/waiting). Follow runs[].runId with runs_get.", Method: "GET", Path: "/api/schedule-job-executions", ReadOnly: true}, - {Name: "schedule_jobs_save", Description: "Create or update a scheduled job. Two exclusive kinds: trigger jobs (skipDispatch=false, require workflowId) scan issues in issueStatuses (backlog/todo/in_progress/in_review/blocked; default backlog+todo), run baseline guard, and dispatch SOP with optional maxDispatch (1-10 successful issue dispatches per execution; omitted or 0 defaults to 10); AI jobs (skipDispatch=true, require assistantPrompt or sharedTaskId+sharedTaskVersion+parameterValues) run a prompt with timeoutMinutes (1-240; omitted or 0 defaults to 30). Timing is intervalSec or 5-field cron (Asia/Shanghai). Optional notifications bind up to 3 configured project Bots (botId, events succeeded/failed, template, contentMode template/ai, aiInstruction). Use notification_bots_list to select an existing Bot. AI content reuses this task output; {{task.name}}, {{result}} and {{ai.summary}} are supported.", Method: "PUT", Path: "/api/schedule-jobs"}, + {Name: "schedule_jobs_save", Description: "Create or update a scheduled job. Two exclusive kinds: trigger jobs (skipDispatch=false, require workflowId) scan issues in issueStatuses (backlog/todo/in_progress/in_review/blocked; default backlog+todo), run baseline guard, and dispatch SOP with optional maxDispatch (1-10 successful issue dispatches per execution; omitted or 0 defaults to 10). AI jobs (skipDispatch=true, require assistantPrompt or sharedTaskId+sharedTaskVersion+parameterValues) run a prompt using the executor and model selected by assistantModel (for example codex:). Omit assistantModel to use the execution account's default. Set timeoutMinutes (1-240; omitted or 0 defaults to 30). Timing is intervalSec or 5-field cron (Asia/Shanghai). Optional notifications bind up to 3 configured project Bots (botId, events succeeded/failed, template, contentMode template/ai, aiInstruction). Use notification_bots_list to select an existing Bot. AI content reuses this task output; {{task.name}}, {{result}} and {{ai.summary}} are supported.", Method: "PUT", Path: "/api/schedule-jobs"}, {Name: "schedule_jobs_delete", Description: "Delete a scheduled SOP job", Method: "DELETE", Path: "/api/schedule-jobs/{id}"}, {Name: "schedule_jobs_run", Description: "Start a scheduled job on the server and return immediately (lastStatus=running). Closing the client does not cancel it; poll schedule_jobs_list until lastStatus leaves running.", Method: "POST", Path: "/api/schedule-jobs/{id}/run"}, {Name: "assistant_sessions_list", Description: "List the assistant conversations the caller may read: their own sessions, SOP shared sessions of authorized runs, and conversations of projects they belong to. Use it to resolve a chat session link before reading it.", Method: "GET", Path: "/api/assistant/sessions", ReadOnly: true}, diff --git a/internal/config/integration_hosts.go b/internal/config/integration_hosts.go new file mode 100644 index 00000000..6af0201e --- /dev/null +++ b/internal/config/integration_hosts.go @@ -0,0 +1,39 @@ +package config + +import ( + "net/url" + "regexp" + "strconv" + "strings" +) + +var integrationHostname = regexp.MustCompile(`^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$`) + +func integrationHost(raw string) string { + value := strings.ToLower(strings.TrimSpace(raw)) + parsed, err := url.Parse("https://" + value) + if err != nil || parsed.Host != value || parsed.User != nil || parsed.Path != "" || + !integrationHostname.MatchString(parsed.Hostname()) || strings.Contains(parsed.Hostname(), "..") { + return "" + } + if port := parsed.Port(); port != "" { + if n, err := strconv.Atoi(port); err != nil || n < 1 || n > 65535 { + return "" + } + } else if strings.Contains(value, ":") { + return "" + } + return parsed.Host +} + +// GongfengHost returns the explicitly configured managed Git host. +func GongfengHost() string { + return integrationHost(env("AGENTFLOW_GONGFENG_HOST")) +} + +func TAPDWebHost() string { + if host := integrationHost(env("AGENTFLOW_TAPD_HOST")); host != "" { + return host + } + return "www.tapd.cn" +} diff --git a/internal/domain/assistant_preferences.go b/internal/domain/assistant_preferences.go index b5bdc139..79d4fa3f 100644 --- a/internal/domain/assistant_preferences.go +++ b/internal/domain/assistant_preferences.go @@ -2,6 +2,14 @@ package domain import "time" +// AssistantDefaults applies to new selections made with the user's own credentials. +type AssistantDefaults struct { + Executor string `json:"executor,omitempty"` + Model string `json:"model,omitempty"` + Effort string `json:"effort,omitempty"` + Approval string `json:"approval,omitempty"` +} + // AssistantPreferencesInstructionsMax caps the user's own rules for Main Bot. const AssistantPreferencesInstructionsMax = 4000 diff --git a/internal/domain/delivery_mr.go b/internal/domain/delivery_mr.go index 46948438..fd3d8262 100644 --- a/internal/domain/delivery_mr.go +++ b/internal/domain/delivery_mr.go @@ -54,7 +54,7 @@ func GongfengMRURL(project string, iid int) string { } return fmt.Sprintf("https://%s/%s/-/merge_requests/%d", host, path, iid) } - return fmt.Sprintf("https://git.example.com/%s/-/merge_requests/%d", project, iid) + return fmt.Sprintf("https://%s/%s/-/merge_requests/%d", GongfengRepositoryHost(), project, iid) } // AggregateDeliveryMRState folds per-MR states into the work item label state. diff --git a/internal/domain/domain_cases_test.go b/internal/domain/domain_cases_test.go index 5ec926a9..83badec1 100644 --- a/internal/domain/domain_cases_test.go +++ b/internal/domain/domain_cases_test.go @@ -123,7 +123,6 @@ func TestPreviewContractAndSessionBranches(t *testing.T) { } for _, bad := range []*PreviewContract{ {Enabled: true, Kind: "service"}, - {Enabled: true, ExecutorID: "other"}, {Enabled: true, SourcePath: "../x"}, } { if bad.Validate() == nil { diff --git a/internal/domain/mr.go b/internal/domain/mr.go index 97539507..893a499b 100644 --- a/internal/domain/mr.go +++ b/internal/domain/mr.go @@ -9,11 +9,9 @@ import ( "time" ) -// Gongfeng MCP often returns http://git.example.com/.../merge_requests/N. Accept -// either scheme and store the canonical https URL. -var githubPRURL = regexp.MustCompile(`https?://github\.com/([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)/pull/(\d+)`) - -var gongfengMRURL = regexp.MustCompile(`https?://git\.example\.com/([^\s"'<>#]+)/merge_requests/(\d+)`) +// Find review links in the order they are cited. We validate their host and +// project below before treating any link in free text as delivery evidence. +var hostedReviewURL = regexp.MustCompile(`https?://([^/\s"'<>#]+)/([^\s"'<>#]+)/(pull|merge_requests)/(\d+)`) var githubPRLink = regexp.MustCompile(`^https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/pull/\d+/?$`) @@ -110,18 +108,21 @@ func ParseGongfengMR(text string) (project string, iid int, url string, ok bool) // ParseGongfengMRs extracts unique Gongfeng merge request URLs in appearance order. func ParseGongfengMRs(text string) []GongfengMRRef { - for _, match := range githubPRURL.FindAllStringSubmatch(text, -1) { - text = strings.ReplaceAll(text, match[0], "https://git.example.com/github:"+match[1]+"/merge_requests/"+match[2]) - } - matches := gongfengMRURL.FindAllStringSubmatch(text, -1) - if len(matches) == 0 { - return nil - } - out := make([]GongfengMRRef, 0, len(matches)) + var out []GongfengMRRef seen := map[string]struct{}{} - for _, match := range matches { - project := strings.TrimSuffix(strings.TrimSuffix(match[1], "/"), "/-") - iid, _ := strconv.Atoi(match[2]) + for _, match := range hostedReviewURL.FindAllStringSubmatch(text, -1) { + host, path, kind := match[1], match[2], match[3] + var project string + if kind == "pull" && strings.EqualFold(host, "github.com") && githubRepositoryPath.MatchString(path) { + project = "github:" + path + } else if kind == "merge_requests" && IsGongfengHost(host) { + path = strings.TrimSuffix(strings.TrimSuffix(path, "/"), "/-") + project = normalizeGongfengProjectPath(path) + if project == "" && IsSafeGongfengProjectID(path) { + project = path + } + } + iid, _ := strconv.Atoi(match[4]) if project == "" || iid <= 0 { continue } diff --git a/internal/domain/preview.go b/internal/domain/preview.go index 23465294..0f76175d 100644 --- a/internal/domain/preview.go +++ b/internal/domain/preview.go @@ -43,14 +43,14 @@ const ( ) // PreviewContract is the run-level delivery contract frozen into -// WorkflowSnapshot. Enabling it injects a CodeBuddy build node. The static +// WorkflowSnapshot. Enabling it injects a build node. The static // site is archived when that node succeeds, so a later confirmation can open // the preview before the run itself finishes. type PreviewContract struct { Enabled bool `json:"enabled"` Kind string `json:"kind"` // static; later service/environment - ExecutorID string `json:"executorId,omitempty"` // currently only codebuddy - Model string `json:"model,omitempty"` // CodeBuddy model id + ExecutorID string `json:"executorId,omitempty"` // empty follows the run's responsible user + Model string `json:"model,omitempty"` // model ID on the selected CLI SourcePath string `json:"sourcePath,omitempty"` // relative to the run workspace; default dist IndexFile string `json:"indexFile,omitempty"` // default index.html SPAFallback bool `json:"spaFallback,omitempty"` @@ -95,14 +95,19 @@ func (c *PreviewContract) SourceOrDist() string { return PreviewDefaultSource } -func (c *PreviewContract) ExecutorOrCodeBuddy() string { +func (c *PreviewContract) SelectedExecutorID() string { if c == nil { - return PreviewBuildExecutor + return "" } if id := strings.TrimSpace(c.ExecutorID); id != "" { return id } - return PreviewBuildExecutor + model := strings.TrimSpace(c.Model) + if model != "" && model != PreviewDefaultModel && model != "default-model" { + // Old preview contracts could pin a CodeBuddy model without an executor. + return PreviewBuildExecutor + } + return "" } func (c *PreviewContract) ModelOrDefault() string { @@ -135,8 +140,12 @@ func (c *PreviewContract) Normalize() { return } c.Kind = c.KindOrStatic() - c.ExecutorID = c.ExecutorOrCodeBuddy() - c.Model = c.ModelOrDefault() + c.ExecutorID = c.SelectedExecutorID() + if c.ExecutorID == "" { + c.Model = "" + } else { + c.Model = c.ModelOrDefault() + } c.SourcePath = c.SourceOrDist() c.IndexFile = c.Index() if c.RetentionSec <= 0 || c.RetentionSec > PreviewMaxRetentionSec { @@ -152,12 +161,6 @@ func (c *PreviewContract) Validate() error { if !c.Static() { return fmt.Errorf("frontend preview currently supports static sites only") } - if !strings.EqualFold(c.ExecutorID, PreviewBuildExecutor) { - return fmt.Errorf("frontend preview currently supports CodeBuddy CLI only") - } - if strings.TrimSpace(c.Model) == "" { - return fmt.Errorf("frontend preview requires a CodeBuddy model") - } if strings.Contains(c.SourcePath, "..") || strings.HasPrefix(c.SourcePath, "/") { return fmt.Errorf("frontend preview sourcePath %q is invalid", c.SourcePath) } diff --git a/internal/domain/preview_build.go b/internal/domain/preview_build.go index 2ca3eeff..f593c99f 100644 --- a/internal/domain/preview_build.go +++ b/internal/domain/preview_build.go @@ -5,7 +5,7 @@ import ( "strings" ) -// StripPreviewBuild removes the synthetic CodeBuddy preview node so the SOP +// StripPreviewBuild removes the synthetic preview node so the SOP // catalog never persists an engine-injected step. func StripPreviewBuild(wf WorkflowDefinition) WorkflowDefinition { nodes := make([]WorkflowNode, 0, len(wf.Nodes)) @@ -32,14 +32,24 @@ func StripPreviewBuild(wf WorkflowDefinition) WorkflowDefinition { // (the canvas allows inserting the build anywhere in the flow); only when the // node is missing is it appended after every current success sink. func AttachPreviewBuild(wf WorkflowDefinition) (WorkflowDefinition, error) { + if wf.Preview != nil { + preview := *wf.Preview + wf.Preview = &preview + } if err := wf.Preview.Validate(); err != nil { return wf, err } if !wf.Preview.Static() { return StripPreviewBuild(wf), nil } - for _, node := range wf.Nodes { + for i, node := range wf.Nodes { if IsPreviewBuildNode(node.ID) { + // Older canvases persisted the original synthetic executor on + // the node. The preview contract owns this choice. + if node.ExecutorID != wf.Preview.SelectedExecutorID() { + wf.Nodes = append([]WorkflowNode(nil), wf.Nodes...) + wf.Nodes[i].ExecutorID = wf.Preview.SelectedExecutorID() + } return wf, nil } } @@ -65,7 +75,7 @@ func PreviewBuildNode(wf WorkflowDefinition) WorkflowNode { Name: "构建静态站点", Type: "agent", AgentID: PreviewBuildAgentID, - ExecutorID: PreviewBuildExecutor, + ExecutorID: contract.SelectedExecutorID(), ExecutionScope: ExecutionScopeRun, ArtifactOutputs: []ArtifactContract{PreviewBuildArtifact(contract)}, OnFailure: "fail", @@ -78,13 +88,17 @@ func PreviewBuildNode(wf WorkflowDefinition) WorkflowNode { } func PreviewBuildAgent(contract *PreviewContract) AgentDefinition { - contract.Normalize() + executorID := contract.SelectedExecutorID() + model := "" + if executorID != "" { + model = contract.ModelOrDefault() + } return AgentDefinition{ ID: PreviewBuildAgentID, Name: "构建静态站点", - Description: "系统步骤:用 CodeBuddy 产出可托管的静态站点,再由预览收尾归档。", - ExecutorID: PreviewBuildExecutor, - Model: contract.ModelOrDefault(), + Description: "系统步骤:构建可托管的静态站点并归档为预览。", + ExecutorID: executorID, + Model: model, Prompt: PreviewBuildPrompt(contract), ArtifactOutputs: []ArtifactContract{PreviewBuildArtifact(contract)}, Loop: AgentLoopPolicy{ @@ -109,7 +123,7 @@ func PreviewBuildPrompt(contract *PreviewContract) string { index := contract.Index() entry := contract.EntryRel() return "把当前工作区里的前端应用打成可独立托管的静态站点,不要让用户再手写构建脚本。\n\n" + - "这是 AgentFlow 在 SOP 勾选「前端预览」后自动追加的 CodeBuddy 步骤。工作区可能包含一个或多个代码仓库子目录,上游节点已经完成实现与测试。构建完成后平台会打包静态目录并删除工作区。\n\n" + + "这是 AgentFlow 在 SOP 勾选「前端预览」后自动追加的构建步骤。工作区可能包含一个或多个代码仓库子目录,上游节点已经完成实现与测试。构建完成后平台会打包静态目录并删除工作区。\n\n" + "### 步骤\n\n" + "1. 识别前端工程(package.json、vite、webpack、rspack、next 静态导出等)。\n" + "2. 若工作区没有前端工程(无 Vite/webpack/Next 等配置、无前端依赖的 package.json、无 index.html),不要另起项目或手写预览页,不要创建 `" + source + "/" + index + "`,直接说明原因并结束。\n" + diff --git a/internal/domain/preview_build_test.go b/internal/domain/preview_build_test.go index 06220d1e..666d31ca 100644 --- a/internal/domain/preview_build_test.go +++ b/internal/domain/preview_build_test.go @@ -6,10 +6,10 @@ import ( "time" ) -func TestAttachPreviewBuildAppendsCodeBuddyNode(t *testing.T) { +func TestAttachPreviewBuildUsesSelectedExecutor(t *testing.T) { wf := WorkflowDefinition{ ID: "front", - Preview: &PreviewContract{Enabled: true, Model: "gpt-5.6-terra"}, + Preview: &PreviewContract{Enabled: true, ExecutorID: "codex", Model: "test-model"}, Nodes: []WorkflowNode{ {ID: "impl", Name: "实现", Type: "script"}, {ID: "test", Name: "测试", Type: "script"}, @@ -24,7 +24,7 @@ func TestAttachPreviewBuildAppendsCodeBuddyNode(t *testing.T) { t.Fatalf("nodes = %d, want 3", len(got.Nodes)) } last := got.Nodes[len(got.Nodes)-1] - if last.ID != PreviewBuildNodeID || last.AgentID != PreviewBuildAgentID || last.ExecutorID != PreviewBuildExecutor { + if last.ID != PreviewBuildNodeID || last.AgentID != PreviewBuildAgentID || last.ExecutorID != "codex" { t.Fatalf("injected node = %+v", last) } prompt := PreviewBuildPrompt(got.Preview) @@ -47,7 +47,7 @@ func TestAttachPreviewBuildAppendsCodeBuddyNode(t *testing.T) { t.Fatalf("missing edge from success sink: %+v", got.Edges) } agent := PreviewBuildAgent(got.Preview) - if agent.Model != "gpt-5.6-terra" || agent.ExecutorID != PreviewBuildExecutor { + if agent.Model != "test-model" || agent.ExecutorID != "codex" { t.Fatalf("synthetic agent = %+v", agent) } } @@ -86,14 +86,17 @@ func TestPreviewContractClampsRetentionTo30Days(t *testing.T) { } } -func TestPreviewContractRejectsNonCodeBuddy(t *testing.T) { - c := &PreviewContract{Enabled: true, ExecutorID: "claude", Model: "x"} - if err := c.Validate(); err == nil { - t.Fatal("expected CodeBuddy-only error") - } - disabled := &PreviewContract{Enabled: false, ExecutorID: "claude"} - if err := disabled.Validate(); err != nil { - t.Fatalf("disabled preview must skip executor checks: %v", err) +func TestPreviewContractOverridesLegacySyntheticExecutor(t *testing.T) { + wf := WorkflowDefinition{ + Preview: &PreviewContract{Enabled: true, ExecutorID: "claude", Model: "custom"}, + Nodes: []WorkflowNode{{ID: PreviewBuildNodeID, AgentID: PreviewBuildAgentID, ExecutorID: "codebuddy"}}, + } + got, err := AttachPreviewBuild(wf) + if err != nil || got.Nodes[0].ExecutorID != "claude" || PreviewBuildAgent(got.Preview).Model != "custom" { + t.Fatalf("preview = %+v, error = %v", got.Nodes, err) + } + if wf.Nodes[0].ExecutorID != "codebuddy" { + t.Fatal("attach changed the input snapshot") } } diff --git a/internal/domain/project.go b/internal/domain/project.go index ba5e4943..0ee00027 100644 --- a/internal/domain/project.go +++ b/internal/domain/project.go @@ -4,6 +4,8 @@ import ( "fmt" "strings" "time" + + "agentflow/internal/config" ) type Project struct { @@ -156,10 +158,20 @@ type RepositoryContext struct { WorkspaceDir string `json:"workspaceDir,omitempty"` } -// GongfengRepoHost is the hostname of the optional legacy GitLab-compatible -// hosting service. Repository links pasted by users are normalized against it. +// GongfengRepoHost identifies links in older repository and run records. const GongfengRepoHost = "git.example.com" +func GongfengRepositoryHost() string { + if host := config.GongfengHost(); host != "" { + return host + } + return GongfengRepoHost +} + +func IsGongfengHost(host string) bool { + return strings.EqualFold(host, GongfengRepositoryHost()) || strings.EqualFold(host, GongfengRepoHost) +} + // GongfengRepoInfo carries the repository identity parsed out of a pasted // Gongfeng link, so a repository can be configured with a single URL. type GongfengRepoInfo struct { @@ -210,26 +222,30 @@ func ParseGongfengRepoURL(raw string) (GongfengRepoInfo, bool) { if i := strings.LastIndex(pathSource, "@"); i >= 0 { pathSource = pathSource[i+1:] } - var path string - if !strings.Contains(s, "://") && !strings.Contains(s, "@") && !strings.Contains(pathSource, ":") { - // Bare project path (group/repository) pasted without URL decoration. - path = pathSource - } else if strings.Contains(pathSource, "/") { - host := pathSource[:strings.IndexAny(pathSource, "/:")] - if !strings.EqualFold(host, GongfengRepoHost) { - return GongfengRepoInfo{}, false + path := "" + for _, host := range []string{GongfengRepositoryHost(), GongfengRepoHost} { + if len(pathSource) <= len(host) || !strings.EqualFold(pathSource[:len(host)], host) { + continue } - if pathSource[len(host)] == ':' { - // git.example.com:group/repo.git (scp) or git.example.com:22/group/repo.git - path = pathSource[len(host)+1:] + tail := pathSource[len(host):] + switch tail[0] { + case '/': + path = tail[1:] + case ':': + path = tail[1:] if j := strings.Index(path, "/"); j >= 0 && isAllDigits(path[:j]) { path = path[j+1:] } - } else { - path = pathSource[len(host)+1:] } - } else { - // bare host without path is not a repository reference + if path != "" { + break + } + } + if path == "" && !strings.ContainsAny(s, ":@") { + // Trusted callers can still normalize saved project IDs. + path = pathSource + } + if path == "" { return GongfengRepoInfo{}, false } project := normalizeGongfengProjectPath(path) @@ -238,10 +254,11 @@ func ParseGongfengRepoURL(raw string) (GongfengRepoInfo, bool) { } info := GongfengRepoInfo{Project: project} info.Name = project[strings.LastIndex(project, "/")+1:] - info.WebURL = "https://" + GongfengRepoHost + "/" + project + host := GongfengRepositoryHost() + info.WebURL = "https://" + host + "/" + project info.CloneURL = info.WebURL + ".git" - if sshClone { - info.CloneURL = "git@" + GongfengRepoHost + ":" + project + ".git" + if sshClone && !strings.Contains(host, ":") { + info.CloneURL = "git@" + host + ":" + project + ".git" } return info, true } @@ -254,7 +271,6 @@ func normalizeGongfengProjectPath(path string) string { // absolute local paths are never repository paths return "" } - p = strings.TrimPrefix(p, GongfengRepoHost+"/") if strings.HasSuffix(strings.ToLower(p), ".git") { p = p[:len(p)-4] } diff --git a/internal/domain/project_test.go b/internal/domain/project_test.go index 2c99bdb1..be7ef707 100644 --- a/internal/domain/project_test.go +++ b/internal/domain/project_test.go @@ -2,6 +2,25 @@ package domain import "testing" +func TestRepositoryURLRequiresAHostAndSupportsManagedGit(t *testing.T) { + t.Setenv("AGENTFLOW_GONGFENG_HOST", "git.review.test:8443") + if _, ok := ParseRepositoryURL("Tencent/LoopForge"); ok { + t.Fatal("an unqualified repository was silently routed to a hosting provider") + } + github, ok := ParseRepositoryURL("github:Tencent/LoopForge") + if !ok || github.WebURL != "https://github.com/Tencent/LoopForge" { + t.Fatalf("GitHub reference = %+v, %v", github, ok) + } + managed, ok := ParseRepositoryURL("https://git.review.test:8443/group/repo/-/tree/main") + if !ok || managed.Project != "group/repo" || managed.CloneURL != "https://git.review.test:8443/group/repo.git" { + t.Fatalf("managed reference = %+v, %v", managed, ok) + } + refs := ParseGongfengMRs("https://git.review.test:8443/group/repo/-/merge_requests/7 https://github.com/Tencent/LoopForge/pull/8") + if len(refs) != 2 || refs[0].URL != "https://git.review.test:8443/group/repo/-/merge_requests/7" || refs[1].Project != "github:Tencent/LoopForge" { + t.Fatalf("review links = %+v", refs) + } +} + func TestIsSafeGongfengProjectID(t *testing.T) { for _, s := range []string{"12345", "gateway", "legacy-project_id", "repo.v2"} { if !IsSafeGongfengProjectID(s) { diff --git a/internal/domain/public_repository.go b/internal/domain/public_repository.go index 772e262b..8c63aa80 100644 --- a/internal/domain/public_repository.go +++ b/internal/domain/public_repository.go @@ -39,5 +39,11 @@ func ParseRepositoryURL(raw string) (GongfengRepoInfo, bool) { base := "https://github.com/" + path return GongfengRepoInfo{Project: "github:" + path, Name: strings.TrimSuffix(parts[1], ".git"), WebURL: base, CloneURL: base + ".git"}, true } + if !strings.ContainsAny(s, ":@") { + host, _, _ := strings.Cut(s, "/") + if !IsGongfengHost(host) { + return GongfengRepoInfo{}, false + } + } return ParseGongfengRepoURL(raw) } diff --git a/internal/domain/runner.go b/internal/domain/runner.go index 963a4b77..02f5e247 100644 --- a/internal/domain/runner.go +++ b/internal/domain/runner.go @@ -141,6 +141,13 @@ func (r Runner) SupportsGitHTTP() bool { // RunnerVersionGitSSHKnownHosts is the first runner to accept platform SSH pins. const RunnerVersionGitSSHKnownHosts = "0.11.1" +// Older runners would ignore the custom endpoint and use the official one. +const RunnerVersionCodeBuddyBaseURL = "0.11.2" + +func (r Runner) SupportsCodeBuddyBaseURL() bool { + return versionAtLeast(r.RunnerVersion, RunnerVersionCodeBuddyBaseURL) +} + func (r Runner) SupportsSharedPush() bool { return versionAtLeast(r.RunnerVersion, RunnerVersionSharedPush) } @@ -451,6 +458,7 @@ func PublicRunnerTask(task RunnerTask) RunnerTask { } copyInvocation := *task.Invocation copyInvocation.CodeBuddyAPIKey = "" + copyInvocation.CodeBuddyBaseURL = "" copyInvocation.CodeBuddyInternetEnvironment = "" copyInvocation.CodexAPIKey = "" copyInvocation.CodexBaseURL = "" @@ -521,6 +529,7 @@ type RunnerInvocation struct { HumanContext string `json:"humanContext,omitempty"` CredentialSource string `json:"credentialSource,omitempty"` CodeBuddyAPIKey string `json:"codebuddyApiKey,omitempty"` + CodeBuddyBaseURL string `json:"codebuddyBaseUrl,omitempty"` CodeBuddyInternetEnvironment string `json:"codebuddyInternetEnvironment,omitempty"` CodexAPIKey string `json:"codexApiKey,omitempty"` CodexBaseURL string `json:"codexBaseUrl,omitempty"` diff --git a/internal/domain/user.go b/internal/domain/user.go index d5502629..1cbc4350 100644 --- a/internal/domain/user.go +++ b/internal/domain/user.go @@ -7,12 +7,13 @@ import ( // User 表示系统注册或登录的员工实体,用于后续资源归属与权限隔离。 type User struct { - CodexAPIKey string `json:"codexApiKey,omitempty"` - CodexAPIKeyConfigured bool `json:"codexApiKeyConfigured,omitempty"` - CodexBaseURL string `json:"codexBaseUrl,omitempty"` - ClaudeCodeAPIKey string `json:"claudeCodeApiKey,omitempty"` - ClaudeCodeAPIKeyConfigured bool `json:"claudeCodeApiKeyConfigured,omitempty"` - ClaudeCodeBaseURL string `json:"claudeCodeBaseUrl,omitempty"` + AssistantDefaults AssistantDefaults `json:"-"` + CodexAPIKey string `json:"codexApiKey,omitempty"` + CodexAPIKeyConfigured bool `json:"codexApiKeyConfigured,omitempty"` + CodexBaseURL string `json:"codexBaseUrl,omitempty"` + ClaudeCodeAPIKey string `json:"claudeCodeApiKey,omitempty"` + ClaudeCodeAPIKeyConfigured bool `json:"claudeCodeApiKeyConfigured,omitempty"` + ClaudeCodeBaseURL string `json:"claudeCodeBaseUrl,omitempty"` // CodexModels and ClaudeCodeModels are the model catalogs AI 对话 offers // for that CLI, in display order. Empty follows the CLI's built-in models // on the official endpoint, or the models the Base URL publishes. @@ -39,12 +40,31 @@ type User struct { GongfengTokenExpiresAt time.Time `json:"-"` CodeBuddyAPIKey string `json:"codeBuddyApiKey,omitempty"` CodeBuddyAPIKeyConfigured bool `json:"codeBuddyApiKeyConfigured,omitempty"` + CodeBuddyBaseURL string `json:"codeBuddyBaseUrl,omitempty"` CodeBuddyInternetEnvironment string `json:"codeBuddyInternetEnvironment,omitempty"` CodeBuddyModels []CLIModel `json:"codeBuddyModels,omitempty"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` } +// HasExecutorCredential reports whether the user has their own key for a CLI. +func (u User) HasExecutorCredential(kind string) bool { + var key string + switch kind { + case "codebuddy": + key = u.CodeBuddyAPIKey + case "codex": + key = u.CodexAPIKey + case "claude-code": + key = u.ClaudeCodeAPIKey + default: + if IsAgentCLIKind(kind) { + key = u.AgentCLICredentials[kind].APIKey + } + } + return strings.TrimSpace(key) != "" +} + const PlatformRoleAdmin = "admin" // GitSSHKey is the public description of a personal SSH credential. diff --git a/internal/domain/workflow.go b/internal/domain/workflow.go index 59175e63..2c7c0618 100644 --- a/internal/domain/workflow.go +++ b/internal/domain/workflow.go @@ -56,27 +56,27 @@ type WorkflowNode struct { // SOPWorkflowID is the referenced workflow when Type is "sop". SOPWorkflowID string `json:"sopWorkflowId,omitempty"` // RunOnWorkspaceRebuild replays this script when restoring an already-used environment. - RunOnWorkspaceRebuild bool `json:"runOnWorkspaceRebuild,omitempty"` - ScriptLanguage string `json:"scriptLanguage,omitempty"` // shell, python - Script string `json:"script,omitempty"` + RunOnWorkspaceRebuild bool `json:"runOnWorkspaceRebuild,omitempty"` + ScriptLanguage string `json:"scriptLanguage,omitempty"` // shell, python + Script string `json:"script,omitempty"` // CredentialEnv requests platform-managed credentials as environment // variables for script and verification commands: each entry maps an // environment variable name to a credential kind (a RunCredentials.Extra // key registered by the deployment). A declared credential the // responsible user has not saved fails the node up front; the secret // itself never appears in workflow definitions, node configs or logs. - CredentialEnv map[string]string `json:"credentialEnv,omitempty"` - ExecutionScope string `json:"executionScope,omitempty"` // run, repositories; empty = run - Command string `json:"command,omitempty"` // legacy command-node payload - ArtifactOutputs []ArtifactContract `json:"artifactOutputs,omitempty"` - RejectTo string `json:"rejectTo,omitempty"` - OnFailure string `json:"onFailure,omitempty"` // fail, reject - RetryStrategy string `json:"retryStrategy,omitempty"` // targeted_fix, full_redo - CarryOver []string `json:"carryOver,omitempty"` - MaxAttempts int `json:"maxAttempts"` - MaxReworks int `json:"maxReworks"` - Notifications []NodeNotification `json:"notifications,omitempty"` - Position Position `json:"position"` + CredentialEnv map[string]string `json:"credentialEnv,omitempty"` + ExecutionScope string `json:"executionScope,omitempty"` // run, repositories; empty = run + Command string `json:"command,omitempty"` // legacy command-node payload + ArtifactOutputs []ArtifactContract `json:"artifactOutputs,omitempty"` + RejectTo string `json:"rejectTo,omitempty"` + OnFailure string `json:"onFailure,omitempty"` // fail, reject + RetryStrategy string `json:"retryStrategy,omitempty"` // targeted_fix, full_redo + CarryOver []string `json:"carryOver,omitempty"` + MaxAttempts int `json:"maxAttempts"` + MaxReworks int `json:"maxReworks"` + Notifications []NodeNotification `json:"notifications,omitempty"` + Position Position `json:"position"` } // ValidateWorkflowMetricStages prevents silently dropping a mistyped stage. @@ -184,6 +184,10 @@ type WorkflowDefinition struct { Edges []WorkflowEdge `json:"edges"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` + // ExecutorDefaults is populated on a run snapshot for roles + // that inherit the responsible user's executor. An empty entry defers + // selection until the role starts on the bound machine. + ExecutorDefaults map[string]AssistantDefaults `json:"executorDefaults,omitempty"` } // UnmarshalJSON migrates the pre-workflow-sandbox shape while the legacy node diff --git a/internal/engine/align.go b/internal/engine/align.go index 8b5e3049..57193b54 100644 --- a/internal/engine/align.go +++ b/internal/engine/align.go @@ -4,10 +4,12 @@ import ( "context" "fmt" "os" + "slices" "strings" "time" "agentflow/internal/domain" + "agentflow/internal/repo" "agentflow/internal/runtime" ) @@ -18,6 +20,26 @@ const BaselineAlignWorkflowID = "scheduled-baseline-align" // BaselineAlignAgentID is the platform-shared resolve role for that SOP. const BaselineAlignAgentID = domain.BaselineAlignAgentID +func configureBaselineAlignCLI(wf domain.WorkflowDefinition) (domain.WorkflowDefinition, error) { + if wf.ID != BaselineAlignWorkflowID { + return wf, nil + } + executorID := strings.TrimSpace(os.Getenv("AGENTFLOW_BASELINE_ALIGN_EXECUTOR")) + if executorID == "" { + return wf, nil + } + if _, ok := repo.BuiltInExecutor(executorID); !ok { + return wf, fmt.Errorf("AGENTFLOW_BASELINE_ALIGN_EXECUTOR: unsupported executor %q", executorID) + } + wf.Nodes = slices.Clone(wf.Nodes) + for i, node := range wf.Nodes { + if node.Type == "agent" && node.AgentID == BaselineAlignAgentID { + wf.Nodes[i].ExecutorID = executorID + } + } + return wf, nil +} + // AlignConflictError means the shared integrate branch and the repository // default branch diverged. Scheduled issue SOPs for that repository must wait. type AlignConflictError struct { diff --git a/internal/engine/align_test.go b/internal/engine/align_test.go index 33e194e0..391a9347 100644 --- a/internal/engine/align_test.go +++ b/internal/engine/align_test.go @@ -7,8 +7,48 @@ import ( "testing" "agentflow/internal/domain" + "agentflow/internal/repo" + "agentflow/internal/runtime" ) +func TestBaselineAlignRunKeepsConfiguredCLI(t *testing.T) { + store, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(store.Close) + wf := domain.WorkflowDefinition{ + ID: BaselineAlignWorkflowID, Name: "Align", SandboxProfileID: "local", + Nodes: []domain.WorkflowNode{{ID: "resolve", Type: "agent", AgentID: BaselineAlignAgentID}}, + } + if err := store.PutWorkflow(wf); err != nil { + t.Fatal(err) + } + eng := New(store, runtime.NewManager(t.TempDir())) + eng.ConfigureExecution("", "", 0, false) + for _, choice := range []struct{ setting, want string }{ + {"", "codebuddy"}, + {"codex", "codex"}, + } { + t.Setenv("AGENTFLOW_BASELINE_ALIGN_EXECUTOR", choice.setting) + run, err := eng.Start(wf.ID, "") + if err != nil { + t.Fatal(err) + } + t.Setenv("AGENTFLOW_BASELINE_ALIGN_EXECUTOR", "claude") + snapshot := run.WorkflowSnapshot + node := snapshot.Nodes[0] + agent, ok := workflowAgent(store, snapshot, node.AgentID) + if !ok { + t.Fatal("baseline resolver is missing") + } + executor, err := resolveNodeExecutor(store, node, agent) + if err != nil || executor.ID != choice.want { + t.Fatalf("baseline executor = %q, want %q (error %v)", executor.ID, choice.want, err) + } + } +} + func TestExtractConflictBlocks(t *testing.T) { t.Parallel() dir := t.TempDir() diff --git a/internal/engine/assets.go b/internal/engine/assets.go index 2e2e2168..18719069 100644 --- a/internal/engine/assets.go +++ b/internal/engine/assets.go @@ -204,10 +204,29 @@ func workflowAgent(st *repo.Store, wf domain.WorkflowDefinition, id string) (dom if domain.IsPreviewBuildAgent(id) { return domain.PreviewBuildAgent(wf.Preview), true } + if wf.Generic { + if template, ok := st.GenericTemplateByWorkflow(wf.ID); ok { + for _, role := range template.Agents { + if role.ID == id { + return role, true + } + } + } + } if agent, ok := st.Agent(id); ok { if st.AgentShadowsTemplateOutside(agent, wf.ProjectID) { return st.GenericAgentByID(id) } + if wf.ID == BaselineAlignWorkflowID && id == BaselineAlignAgentID { + for _, node := range wf.Nodes { + if node.Type == "agent" && node.AgentID == id && node.ExecutorID != "" { + if agent.ExecutorID != node.ExecutorID { + agent.ExecutorID, agent.Model, agent.Effort = node.ExecutorID, "", "" + } + break + } + } + } return agent, true } return st.GenericAgentByID(id) diff --git a/internal/engine/codebuddy_auth.go b/internal/engine/codebuddy_auth.go index 48696cfb..0207912a 100644 --- a/internal/engine/codebuddy_auth.go +++ b/internal/engine/codebuddy_auth.go @@ -25,7 +25,7 @@ func resolveCodeBuddyCredential(s *repo.Store, userID int64) runtime.CodeBuddyCr return runtime.CodeBuddyCredential{} } if strings.TrimSpace(user.CodeBuddyAPIKey) != "" { - return runtime.CodeBuddyCredential{APIKey: user.CodeBuddyAPIKey, InternetEnvironment: user.CodeBuddyInternetEnvironment} + return runtime.CodeBuddyUserCredential(user) } shared, ok := s.SharedCodeBuddyKey() if !ok || (shared.SponsorID != 0 && shared.SponsorID == user.ID) { diff --git a/internal/engine/node_execute.go b/internal/engine/node_execute.go index 5ca17b72..f20ea0f7 100644 --- a/internal/engine/node_execute.go +++ b/internal/engine/node_execute.go @@ -233,7 +233,10 @@ func workflowSandboxRequirements(st *repo.Store, wf domain.WorkflowDefinition) ( if !ok { return runtime.SandboxRequirements{}, fmt.Errorf("agent %q not found", node.AgentID) } - executor, err := resolveNodeExecutor(st, node, agent) + executor, err := workflowNodeExecutor(st, wf, node, agent) + if errors.Is(err, errSOPExecutorUnconfigured) { + continue + } if err != nil { return runtime.SandboxRequirements{}, err } @@ -402,6 +405,12 @@ func (e *Engine) executeNode(ctx context.Context, runID string, wf domain.Workfl failNode(err, false) return } + current, err = e.resolveDeferredSOPExecutor(current, node) + if err != nil { + failNode(err, nodeRejects(node)) + return + } + wf.ExecutorDefaults = current.WorkflowSnapshot.ExecutorDefaults profile := domain.SandboxProfile{} if current.WorkflowSnapshot.SandboxSnapshot != nil { profile = current.WorkflowSnapshot.SandboxSnapshot.Profile @@ -689,7 +698,7 @@ func (e *Engine) executeNode(ctx context.Context, runID string, wf domain.Workfl err = fmt.Errorf("agent %q not found", node.AgentID) break } - ex, errResolve := resolveNodeExecutor(e.repo, node, agent) + ex, errResolve := workflowNodeExecutor(e.repo, wf, node, agent) if errResolve != nil { err = errResolve break diff --git a/internal/engine/run_events.go b/internal/engine/run_events.go index 95041e20..f0a6aea9 100644 --- a/internal/engine/run_events.go +++ b/internal/engine/run_events.go @@ -35,13 +35,17 @@ func (e *Engine) IngestOTLPTraces(events []domain.TelemetryEvent) int { if runID == "" { continue } - if _, ok := e.repo.RunState(runID); !ok { + run, ok := e.repo.RunState(runID) + if !ok { continue } nodeID := strings.TrimSpace(event.NodeID) if nodeID == "" { nodeID = strings.TrimSpace(event.Context.NodeID) } + if node := run.Nodes[nodeID]; node != nil && node.Provider != "" { + event.Provider, event.Source.Provider = node.Provider, node.Provider + } e.observe(runID, nodeID, event) accepted++ } @@ -220,10 +224,10 @@ func (e *Engine) observationContext(run domain.Run, nodeID string, nr *domain.No ctx.AgentID = node.AgentID ctx.ExecutorID = node.ExecutorID ctx.MetricStage = node.MetricStage - if agent, ok := e.repo.Agent(node.AgentID); ok { + if agent, ok := workflowAgent(e.repo, run.WorkflowSnapshot, node.AgentID); ok { ctx.AgentVersion = agent.Version - if agent.ExecutorID != "" { - ctx.ExecutorID = agent.ExecutorID + if executor, err := workflowNodeExecutor(e.repo, run.WorkflowSnapshot, node, agent); err == nil { + ctx.ExecutorID = executor.ID } } break diff --git a/internal/engine/run_ops.go b/internal/engine/run_ops.go index 24c1af67..8a2ae3fb 100644 --- a/internal/engine/run_ops.go +++ b/internal/engine/run_ops.go @@ -844,7 +844,10 @@ func (e *Engine) RefreshRunSOP(runID string) error { // an existing workspace. A new Run will pick up the latest sandbox asset. latest.SandboxProfileID = r.WorkflowSnapshot.SandboxProfileID latest.SandboxSnapshot = r.WorkflowSnapshot.SandboxSnapshot - var err error + latest, err := configureBaselineAlignCLI(latest) + if err != nil { + return err + } latest, err = domain.AttachPreviewBuild(latest) if err != nil { return err @@ -978,6 +981,9 @@ func overlayLatestNodeBindings(st *repo.Store, r *domain.Run, nodeIDs map[string if !ok { continue } + if n.AgentID != src.AgentID || n.ExecutorID != src.ExecutorID { + delete(r.WorkflowSnapshot.ExecutorDefaults, n.ID) + } n.AgentID, n.ExecutorID = src.AgentID, src.ExecutorID n.ArtifactOutputs = src.ArtifactOutputs n.OnFailure, n.RejectTo = src.OnFailure, src.RejectTo diff --git a/internal/engine/run_start.go b/internal/engine/run_start.go index 7899fff5..64751011 100644 --- a/internal/engine/run_start.go +++ b/internal/engine/run_start.go @@ -90,7 +90,11 @@ func (e *Engine) startWorkflowDefinition(wf domain.WorkflowDefinition, input str } } wf = defaultWorkflowSandboxProfile(wf) - wf, err := domain.AttachPreviewBuild(wf) + wf, err := configureBaselineAlignCLI(wf) + if err != nil { + return domain.Run{}, err + } + wf, err = domain.AttachPreviewBuild(wf) if err != nil { return domain.Run{}, err } @@ -110,6 +114,14 @@ func (e *Engine) startWorkflowDefinition(wf domain.WorkflowDefinition, input str if err != nil { return domain.Run{}, err } + e.selectSOPExecutionTarget(&executionContext) + wf.ExecutorDefaults = nil + if executionContext.ResponsibleUserID > 0 { + wf.ExecutorDefaults, _, err = e.planSOPExecutors(wf, executionContext, false) + if err != nil { + return domain.Run{}, err + } + } if _, err := workflowSandboxRequirements(e.repo, wf); err != nil { return domain.Run{}, err } @@ -129,25 +141,6 @@ func (e *Engine) startWorkflowDefinition(wf domain.WorkflowDefinition, input str firstRepository = repositories[0] } executionContext.RunID, executionContext.TraceID, executionContext.WorkflowID, executionContext.WorkflowVersion = id, id, workflowID, wf.Version - if executionContext.ParentRunID == "" && !executionContext.ExecutionPinned { - executionContext.ExecutionRunnerID = e.repo.DefaultRunner(executionContext.ResponsibleUserID) - executionContext.WorkspaceRunID = "" - } - if executionContext.ExecutionRunnerID == "" && !executionContext.ExecutionPinned { - if runner, ok := e.cloudPoolRunner(executionContext.ProjectID); ok { - executionContext.ExecutionRunnerID = runner.ID - executionContext.ExecutionPool = domain.ExecutionModeCloud - } else if e.cloudPoolRequired(executionContext.ProjectID) { - // The first node binds a pool runner once one is online. - executionContext.ExecutionPool = domain.ExecutionModeCloud - } - } - if executionContext.ExecutionRunnerID != "" || executionContext.ExecutionPool == domain.ExecutionModeCloud { - executionContext.ExecutionMode = domain.ExecutionModeRunner - executionContext.RunnerWorkspaceLayout = domain.RunnerWorkspaceLayoutShared - } else { - executionContext.ExecutionMode = domain.ExecutionModeCloud - } if err := e.requireWorkBranchCapabilities(executionContext.ExecutionRunnerID, repositories); err != nil { return domain.Run{}, err } @@ -209,6 +202,28 @@ func (e *Engine) startWorkflowDefinition(wf domain.WorkflowDefinition, input str return r, nil } +func (e *Engine) selectSOPExecutionTarget(executionContext *domain.TelemetryContext) { + if executionContext.ParentRunID == "" && !executionContext.ExecutionPinned { + executionContext.ExecutionRunnerID = e.repo.DefaultRunner(executionContext.ResponsibleUserID) + executionContext.WorkspaceRunID = "" + } + if executionContext.ExecutionRunnerID == "" && !executionContext.ExecutionPinned { + if runner, ok := e.cloudPoolRunner(executionContext.ProjectID); ok { + executionContext.ExecutionRunnerID = runner.ID + executionContext.ExecutionPool = domain.ExecutionModeCloud + } else if e.cloudPoolRequired(executionContext.ProjectID) { + // The first node binds a pool runner once one is online. + executionContext.ExecutionPool = domain.ExecutionModeCloud + } + } + if executionContext.ExecutionRunnerID != "" || executionContext.ExecutionPool == domain.ExecutionModeCloud { + executionContext.ExecutionMode = domain.ExecutionModeRunner + executionContext.RunnerWorkspaceLayout = domain.RunnerWorkspaceLayoutShared + } else { + executionContext.ExecutionMode = domain.ExecutionModeCloud + } +} + func (e *Engine) executes() bool { e.mu.Lock() defer e.mu.Unlock() diff --git a/internal/engine/runner_dispatch.go b/internal/engine/runner_dispatch.go index 066fbbb2..bd665c11 100644 --- a/internal/engine/runner_dispatch.go +++ b/internal/engine/runner_dispatch.go @@ -226,11 +226,16 @@ func (e *Engine) dispatchRunnerTask(ctx context.Context, runnerID string, run do invocation.ClaudeCodeAPIKey = sb.credentialSnapshot().ClaudeCode.APIKey invocation.ClaudeCodeBaseURL = sb.credentialSnapshot().ClaudeCode.BaseURL case "codebuddy": - if strings.TrimSpace(sb.credentialSnapshot().CodeBuddy.APIKey) == "" { + credential := sb.credentialSnapshot().CodeBuddy + if strings.TrimSpace(credential.APIKey) == "" { return "", errors.New("当前责任人未配置 CodeBuddy API Key:请先在个人配置中配置") } - invocation.CodeBuddyAPIKey = sb.credentialSnapshot().CodeBuddy.APIKey - invocation.CodeBuddyInternetEnvironment = sb.credentialSnapshot().CodeBuddy.InternetEnvironment + if credential.BaseURL != "" && !runner.SupportsCodeBuddyBaseURL() { + return "", fmt.Errorf("执行机器需升级至 %s 才能使用 CodeBuddy Base URL", domain.RunnerVersionCodeBuddyBaseURL) + } + invocation.CodeBuddyAPIKey = credential.APIKey + invocation.CodeBuddyBaseURL = credential.BaseURL + invocation.CodeBuddyInternetEnvironment = credential.InternetEnvironment default: if runtime.IsAgentCLI(ex.Kind) { cred := sb.credentialSnapshot().AgentCLI[ex.Kind] @@ -523,11 +528,14 @@ func (e *Engine) validateExecutionReconnect(run domain.Run, nodeID string) error } provider := "terminal" if node.Type != "script" && node.Type != "command" && node.Type != "approval" { - agent, found := e.repo.Agent(node.AgentID) + agent, found := workflowAgent(e.repo, run.WorkflowSnapshot, node.AgentID) if !found { return fmt.Errorf("无法重连原执行环境:agent %s 不存在", node.AgentID) } - executor, err := resolveNodeExecutor(e.repo, node, agent) + executor, err := workflowNodeExecutor(e.repo, run.WorkflowSnapshot, node, agent) + if errors.Is(err, errSOPExecutorUnconfigured) { + return nil + } if err != nil { return fmt.Errorf("无法重连原执行环境:%w", err) } diff --git a/internal/engine/sop_executors.go b/internal/engine/sop_executors.go new file mode 100644 index 00000000..473861c9 --- /dev/null +++ b/internal/engine/sop_executors.go @@ -0,0 +1,222 @@ +package engine + +import ( + "errors" + "fmt" + "strings" + + "agentflow/internal/domain" + "agentflow/internal/repo" +) + +type SOPExecutorRequirement struct { + Kind string `json:"kind,omitempty"` + Name string `json:"name"` + Configured bool `json:"configured"` +} + +var errSOPExecutorUnconfigured = errors.New("请在个人配置中添加当前执行环境可用的执行器,再重试此节点") + +type sopExecutorAccess struct { + user domain.User + runner domain.Runner + usesRunner bool + sharedCodeBuddy bool +} + +func (e *Engine) sopExecutorAccess(ec domain.TelemetryContext) sopExecutorAccess { + user, _ := e.repo.User(ec.ResponsibleUserID) + runner, _ := e.repo.Runner(ec.ExecutionRunnerID) + return sopExecutorAccess{ + user: user, runner: runner, usesRunner: ec.ExecutionRunnerID != "", + sharedCodeBuddy: resolveCodeBuddyCredential(e.repo, user.ID).Sponsored, + } +} + +func (a sopExecutorAccess) configured(kind string) bool { + if a.usesRunner { + if !a.runner.SupportsProvider(kind) { + return false + } + if domain.SupportsRunnerLogin(kind) && a.runner.RuntimeAuthMode(kind) == domain.RuntimeAuthLocal { + return true + } + if kind == "codebuddy" && strings.TrimSpace(a.user.CodeBuddyBaseURL) != "" && !a.runner.SupportsCodeBuddyBaseURL() { + return false + } + } + return a.user.HasExecutorCredential(kind) || kind == "codebuddy" && a.sharedCodeBuddy +} + +func (a sopExecutorAccess) defaults() domain.AssistantDefaults { + preferred := a.user.AssistantDefaults + if ex, ok := repo.BuiltInExecutorForKind(preferred.Executor); ok && a.user.HasExecutorCredential(ex.Kind) && a.configured(ex.Kind) { + model := strings.TrimSpace(preferred.Model) + if model == "" { + model = a.firstSavedModel(ex.Kind) + } + return domain.AssistantDefaults{Executor: ex.ID, Model: model, Effort: preferred.Effort} + } + executors := repo.BuiltInExecutors() + for _, ex := range executors { + if a.user.HasExecutorCredential(ex.Kind) && a.configured(ex.Kind) { + return domain.AssistantDefaults{Executor: ex.ID, Model: a.firstSavedModel(ex.Kind)} + } + } + for _, ex := range executors { + if a.usesRunner && domain.SupportsRunnerLogin(ex.Kind) && a.runner.RuntimeAuthMode(ex.Kind) == domain.RuntimeAuthLocal && a.configured(ex.Kind) { + return domain.AssistantDefaults{Executor: ex.ID} + } + } + if a.configured("codebuddy") { + return domain.AssistantDefaults{Executor: "codebuddy"} + } + return domain.AssistantDefaults{} +} + +func (a sopExecutorAccess) firstSavedModel(kind string) string { + var models []domain.CLIModel + switch kind { + case "codebuddy": + models = a.user.CodeBuddyModels + case "codex": + models = a.user.CodexModels + case "claude-code": + models = a.user.ClaudeCodeModels + default: + models = a.user.AgentCLICredentials[kind].Models + } + if len(models) != 0 { + return models[0].ID + } + return "" +} + +func templateSOPRoleIDs(st *repo.Store, wf domain.WorkflowDefinition) map[string]bool { + source := wf.ID + if !wf.Generic { + source = "" + for _, tag := range wf.Tags { + if id, found := strings.CutPrefix(tag, "generic-source:"); found { + source = id + break + } + } + } + template, ok := st.GenericTemplateByWorkflow(source) + if !ok { + return nil + } + ids := make(map[string]bool, len(template.Agents)) + for _, role := range template.Agents { + ids[role.ID] = true + if !wf.Generic { + ids[role.ID+"-"+wf.ProjectID] = true + } + } + return ids +} + +// Only roles without a pinned model or effort can inherit an executor. +// The caller decides which legacy CodeBuddy roles are eligible. +func followsSOPExecutorDefault(node domain.WorkflowNode, role domain.AgentDefinition) bool { + return node.Type == "agent" && node.ExecutorID == "" && + (role.ExecutorID == "" || role.ExecutorID == "codebuddy") && + strings.TrimSpace(role.Model) == "" && strings.TrimSpace(role.Effort) == "" +} + +func (e *Engine) planSOPExecutors(wf domain.WorkflowDefinition, ec domain.TelemetryContext, preflight bool) (map[string]domain.AssistantDefaults, []SOPExecutorRequirement, error) { + roleIDs := templateSOPRoleIDs(e.repo, wf) + access := e.sopExecutorAccess(ec) + defaults := access.defaults() + selected := make(map[string]domain.AssistantDefaults) + requirements := make([]SOPExecutorRequirement, 0) + seen := make(map[string]bool) + for _, node := range wf.Nodes { + if node.Type != "agent" { + continue + } + role, ok := workflowAgent(e.repo, wf, node.AgentID) + if !ok { + if !preflight { + continue + } + return nil, nil, fmt.Errorf("agent %q not found", node.AgentID) + } + legacyTemplate := roleIDs[role.ID] && role.ProjectID == wf.ProjectID + baselineResolver := wf.ID == BaselineAlignWorkflowID && role.ID == BaselineAlignAgentID + var ex domain.ExecutorDefinition + if (role.ExecutorID == "" || legacyTemplate || baselineResolver) && followsSOPExecutorDefault(node, role) { + selected[node.ID] = defaults + if defaults.Executor != "" { + ex, _ = repo.BuiltInExecutor(defaults.Executor) + } + } else if preflight { + var err error + ex, err = resolveNodeExecutor(e.repo, node, role) + if err != nil { + return nil, nil, err + } + } + if preflight && !seen[ex.Kind] { + seen[ex.Kind] = true + requirements = append(requirements, SOPExecutorRequirement{ + Kind: ex.Kind, Name: ex.Name, Configured: ex.Kind != "" && access.configured(ex.Kind), + }) + } + } + return selected, requirements, nil +} + +// SOPExecutorRequirements checks the same executor configuration a manual +// start uses. It only reports provider names and configuration status. +func (e *Engine) SOPExecutorRequirements(wf domain.WorkflowDefinition, userID int64, projectID string) ([]SOPExecutorRequirement, error) { + wf, err := configureBaselineAlignCLI(wf) + if err != nil { + return nil, err + } + wf, err = domain.AttachPreviewBuild(wf) + if err != nil { + return nil, err + } + ec := domain.TelemetryContext{ResponsibleUserID: userID, ProjectID: projectID} + e.selectSOPExecutionTarget(&ec) + _, requirements, err := e.planSOPExecutors(wf, ec, true) + return requirements, err +} + +func workflowNodeExecutor(st *repo.Store, wf domain.WorkflowDefinition, node domain.WorkflowNode, role domain.AgentDefinition) (domain.ExecutorDefinition, error) { + if defaults, ok := wf.ExecutorDefaults[node.ID]; ok && followsSOPExecutorDefault(node, role) { + if defaults.Executor == "" { + return domain.ExecutorDefinition{}, errSOPExecutorUnconfigured + } + role.ExecutorID, role.Model, role.Effort = defaults.Executor, defaults.Model, defaults.Effort + } + return resolveNodeExecutor(st, node, role) +} + +// Runs can be queued before their responsible user has configured an executor. +// Resolve the deferred default on the bound machine before the first role runs. +func (e *Engine) resolveDeferredSOPExecutor(run domain.Run, node domain.WorkflowNode) (domain.Run, error) { + defaults, pending := run.WorkflowSnapshot.ExecutorDefaults[node.ID] + if !pending || defaults.Executor != "" { + return run, nil + } + role, found := workflowAgent(e.repo, run.WorkflowSnapshot, node.AgentID) + if !found || !followsSOPExecutorDefault(node, role) { + return run, nil + } + selected := e.sopExecutorAccess(run.ExecutionContext).defaults() + if selected.Executor == "" { + return run, errSOPExecutorUnconfigured + } + err := e.updateRunErr(run.ID, func(current *domain.Run) { + for id, choice := range current.WorkflowSnapshot.ExecutorDefaults { + if choice.Executor == "" { + current.WorkflowSnapshot.ExecutorDefaults[id] = selected + } + } + run = *current + }) + return run, err +} diff --git a/internal/engine/sop_executors_test.go b/internal/engine/sop_executors_test.go new file mode 100644 index 00000000..cdfc6767 --- /dev/null +++ b/internal/engine/sop_executors_test.go @@ -0,0 +1,158 @@ +package engine + +import ( + "errors" + "testing" + + "agentflow/internal/domain" + "agentflow/internal/repo" +) + +func TestGenericSOPCopyUsesPersonalDefaultForUnpinnedRoles(t *testing.T) { + st, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { st.Close() }) + if err := st.PutGenericTemplate(repo.GenericTemplate{ + Workflow: domain.WorkflowDefinition{ID: "sop-template", Name: "Template"}, + Agents: []domain.AgentDefinition{{ID: "reviewer"}, {ID: "author"}}, + }); err != nil { + t.Fatal(err) + } + for _, agent := range []domain.AgentDefinition{ + {ID: "reviewer-beta", Name: "Reviewer", ProjectID: "beta", ExecutorID: "codebuddy"}, + {ID: "author", Name: "Author", ProjectID: "beta", ExecutorID: "codebuddy", Model: "explicit-model"}, + {ID: "custom", Name: "Custom role", ProjectID: "beta", ExecutorID: "codebuddy"}, + } { + if err := st.PutAgent(agent); err != nil { + t.Fatal(err) + } + } + workflow := domain.WorkflowDefinition{ + ID: "copy", ProjectID: "beta", Tags: []string{"generic-source:sop-template"}, + Nodes: []domain.WorkflowNode{ + {ID: "review", Type: "agent", AgentID: "reviewer-beta"}, + {ID: "author", Type: "agent", AgentID: "author"}, + {ID: "custom", Type: "agent", AgentID: "custom"}, + }, + } + e := &Engine{repo: st} + execution := domain.TelemetryContext{ResponsibleUserID: 1} + workflow.ExecutorDefaults, _, err = e.planSOPExecutors(workflow, execution, false) + if err != nil { + t.Fatal(err) + } + run := domain.Run{ + ID: "run-deferred", WorkflowID: workflow.ID, WorkflowSnapshot: workflow, ExecutionContext: execution, Status: "running", + } + if err := st.PutRun(run); err != nil { + t.Fatal(err) + } + if _, err := workflowSandboxRequirements(st, workflow); err != nil { + t.Fatalf("an unresolved role should not prevent workspace preparation: %v", err) + } + if _, err := e.resolveDeferredSOPExecutor(run, workflow.Nodes[0]); !errors.Is(err, errSOPExecutorUnconfigured) { + t.Fatalf("the role should report missing configuration before invoking a CLI: %v", err) + } + defaults := domain.AssistantDefaults{Executor: "dsh", Model: "deepseek-v4.1-flash"} + if _, err := st.UpdateUserCredentials(1, repo.UserCredentialUpdate{ + AgentCLICredentials: map[string]repo.AgentCLICredentialUpdate{"dsh": {APIKey: "fixture-key"}}, + AssistantDefaults: &defaults, + }); err != nil { + t.Fatal(err) + } + if _, err := e.resolveDeferredSOPExecutor(run, workflow.Nodes[0]); err != nil { + t.Fatal(err) + } + stored, ok := st.RunState(run.ID) + if !ok { + t.Fatal("run not found") + } + workflow = stored.WorkflowSnapshot + if len(workflow.ExecutorDefaults) != 1 || workflow.ExecutorDefaults["review"] != defaults { + t.Fatalf("only the inherited template role should use personal defaults: %+v", workflow.ExecutorDefaults) + } + for i, want := range []domain.ExecutorDefinition{ + {Kind: "dsh", Model: "deepseek-v4.1-flash"}, + {Kind: "codebuddy", Model: "explicit-model"}, + {Kind: "codebuddy"}, + } { + node := workflow.Nodes[i] + role, _ := workflowAgent(st, workflow, node.AgentID) + got, err := workflowNodeExecutor(st, workflow, node, role) + if err != nil || got.Kind != want.Kind || got.Model != want.Model { + t.Fatalf("%s executor = %+v, err = %v; want %s / %s", node.ID, got, err, want.Kind, want.Model) + } + } +} + +func TestGenericSOPExecutorPrefersRunnerLoginOverSharedKey(t *testing.T) { + access := sopExecutorAccess{ + usesRunner: true, + sharedCodeBuddy: true, + runner: domain.Runner{Runtimes: []domain.RunnerRuntime{ + {Provider: "codebuddy", AuthMode: domain.RuntimeAuthPersonal, Status: domain.RuntimeStatusOnline}, + {Provider: "codex", AuthMode: domain.RuntimeAuthLocal, Status: domain.RuntimeStatusOnline}, + }}, + } + if got := access.defaults().Executor; got != "codex" { + t.Fatalf("executor with configured machine login = %s, want codex", got) + } +} + +func TestSOPExecutorDefaultForBaselinePreviewAndProjectRole(t *testing.T) { + st, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(st.Close) + // Existing installations may still have the seeded CodeBuddy resolver. + baseline := repo.BaselineAlignResolverAgent() + baseline.ExecutorID = "codebuddy" + for _, role := range []domain.AgentDefinition{ + baseline, + {ID: "project-reviewer", Name: "Reviewer", ProjectID: "demo"}, + {ID: "pinned", Name: "Pinned", ProjectID: "demo", ExecutorID: "codebuddy"}, + } { + if err := st.PutAgent(role); err != nil { + t.Fatal(err) + } + } + preference := domain.AssistantDefaults{Executor: "codex", Model: "fixture-model"} + if _, err := st.UpdateUserCredentials(1, repo.UserCredentialUpdate{ + CodexAPIKey: "fixture-key", AssistantDefaults: &preference, + }); err != nil { + t.Fatal(err) + } + e := &Engine{repo: st} + baselineFlow := domain.WorkflowDefinition{ID: BaselineAlignWorkflowID, Nodes: []domain.WorkflowNode{ + {ID: "resolve", Type: "agent", AgentID: baseline.ID}, + }} + t.Setenv("AGENTFLOW_BASELINE_ALIGN_EXECUTOR", "") + requirements, err := e.SOPExecutorRequirements(baselineFlow, 1, "demo") + if err != nil || len(requirements) != 1 || requirements[0].Kind != "codex" || !requirements[0].Configured { + t.Fatalf("baseline preflight = %+v, %v", requirements, err) + } + t.Setenv("AGENTFLOW_BASELINE_ALIGN_EXECUTOR", "claude") + requirements, err = e.SOPExecutorRequirements(baselineFlow, 1, "demo") + if err != nil || len(requirements) != 1 || requirements[0].Kind != "claude-code" { + t.Fatalf("baseline override = %+v, %v", requirements, err) + } + + projectFlow, err := domain.AttachPreviewBuild(domain.WorkflowDefinition{ + ID: "project-flow", ProjectID: "demo", Preview: &domain.PreviewContract{Enabled: true}, + Nodes: []domain.WorkflowNode{ + {ID: "review", Type: "agent", AgentID: "project-reviewer"}, + {ID: "pinned", Type: "agent", AgentID: "pinned"}, + }, + }) + if err != nil { + t.Fatal(err) + } + defaults, _, err := e.planSOPExecutors(projectFlow, domain.TelemetryContext{ResponsibleUserID: 1}, false) + if err != nil || len(defaults) != 2 || + defaults["review"] != preference || defaults[domain.PreviewBuildNodeID] != preference { + t.Fatalf("project role and preview defaults = %+v, %v", defaults, err) + } +} diff --git a/internal/engine/workspace_preparation.go b/internal/engine/workspace_preparation.go index a599845a..1491e5ba 100644 --- a/internal/engine/workspace_preparation.go +++ b/internal/engine/workspace_preparation.go @@ -431,7 +431,7 @@ func workspaceConversationRequirements(st *repo.Store, wf domain.WorkflowDefinit if !ok { continue } - executor, err := resolveNodeExecutor(st, node, agent) + executor, err := workflowNodeExecutor(st, wf, node, agent) if err != nil { continue } diff --git a/internal/gitwork/auth.go b/internal/gitwork/auth.go index 7a8ab84e..1fbe65b4 100644 --- a/internal/gitwork/auth.go +++ b/internal/gitwork/auth.go @@ -12,6 +12,8 @@ import ( "path/filepath" "regexp" "strings" + + "agentflow/internal/config" ) // TokenEnv is the host-level fallback token, only used for output redaction. @@ -78,16 +80,13 @@ func TokenFrom(ctx context.Context) string { // gongfengInsteadOfPrefixes are rewritten to HTTPS + private:token. Same list // for command-line -c and GIT_CONFIG_COUNT so clone/fetch/push and an Agent // CLI's own git all see one rewrite. -var gongfengInsteadOfPrefixes = []string{ - "git@git.example.com:", - "ssh://git@git.example.com/", - "https://git.example.com/", - "http://git.example.com/", +func gongfengInsteadOfPrefixes(host string) []string { + return []string{"git@" + host + ":", "ssh://git@" + host + "/", "https://" + host + "/", "http://" + host + "/"} } -func authedBase(token string) string { +func authedBase(token, host string) string { user, secret := SplitToken(token) - return "https://" + user + ":" + secret + "@git.example.com/" + return (&url.URL{Scheme: "https", User: url.UserPassword(user, secret), Host: host, Path: "/"}).String() } // SandboxEnv is the git environment for a child process: no interactive @@ -96,16 +95,18 @@ func authedBase(token string) string { func SandboxEnv(token string) map[string]string { extra := map[string]string{"GIT_TERMINAL_PROMPT": "0", "GIT_ALLOW_PROTOCOL": AllowedProtocols} user, secret := SplitToken(token) - if secret == "" { + host := config.GongfengHost() + if secret == "" || host == "" { return extra } // The credential helper reads these. The token stays out of the helper // text, which git runs through a shell. extra[gitHTTPUserEnv] = user extra[gitHTTPPassEnv] = secret - authed := authedBase(token) - extra["GIT_CONFIG_COUNT"] = fmt.Sprintf("%d", len(gongfengInsteadOfPrefixes)) - for i, prefix := range gongfengInsteadOfPrefixes { + authed := authedBase(token, host) + prefixes := gongfengInsteadOfPrefixes(host) + extra["GIT_CONFIG_COUNT"] = fmt.Sprintf("%d", len(prefixes)) + for i, prefix := range prefixes { extra[fmt.Sprintf("GIT_CONFIG_KEY_%d", i)] = "url." + authed + ".insteadof" extra[fmt.Sprintf("GIT_CONFIG_VALUE_%d", i)] = prefix } @@ -193,12 +194,14 @@ func credentialHelper() string { // token without writing it to any git config file. func AuthConfigArgs(token string) []string { _, secret := SplitToken(token) - if secret == "" { + host := config.GongfengHost() + if secret == "" || host == "" { return nil } - args := []string{"-c", "credential.helper=", "-c", "credential.helper=" + credentialHelper()} - authed := authedBase(token) - for _, prefix := range gongfengInsteadOfPrefixes { + helperKey := "credential.https://" + host + ".helper=" + args := []string{"-c", helperKey, "-c", helperKey + credentialHelper()} + authed := authedBase(token, host) + for _, prefix := range gongfengInsteadOfPrefixes(host) { args = append(args, "-c", "url."+authed+".insteadof="+prefix) } return args diff --git a/internal/gitwork/auth_test.go b/internal/gitwork/auth_test.go index aab62cc9..d6c73d57 100644 --- a/internal/gitwork/auth_test.go +++ b/internal/gitwork/auth_test.go @@ -32,36 +32,36 @@ func TestWithEnvValueReplacesPWD(t *testing.T) { func TestRewriteRemoteForGitToken(t *testing.T) { token := "tok_secret" - got := RewriteRemoteForToken("git@git.example.com:example/skillhub.git", token) - if got != "https://private:tok_secret@git.example.com/example/skillhub.git" { + got := RewriteRemoteForToken("git@git.review.test:example/skillhub.git", token) + if got != "https://private:tok_secret@git.review.test/example/skillhub.git" { t.Fatalf("ssh rewrite = %q", got) } - got = RewriteRemoteForToken("https://git.example.com/example/skillhub.git", token) - if got != "https://private:tok_secret@git.example.com/example/skillhub.git" { + got = RewriteRemoteForToken("https://git.review.test/example/skillhub.git", token) + if got != "https://private:tok_secret@git.review.test/example/skillhub.git" { t.Fatalf("https rewrite = %q", got) } - got = RewriteRemoteForToken("https://oauth2:already@git.example.com/example/skillhub.git", token) - if got != "https://private:tok_secret@git.example.com/example/skillhub.git" { + got = RewriteRemoteForToken("https://oauth2:already@git.review.test/example/skillhub.git", token) + if got != "https://private:tok_secret@git.review.test/example/skillhub.git" { t.Fatalf("oauth2 user should be rewritten to private, got %q", got) } - got = RewriteRemoteForToken("https://private:already@git.example.com/example/skillhub.git", token) - if got != "https://private:already@git.example.com/example/skillhub.git" { + got = RewriteRemoteForToken("https://private:already@git.review.test/example/skillhub.git", token) + if got != "https://private:already@git.review.test/example/skillhub.git" { t.Fatalf("existing private user rewrite = %q", got) } - if got := RewriteRemoteForToken("git@git.example.com:example/skillhub.git", "oauth2:oauth_secret"); got != "https://oauth2:oauth_secret@git.example.com/example/skillhub.git" { + if got := RewriteRemoteForToken("git@git.review.test:example/skillhub.git", "oauth2:oauth_secret"); got != "https://oauth2:oauth_secret@git.review.test/example/skillhub.git" { t.Fatalf("oauth2 token rewrite = %q", got) } if RewriteRemoteForToken("/tmp/local-repo", token) != "/tmp/local-repo" { t.Fatalf("local path should stay unchanged") } - if RewriteRemoteForToken("git@git.example.com:example/skillhub.git", "") != "git@git.example.com:example/skillhub.git" { + if RewriteRemoteForToken("git@git.review.test:example/skillhub.git", "") != "git@git.review.test:example/skillhub.git" { t.Fatalf("empty token should keep original remote") } } func TestRedactGitOutput(t *testing.T) { t.Setenv(TokenEnv, "tok_env") - got := Redact("fatal: https://private:tok_repo@git.example.com/x.git tok_env", "tok_repo") + got := Redact("fatal: https://private:tok_repo@git.review.test/x.git tok_env", "tok_repo") if strings.Contains(got, "tok_repo") || strings.Contains(got, "tok_env") { t.Fatalf("token leaked in git output: %q", got) } @@ -71,16 +71,17 @@ func TestRedactGitOutput(t *testing.T) { } func TestGitEnvAddsInsteadOfWhenTokenSet(t *testing.T) { + t.Setenv("AGENTFLOW_GONGFENG_HOST", "git.review.test") t.Setenv(TokenEnv, "") env := Env("tok_secret") joined := strings.Join(env, "\n") if !strings.Contains(joined, "GIT_CONFIG_COUNT=") { t.Fatal("expected GIT_CONFIG_COUNT") } - if !strings.Contains(joined, "git@git.example.com:") { + if !strings.Contains(joined, "git@git.review.test:") { t.Fatal("expected ssh insteadOf") } - if !strings.Contains(joined, "https://private:tok_secret@git.example.com/") { + if !strings.Contains(joined, "https://private:tok_secret@git.review.test/") { t.Fatal("expected private user insteadOf") } if !strings.Contains(joined, gitHTTPPassEnv+"=tok_secret") { @@ -100,28 +101,30 @@ func TestGitTokenFromContextOverridesEnv(t *testing.T) { } func TestGitAuthConfigArgs(t *testing.T) { + t.Setenv("AGENTFLOW_GONGFENG_HOST", "git.review.test") if AuthConfigArgs("") != nil { t.Fatal("empty token should not add -c") } args := AuthConfigArgs("tok_secret") joined := strings.Join(args, "\n") - if !strings.Contains(joined, "credential.helper=") { + if !strings.Contains(joined, "credential.https://git.review.test.helper=") { t.Fatalf("missing credential.helper: %q", args) } - if !strings.Contains(joined, "url.https://private:tok_secret@git.example.com/.insteadof=git@git.example.com:") { + if !strings.Contains(joined, "url.https://private:tok_secret@git.review.test/.insteadof=git@git.review.test:") { t.Fatalf("missing ssh insteadOf: %q", args) } for i := 0; i+1 < len(args); i++ { - if args[i] == "-c" && strings.HasPrefix(args[i+1], "credential.helper=!") && strings.Contains(args[i+1], "tok_secret") { + if args[i] == "-c" && strings.HasPrefix(args[i+1], "credential.https://git.review.test.helper=!") && strings.Contains(args[i+1], "tok_secret") { t.Fatalf("token interpolated into credential helper: %s", args[i+1]) } } } func TestCredentialHelperLeavesTokenOutOfShell(t *testing.T) { + t.Setenv("AGENTFLOW_GONGFENG_HOST", "git.review.test") token := "tok\";touch /tmp/pwned;#" for _, arg := range AuthConfigArgs(token) { - if strings.HasPrefix(arg, "credential.helper=!") && strings.Contains(arg, token) { + if strings.HasPrefix(arg, "credential.https://git.review.test.helper=!") && strings.Contains(arg, token) { t.Fatalf("credential helper contains the token: %s", arg) } } diff --git a/internal/gitwork/gitwork_cases_test.go b/internal/gitwork/gitwork_cases_test.go index 87d62c9f..58089eed 100644 --- a/internal/gitwork/gitwork_cases_test.go +++ b/internal/gitwork/gitwork_cases_test.go @@ -47,6 +47,7 @@ func TestGitIdentityAndStageUntracked(t *testing.T) { } func TestGitAuthAndPatchHelpers(t *testing.T) { + t.Setenv("AGENTFLOW_GONGFENG_HOST", "git.review.test") for _, tc := range []struct { raw, user, token string }{ diff --git a/internal/gongfeng/gongfeng_cases_test.go b/internal/gongfeng/gongfeng_cases_test.go index 01928a9c..6f7c4c4f 100644 --- a/internal/gongfeng/gongfeng_cases_test.go +++ b/internal/gongfeng/gongfeng_cases_test.go @@ -79,8 +79,16 @@ func TestGongfengConfigHelpers(t *testing.T) { t.Setenv("AGENTFLOW_GONGFENG_OAUTH_CLIENT_ID", " id ") t.Setenv("AGENTFLOW_GONGFENG_OAUTH_CLIENT_SECRET", " secret ") t.Setenv("AGENTFLOW_GONGFENG_OAUTH_REDIRECT_URI", " cb ") + t.Setenv("AGENTFLOW_GONGFENG_HOST", "") + t.Setenv("AGENTFLOW_GONGFENG_OAUTH_AUTHORIZE_URL", "") + t.Setenv("AGENTFLOW_GONGFENG_OAUTH_TOKEN_URL", "") + t.Setenv("AGENTFLOW_GONGFENG_OAUTH_API_BASE", "") + if cfg := ConfigFromEnv(); cfg.Enabled() || cfg.APIBase != "" { + t.Fatalf("unexpected endpoints without a configured host: %#v", cfg) + } + t.Setenv("AGENTFLOW_GONGFENG_HOST", "git.review.test") cfg := ConfigFromEnv() - if !cfg.Enabled() || cfg.ClientID != "id" { + if !cfg.Enabled() || cfg.ClientID != "id" || cfg.APIBase != "https://git.review.test/api/v3" { t.Fatalf("config = %#v", cfg) } if _, err := AuthorizeURL(Config{}, "x"); err == nil { diff --git a/internal/gongfeng/oauth.go b/internal/gongfeng/oauth.go index 23922d1b..ff898625 100644 --- a/internal/gongfeng/oauth.go +++ b/internal/gongfeng/oauth.go @@ -14,12 +14,11 @@ import ( "strconv" "strings" "time" + + "agentflow/internal/config" ) const ( - defaultAuthorizeURL = "https://git.example.com/oauth/authorize" - defaultTokenURL = "https://git.example.com/oauth/token" - defaultAPIBase = "https://git.example.com/api/v3" // Repository clone and push need both scopes. The application must allow them. RepositoryScope = "read_repository write_repository" defaultTTL = 2 * time.Hour @@ -31,7 +30,7 @@ const ( // while the caller holds the user's refresh lock, so it must never hang. var httpClient = &http.Client{Timeout: 15 * time.Second} -// Config is the OAuth application registered on git.example.com. +// Config describes the OAuth application registered on the deployment's host. type Config struct { ClientID string ClientSecret string @@ -43,20 +42,34 @@ type Config struct { // Enabled reports whether the process has enough configuration to start a grant. func (c Config) Enabled() bool { + return c.RefreshEnabled() && c.AuthorizeURL != "" && c.APIBase != "" +} + +func (c Config) RefreshEnabled() bool { + return c.clientConfigured() && c.TokenURL != "" +} + +func (c Config) clientConfigured() bool { return strings.TrimSpace(c.ClientID) != "" && strings.TrimSpace(c.ClientSecret) != "" && strings.TrimSpace(c.RedirectURI) != "" } -// ConfigFromEnv reads the application credentials. Authorize, token and API -// URLs fall back to git.example.com; the overrides exist so tests can point at a -// local server. +// ConfigFromEnv derives endpoints from the configured host. Explicit OAuth +// endpoint overrides still take precedence. func ConfigFromEnv() Config { + host := config.GongfengHost() + endpoint := func(path string) string { + if host == "" { + return "" + } + return "https://" + host + path + } return Config{ ClientID: strings.TrimSpace(os.Getenv("AGENTFLOW_GONGFENG_OAUTH_CLIENT_ID")), ClientSecret: strings.TrimSpace(os.Getenv("AGENTFLOW_GONGFENG_OAUTH_CLIENT_SECRET")), RedirectURI: strings.TrimSpace(os.Getenv("AGENTFLOW_GONGFENG_OAUTH_REDIRECT_URI")), - AuthorizeURL: envOr("AGENTFLOW_GONGFENG_OAUTH_AUTHORIZE_URL", defaultAuthorizeURL), - TokenURL: envOr("AGENTFLOW_GONGFENG_OAUTH_TOKEN_URL", defaultTokenURL), - APIBase: strings.TrimRight(envOr("AGENTFLOW_GONGFENG_OAUTH_API_BASE", defaultAPIBase), "/"), + AuthorizeURL: envOr("AGENTFLOW_GONGFENG_OAUTH_AUTHORIZE_URL", endpoint("/oauth/authorize")), + TokenURL: envOr("AGENTFLOW_GONGFENG_OAUTH_TOKEN_URL", endpoint("/oauth/token")), + APIBase: strings.TrimRight(envOr("AGENTFLOW_GONGFENG_OAUTH_API_BASE", endpoint("/api/v3")), "/"), } } @@ -92,7 +105,7 @@ func (t Token) Expiry(now time.Time) time.Time { // AuthorizeURL is the browser location that asks the user to approve the app. func AuthorizeURL(cfg Config, state string) (string, error) { - if !cfg.Enabled() { + if !cfg.clientConfigured() || cfg.AuthorizeURL == "" { return "", fmt.Errorf("工蜂 OAuth 未配置") } u, err := url.Parse(cfg.AuthorizeURL) @@ -162,7 +175,7 @@ func Username(ctx context.Context, cfg Config, accessToken string) (string, erro } func requestToken(ctx context.Context, cfg Config, form url.Values) (Token, error) { - if !cfg.Enabled() { + if !cfg.RefreshEnabled() { return Token{}, fmt.Errorf("工蜂 OAuth 未配置") } req, err := http.NewRequestWithContext(ctx, http.MethodPost, cfg.TokenURL, strings.NewReader(form.Encode())) diff --git a/internal/httpapi/agent_tool_catalog.go b/internal/httpapi/agent_tool_catalog.go index b40f8e24..937f9c13 100644 --- a/internal/httpapi/agent_tool_catalog.go +++ b/internal/httpapi/agent_tool_catalog.go @@ -315,9 +315,13 @@ func (h *agentToolGateway) buildCatalog(ctx context.Context, session *AgentToolS session.mu.Unlock() return out } + clarifyRepos := len(session.clarifyRepos) > 0 session.mu.Unlock() out := make([]agentToolDescriptor, 0, 16) + if session.Mode == AgentToolClarify && clarifyRepos { + out = append(out, clarifySourceTools...) + } seen := map[string]bool{} for _, server := range session.MCPServers { kind := classifyClarifyMCP(server) diff --git a/internal/httpapi/agent_tool_mcp.go b/internal/httpapi/agent_tool_mcp.go index 4e72c2f9..96b7dc95 100644 --- a/internal/httpapi/agent_tool_mcp.go +++ b/internal/httpapi/agent_tool_mcp.go @@ -387,6 +387,9 @@ func (h *agentToolGateway) dispatch(ctx context.Context, session *AgentToolSessi if session.Mode == AgentToolAssistant && session.ExecMode.ReviewWrites { ctx = withAssistantApprovalReviewer(ctx, session.approvalReviewer) } + if tool.Kind == "clarify-source" { + return readClarifySource(session, tool.Name, args) + } if tool.Kind == "workspace" { return h.callMainBotWorkspace(ctx, session, tool.Name, args) } diff --git a/internal/httpapi/agent_tool_session.go b/internal/httpapi/agent_tool_session.go index 15d0688d..e9ddb2d3 100644 --- a/internal/httpapi/agent_tool_session.go +++ b/internal/httpapi/agent_tool_session.go @@ -98,6 +98,7 @@ type AgentToolSession struct { Final chan AgentTerminalResult mu sync.Mutex + clarifyRepos map[string]string // read-only analysis checkouts for this turn catalog []agentToolDescriptor terminalOnly bool runIDs []string diff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.go index b28c5d4a..97b361e6 100644 --- a/internal/httpapi/assistant.go +++ b/internal/httpapi/assistant.go @@ -117,7 +117,7 @@ func (h *assistantHandlers) chat(c *gin.Context) { } stored, ok := h.repo.User(current.ID) if !ok { - c.JSON(400, gin.H{"error": "请先在个人配置中配置自己的 CodeBuddy API Key"}) + c.JSON(400, gin.H{"error": "当前用户不可用"}) return } var req assistantRequest @@ -131,8 +131,6 @@ func (h *assistantHandlers) chat(c *gin.Context) { if !requireAssistantApprovalUser(c, current.ID, req.ApprovalUserID) { return } - req.Executor = assistantExecutor(req.Executor) - req.Model = assistantRequestModel(req.Executor, req.Model) if len(req.Messages) == 0 { c.JSON(400, gin.H{"error": "请提供对话消息"}) return @@ -187,6 +185,7 @@ func (h *assistantHandlers) chat(c *gin.Context) { } req.ExecutionTarget = target } + req.Model = h.assistantChatRequestModel(req, old, stored) cliEngine, _ := assistantModelEngine(req.Model) loginRunner := h.assistantLoginRunner(stored.ID, req.ExecutionTarget, cliEngine) runnerLogin := loginRunner.ID != "" @@ -234,9 +233,10 @@ func (h *assistantHandlers) chat(c *gin.Context) { return } catalogEngine, _ := assistantModelEngine(req.Model) - catalog := loadAssistantModels(user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey) + var catalog assistantModelCatalog if catalogEngine == assistantEngineCodeBuddy { - catalog = h.turnCatalog(c.Request.Context(), user, req.Model) + _, modelID := assistantModelEngine(req.Model) + catalog = h.turnCatalog(c.Request.Context(), user, modelID) } if !runnerLogin { selected, err := assistantTurnCatalogModel(req.Model, catalog, user, req.RequireExactModel) @@ -294,7 +294,9 @@ func (h *assistantHandlers) chat(c *gin.Context) { defer cancel() var emit func(string, any) var activity assistantActivityLog - reviewer := h.approvalReviewer(req, user, func(event assistantStreamEvent) { + reviewRequest := req + reviewRequest.Model = cliModel + reviewer := h.approvalReviewer(reviewRequest, user, func(event assistantStreamEvent) { if emit != nil { emit("thought", event) } else { @@ -1519,6 +1521,14 @@ type assistantCLIRequest struct { func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.User, onEvent func(assistantStreamEvent)) (output string, returnedSessionID string, returnedErr error) { req.Model = assistantRequestModel(req.Executor, req.Model) engine, engineModel := assistantModelEngine(req.Model) + if req.SessionRoot == "" && (req.ReviewOnly || req.ReportOnly) { + root, err := os.MkdirTemp("", "agentflow-helper-") + if err != nil { + return "", "", err + } + defer os.RemoveAll(root) + req.SessionRoot = root + } if req.Execute == nil { if execute, runnerLogin := helperCLIExecution(ctx, req.SessionRoot, user.ID, engine); execute != nil { req.Execute = execute @@ -1531,7 +1541,7 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U } attempt := assistantDiagnosticsFrom(ctx).begin(engine, engineModel, req.Resume, user) defer func() { attempt.finish(returnedErr) }() - if engine != assistantEngineCodeBuddy && (req.ReportOnly || (!req.Native && !req.ReviewOnly)) { + if engine != assistantEngineCodeBuddy && !req.Native && !req.ReviewOnly { return "", "", errAssistantEngineUnsupported } var bin string @@ -1558,23 +1568,8 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U return "", "", err } } - reportRoot := "" - if req.ReportOnly { - reportRoot, err = os.MkdirTemp("", "agentflow-sop-report-") - if err != nil { - return "", "", err - } - defer os.RemoveAll(reportRoot) - } config := filepath.Join(root, "mcp.json") - if req.ReportOnly && req.MCPConfig != "" { - config = req.MCPConfig - } else if req.ReportOnly { - config = filepath.Join(reportRoot, "mcp.json") - if err = os.WriteFile(config, []byte(`{"mcpServers":{}}`), 0600); err != nil { - return "", "", err - } - } else if req.Native && strings.TrimSpace(req.MCPConfig) != "" { + if req.Native && strings.TrimSpace(req.MCPConfig) != "" { config = req.MCPConfig } else if err = os.WriteFile(config, []byte(`{"mcpServers":{}}`), 0600); err != nil { return "", "", err @@ -1584,7 +1579,12 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U sessionID = newAssistantSessionID() } var inv assistantCLIInvocation - engineOpts := assistantEngineInvocationOpts{Bin: bin, Root: root, Config: config, Prompt: req.Prompt, Model: engineModel, Effort: req.Effort, SessionID: sessionID, Resume: req.Resume, SystemPrompt: req.SystemPrompt, ReviewOnly: req.ReviewOnly, Workspace: req.Workspace, RunnerLogin: req.RunnerLogin, ImagePaths: req.ImagePaths, ImageInput: req.ImageInput} + engineOpts := assistantEngineInvocationOpts{ + Bin: bin, Root: root, Config: config, Prompt: req.Prompt, Model: engineModel, Effort: req.Effort, + SessionID: sessionID, Resume: req.Resume, SystemPrompt: req.SystemPrompt, + ReviewOnly: req.ReviewOnly, ReportOnly: req.ReportOnly, + Workspace: req.Workspace, RunnerLogin: req.RunnerLogin, ImagePaths: req.ImagePaths, ImageInput: req.ImageInput, + } switch engine { case assistantEngineClaude: if !req.RunnerLogin { @@ -1604,8 +1604,8 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U inv, err = prepareAssistantAgentCLIInvocation(engine, engineOpts) break } - inv.command, err = prepareAssistantCommand(assistantCommandOpts{Bin: bin, Config: config, Prompt: req.Prompt, Model: req.Model, Effort: req.Effort, SessionID: sessionID, Resume: req.Resume, SystemPrompt: req.SystemPrompt, Native: req.Native, Settings: req.Settings, ReportOnly: req.ReportOnly, ReviewOnly: req.ReviewOnly, Workspace: req.Workspace, ImagePaths: req.ImagePaths}) - inv.credentials = runtime.RunCredentials{CodeBuddy: runtime.CodeBuddyCredential{APIKey: user.CodeBuddyAPIKey, InternetEnvironment: user.CodeBuddyInternetEnvironment}} + inv.command, err = prepareAssistantCommand(assistantCommandOpts{Bin: bin, Config: config, Prompt: req.Prompt, Model: engineModel, Effort: req.Effort, SessionID: sessionID, Resume: req.Resume, SystemPrompt: req.SystemPrompt, Native: req.Native, Settings: req.Settings, ReportOnly: req.ReportOnly, ReviewOnly: req.ReviewOnly, Workspace: req.Workspace, ImagePaths: req.ImagePaths}) + inv.credentials = runtime.RunCredentials{CodeBuddy: runtime.CodeBuddyUserCredential(user)} inv.sessionRef = sessionID } if err != nil { @@ -1621,9 +1621,6 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U } command := inv.command.WithPrivateHomeDir(filepath.Join(root, "home")) workspace := filepath.Join(root, "ws") - if req.ReportOnly { - workspace = reportRoot - } var final, claudeResultText, claudeMessageID string var claudeTextBlocks []string var resultError bool @@ -1760,6 +1757,9 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U return "", sessionID, assistantCredentialError{engine: engine} } if credentialRejected && strings.TrimSpace(final) == "" && err == nil && ctx.Err() == nil { + if user.CodeBuddyBaseURL != "" { + return "", sessionID, assistantCredentialError{engine: assistantEngineCodeBuddy} + } return "", sessionID, errAssistantCredentialRejected } if ctx.Err() != nil { diff --git a/internal/httpapi/assistant_approval_review.go b/internal/httpapi/assistant_approval_review.go index b1afcd5d..65057300 100644 --- a/internal/httpapi/assistant_approval_review.go +++ b/internal/httpapi/assistant_approval_review.go @@ -139,13 +139,16 @@ func approvalReviewInput(req assistantRequest, user domain.User) assistantApprov func (h *assistantHandlers) approvalReviewer(req assistantRequest, user domain.User, notify func(assistantStreamEvent)) assistantApprovalReviewer { input := approvalReviewInput(req, user) - var catalog assistantModelCatalog - if h.reviewCatalog != nil { - catalog = h.reviewCatalog(user.CodeBuddyInternetEnvironment) + selected := assistantRequestModel(req.Executor, req.Model) + engine, _ := assistantModelEngine(selected) + var models []string + if engine != assistantEngineCodeBuddy || user.CodeBuddyBaseURL != "" || (req.RequireExactModel && selected != "") { + models = []string{selected} + } else if h.reviewCatalog != nil { + models = assistantApprovalReviewModels(h.reviewCatalog(user.CodeBuddyInternetEnvironment)) } else { - catalog = h.chatCatalog(user) + models = assistantApprovalReviewModels(h.chatCatalog(context.Background(), user)) } - models := assistantApprovalReviewModels(catalog) var modelMu sync.Mutex primaryUnavailable := false return func(ctx context.Context, tool, description string, args map[string]any) assistantApprovalReview { @@ -208,7 +211,10 @@ func (h *assistantHandlers) approvalReviewer(req assistantRequest, user domain.U } func runAssistantApprovalReview(ctx context.Context, input assistantApprovalInput, user domain.User, model string) (assistantApprovalReview, error) { - if model == "" || strings.TrimSpace(user.CodeBuddyAPIKey) == "" { + engine, _ := assistantModelEngine(model) + key, _ := assistantEngineCredential(user, engine) + _, login := helperCLIExecution(ctx, "", user.ID, engine) + if model == "" || key == "" && !login { return assistantApprovalReview{}, fmt.Errorf("review model or credential unavailable") } root, err := os.MkdirTemp("", "agentflow-approval-review-") diff --git a/internal/httpapi/assistant_cases_test.go b/internal/httpapi/assistant_cases_test.go index 3c1046ad..5429bf72 100644 --- a/internal/httpapi/assistant_cases_test.go +++ b/internal/httpapi/assistant_cases_test.go @@ -193,7 +193,7 @@ func TestAssistantTaskHandlersAndExecution(t *testing.T) { } noKey := user noKey.CodeBuddyAPIKey = "" - if err := h.executeAssistantTask(context.Background(), noKey, &task); err == nil || !strings.Contains(task.LastError, "API Key") { + if err := h.executeAssistantTask(context.Background(), noKey, &task); err == nil || task.LastError != errFeatureCredentials.Error() { t.Fatalf("missing key = %v %+v", err, task) } } diff --git a/internal/httpapi/assistant_codebuddy_default_test.go b/internal/httpapi/assistant_codebuddy_default_test.go index 655b8d00..7e20c06c 100644 --- a/internal/httpapi/assistant_codebuddy_default_test.go +++ b/internal/httpapi/assistant_codebuddy_default_test.go @@ -2,18 +2,76 @@ package httpapi import ( "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" "testing" "agentflow/internal/domain" ) +func TestCodeBuddyBaseURLSettingsAndCatalog(t *testing.T) { + const key = "ck_fixture_gateway" + const model = "fixture-flash" + gateway := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet || r.URL.Path != "/gateway/v1/models" || r.Header.Get("Authorization") != "Bearer "+key { + http.Error(w, "unexpected model discovery request", http.StatusBadRequest) + return + } + _, _ = io.WriteString(w, `{"data":[{"id":"`+model+`"}]}`) + })) + t.Cleanup(gateway.Close) + f := cvBNewHTTPFixture(t) + baseURL := gateway.URL + "/gateway/v1" + userPath := "/api/users/" + strconv.FormatInt(f.user.ID, 10) + set := func(fields map[string]any, want int) domain.User { + t.Helper() + r := cvBRequest(t, f, http.MethodPut, userPath+"/credentials", fields, true) + if r.Code != want || strings.Contains(r.Body.String(), key) { + t.Fatalf("credential update returned %d, want %d with redacted data", r.Code, want) + } + var public domain.User + if want == http.StatusOK { + if err := json.Unmarshal(r.Body.Bytes(), &public); err != nil { + t.Fatal(err) + } + } + return public + } + set(map[string]any{"codeBuddyApiKey": key, "codeBuddyInternetEnvironment": "ioa"}, http.StatusOK) + set(map[string]any{"codeBuddyBaseUrl": "https://user:pass@gateway.example/v1"}, http.StatusBadRequest) + if saved := set(map[string]any{"codeBuddyBaseUrl": " " + baseURL + " "}, http.StatusOK); saved.CodeBuddyBaseURL != baseURL || !saved.CodeBuddyAPIKeyConfigured || saved.CodeBuddyInternetEnvironment != "ioa" { + t.Fatal("updating the URL did not preserve the key and edition") + } + response := cvBRequest(t, f, http.MethodGet, "/api/assistant/models", nil, true) + var catalog assistantModelCatalog + if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &catalog) != nil || catalog.Default != model || !assistantCatalogLists(catalog, model) { + t.Fatalf("gateway model not offered: %s", response.Body.String()) + } + probe := cvBRequest(t, f, http.MethodPost, userPath+"/cli-models/probe", map[string]string{"engine": "codebuddy"}, true) + if probe.Code != http.StatusOK || !strings.Contains(probe.Body.String(), `"id":"`+model+`"`) { + t.Fatalf("gateway probe returned %d: %s", probe.Code, probe.Body.String()) + } + if saved := set(map[string]any{"codeBuddyBaseUrl": ""}, http.StatusOK); saved.CodeBuddyBaseURL != "" || !saved.CodeBuddyAPIKeyConfigured { + t.Fatal("clearing the custom URL must preserve authentication") + } + set(map[string]any{"codeBuddyBaseUrl": baseURL}, http.StatusOK) + if saved := set(map[string]any{"codeBuddyApiKeyClear": true}, http.StatusOK); saved.CodeBuddyBaseURL != "" || saved.CodeBuddyAPIKeyConfigured { + t.Fatal("deleting the credential must remove the gateway") + } +} + // A request without a model runs on the default the picker shows: the first // saved personal CodeBuddy model. Environment models stay accepted. func TestCodeBuddyPersonalModelsDefaultMatchesPicker(t *testing.T) { user := domain.User{CodeBuddyAPIKey: "test-only", CodeBuddyModels: []domain.CLIModel{{ID: "personal-a"}, {ID: "personal-b", Name: "B"}}} base := assistantModelCatalog{Default: "env-default", Models: []assistantModel{{ID: "env-default"}, {ID: "env-other"}}} - catalog := withCodeBuddyPersonalModels(base, user) + ctx := context.Background() + catalog := withCodeBuddyPersonalModels(ctx, base, user) if catalog.Default != "personal-a" { t.Fatalf("default = %q, want the first saved model", catalog.Default) } @@ -27,10 +85,10 @@ func TestCodeBuddyPersonalModelsDefaultMatchesPicker(t *testing.T) { } // Without saved models (or without a personal key) nothing changes. - if got := withCodeBuddyPersonalModels(base, domain.User{CodeBuddyAPIKey: "test-only"}); got.Default != "env-default" || len(got.Models) != 2 { + if got := withCodeBuddyPersonalModels(ctx, base, domain.User{CodeBuddyAPIKey: "test-only"}); got.Default != "env-default" || len(got.Models) != 2 { t.Fatalf("catalog without saved models changed: %+v", got) } - if got := withCodeBuddyPersonalModels(base, domain.User{CodeBuddyModels: user.CodeBuddyModels}); got.Default != "env-default" { + if got := withCodeBuddyPersonalModels(ctx, base, domain.User{CodeBuddyModels: user.CodeBuddyModels}); got.Default != "env-default" { t.Fatalf("saved models without a key changed the default: %+v", got) } diff --git a/internal/httpapi/assistant_engine_cli.go b/internal/httpapi/assistant_engine_cli.go index f9629891..c5a4dc8d 100644 --- a/internal/httpapi/assistant_engine_cli.go +++ b/internal/httpapi/assistant_engine_cli.go @@ -44,6 +44,7 @@ type assistantEngineInvocationOpts struct { // ReviewOnly is a one-shot call without MCP servers or session history, // such as a title summary. ReviewOnly bool + ReportOnly bool User runtime.ProviderCredential } @@ -220,7 +221,7 @@ func prepareAssistantClaudeInvocation(o assistantEngineInvocationOpts) (assistan if effort := strings.TrimSpace(o.Effort); effort != "" { argv = append(argv, "--effort", effort) } - if o.ReviewOnly { + if o.ReviewOnly || o.ReportOnly { argv = append(argv, "--tools", "", "--no-session-persistence") } if o.Resume { @@ -392,4 +393,4 @@ func writeCodexThread(root, sessionID, threadID string) error { return os.WriteFile(codexThreadsPath(root), data, 0o600) } -var errAssistantEngineUnsupported = errors.New("该调用只支持 CodeBuddy 模型") +var errAssistantEngineUnsupported = errors.New("此调用未启用 CLI 会话或单次模型调用模式") diff --git a/internal/httpapi/assistant_engines.go b/internal/httpapi/assistant_engines.go index fa209d76..cc53cc10 100644 --- a/internal/httpapi/assistant_engines.go +++ b/internal/httpapi/assistant_engines.go @@ -24,10 +24,8 @@ import ( "agentflow/internal/runtime" ) -// AI 对话 runs on CodeBuddy by default. A model ID prefixed with another CLI -// ("codex:", "claude-code:" or an agent CLI kind such as "opencode:") runs the -// turn on that CLI with the caller's own key and Base URL from 个人配置; the -// part after the prefix is passed to the CLI as-is. +// The assistant stores CLI-prefixed model IDs. Bare concrete IDs from older +// CodeBuddy sessions retain the CodeBuddy interpretation. const ( assistantEngineCodeBuddy = "codebuddy" assistantEngineCodex = "codex" @@ -41,6 +39,9 @@ func assistantCLIEngines() []string { func assistantModelEngine(id string) (engine, model string) { id = strings.TrimSpace(id) + if rest, ok := strings.CutPrefix(id, assistantEngineCodeBuddy+":"); ok { + return assistantEngineCodeBuddy, strings.TrimSpace(rest) + } for _, engine := range assistantCLIEngines() { if rest, ok := strings.CutPrefix(id, engine+":"); ok { return engine, strings.TrimSpace(rest) @@ -55,6 +56,7 @@ type assistantEngineOption struct { ID string `json:"id"` Name string `json:"name"` Configured bool `json:"configured"` + Personal bool `json:"personal"` Credential string `json:"credential"` } @@ -83,6 +85,7 @@ func assistantEngineOptions(user domain.User, sponsored bool) []assistantEngineO ID: engine, Name: assistantEngineLabel(engine), Configured: key != "" || (engine == assistantEngineCodeBuddy && sponsored), + Personal: key != "", Credential: assistantEngineCredentialField(engine), }) } @@ -108,7 +111,7 @@ func assistantEngineCredential(user domain.User, engine string) (apiKey, baseURL case assistantEngineClaude: return strings.TrimSpace(user.ClaudeCodeAPIKey), strings.TrimSpace(user.ClaudeCodeBaseURL) case assistantEngineCodeBuddy: - return strings.TrimSpace(user.CodeBuddyAPIKey), "" + return strings.TrimSpace(user.CodeBuddyAPIKey), strings.TrimSpace(user.CodeBuddyBaseURL) } cred := user.AgentCLICredentials[engine] if runtime.IsAgentCLI(engine) && engine != runtime.AgentCLICursor { @@ -166,7 +169,7 @@ func assistantEngineBuiltinModels(engine string) []assistantDiscoveredModel { // assistantValidEngineModel guards model IDs that reach a CLI argument or a // TOML config override. func assistantValidEngineModel(model string) bool { - if model == "" || len(model) > 128 { + if model == "" || len(model) > 128 || strings.HasPrefix(model, "-") { return false } for _, r := range model { @@ -251,30 +254,26 @@ func assistantEngineMissingKey(engine string) string { } // assistantTurnUser checks personal credentials or the chosen runner login. -// Non-CodeBuddy turns can still borrow a CodeBuddy key for approval reviews. func (h *assistantHandlers) assistantTurnUser(stored domain.User, model string, runnerLogin bool) (domain.User, string, string) { engine, id := assistantModelEngine(model) if engine != assistantEngineCodeBuddy { - if runnerLogin { - if id == "" { - id = "default" - } - if !assistantValidEngineModel(id) { - return stored, "", "模型 ID 无效" - } - model = engine + ":" + id - } else if key, _ := assistantEngineCredential(stored, engine); key == "" { + if id == "" { + id = assistantDefaultModel + } + if !assistantValidEngineModel(id) { + return stored, "", "模型 ID 无效" + } + if key, _ := assistantEngineCredential(stored, engine); !runnerLogin && key == "" { return stored, "", assistantEngineMissingKey(engine) } - user, _, _ := h.assistantChatUser(stored) - return user, model, "" + return stored, engine + ":" + id, "" } user, shared, ok := h.assistantChatUser(stored) if !ok { return stored, "", "请先在个人配置中配置自己的 CodeBuddy API Key" } if len(shared) > 0 { - forced, allowed := assistantSponsoredModelFor(shared, model) + forced, allowed := assistantSponsoredModelFor(shared, id) if !allowed { return stored, "", errAssistantSponsoredModel(shared) } @@ -290,7 +289,7 @@ func (h *assistantHandlers) assistantTurnUser(stored domain.User, model string, func assistantAllowedUserModel(id string, catalog assistantModelCatalog, user domain.User) string { engine, model := assistantModelEngine(id) if engine == assistantEngineCodeBuddy { - return assistantAllowedModel(id, catalog) + return assistantAllowedModel(model, catalog) } if key, _ := assistantEngineCredential(user, engine); key == "" || !assistantValidEngineModel(model) { return catalog.Default @@ -312,16 +311,14 @@ func assistantTurnCatalogModel(requested string, catalog assistantModelCatalog, return model, nil } -// assistantScheduledModel normalizes the model of an AI scheduled task on -// save. The run uses the project owner's keys and CodeBuddy environment, not -// the editor's, so a well-formed model is kept as-is; it is checked against -// the owner's account when it runs (see scheduledRunModel). +// assistantScheduledModel normalizes a scheduled model without replacing a +// well-formed selection. The account bound to the task validates it at run time. func assistantScheduledModel(id string, catalog assistantModelCatalog) string { engine, model := assistantModelEngine(id) - if engine != assistantEngineCodeBuddy && assistantValidEngineModel(model) { - return engine + ":" + model - } - if engine == assistantEngineCodeBuddy && assistantValidEngineModel(model) { + if assistantValidEngineModel(model) { + if engine != assistantEngineCodeBuddy || model == assistantDefaultModel && assistantModelHasEnginePrefix(id) { + return engine + ":" + model + } return model } return assistantAllowedModel(id, catalog) @@ -666,11 +663,30 @@ func writeAssistantEngineState(root string, state assistantEngineState) error { return os.WriteFile(filepath.Join(root, "engine.json"), data, 0o600) } +// assistantChatRequestModel keeps an existing conversation's model when +// omitted, or chooses a personal CLI for a new conversation with no selection. +func (h *assistantHandlers) assistantChatRequestModel(req assistantRequest, saved domain.AssistantSession, user domain.User) string { + if strings.TrimSpace(req.Executor) == "" && assistantModelUnspecified(req.Model) { + if saved.Model != "" || saved.Executor != "" { + return assistantRequestModel(saved.Executor, saved.Model) + } + if preferred := personalDefaultModel(user); preferred != "" { + return preferred + } + if _, _, codeBuddyAvailable := h.assistantChatUser(user); !codeBuddyAvailable { + if model, err := resolveFeatureModel(user, ""); err == nil { + return model + } + } + } + return assistantRequestModel(req.Executor, req.Model) +} + // assistantRequestModel maps a legacy executor field onto the model prefix // the conversation engines use. A model that already names its CLI is kept. func assistantRequestModel(executor, model string) string { model = strings.TrimSpace(model) - if engine, _ := assistantModelEngine(model); engine != assistantEngineCodeBuddy { + if assistantModelHasEnginePrefix(model) { return model } switch assistantExecutor(executor) { diff --git a/internal/httpapi/assistant_failure.go b/internal/httpapi/assistant_failure.go index b05bc163..f3891f14 100644 --- a/internal/httpapi/assistant_failure.go +++ b/internal/httpapi/assistant_failure.go @@ -160,7 +160,7 @@ func classifyAssistantFailureText(f domain.AssistantFailure, err error, text str case has("rate limit", "rate_limit", "too many requests", "http 429", "status 429", "status code 429", "status=429"): f.Code, f.Phase, f.Message, f.Suggestion = "RATE_LIMITED", "provider", "模型服务请求过于频繁(429)", "请稍后再试,或检查模型服务的限流配置。" case errors.Is(err, errAssistantCredentialRejected), has("unauthorized", "invalid api key", "invalid_api_key", "invalid token", "api key expired", "invalid credential", "http 401", "status 401", "status code 401", "status=401", "authentication_error"): - f.Code, f.Phase, f.Message, f.Suggestion = "AUTHENTICATION_FAILED", "provider", "CodeBuddy 凭据无效或已过期,请检查个人配置后重试", "请检查所用 CLI 的 API Key 和 Base URL。" + f.Code, f.Phase, f.Message, f.Suggestion = "AUTHENTICATION_FAILED", "provider", "模型服务凭据无效或已过期,请检查个人配置后重试", "请检查所用 CLI 的 API Key 和 Base URL。" var credential assistantCredentialError if errors.As(err, &credential) { f.Message = credential.Error() diff --git a/internal/httpapi/assistant_generation.go b/internal/httpapi/assistant_generation.go index 403f094b..a8057832 100644 --- a/internal/httpapi/assistant_generation.go +++ b/internal/httpapi/assistant_generation.go @@ -28,7 +28,7 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) { } stored, ok := h.repo.User(current.ID) if !ok { - c.JSON(400, gin.H{"error": "请先配置个人 CodeBuddy API Key"}) + c.JSON(400, gin.H{"error": "当前用户不可用"}) return } var body struct { @@ -50,7 +50,6 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) { c.JSON(400, gin.H{"error": err.Error()}) return } - req.Model = assistantRequestModel(req.Executor, req.Model) if len(req.Messages) == 0 || req.Messages[len(req.Messages)-1].Role != "user" { c.JSON(400, gin.H{"error": "请提供用户消息"}) return @@ -93,6 +92,7 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) { return } } + req.Model = h.assistantChatRequestModel(req, old, stored) cliEngine, _ := assistantModelEngine(req.Model) loginRunner := h.assistantLoginRunner(stored.ID, req.ExecutionTarget, cliEngine) runnerLogin := loginRunner.ID != "" @@ -131,9 +131,10 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) { return } catalogEngine, _ := assistantModelEngine(req.Model) - catalog := loadAssistantModels(user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey) + var catalog assistantModelCatalog if catalogEngine == assistantEngineCodeBuddy { - catalog = h.turnCatalog(c.Request.Context(), user, req.Model) + _, modelID := assistantModelEngine(req.Model) + catalog = h.turnCatalog(c.Request.Context(), user, modelID) } if !runnerLogin { selected, err := assistantTurnCatalogModel(req.Model, catalog, user, req.RequireExactModel) @@ -514,7 +515,7 @@ func (h *assistantHandlers) steerGeneration(c *gin.Context) { } stored, ok := h.repo.User(current.ID) if !ok { - c.JSON(400, gin.H{"error": "请先配置个人 CodeBuddy API Key"}) + c.JSON(400, gin.H{"error": "当前用户不可用"}) return } ownerID, _, err := h.conversationScope(c, c.Param("id"), "", "", stored.ID) @@ -577,7 +578,7 @@ func (h *assistantHandlers) steerGeneration(c *gin.Context) { } // A CodeBuddy model this instance has not listed yet refreshes the list // first, like a new turn, instead of silently becoming the default. - catalog := loadAssistantModels(user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey) + var catalog assistantModelCatalog if engine, _ := assistantModelEngine(model); engine == assistantEngineCodeBuddy { catalog = h.turnCatalog(c.Request.Context(), user, model) } diff --git a/internal/httpapi/assistant_mcp.go b/internal/httpapi/assistant_mcp.go index 9670e29e..197f593f 100644 --- a/internal/httpapi/assistant_mcp.go +++ b/internal/httpapi/assistant_mcp.go @@ -420,6 +420,11 @@ func redactAssistantSecrets(text string, user domain.User) string { text = strings.ReplaceAll(text, secret, "[redacted]") } } + for _, credential := range runtime.AgentCLIUserCredentials(user) { + if key := strings.TrimSpace(credential.APIKey); key != "" { + text = strings.ReplaceAll(text, key, "[redacted]") + } + } return gitSecretRedactions.redact(text, "[redacted]") } diff --git a/internal/httpapi/assistant_models.go b/internal/httpapi/assistant_models.go index 060ce9e1..30ef8856 100644 --- a/internal/httpapi/assistant_models.go +++ b/internal/httpapi/assistant_models.go @@ -45,8 +45,9 @@ type assistantModelCatalog struct { SponsoredModel string `json:"sponsoredModel,omitempty"` SponsoredModels []string `json:"sponsoredModels,omitempty"` // Engines lists the CLIs a signed-in user can switch between. - Engines []assistantEngineOption `json:"engines,omitempty"` - CursorModelsPending bool `json:"cursorModelsPending,omitempty"` + Engines []assistantEngineOption `json:"engines,omitempty"` + Preferences *domain.AssistantDefaults `json:"preferences,omitempty"` + CursorModelsPending bool `json:"cursorModelsPending,omitempty"` } func prefetchAssistantModels() {} @@ -63,8 +64,9 @@ var ( const cliModelTTL = time.Hour type cliModelEntry struct { - models []string - at time.Time + environment string + models []string + at time.Time } // cliModelCacheKey separates accounts within one environment: without a key @@ -133,11 +135,17 @@ func refreshCLIModels(ctx context.Context, environment, apiKey string) { models := discoverCLIModels(ctx, environment, apiKey) cliModelMu.Lock() if models != nil || !ok { - cliModelCache[cacheKey] = cliModelEntry{models: models, at: time.Now()} + cliModelCache[cacheKey] = cliModelEntry{environment: environment, models: models, at: time.Now()} } cliModelMu.Unlock() } +func refreshOfficialCodeBuddyModels(ctx context.Context, user domain.User) { + if user.CodeBuddyBaseURL == "" && strings.TrimSpace(user.CodeBuddyAPIKey) != "" { + refreshCLIModels(ctx, user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey) + } +} + // assistantKnownCatalog validates settings that are not tied to one user's // environment, such as SOP roles and notification bots. func assistantKnownCatalog() assistantModelCatalog { @@ -166,9 +174,8 @@ func cachedCLIModels(environment, apiKey string) []string { return cliModelCache[cacheKey].models } -// models returns the chat model catalog for the caller's CodeBuddy -// environment. Guests get the configured models only; actually chatting still -// requires login plus a configured or sponsored CodeBuddy key. +// models returns the available CLIs and the caller's models. Public catalog +// reads require no credential. Running a model requires a configured identity. func (h *assistantHandlers) models(c *gin.Context) { if raw := strings.TrimSpace(c.Query("executor")); raw != "" && assistantExecutor(raw) != "codebuddy" { engine := assistantExecutor(raw) @@ -222,19 +229,15 @@ func (h *assistantHandlers) models(c *gin.Context) { // 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(key.InternetEnvironment, key.APIKey, key.Models), key.Models) - case signedIn: + case signedIn && strings.TrimSpace(user.CodeBuddyAPIKey) != "": // 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 = loadAssistantModels(user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey) - if saved := codeBuddyPersonalModels(user); len(saved) > 0 { - catalog.Default = saved[0].ID - if listed := selectableCodeBuddyModels(saved); len(listed) > 0 { - catalog.Models = listed - } - } + catalog = personalCodeBuddyCatalog(c.Request.Context(), user) + case signedIn: + // Do not probe a CLI the user has not configured. + catalog.Default = assistantDefaultModel default: - catalog = loadAssistantModels("", "") + catalog = assistantChatCatalog("", "", nil) } if catalog.Default == assistantDefaultModel { models := user.CodeBuddyModels @@ -249,6 +252,9 @@ func (h *assistantHandlers) models(c *gin.Context) { } if signedIn { c.Header("Cache-Control", "private, no-store") + if user.AssistantDefaults != (domain.AssistantDefaults{}) { + catalog.Preferences = &user.AssistantDefaults + } catalog.Engines = assistantEngineOptions(user, usingSharedKey) var runnerLogin map[string]bool if c.Query("schedule") == "1" { @@ -269,6 +275,21 @@ func (h *assistantHandlers) models(c *gin.Context) { c.JSON(200, catalog) } +func personalCodeBuddyCatalog(ctx context.Context, user domain.User) assistantModelCatalog { + if strings.TrimSpace(user.CodeBuddyAPIKey) == "" { + return assistantModelCatalog{Default: assistantDefaultModel} + } + refreshOfficialCodeBuddyModels(ctx, user) + catalog := assistantChatCatalog(user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey, nil) + if personal := codeBuddyPersonalModels(ctx, user); len(personal) > 0 { + catalog.Default = personal[0].ID + if listed := selectableCodeBuddyModels(personal); len(listed) > 0 { + catalog.Models = listed + } + } + return catalog +} + // Keep the CLI default as an execution fallback and for older saved records. // The model pickers offer the concrete models available to the caller. func selectableCodeBuddyModels(models []assistantModel) []assistantModel { @@ -285,25 +306,26 @@ func codeBuddyIsDefaultModel(id string) bool { return id == assistantDefaultModel || id == "default-model" } -// withCodeBuddyPersonalModels accepts the user's saved CodeBuddy models and +// withCodeBuddyPersonalModels accepts the user's own CodeBuddy catalog and // defaults requests without a model to the first of them. The environment's // models stay accepted. -func withCodeBuddyPersonalModels(catalog assistantModelCatalog, user domain.User) assistantModelCatalog { - saved := codeBuddyPersonalModels(user) - if len(saved) == 0 { +func withCodeBuddyPersonalModels(ctx context.Context, catalog assistantModelCatalog, user domain.User) assistantModelCatalog { + personal := codeBuddyPersonalModels(ctx, user) + if len(personal) == 0 { return catalog } - catalog.Models = append(catalog.Models, saved...) - catalog.Default = saved[0].ID + catalog.Models = append(catalog.Models, personal...) + catalog.Default = personal[0].ID return catalog } -func codeBuddyPersonalModels(user domain.User) []assistantModel { +func codeBuddyPersonalModels(ctx context.Context, user domain.User) []assistantModel { if strings.TrimSpace(user.CodeBuddyAPIKey) == "" { return nil } var models []assistantModel - for _, item := range assistantSavedModels(user, assistantEngineCodeBuddy) { + personal, _ := assistantDiscoveredModelsFor(ctx, user, assistantEngineCodeBuddy) + for _, item := range personal { name := item.Name if name == "" { name = item.ID @@ -341,8 +363,8 @@ func assistantChatCatalog(environment, apiKey string, shared []string) assistant return catalog } -// loadAssistantModels combines configured models with the discovery cache for -// this credential and network environment. +// loadAssistantModels never blocks on discovery; validation accepts models the +// caller's environment has advertised. func loadAssistantModels(environment, apiKey string) assistantModelCatalog { catalog := assistantFixedCatalog() seen := map[string]bool{} @@ -358,27 +380,18 @@ func loadAssistantModels(environment, apiKey string) assistantModelCatalog { return catalog } -// assistantModelsForRequest refreshes an execution account's catalog when a -// selected model is missing, including after a process restart. +// assistantModelsForRequest looks up a concrete model with the execution +// account's credentials, including after the local discovery cache expired. func assistantModelsForRequest(ctx context.Context, user domain.User, model string) assistantModelCatalog { - environment, apiKey := user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey - catalog := loadAssistantModels(environment, apiKey) - if model = strings.TrimSpace(model); model != "" && !assistantCatalogLists(catalog, model) { - refreshCLIModels(ctx, environment, apiKey) - catalog = loadAssistantModels(environment, apiKey) + environment, key := user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey + catalog := withCodeBuddyPersonalModels(ctx, loadAssistantModels(environment, key), user) + if model != "" && !assistantCatalogLists(catalog, model) { + refreshOfficialCodeBuddyModels(ctx, user) + catalog = withCodeBuddyPersonalModels(ctx, loadAssistantModels(environment, key), user) } return catalog } -func assistantCatalogLists(catalog assistantModelCatalog, id string) bool { - for _, model := range catalog.Models { - if model.ID == id { - return true - } - } - return false -} - // assistantFixedCatalog mirrors `codebuddy --help` (CodeBuddy Code 2.180.0) // --model list, names/credits from the CLI's remote product catalog. Two ids // are kept although the CLI no longer advertises them: deepseek-v4-flash-ioa diff --git a/internal/httpapi/assistant_models_test.go b/internal/httpapi/assistant_models_test.go index abda264c..4663a5e4 100644 --- a/internal/httpapi/assistant_models_test.go +++ b/internal/httpapi/assistant_models_test.go @@ -27,7 +27,7 @@ func TestAssistantModelPickerOmitsCodeBuddyCLIDefault(t *testing.T) { assistantCatalogLists(catalog, assistantDefaultModel) || assistantCatalogLists(catalog, "default-model") || !assistantCatalogLists(catalog, "model-b") { t.Fatalf("model picker shows the wrong choices: %+v", catalog) } - if got := assistantAllowedModel("", h.chatCatalog(user)); got != assistantDefaultModel { + if got := assistantAllowedModel("", h.chatCatalog(context.Background(), user)); got != assistantDefaultModel { t.Fatalf("an omitted request model should still use the CLI fallback, got %q", got) } t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "") diff --git a/internal/httpapi/assistant_native_session.go b/internal/httpapi/assistant_native_session.go index a450f6b0..4786cb69 100644 --- a/internal/httpapi/assistant_native_session.go +++ b/internal/httpapi/assistant_native_session.go @@ -185,7 +185,7 @@ func assistantProjectScopeNote(projectID string) string { return "\n本对话属于项目 " + projectID + "(即上面的 projectId),这就是用户当前所在的项目,不要说没有选中项目。需求、仓库、角色、SOP 等项目内资源默认写入该项目。" + "新建项目(projects_save)是独立的顶层项目,不归属当前项目,也不会把本对话切过去;保存后让用户点卡片上的「进入项目」继续。删除项目用 projects_delete(归档,数据保留,可用 projects_restore 恢复)。" + "你不能替用户切换本对话的项目;要到其他项目继续,请用户点对话右上角的项目名称选择目标项目(会在该项目里新开对话)。不要让用户去输入框上方找项目选择器,对话开始后那里不再显示。" + common + - "你不能在工蜂上新建仓库或直接推送文件:请用户在 https://git.example.com/projects/new 建好仓库(空仓库即可)后把地址发来,再用 repositories_save 绑定;文件通过工作区写入后提交 MR,空仓库会自动初始化默认分支。" + "如需绑定新仓库,请用户在使用的代码托管服务上创建仓库,然后提供完整仓库地址,再用 repositories_save 绑定。文件通过工作区写入后提交 PR 或 MR,空仓库会自动初始化默认分支。" } func assistantTurnContext(req assistantRequest) string { diff --git a/internal/httpapi/assistant_notification_report.go b/internal/httpapi/assistant_notification_report.go index 87c0907a..be6731a7 100644 --- a/internal/httpapi/assistant_notification_report.go +++ b/internal/httpapi/assistant_notification_report.go @@ -4,8 +4,8 @@ import ( "agentflow/internal/domain" "agentflow/internal/notification" "context" + "errors" "path/filepath" - "strings" ) func (h *assistantHandlers) generateSOPReport(ctx context.Context, run domain.Run, model, prompt string) (domain.AINotificationContent, error) { @@ -13,13 +13,16 @@ func (h *assistantHandlers) generateSOPReport(ctx context.Context, run domain.Ru } func (h *assistantHandlers) generateReport(ctx context.Context, run domain.Run, model, prompt, system string) (domain.AINotificationContent, error) { user, ok := h.repo.User(run.ExecutionContext.ResponsibleUserID) - if !ok || strings.TrimSpace(user.CodeBuddyAPIKey) == "" { + if !ok { return domain.AINotificationContent{}, notification.ErrReportCredentials } - catalog := assistantModelsForRequest(ctx, user, model) - if assistantAllowedModel(model, catalog) != model { + model, err := resolveFeatureModel(user, model) + if errors.Is(err, errFeatureModel) { return domain.AINotificationContent{}, notification.ErrReportModel } + if err != nil { + return domain.AINotificationContent{}, notification.ErrReportCredentials + } modelCtx, cancel := context.WithCancel(ctx) defer cancel() @@ -49,9 +52,9 @@ func (h *assistantHandlers) generateReport(ctx context.Context, run domain.Run, _, cliErr := generate(modelCtx, input, user) if result, ok := session.takeFinal(); ok && result.Report != nil { report := *result.Report - report.Title = redactAssistantSecrets(strings.ReplaceAll(report.Title, user.CodeBuddyAPIKey, "[redacted]"), user) - report.Summary = redactAssistantSecrets(strings.ReplaceAll(report.Summary, user.CodeBuddyAPIKey, "[redacted]"), user) - report.Body = redactAssistantSecrets(strings.ReplaceAll(report.Body, user.CodeBuddyAPIKey, "[redacted]"), user) + report.Title = redactAssistantSecrets(report.Title, user) + report.Summary = redactAssistantSecrets(report.Summary, user) + report.Body = redactAssistantSecrets(report.Body, user) return report, nil } if ctx.Err() != nil { diff --git a/internal/httpapi/assistant_notification_report_test.go b/internal/httpapi/assistant_notification_report_test.go index dcb0a615..d18cdcc8 100644 --- a/internal/httpapi/assistant_notification_report_test.go +++ b/internal/httpapi/assistant_notification_report_test.go @@ -4,6 +4,7 @@ import ( "agentflow/internal/domain" "agentflow/internal/notification" "agentflow/internal/repo" + "agentflow/internal/runtime" "context" "encoding/json" "errors" @@ -28,6 +29,26 @@ func activeReportSession(t *testing.T) *AgentToolSession { return nil } +func TestSOPReportClaudeInvocationDisablesToolsAndSessionPersistence(t *testing.T) { + var argv []string + _, _, err := runAssistantCLI(t.Context(), assistantCLIRequest{ + Model: "claude-code:fixture-model", Prompt: "Write a report", SessionRoot: t.TempDir(), + ReportOnly: true, Native: true, RemoteBinary: true, + Execute: func(_ context.Context, _ string, command runtime.CommandSpec, _ runtime.RunCredentials, sink runtime.EventSink) (string, error) { + argv = append([]string(nil), command.Argv...) + sink(domain.TelemetryEvent{Name: "process.stdout", Message: `{"type":"result","subtype":"success","result":"Report"}`}) + return "", nil + }, + }, domain.User{ID: 1, ClaudeCodeAPIKey: "fixture-key"}, nil) + if err != nil { + t.Fatal(err) + } + tools := slices.Index(argv, "--tools") + if tools < 0 || tools+1 >= len(argv) || argv[tools+1] != "" || !slices.Contains(argv, "--no-session-persistence") { + t.Fatalf("report-only flags missing from Claude invocation: %v", argv) + } +} + func TestSOPReportUsesResponsibleUserAndMCPSubmission(t *testing.T) { store, err := repo.OpenTest() if err != nil { diff --git a/internal/httpapi/assistant_process.go b/internal/httpapi/assistant_process.go index a01c1fb4..88c87c0c 100644 --- a/internal/httpapi/assistant_process.go +++ b/internal/httpapi/assistant_process.go @@ -74,7 +74,6 @@ func (h *assistantHandlers) conversationExecutor(s *AgentToolSession, root strin request := domain.RunnerWorkspaceRequest{Operation: domain.RunnerWorkspaceOperationConversationCLI} workspace := "" if s.RuntimeMode == domain.AssistantModeWorkspace { - ctx = withAssistantDockerBuildProgress(ctx, s) runID := s.workspaceRun() run, ok := h.repo.RunState(runID) if !ok { @@ -166,6 +165,10 @@ func (h *assistantHandlers) conversationExecutor(s *AgentToolSession, root strin if (s.runnerLogin || s.transient) && !runner.SupportsCLISettings() { return preDispatchError(fmt.Errorf("执行机器需升级至 %s 才能使用对话本机登录和 CLI 测试", domain.RunnerVersionCLISettings)) } + if req.Command != nil && req.Command.Provider == assistantEngineCodeBuddy && + req.Command.Credentials.CodeBuddy.BaseURL != "" && !runner.SupportsCodeBuddyBaseURL() { + return preDispatchError(fmt.Errorf("执行机器需升级至 %s 才能使用 CodeBuddy Base URL", domain.RunnerVersionCodeBuddyBaseURL)) + } raw, err := json.Marshal(req) if err != nil { return preDispatchError(err) @@ -535,7 +538,10 @@ func (h *assistantHandlers) testRunnerCLI(ctx context.Context, runnerID, provide defer os.RemoveAll(root) model := provider + ":default" if provider == assistantEngineCodeBuddy { - model = assistantFixedCatalog().Default + model = loadAssistantModels(user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey).Default + if user.CodeBuddyBaseURL != "" { + model = personalCodeBuddyCatalog(ctx, user).Default + } } else if !runnerLogin { models, _ := assistantDiscoveredModelsFor(ctx, user, provider) if len(models) == 0 { diff --git a/internal/httpapi/assistant_provider.go b/internal/httpapi/assistant_provider.go index d58e8b98..50033f53 100644 --- a/internal/httpapi/assistant_provider.go +++ b/internal/httpapi/assistant_provider.go @@ -57,7 +57,7 @@ func validateAssistantProvider(req *assistantRequest, user domain.User) error { func assistantProviderCredentials(user domain.User) runtime.RunCredentials { return runtime.RunCredentials{ - CodeBuddy: runtime.CodeBuddyCredential{APIKey: user.CodeBuddyAPIKey, InternetEnvironment: user.CodeBuddyInternetEnvironment}, + CodeBuddy: runtime.CodeBuddyUserCredential(user), Codex: runtime.ProviderCredential{APIKey: user.CodexAPIKey, BaseURL: user.CodexBaseURL}, ClaudeCode: runtime.ProviderCredential{APIKey: user.ClaudeCodeAPIKey, BaseURL: user.ClaudeCodeBaseURL}, Extra: runtime.ExtraRunCredentials(user.ID), diff --git a/internal/httpapi/assistant_schedule.go b/internal/httpapi/assistant_schedule.go index dcfe1873..aa4288e3 100644 --- a/internal/httpapi/assistant_schedule.go +++ b/internal/httpapi/assistant_schedule.go @@ -102,7 +102,7 @@ func (h *assistantHandlers) runScheduleJobPromptResult(job domain.ScheduleJob, o if err != nil { return result, err } - model := strings.TrimSpace(job.AssistantModel) + model := scheduledAssistantDefault(h.repo, user, job.AssistantModel) if shared != nil { // On the shared key a run only uses the models the administrator // allows, and never silently switches to another one. @@ -148,9 +148,8 @@ func (h *assistantHandlers) runScheduleJobPromptResult(job domain.ScheduleJob, o // recorded owner for a legacy job. A bound job can only use that member's // credentials. The platform's CodeBuddy key is the last resort. func (h *assistantHandlers) scheduleJobAssistantUser(job domain.ScheduleJob, model string) (domain.User, []string, error) { - engine, _ := assistantModelEngine(model) if job.RunAsUserID > 0 { - return h.scheduleJobRunAsUser(job, engine) + return h.scheduleJobRunAsUser(job, model) } var candidates []domain.User add := func(id int64) { @@ -169,21 +168,26 @@ func (h *assistantHandlers) scheduleJobAssistantUser(job domain.ScheduleJob, mod } // Try each candidate's own credentials before considering the shared key. for _, user := range candidates { + engine, _ := assistantModelEngine(scheduledAssistantDefault(h.repo, user, model)) if scheduleHasPersonalCredential(h.repo, user, engine) { return user, nil, nil } } + engine, _ := assistantModelEngine(model) for _, user := range candidates { if user, shared, ok := scheduleCredentialUser(h.repo, user, engine); ok { return user, shared, nil } } + if assistantModelUnspecified(model) { + return domain.User{}, nil, fmt.Errorf("项目 Owner 缺少可用的执行器凭据。请编辑并保存一次任务,以你的凭据执行") + } return domain.User{}, nil, fmt.Errorf("项目 Owner 缺少 %s 凭据。请编辑并保存一次任务,以你的凭据执行", assistantEngineLabel(engine)) } // scheduleJobRunAsUser runs a bound job as that member while they can still // write to the project. -func (h *assistantHandlers) scheduleJobRunAsUser(job domain.ScheduleJob, engine string) (domain.User, []string, error) { +func (h *assistantHandlers) scheduleJobRunAsUser(job domain.ScheduleJob, model string) (domain.User, []string, error) { name := firstNonEmpty(job.RunAsName, fmt.Sprintf("用户 %d", job.RunAsUserID)) user, ok := h.repo.User(job.RunAsUserID) if !ok { @@ -192,8 +196,12 @@ func (h *assistantHandlers) scheduleJobRunAsUser(job domain.ScheduleJob, engine if !scheduleProjectWriter(h.repo, job.ProjectID, user) { return domain.User{}, nil, fmt.Errorf("%s 已不是该项目的可写成员,请编辑并保存一次任务,以你的凭据执行", name) } + engine, _ := assistantModelEngine(scheduledAssistantDefault(h.repo, user, model)) runUser, shared, ok := scheduleCredentialUser(h.repo, user, engine) if !ok { + if assistantModelUnspecified(model) { + return domain.User{}, nil, fmt.Errorf("任务保存人 %s 缺少可用的执行器凭据,请在个人配置中设置", name) + } if assistantSupportsRunnerLogin(engine) { return domain.User{}, nil, fmt.Errorf("任务保存人 %s 缺少 %s 凭据,请在其默认执行机器启用账号登录,或在个人配置填写 API Key", name, assistantEngineLabel(engine)) } @@ -228,6 +236,29 @@ func scheduleHasPersonalCredential(r *repo.Store, user domain.User, engine strin return key != "" || scheduleLoginRunner(r, user.ID, engine).ID != "" } +// Keep explicit schedule selections, including a CLI's own default. Unset +// legacy selections can use the actor's default or another available CLI. +func scheduledAssistantDefault(r *repo.Store, user domain.User, model string) string { + model = strings.TrimSpace(model) + if !assistantModelUnspecified(model) { + return model + } + if preferred := personalDefaultModel(user); preferred != "" { + return preferred + } + for _, option := range assistantEngineOptions(user, false) { + if !scheduleHasPersonalCredential(r, user, option.ID) { + continue + } + if option.ID == assistantEngineCodeBuddy { + // Resolve the legacy default with this account's CodeBuddy catalog. + return model + } + return featureDefaultModel(user, option.ID) + } + return model +} + // scheduleCredentialUser keeps the actor's identity, substituting only the // CodeBuddy key and its environment when the platform sponsors the run. func scheduleCredentialUser(r *repo.Store, user domain.User, engine string) (domain.User, []string, bool) { @@ -242,6 +273,7 @@ func scheduleCredentialUser(r *repo.Store, user domain.User, engine string) (dom return user, nil, false } user.CodeBuddyAPIKey = key.APIKey + user.CodeBuddyBaseURL = "" user.CodeBuddyInternetEnvironment = key.InternetEnvironment return user, key.Models, true } diff --git a/internal/httpapi/assistant_sponsor.go b/internal/httpapi/assistant_sponsor.go index a2366b74..98e88054 100644 --- a/internal/httpapi/assistant_sponsor.go +++ b/internal/httpapi/assistant_sponsor.go @@ -44,6 +44,7 @@ func (h *assistantHandlers) assistantChatUser(user domain.User) (chatUser domain return user, nil, false } user.CodeBuddyAPIKey = key.APIKey + user.CodeBuddyBaseURL = "" user.CodeBuddyInternetEnvironment = key.InternetEnvironment user.CodeBuddyModels = nil return user, key.Models, true @@ -69,12 +70,12 @@ func (h *assistantHandlers) usesSharedKey(user domain.User) bool { // 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(user domain.User) assistantModelCatalog { +func (h *assistantHandlers) chatCatalog(ctx context.Context, user domain.User) assistantModelCatalog { key, shared := h.assistantSharedKey() if !shared || !h.usesSharedKey(user) { - return withCodeBuddyPersonalModels(loadAssistantModels(user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey), user) + return withCodeBuddyPersonalModels(ctx, assistantChatCatalog(user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey, nil), user) } - return restrictAssistantCatalog(assistantChatCatalog(key.InternetEnvironment, key.APIKey, key.Models), key.Models) + return restrictAssistantCatalog(assistantChatCatalog(user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey, key.Models), key.Models) } // turnCatalog is chatCatalog for a turn on model. The CodeBuddy model list is @@ -82,19 +83,28 @@ func (h *assistantHandlers) chatCatalog(user domain.User) assistantModelCatalog // list, or before a restart, would otherwise be replaced by the default // without a word. A miss refreshes the list once before deciding. func (h *assistantHandlers) turnCatalog(ctx context.Context, user domain.User, model string) assistantModelCatalog { - catalog := h.chatCatalog(user) + catalog := h.chatCatalog(ctx, user) model = strings.TrimSpace(model) if model == "" || assistantCatalogLists(catalog, model) { return catalog } - refreshCLIModels(ctx, user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey) - catalog = h.chatCatalog(user) + refreshOfficialCodeBuddyModels(ctx, user) + catalog = h.chatCatalog(ctx, user) if !assistantCatalogLists(catalog, model) { log.Printf("assistant model %q is not offered to user %d after catalog refresh", model, user.ID) } return catalog } +func assistantCatalogLists(catalog assistantModelCatalog, id string) bool { + for _, model := range catalog.Models { + if model.ID == id { + return true + } + } + return false +} + // restrictAssistantCatalog keeps the allowed models, in the allowed order. func restrictAssistantCatalog(catalog assistantModelCatalog, allowed []string) assistantModelCatalog { byID := map[string]assistantModel{} diff --git a/internal/httpapi/assistant_sponsor_test.go b/internal/httpapi/assistant_sponsor_test.go index 80239bef..855cb008 100644 --- a/internal/httpapi/assistant_sponsor_test.go +++ b/internal/httpapi/assistant_sponsor_test.go @@ -26,8 +26,8 @@ func TestSharedCodeBuddyEffortsIgnoreAnOldPersonalOverride(t *testing.T) { h := &assistantHandlers{ deps: &deps{repo: st}, generate: func(_ context.Context, _ string, user domain.User) (string, error) { - if len(user.CodeBuddyModels) != 0 || user.ID != member.ID { - t.Error("shared-key turn must use its own catalog and keep the caller's identity") + if len(user.CodeBuddyModels) != 0 || user.CodeBuddyBaseURL != "" || user.ID != member.ID { + t.Error("shared-key turn must use its own endpoint and catalog while keeping the caller's identity") } return `{"message":"ok","drafts":[]}`, nil }, @@ -50,6 +50,14 @@ func TestSharedCodeBuddyEffortsIgnoreAnOldPersonalOverride(t *testing.T) { if err != nil || len(afterClear.CodeBuddyModels) != 1 { t.Fatalf("expected the personal model catalog to remain saved after clearing its key: %v", err) } + baseURL := "https://personal.example/v1" + member, err = st.UpdateUserCredentials(member.ID, repo.UserCredentialUpdate{CodeBuddyBaseURL: &baseURL}) + if err != nil { + t.Fatal(err) + } + if scheduled, _, ok := scheduleCredentialUser(st, member, assistantEngineCodeBuddy); !ok || scheduled.CodeBuddyBaseURL != "" { + t.Fatal("a scheduled run on the shared key must not use the caller's personal endpoint") + } c, rec := workbenchContext(afterClear, http.MethodGet, "/api/assistant/models", &bytes.Buffer{}) h.models(c) var catalog assistantModelCatalog @@ -200,7 +208,7 @@ func TestOwnKeyKeepsItsEnvironmentDefaultWhileAKeyIsShared(t *testing.T) { t.Fatalf("own-key catalog must list the user's environment only: %s", mrec.Body.String()) } - chat := h.chatCatalog(stored) + 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) } @@ -217,7 +225,7 @@ func TestOwnKeyKeepsItsEnvironmentDefaultWhileAKeyIsShared(t *testing.T) { } stored, _ = st.User(member.ID) borrowed, _, _ := h.assistantChatUser(stored) - if got := assistantAllowedModel("", h.chatCatalog(borrowed)); got != "glm-5.1" { + 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) } } @@ -302,7 +310,7 @@ func TestPlatformSharedKeyLimitsChatToAllowedModels(t *testing.T) { 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(used)); got != want { + if got := assistantAllowedModel(model, h.chatCatalog(context.Background(), used)); got != want { t.Fatalf("model %q resolves to %q, want %q", model, got, want) } } @@ -384,7 +392,7 @@ func TestTurnCatalogRefreshesBeforeFallingBackToTheDefault(t *testing.T) { } stored, _ := st.User(member.ID) h := &assistantHandlers{deps: &deps{repo: st}} - if got := assistantAllowedModel("claude-opus-5.5", h.chatCatalog(stored)); got == "claude-opus-5.5" { + if got := assistantAllowedModel("claude-opus-5.5", h.chatCatalog(context.Background(), stored)); got == "claude-opus-5.5" { t.Fatalf("precondition: a cold cache must not list the model yet") } if got := assistantAllowedModel("claude-opus-5.5", h.turnCatalog(context.Background(), stored, "claude-opus-5.5")); got != "claude-opus-5.5" { diff --git a/internal/httpapi/assistant_task_engines_test.go b/internal/httpapi/assistant_task_engines_test.go index c4e8f6d5..4125a0c2 100644 --- a/internal/httpapi/assistant_task_engines_test.go +++ b/internal/httpapi/assistant_task_engines_test.go @@ -18,6 +18,7 @@ func TestAssistantScheduledModelKeepsCLIModels(t *testing.T) { for in, want := range map[string]string{ "codex:gpt-6-sol": "codex:gpt-6-sol", " claude-code:opus ": "claude-code:opus", + "codebuddy:default": "codebuddy:default", catalog.Default: catalog.Default, "glm-5.3-ioa": "glm-5.3-ioa", " unknown-model ": "unknown-model", @@ -93,6 +94,10 @@ func TestScheduledTaskRunsOnTaskCLI(t *testing.T) { t.Fatalf("missing claude key = %v %q", err, task.LastError) } task.Model = "" + if err := h.executeAssistantTask(context.Background(), user, &task); err != nil || !strings.HasPrefix(task.Model, "codex:") { + t.Fatalf("unset scheduled model did not use Codex: %v %q", err, task.Model) + } + task.Model = "codebuddy:default" if err := h.executeAssistantTask(context.Background(), user, &task); err == nil || !strings.Contains(task.LastError, "CodeBuddy API Key") { t.Fatalf("missing codebuddy key = %v %q", err, task.LastError) } @@ -105,8 +110,10 @@ func TestScheduleJobAssistantUserNeedsModelCLIKey(t *testing.T) { _ = st.PutProject(domain.Project{ID: "owner-project", Name: "Owner", OwnerID: owner.ID}) h := &assistantHandlers{deps: &deps{repo: st}} job := domain.ScheduleJob{ProjectID: "owner-project"} - if got, shared, err := h.scheduleJobAssistantUser(job, "codex:gpt-6-sol"); err != nil || got.ID != owner.ID || shared != nil { - t.Fatalf("codex owner = %+v %v %v", got, shared, err) + for _, model := range []string{"codex:gpt-6-sol", "default", ""} { + if got, shared, err := h.scheduleJobAssistantUser(job, model); err != nil || got.ID != owner.ID || shared != nil { + t.Fatalf("codex owner for %q = %+v %v %v", model, got, shared, err) + } } if _, _, err := h.scheduleJobAssistantUser(job, "glm-5.3-ioa"); err == nil || !strings.Contains(err.Error(), "CodeBuddy") { t.Fatalf("codebuddy without key = %v", err) diff --git a/internal/httpapi/assistant_tasks.go b/internal/httpapi/assistant_tasks.go index 53c4ac99..ab9f5364 100644 --- a/internal/httpapi/assistant_tasks.go +++ b/internal/httpapi/assistant_tasks.go @@ -132,11 +132,12 @@ func (h *assistantHandlers) runTaskNow(c *gin.Context) { } user, ok := h.repo.User(current.ID) task, err := loadAssistantTask(h.repo, current.ID, c.Param("id")) - engine, _ := assistantModelEngine(task.Model) + model := scheduledAssistantDefault(h.repo, user, task.Model) + engine, _ := assistantModelEngine(model) if !ok || !scheduleHasPersonalCredential(h.repo, user, engine) { - msg := "请先在个人配置中配置自己的 CodeBuddy API Key" - if engine != assistantEngineCodeBuddy { - msg = assistantEngineMissingKey(engine) + msg := assistantEngineMissingKey(engine) + if assistantModelUnspecified(model) { + msg = errFeatureCredentials.Error() } c.JSON(400, gin.H{"error": msg}) return @@ -230,7 +231,8 @@ func (h *assistantHandlers) executeAssistantTask(ctx context.Context, user domai if strings.TrimSpace(task.ID) != "" { _ = saveAssistantTask(h.repo, user.ID, *task) } - engine, _ := assistantModelEngine(task.Model) + model := scheduledAssistantDefault(h.repo, user, task.Model) + engine, _ := assistantModelEngine(model) machine := scheduleLoginRunner(h.repo, user.ID, engine) machineOffline := machine.ID != "" && machine.Status != domain.RunnerStatusOnline fail := func(msg string) error { @@ -246,7 +248,6 @@ func (h *assistantHandlers) executeAssistantTask(ctx context.Context, user domai } // Select the credential and machine before creating the conversation. - model := strings.TrimSpace(task.Model) var target *domain.AssistantExecutionTarget if machine.ID != "" && !machineOffline { target = &domain.AssistantExecutionTarget{Pool: domain.ExecutionModeRunner, RunnerID: machine.ID} @@ -255,10 +256,10 @@ func (h *assistantHandlers) executeAssistantTask(ctx context.Context, user domai if machineOffline { return fail(fmt.Sprintf("未配置 %s API Key。请启动 Runner,或在个人配置中填写 Key 后重试", assistantEngineLabel(engine))) } - if engine != assistantEngineCodeBuddy { - return fail(assistantEngineMissingKey(engine)) + if assistantModelUnspecified(model) { + return fail(errFeatureCredentials.Error()) } - return fail("未配置 CodeBuddy API Key") + return fail(assistantEngineMissingKey(engine)) } var err error if model, err = scheduledRunModel(ctx, model, user); err != nil { @@ -493,17 +494,22 @@ func firstNonEmpty(values ...string) string { // silently switches to another, possibly more expensive, model. func scheduledRunModel(ctx context.Context, requested string, user domain.User) (string, error) { requested = strings.TrimSpace(requested) - env := user.CodeBuddyInternetEnvironment - catalog := withCodeBuddyPersonalModels(loadAssistantModels(env, user.CodeBuddyAPIKey), user) - model := assistantAllowedUserModel(requested, catalog, user) - if requested == "" || model == requested { - return model, nil - } - if engine, _ := assistantModelEngine(requested); engine == assistantEngineCodeBuddy { - refreshCLIModels(ctx, env, user.CodeBuddyAPIKey) - if model = assistantAllowedUserModel(requested, loadAssistantModels(env, user.CodeBuddyAPIKey), user); model == requested { + engine, id := assistantModelEngine(requested) + if engine == assistantEngineCodeBuddy { + env := user.CodeBuddyInternetEnvironment + catalog := withCodeBuddyPersonalModels(ctx, loadAssistantModels(env, user.CodeBuddyAPIKey), user) + if id == "" || codeBuddyIsDefaultModel(id) { + return catalog.Default, nil + } + if model := assistantAllowedModel(id, catalog); model == id { return model, nil } + refreshOfficialCodeBuddyModels(ctx, user) + if model := assistantAllowedModel(id, loadAssistantModels(env, user.CodeBuddyAPIKey)); model == id { + return model, nil + } + } else if model := assistantAllowedUserModel(requested, assistantModelCatalog{}, user); model == requested { + return model, nil } return "", fmt.Errorf("定时任务指定的模型 %s 在负责人的账号下不可用,本次没有运行;请在定时任务里改选可用的模型", requested) } diff --git a/internal/httpapi/assistant_title.go b/internal/httpapi/assistant_title.go index 494ea353..9f53a1b5 100644 --- a/internal/httpapi/assistant_title.go +++ b/internal/httpapi/assistant_title.go @@ -116,10 +116,10 @@ func (h *assistantHandlers) scheduleAssistantTitle(ctx context.Context, ownerID // assistantTitleModel picks the model and effort that name a session. // CodeBuddy uses its cheapest model, limited to shared when the turn borrows -// the platform key. Other CLIs reuse the session's model at its weakest +// the platform key. Other CLIs and custom gateways reuse the session's model at its weakest // effort; the gateway behind a Base URL may serve nothing else. func assistantTitleModel(ctx context.Context, user domain.User, model string, shared []string) (string, string) { - if engine, _ := assistantModelEngine(model); engine != assistantEngineCodeBuddy { + if engine, _ := assistantModelEngine(model); engine != assistantEngineCodeBuddy || user.CodeBuddyBaseURL != "" { if efforts := assistantModelEfforts(ctx, user, model); len(efforts) > 0 { return model, efforts[0] } diff --git a/internal/httpapi/auth_binary_cases_test.go b/internal/httpapi/auth_binary_cases_test.go index 1e2c1534..28ebed6d 100644 --- a/internal/httpapi/auth_binary_cases_test.go +++ b/internal/httpapi/auth_binary_cases_test.go @@ -197,6 +197,7 @@ func TestGinMiddlewareAndSmallViews(t *testing.T) { } func TestGongfengOAuthAuthenticatedStart(t *testing.T) { + t.Setenv("AGENTFLOW_GONGFENG_HOST", "git.review.test") f := cvBNewHTTPFixture(t) t.Setenv("AGENTFLOW_GONGFENG_OAUTH_CLIENT_ID", "client") t.Setenv("AGENTFLOW_GONGFENG_OAUTH_CLIENT_SECRET", "secret") diff --git a/internal/httpapi/bot_interactions.go b/internal/httpapi/bot_interactions.go index 61946389..1d334ee4 100644 --- a/internal/httpapi/bot_interactions.go +++ b/internal/httpapi/bot_interactions.go @@ -7,6 +7,7 @@ import ( "context" "errors" "fmt" + "os" "strings" ) @@ -71,14 +72,15 @@ func (h *assistantHandlers) generateBotReply(ctx context.Context, bot domain.Not if err != nil { return "绑定的平台账号不可用或已失去项目权限,请在平台检查配置。", nil } - if strings.TrimSpace(user.CodeBuddyAPIKey) == "" { - return "你的平台账号尚未配置 CodeBuddy Key,请在平台个人配置中配置。", nil - } - model := bot.Model - if model == "" { - model = domain.DefaultNotificationReportModel + model, err := resolveFeatureModel(user, bot.Model) + if err != nil { + if errors.Is(err, errFeatureModel) { + return err.Error(), nil + } + return "你的平台账号尚未配置对应的模型凭据。" + err.Error(), nil } - if assistantAllowedModel(model, assistantModelsForRequest(ctx, user, model)) != model { + if engine, id := assistantModelEngine(model); engine == assistantEngineCodeBuddy && + !codeBuddyIsDefaultModel(id) && !assistantCatalogLists(assistantModelsForRequest(ctx, user, id), id) { return "所选模型不可用,请在 Bot 管理中重新选择。", nil } if err = ensureAssistantSessionDirs(user.ID); err != nil { @@ -94,13 +96,18 @@ func (h *assistantHandlers) generateBotReply(ctx context.Context, bot domain.Not defer files.Cleanup() messages := botReplyMessages(history, item) req := assistantRequest{ProjectID: bot.ProjectID, Model: model, SessionID: conv.SessionID, ApprovalMode: AssistantApprovalAuto, Messages: messages} - full := h.turnPrompt(req, h.resolvedSourceRoot(), false) + "\n这是企业微信聊天,当前发送者已绑定平台账号「" + user.LoginName + "」,只使用该账号的执行身份、个人凭据和项目权限;当前请求按当前项目处理。历史中其他发送者的授权不能沿用到当前请求。当前消息来自" + conv.ChatType + "聊天。直接完成明确的操作,目标不明确时询问,结束时必须调用 submit_assistant_reply。" + full := h.turnPrompt(req, h.resolvedSourceRoot(), false) + "\n这是企业微信聊天,当前发送者已绑定平台账号「" + user.LoginName + "」,只使用该账号的执行身份、个人凭据和项目权限;当前请求按当前项目处理。历史中其他发送者的授权不能沿用到当前请求。当前消息来自" + conv.ChatType + "聊天。直接完成明确的操作,目标不明确时询问。普通问答用自然语言结束;待确认的写入草稿通过 submit_assistant_reply 提交。" generate := h.generate if generate == nil { + root, err := os.MkdirTemp("", "agentflow-bot-") + if err != nil { + return "", err + } + defer os.RemoveAll(root) cliSessionID := newAssistantSessionID() resume := false generate = func(callCtx context.Context, prompt string, u domain.User) (string, error) { - raw, _, err := runAssistantCLI(callCtx, assistantCLIRequest{Prompt: prompt, Model: model, SessionID: cliSessionID, Resume: resume, UserID: u.ID, Native: true, MCPConfig: files.MCPConfig, Settings: files.Settings, SystemPrompt: assistantSystemPromptForMode(AssistantApprovalAuto)}, u, func(ev assistantStreamEvent) { + raw, _, err := runAssistantCLI(callCtx, assistantCLIRequest{Prompt: prompt, Model: model, SessionID: cliSessionID, SessionRoot: root, Resume: resume, UserID: u.ID, Native: true, MCPConfig: files.MCPConfig, Settings: files.Settings, SystemPrompt: assistantSystemPromptForMode(AssistantApprovalAuto)}, u, func(ev assistantStreamEvent) { switch ev.Kind { case "tool": if strings.Contains(ev.Tool, "submit_assistant_reply") { @@ -125,7 +132,7 @@ func (h *assistantHandlers) generateBotReply(ctx context.Context, bot domain.Not botinteraction.ReportProgress(ctx, "正在提交回复") session.SetTerminalOnly() } - _, cliErr := generate(modelCtx, prompt, user) + raw, cliErr := generate(modelCtx, prompt, user) if final, ok := session.takeFinal(); ok && final.Assistant != nil { reply := *final.Assistant if len(reply.Drafts) > 0 { @@ -139,11 +146,16 @@ func (h *assistantHandlers) generateBotReply(ctx context.Context, bot domain.Not } } } - return redactAssistantSecrets(strings.ReplaceAll(reply.Message, user.CodeBuddyAPIKey, "[redacted]"), user), nil + return redactAssistantSecrets(reply.Message, user), nil } if ctx.Err() != nil { return "", ctx.Err() } + if cliErr == nil { + if reply, ok := recoverNativeAssistantReply(raw, bot.ProjectID); ok && len(reply.Drafts) == 0 && !assistantProgressOnly(reply.Message, messages) { + return redactAssistantSecrets(reply.Message, user), nil + } + } if cliErr != nil && !nativeShouldRetryTerminal(ctx, cliErr) { return "", cliErr } diff --git a/internal/httpapi/bot_interactions_test.go b/internal/httpapi/bot_interactions_test.go index 6ea1513a..fb1c74d1 100644 --- a/internal/httpapi/bot_interactions_test.go +++ b/internal/httpapi/bot_interactions_test.go @@ -152,7 +152,7 @@ func TestBotMissingSubmissionRetriesOnlyTerminalStep(t *testing.T) { h.generate = func(ctx context.Context, prompt string, user domain.User) (string, error) { calls++ if calls == 1 { - return "查询结果已经准备好,但未提交终态", nil + return "请稍等,我正在查询项目的运行记录。", nil } if strings.Contains(prompt, "原始查询标记") || !strings.Contains(prompt, "不要重新查询") { t.Fatal("retry restarted task", prompt) diff --git a/internal/httpapi/catalog.go b/internal/httpapi/catalog.go index 54fd6414..912a71eb 100644 --- a/internal/httpapi/catalog.go +++ b/internal/httpapi/catalog.go @@ -146,7 +146,7 @@ func (h *catalogHandlers) repositories(c *gin.Context) { h.saveRepository(c, v) return } - // One pasted repository reference (web / SSH / clone / git clone / group/repo) + // One pasted repository reference (web / SSH / clone / git clone) // An unknown HTTPS host is a Git transport, not an unknown hosting adapter. _, knownHost := domain.ParseRepositoryURL(sshReference) if v.Provider == domain.RepositoryProviderHTTPS || !knownHost && strings.HasPrefix(strings.TrimPrefix(sshReference, "git clone "), "https://") { @@ -182,7 +182,7 @@ func (h *catalogHandlers) repositories(c *gin.Context) { h.saveRepository(c, v) return } - // One pasted repository reference (web / SSH / clone / git clone / group/repo) + // One pasted repository reference (web / SSH / clone / git clone) // is enough. Prefer repoUrl so an SSH paste keeps an SSH clone URL. var parsed domain.GongfengRepoInfo var parsedOK bool @@ -197,7 +197,7 @@ func (h *catalogHandlers) repositories(c *gin.Context) { if primary != "" { info, ok := domain.ParseRepositoryURL(primary) if !ok { - c.JSON(400, gin.H{"error": "仓库 URL 无法识别,请提供 GitHub 链接或 Git SSH 克隆地址"}) + c.JSON(400, gin.H{"error": "请填写完整的 GitHub、HTTPS 或 Git SSH 仓库地址"}) return } if body.RepoURL != "" && body.URL != "" { @@ -218,6 +218,12 @@ func (h *catalogHandlers) repositories(c *gin.Context) { if v.GongfengProjectID != "" { if info, ok := domain.ParseRepositoryURL(v.GongfengProjectID); ok { v.GongfengProjectID = info.Project + } else if info, ok := domain.ParseGongfengRepoURL(v.GongfengProjectID); ok && !strings.ContainsAny(v.GongfengProjectID, ":@") { + // An explicit legacy project ID is different from a pasted repoUrl. + v.GongfengProjectID = info.Project + if !parsedOK { + parsed, parsedOK = info, true + } } else if !strings.HasPrefix(v.GongfengProjectID, "github:") && !domain.IsSafeGongfengProjectID(v.GongfengProjectID) { c.JSON(400, map[string]string{"error": "仓库链接无法识别:请提供有效的 GitHub 仓库地址"}) return @@ -239,7 +245,7 @@ func (h *catalogHandlers) repositories(c *gin.Context) { } if v.GongfengProjectID != "" { if v.WebURL == "" { - v.WebURL = "https://" + domain.GongfengRepoHost + "/" + v.GongfengProjectID + v.WebURL = "https://" + domain.GongfengRepositoryHost() + "/" + v.GongfengProjectID } if v.CloneURL == "" { v.CloneURL = v.WebURL + ".git" @@ -340,15 +346,7 @@ func (h *catalogHandlers) agents(c *gin.Context) { if !h.requireProjectWriter(c, v.ProjectID) { return } - if strings.TrimSpace(v.ExecutorID) == "" { - v.ExecutorID = "codebuddy" - } - builtIn, ok := repo.BuiltInExecutor(v.ExecutorID) - if !ok { - c.JSON(http.StatusBadRequest, map[string]string{"error": "不支持的 CLI:" + v.ExecutorID}) - return - } - if err := domain.ValidateAgentEffort(v.Effort, builtIn.Kind); err != nil { + if err := validateCatalogAgentExecutor(&v); err != nil { c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()}) return } @@ -375,6 +373,25 @@ func (h *catalogHandlers) agents(c *gin.Context) { } } +func validateCatalogAgentExecutor(agent *domain.AgentDefinition) error { + agent.ExecutorID = strings.TrimSpace(agent.ExecutorID) + agent.Model = strings.TrimSpace(agent.Model) + agent.Effort = strings.TrimSpace(agent.Effort) + if agent.ExecutorID == "" { + if (agent.Model == "" || agent.Model == "default") && agent.Effort == "" { + agent.Model = "" + return nil + } + // Old API callers could pin a CodeBuddy model or effort using only its ID. + agent.ExecutorID = "codebuddy" + } + executor, ok := repo.BuiltInExecutor(agent.ExecutorID) + if !ok { + return fmt.Errorf("不支持的 CLI:%s", agent.ExecutorID) + } + return domain.ValidateAgentEffort(agent.Effort, executor.Kind) +} + func filterAgentsForProject(agents []domain.AgentDefinition, projectID string) []domain.AgentDefinition { out := make([]domain.AgentDefinition, 0, len(agents)) for _, agent := range agents { @@ -1064,6 +1081,12 @@ func (h *catalogHandlers) workflows(c *gin.Context) { return } + if id := v.Preview.SelectedExecutorID(); v.Preview.Static() && id != "" { + if _, supported := repo.BuiltInExecutor(id); !supported { + c.JSON(http.StatusBadRequest, gin.H{"error": "前端预览使用了不支持的 CLI:" + id}) + return + } + } if err := domain.ValidateWorkflowPreparation(v); err != nil { c.JSON(400, gin.H{"error": err.Error()}) return @@ -1240,6 +1263,25 @@ func (h *catalogHandlers) workflow(c *gin.Context) { return } c.JSON(200, stored) + case "/api/workflows/:id/executor-requirements": + if !v.Generic { + c.JSON(http.StatusNotFound, gin.H{"error": "generic template not found"}) + return + } + var userID int64 + projectID := strings.TrimSpace(c.Query("projectId")) + if user, ok := h.requestUser(c.Request, true); ok { + userID = user.ID + } else if project, ok := h.repo.Project(projectID); ok && !authRequired() { + userID = project.OwnerID + } + rows, err := h.engine.SOPExecutorRequirements(v, userID, projectID) + if err != nil { + respond(c, err) + return + } + c.Header("Cache-Control", "private, no-store") + c.JSON(http.StatusOK, rows) case "/api/workflows/:id/agents": template, ok := h.repo.GenericTemplateByWorkflow(id) if !ok { @@ -1258,15 +1300,7 @@ func (h *catalogHandlers) workflow(c *gin.Context) { if !decode(c, &agent) { return } - if strings.TrimSpace(agent.ExecutorID) == "" { - agent.ExecutorID = "codebuddy" - } - builtIn, ok := repo.BuiltInExecutor(agent.ExecutorID) - if !ok { - c.JSON(http.StatusBadRequest, map[string]string{"error": "不支持的 CLI:" + agent.ExecutorID}) - return - } - if err := domain.ValidateAgentEffort(agent.Effort, builtIn.Kind); err != nil { + if err := validateCatalogAgentExecutor(&agent); err != nil { c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()}) return } diff --git a/internal/httpapi/clarify_engine_test.go b/internal/httpapi/clarify_engine_test.go index 042566aa..f7f65b53 100644 --- a/internal/httpapi/clarify_engine_test.go +++ b/internal/httpapi/clarify_engine_test.go @@ -8,28 +8,13 @@ import ( "net/http/httptest" "strings" "testing" + "time" "agentflow/internal/domain" "agentflow/internal/repo" ) -// Issue #228: clarification and run evals run on CodeBuddy only. A model of -// another CLI ("codex:…") must be refused up front, not silently swapped for -// the CodeBuddy default. -func TestClarifyModelEngineError(t *testing.T) { - for _, id := range []string{"", "default", "glm-5.1", "public-model"} { - if err := clarifyModelEngineError(id); err != nil { - t.Fatalf("CodeBuddy model %q refused: %v", id, err) - } - } - for _, id := range []string{"codex:gpt-5.5", "claude-code:sonnet"} { - if err := clarifyModelEngineError(id); err != errClarifyNeedsCodeBuddy { - t.Fatalf("model %q = %v, want errClarifyNeedsCodeBuddy", id, err) - } - } -} - -func TestChatClarifyRefusesOtherCLIModel(t *testing.T) { +func TestChatClarifyRejectsInvalidModel(t *testing.T) { called := false setClarifyExecForTest(func(context.Context, domain.Issue, chatClarifyRequest, func(string, any)) (any, string, map[string]any, error) { called = true @@ -38,7 +23,7 @@ func TestChatClarifyRefusesOtherCLIModel(t *testing.T) { t.Cleanup(func() { setClarifyExecForTest(nil) }) _, h := clarifyTestServer(t) - body, _ := json.Marshal(map[string]any{"projectId": "platform", "message": "加个徽章", "model": "codex:gpt-5.5"}) + body, _ := json.Marshal(map[string]any{"projectId": "platform", "message": "加个徽章", "model": "codex:"}) req := httptest.NewRequest(http.MethodPost, "/api/chat-clarify", bytes.NewReader(body)) req.Header.Set("Content-Type", "application/json") rec := httptest.NewRecorder() @@ -46,15 +31,15 @@ func TestChatClarifyRefusesOtherCLIModel(t *testing.T) { if rec.Code != http.StatusBadRequest { t.Fatalf("status = %d, want 400: %s", rec.Code, rec.Body.String()) } - if !strings.Contains(rec.Body.String(), "只支持 CodeBuddy") { - t.Fatalf("error does not explain the CodeBuddy limit: %s", rec.Body.String()) + if !strings.Contains(rec.Body.String(), "请选择有效的 CLI 模型") { + t.Fatalf("error does not explain invalid model: %s", rec.Body.String()) } if called { - t.Fatal("clarification started with a Codex model") + t.Fatal("clarification started with an invalid model") } } -func TestRunEvalRefusesOtherCLIModel(t *testing.T) { +func TestRunEvalRequiresSelectedCLICredentials(t *testing.T) { f := cvBNewHTTPFixture(t) if _, err := f.s.UpdateUserCredentials(f.user.ID, repo.UserCredentialUpdate{CodeBuddyAPIKey: "eval-key"}); err != nil { t.Fatal(err) @@ -65,10 +50,46 @@ func TestRunEvalRefusesOtherCLIModel(t *testing.T) { t.Fatal(err) } rec := cvBRequest(t, f, http.MethodPost, "/api/runs/eval-codex-run/eval", map[string]any{"model": "codex:gpt-5.5"}, true) - if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "只支持 CodeBuddy") { - t.Fatalf("status = %d body = %s, want 400 explaining the CodeBuddy limit", rec.Code, rec.Body.String()) + if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "Codex API Key") { + t.Fatalf("status = %d body = %s, want 400 asking for the selected CLI credential", rec.Code, rec.Body.String()) } if _, busy := f.s.ActiveRunEval(done.ID); busy { - t.Fatal("a Codex model must not start a run eval") + t.Fatal("a model without matching credentials must not start an eval") + } +} + +func TestRunEvalPreservesSelectedModelInChunkedRequest(t *testing.T) { + f := cvBNewHTTPFixture(t) + if _, err := f.s.UpdateUserCredentials(f.user.ID, repo.UserCredentialUpdate{CodexAPIKey: "eval-fixture"}); err != nil { + t.Fatal(err) + } + run := domain.Run{ID: "eval-chunked", Status: "succeeded", WorkflowID: "missing", ExecutionContext: domain.TelemetryContext{ProjectID: "platform"}} + if err := f.s.PutRun(run); err != nil { + t.Fatal(err) + } + selected := make(chan string, 1) + setRunEvalExecForTest(func(_ context.Context, rec domain.RunEvalRecord, _ domain.Run, user domain.User, _ func(string, any)) (domain.RunEvalResult, error) { + if user.ID == f.user.ID && user.CodexAPIKey == "eval-fixture" { + selected <- rec.Model + } + return domain.RunEvalResult{}, nil + }) + t.Cleanup(func() { setRunEvalExecForTest(nil) }) + req := httptest.NewRequest(http.MethodPost, "/api/runs/eval-chunked/eval", strings.NewReader(`{"model":"codex:private-model"}`)) + req.Header.Set("Content-Type", "application/json") + req.ContentLength = -1 + req.TransferEncoding = []string{"chunked"} + rec := httptest.NewRecorder() + f.h.ServeHTTP(rec, authedRequest(t, req, f.user)) + if rec.Code != http.StatusAccepted { + t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String()) + } + select { + case model := <-selected: + if model != "codex:private-model" { + t.Fatalf("job received the wrong explicit model: %q", model) + } + case <-time.After(3 * time.Second): + t.Fatal("eval job did not receive the requesting account's credential") } } diff --git a/internal/httpapi/clarify_mcp.go b/internal/httpapi/clarify_mcp.go index 15c5fdba..515c90e4 100644 --- a/internal/httpapi/clarify_mcp.go +++ b/internal/httpapi/clarify_mcp.go @@ -3,8 +3,8 @@ package httpapi import ( "context" "encoding/json" - "errors" "fmt" + "net/url" "path/filepath" "regexp" "strconv" @@ -19,28 +19,10 @@ const ( ) var ( - tapdURLRe = regexp.MustCompile(`(?i)https?://(?:www\.)?(?:tapd\.example\.com|tapd\.cn)[^\s<>"')】\]]+`) - gongfengIssueURLRe = regexp.MustCompile(`(?i)https?://git\.example\.com/[^\s<>"')】\]]+/issues/\d+`) + clarifyWebURL = regexp.MustCompile(`(?i)https?://[^\s<>"')】\]]+`) + gongfengIssueURLRe = regexp.MustCompile(`(?i)https?://[^/\s<>"')】\]]+/[^\s<>"')】\]]+/issues/\d+`) ) -func clarifyAllowedModel(ctx context.Context, user domain.User, id string) string { - return assistantAllowedModel(id, assistantModelsForRequest(ctx, user, id)) -} - -// errClarifyNeedsCodeBuddy is returned when a clarification asks for a model of -// another CLI: clarification runs on CodeBuddy only, so a "codex:…" id must be -// refused instead of being swapped for the CodeBuddy default. -var errClarifyNeedsCodeBuddy = errors.New("需求澄清目前只支持 CodeBuddy 模型,请在模型列表中改选 CodeBuddy 模型") - -// clarifyModelEngineError reports whether id names a model of a CLI that -// requirement clarification cannot run. -func clarifyModelEngineError(id string) error { - if engine, _ := assistantModelEngine(id); engine != assistantEngineCodeBuddy { - return errClarifyNeedsCodeBuddy - } - return nil -} - func asStringKeyMap(v any) map[string]any { m, ok := v.(map[string]any) if !ok || m == nil { @@ -191,7 +173,7 @@ func extractTAPDRefs(texts ...string) []clarifyTAPDHit { seen := map[string]bool{} var out []clarifyTAPDHit for _, text := range texts { - for _, match := range tapdURLRe.FindAllString(text, -1) { + for _, match := range clarifyWebURL.FindAllString(text, -1) { raw := strings.TrimRight(match, ".,;:,。;:") ref, err := tracker.ParseTAPDStoryURL(raw) if err != nil || ref.StoryID == "" || seen[ref.StoryID] { @@ -240,8 +222,12 @@ func gongfengProjectPathFromClarifyURL(raw string) string { return "" } path := raw - if i := strings.Index(strings.ToLower(raw), "git.example.com/"); i >= 0 { - path = raw[i+len("git.example.com/"):] + if strings.Contains(raw, "://") { + u, err := url.Parse(raw) + if err != nil || u.User != nil || !domain.IsGongfengHost(u.Host) { + return "" + } + path = u.Path } parts := strings.FieldsFunc(path, func(r rune) bool { return r == '/' }) for i, part := range parts { diff --git a/internal/httpapi/clarify_mcp_test.go b/internal/httpapi/clarify_mcp_test.go index 421bf66b..07871385 100644 --- a/internal/httpapi/clarify_mcp_test.go +++ b/internal/httpapi/clarify_mcp_test.go @@ -1,7 +1,6 @@ package httpapi import ( - "context" "encoding/json" "fmt" "io" @@ -14,29 +13,6 @@ import ( "agentflow/internal/repo" ) -func TestClarifyAllowedModelFallsBackToCatalog(t *testing.T) { - t.Setenv("AGENTFLOW_ASSISTANT_MODEL", "") - t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "public-model") - stubCLIModelDiscovery(t) - discoverCLIModels = func(_ context.Context, _, key string) []string { - return []string{key + "-model"} - } - ctx := context.Background() - refreshCLIModels(ctx, "ioa", "another-key") - user := domain.User{CodeBuddyInternetEnvironment: "ioa", CodeBuddyAPIKey: "responsible-key"} - for requested, want := range map[string]string{ - "": clarifyDefaultModel, - "another-key-model": clarifyDefaultModel, - "not-a-model": clarifyDefaultModel, - "public-model": "public-model", - "responsible-key-model": "responsible-key-model", - } { - if got := clarifyAllowedModel(ctx, user, requested); got != want { - t.Errorf("requested %q: model = %q, want %q", requested, got, want) - } - } -} - func TestClarifyCommandKeepsReadGrepGlob(t *testing.T) { command, err := prepareClarifyCommand("codebuddy", clarifyDefaultModel, "prompt", "clarify-test", "af1", false) if err != nil { diff --git a/internal/httpapi/clarify_source.go b/internal/httpapi/clarify_source.go new file mode 100644 index 00000000..105d4f52 --- /dev/null +++ b/internal/httpapi/clarify_source.go @@ -0,0 +1,144 @@ +package httpapi + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "io/fs" + "maps" + "os" + "path/filepath" + "slices" + "strings" + "unicode/utf8" +) + +var clarifySourceTools = []agentToolDescriptor{ + {Name: "clarify_list_files", Kind: "clarify-source", Description: "List available repositories, or list one directory in a repository. Use offset to page through long directories.", InputSchema: json.RawMessage(`{"type":"object","properties":{"repository":{"type":"string"},"path":{"type":"string"},"offset":{"type":"integer","minimum":0}}}`)}, + {Name: "clarify_read_file", Kind: "clarify-source", Description: "Read a text file from this turn's analysis checkout. Use the returned nextOffset (byte offset) to continue.", InputSchema: json.RawMessage(`{"type":"object","required":["repository","path"],"properties":{"repository":{"type":"string"},"path":{"type":"string"},"offset":{"type":"integer","minimum":0}}}`)}, +} + +func readClarifySource(session *AgentToolSession, tool string, args map[string]any) (string, error) { + if session.Mode != AgentToolClarify { + return "", errAgentToolForbidden + } + repository, _ := args["repository"].(string) + session.mu.Lock() + repos := session.clarifyRepos + session.mu.Unlock() + if repository == "" && tool == "clarify_list_files" { + body, err := json.Marshal(slices.Sorted(maps.Keys(repos))) + return string(body), err + } + dir, ok := repos[repository] + if !ok { + return "", fmt.Errorf("repository is not in the analysis scope") + } + path, _ := args["path"].(string) + if path == "" { + path = "." + } + root, err := os.OpenRoot(dir) + if err != nil { + return "", fmt.Errorf("analysis repository unavailable") + } + defer root.Close() + list := tool == "clarify_list_files" + if !clarifySourcePathAllowed(root, path, list) { + return "", fmt.Errorf("path is not available in the analysis checkout") + } + file, err := root.Open(path) + if err != nil { + return "", fmt.Errorf("cannot open analysis path") + } + defer file.Close() + offset := int64(0) + if value, ok := args["offset"].(json.Number); ok { + var parseErr error + offset, parseErr = value.Int64() + if parseErr != nil || offset < 0 || offset > 4<<20 { + return "", fmt.Errorf("invalid offset") + } + } + if list { + return listClarifySource(file, int(offset)) + } + if _, err := file.Seek(offset, io.SeekStart); err != nil { + return "", fmt.Errorf("cannot seek analysis file") + } + const limit = 16 << 10 + body, err := io.ReadAll(io.LimitReader(file, limit+utf8.UTFMax)) + if err != nil || bytes.IndexByte(body, 0) >= 0 { + return "", fmt.Errorf("analysis file must be readable text") + } + result := map[string]any{"text": string(body)} + if len(body) > limit { + end := limit + for end < len(body) && !utf8.RuneStart(body[end]) { + end++ + } + result["text"] = string(body[:end]) + result["nextOffset"] = offset + int64(end) + } + data, err := json.Marshal(result) + return string(data), err +} + +func clarifySourcePathAllowed(root *os.Root, path string, directory bool) bool { + if !fs.ValidPath(path) || workspacePathSensitive(path) { + return false + } + component := "" + parts := strings.Split(path, "/") + for i, part := range parts { + component = filepath.Join(component, part) + info, err := root.Lstat(component) + if err != nil { + return false + } + if directory || i < len(parts)-1 { + if !info.IsDir() { + return false + } + } else if !info.Mode().IsRegular() { + return false + } + } + return true +} + +func listClarifySource(dir *os.File, offset int) (string, error) { + // Bound directory scanning independently of the result page size. + const scanLimit = 4096 + if offset >= scanLimit { + return "", fmt.Errorf("directory listing limit reached") + } + entries, err := dir.ReadDir(scanLimit) + if err != nil && err != io.EOF { + return "", fmt.Errorf("cannot list analysis directory") + } + names := make([]string, 0, len(entries)) + for _, entry := range entries { + if workspaceTreeSkipped(entry.Name(), entry) || (!entry.IsDir() && !entry.Type().IsRegular()) { + continue + } + name := entry.Name() + if entry.IsDir() { + name += "/" + } + names = append(names, name) + } + slices.Sort(names) + offset = min(offset, len(names)) + end := min(offset+200, len(names)) + page := map[string]any{"entries": names[offset:end]} + if end < len(names) { + page["nextOffset"] = end + } + if len(entries) == scanLimit { + page["truncated"] = true + } + data, err := json.Marshal(page) + return string(data), err +} diff --git a/internal/httpapi/cli_models_probe.go b/internal/httpapi/cli_models_probe.go index 195426d6..34902a21 100644 --- a/internal/httpapi/cli_models_probe.go +++ b/internal/httpapi/cli_models_probe.go @@ -86,15 +86,15 @@ func (h *usersHandlers) probeCLIModels(c *gin.Context) { protocol = runtime.AgentCLIProtocol(engine, *req.Protocol) } c.Header("Cache-Control", "private, no-store") - if engine == assistantEngineCodeBuddy { - if req.Environment != nil { - var ok bool - environment, ok = domain.NormalizeCodeBuddyInternetEnvironment(*req.Environment) - if !ok { - c.JSON(http.StatusBadRequest, cliModelProbeResult{Error: "请选择有效的 CodeBuddy 网络环境"}) - return - } + if engine == assistantEngineCodeBuddy && req.Environment != nil { + var ok bool + environment, ok = domain.NormalizeCodeBuddyInternetEnvironment(*req.Environment) + if !ok { + c.JSON(http.StatusBadRequest, cliModelProbeResult{Error: "请选择有效的 CodeBuddy 网络环境"}) + return } + } + if engine == assistantEngineCodeBuddy && baseURL == "" { ctx, cancel := context.WithTimeout(c.Request.Context(), 15*time.Second) defer cancel() var models []domain.CLIModel @@ -104,6 +104,10 @@ func (h *usersHandlers) probeCLIModels(c *gin.Context) { } } if len(models) == 0 { + if _, err := resolveAssistantEngineBin(engine); errors.Is(err, errAssistantCLIMissing) { + c.JSON(http.StatusOK, cliModelProbeResult{Error: err.Error()}) + return + } c.JSON(http.StatusOK, cliModelProbeResult{Error: "CodeBuddy CLI 没有返回模型,请检查 CLI 和个人凭据"}) return } diff --git a/internal/httpapi/cli_models_probe_test.go b/internal/httpapi/cli_models_probe_test.go index d2d6f70c..50b4f2c3 100644 --- a/internal/httpapi/cli_models_probe_test.go +++ b/internal/httpapi/cli_models_probe_test.go @@ -52,6 +52,27 @@ func TestProbeCLIModelsUsesOfficialEndpointWithoutBaseURL(t *testing.T) { } } +func TestProbeCodeBuddyIOAModelsReportsMissingCLI(t *testing.T) { + h, owner := workbenchFixture(t) + bin := t.TempDir() + t.Setenv("PATH", bin) + t.Setenv("HOME", t.TempDir()) + t.Setenv("AGENTFLOW_CODEBUDDY_BIN", "") + t.Setenv("AGENTFLOW_MANAGED_CLI_ROOT", "") + t.Setenv("AGENTFLOW_RUNTIME_CLI_DIR", t.TempDir()) + original := assistantCLIGlobalDirs + assistantCLIGlobalDirs = []string{bin} + t.Cleanup(func() { assistantCLIGlobalDirs = original }) + + payload := bytes.NewBufferString(`{"engine":"codebuddy","environment":"ioa"}`) + c, w := workbenchContext(owner, http.MethodPost, "/", payload) + c.Params = gin.Params{{Key: "id", Value: strconv.FormatInt(owner.ID, 10)}} + (&usersHandlers{deps: h.deps}).probeCLIModels(c) + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), "没有安装") { + t.Fatalf("missing CodeBuddy CLI: %d %s", w.Code, w.Body.String()) + } +} + func TestDiscoverGeminiModelsKeepsGenerativeIDs(t *testing.T) { service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet || r.URL.Path != "/v1beta/models" || r.Header.Get("x-goog-api-key") != "fixture-key" { diff --git a/internal/httpapi/executor_models.go b/internal/httpapi/executor_models.go index b1603d61..a0a149f9 100644 --- a/internal/httpapi/executor_models.go +++ b/internal/httpapi/executor_models.go @@ -220,7 +220,7 @@ func (h *catalogHandlers) executorModels(c *gin.Context) { if current, ok := h.requestUser(c.Request, true); ok { if stored, found := h.repo.User(current.ID); found { user = stored - refreshCLIModels(c.Request.Context(), user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey) + refreshOfficialCodeBuddyModels(c.Request.Context(), user) } } _, kimiBaseURL := assistantEngineCredential(user, runtime.AgentCLIKimi) diff --git a/internal/httpapi/feature_model.go b/internal/httpapi/feature_model.go new file mode 100644 index 00000000..a7bb710a --- /dev/null +++ b/internal/httpapi/feature_model.go @@ -0,0 +1,88 @@ +package httpapi + +import ( + "errors" + "strings" + + "agentflow/internal/domain" +) + +// A bare concrete ID is the legacy CodeBuddy format. Only an omitted model +// or unqualified "default" can select another CLI based on credentials. +func normalizeFeatureModel(requested string) (string, error) { + requested = strings.TrimSpace(requested) + if requested == "" { + return assistantDefaultModel, nil + } + engine, model := assistantModelEngine(requested) + if !assistantValidEngineModel(model) { + return "", errFeatureModel + } + if engine == assistantEngineCodeBuddy && !assistantModelHasEnginePrefix(requested) { + return model, nil + } + return engine + ":" + model, nil +} + +var ( + errFeatureModel = errors.New("请选择有效的 CLI 模型") + errFeatureCredentials = errors.New("请先在个人配置中配置至少一个 CLI 的凭据") +) + +func assistantModelUnspecified(model string) bool { + model = strings.TrimSpace(model) + return model == "" || model == assistantDefaultModel +} + +func personalDefaultModel(user domain.User) string { + engine := user.AssistantDefaults.Executor + if engine != "" { + if key, _ := assistantEngineCredential(user, engine); key != "" { + return featureDefaultModel(user, engine) + } + } + return "" +} + +func resolveFeatureModel(user domain.User, requested string) (string, error) { + model, err := normalizeFeatureModel(requested) + if err != nil { + return "", err + } + if model == assistantDefaultModel { + if preferred := personalDefaultModel(user); preferred != "" { + return preferred, nil + } + for _, option := range assistantEngineOptions(user, false) { + if option.Configured { + return featureDefaultModel(user, option.ID), nil + } + } + return "", errFeatureCredentials + } + engine, id := assistantModelEngine(model) + if key, _ := assistantEngineCredential(user, engine); key == "" { + return "", errors.New(assistantEngineMissingKey(engine)) + } + if id == assistantDefaultModel || engine == assistantEngineCodeBuddy && codeBuddyIsDefaultModel(id) { + return featureDefaultModel(user, engine), nil + } + return model, nil +} + +func featureDefaultModel(user domain.User, engine string) string { + if defaults := user.AssistantDefaults; defaults.Executor == engine && defaults.Model != "" { + return engine + ":" + defaults.Model + } + if engine == assistantEngineCodeBuddy { + // These features previously used the deployment's CodeBuddy default. + return engine + ":" + assistantFixedCatalog().Default + } + if models := assistantSavedModels(user, engine); len(models) > 0 { + return engine + ":" + models[0].ID + } + if models := assistantEngineBuiltinModels(engine); len(models) > 0 { + return engine + ":" + models[0].ID + } + return engine + ":" + assistantDefaultModel +} diff --git a/internal/httpapi/feature_model_test.go b/internal/httpapi/feature_model_test.go new file mode 100644 index 00000000..56ab80dc --- /dev/null +++ b/internal/httpapi/feature_model_test.go @@ -0,0 +1,257 @@ +package httpapi + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "agentflow/internal/domain" + "agentflow/internal/repo" + + "github.com/gin-gonic/gin" +) + +func TestFeatureModelPreservesExplicitChoice(t *testing.T) { + t.Setenv("AGENTFLOW_ASSISTANT_MODEL", "deployment-default") + codexUser := domain.User{CodexAPIKey: "test-only", CodexModels: []domain.CLIModel{{ID: "personal-model"}}} + codeBuddyUser := domain.User{CodeBuddyAPIKey: "test-only", CodeBuddyInternetEnvironment: "ioa"} + multiCLI := codeBuddyUser + multiCLI.CodexAPIKey = codexUser.CodexAPIKey + multiCLI.CodeBuddyModels = []domain.CLIModel{{ID: "personal-codebuddy-model"}} + preferredCLI := multiCLI + preferredCLI.AssistantDefaults = domain.AssistantDefaults{Executor: "codex", Model: "preferred-model"} + for _, tc := range []struct { + user domain.User + in string + want string + }{ + {codexUser, "", "codex:personal-model"}, + {codexUser, "codex:default", "codex:personal-model"}, + {codexUser, "codex:custom-model", "codex:custom-model"}, + {multiCLI, "", "codebuddy:deployment-default"}, + {multiCLI, "default", "codebuddy:deployment-default"}, + {multiCLI, "codex:custom-model", "codex:custom-model"}, + {preferredCLI, "default", "codex:preferred-model"}, + {preferredCLI, "codex:default", "codex:preferred-model"}, + {preferredCLI, "codebuddy:default", "codebuddy:deployment-default"}, + {preferredCLI, "deepseek-v4.1-flash", "deepseek-v4.1-flash"}, + {codeBuddyUser, "deepseek-v4.1-flash", "deepseek-v4.1-flash"}, + {codeBuddyUser, "codebuddy:deepseek-v4.1-flash", "codebuddy:deepseek-v4.1-flash"}, + } { + if got, err := resolveFeatureModel(tc.user, tc.in); err != nil || got != tc.want { + t.Errorf("model %q resolved to %q, %v; want %q", tc.in, got, err, tc.want) + } + } + if _, err := resolveFeatureModel(codeBuddyUser, "codex:custom-model"); err == nil { + t.Fatal("accepted an explicit CLI without its own credential") + } + h := &assistantHandlers{} + if got := h.assistantChatRequestModel(assistantRequest{}, domain.AssistantSession{}, preferredCLI); got != "codex:preferred-model" { + t.Errorf("new chat default = %q", got) + } + if got := h.assistantChatRequestModel(assistantRequest{}, domain.AssistantSession{Executor: "codebuddy", Model: "deepseek-v4.1-flash"}, preferredCLI); got != "deepseek-v4.1-flash" { + t.Errorf("existing chat choice = %q", got) + } +} + +// The platform workflow installs Codex before running this test. Its only +// model endpoint is a loopback Responses fixture and no CodeBuddy CLI or key +// is present. MCP calls go through the actual session gateway. +func TestFeatureModelsWithoutCodeBuddy(t *testing.T) { + if os.Getenv("AGENTFLOW_TEST_NATIVE_PROVIDERS") != "1" { + t.Skip("set AGENTFLOW_TEST_NATIVE_PROVIDERS=1 with Codex installed") + } + if _, err := resolveCodeBuddyBin(); err == nil { + t.Fatal("this acceptance test requires a machine without CodeBuddy") + } + const selected = "codex:fixture-model" + const key = "fixture-model-key" + store, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + t.Cleanup(store.Close) + must := func(err error) { + t.Helper() + if err != nil { + t.Fatal(err) + } + } + d := &deps{repo: store} + gateway := &agentToolGateway{deps: d} + router := gin.New() + router.Any("/internal/agent-tools/:token/mcp", gateway.ServeHTTP) + mcp := httptest.NewServer(router) + t.Cleanup(mcp.Close) + t.Setenv("AGENTFLOW_AGENT_TOOL_GATEWAY_URL", mcp.URL) + assistant := &assistantHandlers{deps: d, identities: &botIdentityHandlers{deps: d}} + stream := &streamHandlers{deps: d} + const project = "cli-acceptance" + const userID = int64(123) + must(store.PutUser(domain.User{ID: userID, LoginName: "codex-only"})) + must(store.PutProject(domain.Project{ID: project, Name: "CLI acceptance", OwnerID: userID})) + root := t.TempDir() + must(os.WriteFile(filepath.Join(root, "README.md"), []byte("fixture-source"), 0o600)) + must(store.PutRepository(domain.Repository{ID: "fixture", Name: "fixture", ProjectID: project, LocalPath: root})) + issue := domain.Issue{ProjectID: project, Title: "Document fixture", RepositoryID: "fixture"} + run := domain.Run{ID: "fixture-run", ExecutionContext: domain.TelemetryContext{ProjectID: project, ResponsibleUserID: userID}} + + for _, name := range []string{"eval", "approval", "report", "bot", "clarification"} { + t.Run(name, func(t *testing.T) { + var calls, clarifyStep, clarifyRound atomic.Int32 + model := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var body struct { + Model string `json:"model"` + Tools json.RawMessage `json:"tools"` + Input json.RawMessage `json:"input"` + } + if r.Method != "POST" || r.URL.Path != "/v1/responses" { + http.NotFound(w, r) + return + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + http.Error(w, "invalid fixture request", http.StatusBadRequest) + return + } + if body.Model != "fixture-model" || r.Header.Get("Authorization") != "Bearer "+key { + t.Error("Codex received the wrong model or credential") + } + step := calls.Add(1) + switch name { + case "eval": + writeFeatureResponses(w, step, featureResponseText(`{"summary":"evaluated","dimensions":{"control":90,"latency":90,"tools":90,"tokens":90,"recovery":90,"delivery":90}}`)) + case "approval": + writeFeatureResponses(w, step, featureResponseText(`{"outcome":"allow","risk_level":"low","user_authorization":"high","rationale":"approved fixture"}`)) + case "report": + if step > 1 { + writeFeatureResponses(w, step, featureResponseText("Report submitted.")) + return + } + if strings.Contains(string(body.Tools), "clarify_") || strings.Contains(string(body.Tools), "issues_list") { + t.Error("report can see tools outside its submission contract") + } + writeFeatureResponses(w, step, featureResponseTool(t, step, body.Tools, submitNotificationReportTool, `{"body":"report accepted"}`)) + case "bot": + writeFeatureResponses(w, step, featureResponseText("bot accepted")) + case "clarification": + switch clarifyStep.Add(1) { + case 1: + if clarifyRound.Load() == 1 && !strings.Contains(string(body.Input), "previous answer") { + t.Error("next clarification turn lost the transcript") + } + writeFeatureResponses(w, step, featureResponseTool(t, step, body.Tools, "clarify_list_files", `{"repository":"fixture"}`)) + case 2: + if !strings.Contains(string(body.Input), "README.md") { + t.Error("repository listing was not returned") + } + writeFeatureResponses(w, step, featureResponseTool(t, step, body.Tools, "clarify_read_file", `{"repository":"fixture","path":"README.md"}`)) + case 3: + if !strings.Contains(string(body.Input), "fixture-source") { + t.Error("repository text was not returned") + } + writeFeatureResponses(w, step, featureResponseTool(t, step, body.Tools, submitClarificationTool, `{"ready":true,"summary":"Clarification accepted","questions":[]}`)) + default: + writeFeatureResponses(w, step, featureResponseText("Clarification submitted.")) + } + } + })) + t.Cleanup(model.Close) + base := model.URL + "/v1" + user, err := store.UpdateUserCredentials(userID, repo.UserCredentialUpdate{CodexAPIKey: key, CodexBaseURL: &base}) + must(err) + ctx, stop := context.WithTimeout(context.Background(), 24*time.Second) + defer stop() + switch name { + case "eval": + result, err := (&runsHandlers{deps: d}).executeRunEval(ctx, domain.RunEvalRecord{ID: "eval-fixture", Model: selected}, run, user, func(string, any) {}) + if err != nil || result.Summary != "evaluated" { + t.Fatalf("eval result=%+v err=%v", result, err) + } + case "approval": + review := assistant.approvalReviewer(assistantRequest{Model: selected}, user, nil)(ctx, "fixture", "Review fixture", nil) + if !review.allows() || review.Model != selected { + t.Fatalf("review=%+v", review) + } + case "report": + report, err := assistant.generateSOPReport(ctx, run, selected, "Report fixture.") + if err != nil || report.Body != "report accepted" { + t.Fatalf("report=%+v err=%v", report, err) + } + case "bot": + bot := domain.NotificationBot{ID: "fixture-bot", BotID: "fixture-bot-account", ProjectID: project, Model: selected, Enabled: true, InteractionEnabled: true} + must(store.SaveNotificationBot(bot, "fixture-secret")) + now := time.Now() + token, err := store.NewBotBindingChallenge(bot.BotID, "sender", now) + must(err) + code, err := store.ClaimBotBindingChallenge(token, user.ID, now) + must(err) + _, err = store.ConfirmBotUserBinding(bot.BotID, "sender", code, now) + must(err) + reply, err := assistant.generateBotReply(ctx, bot, domain.BotConversation{}, nil, domain.BotInteraction{SenderID: "sender", Content: "Hello from the fixture."}) + if err != nil || reply != "bot accepted" { + t.Fatalf("reply=%q err=%v", reply, err) + } + case "clarification": + req := chatClarifyRequest{Model: selected, Message: "Document fixture"} + for round := 0; round < 2; round++ { + clarifyRound.Store(int32(round)) + clarifyStep.Store(0) + out, _, info, err := stream.executeClarify(ctx, issue, req, nil) + if err != nil || !strings.Contains(fmt.Sprint(out), "Clarification accepted") || info["analyzed"] != true { + t.Fatalf("clarification=%v, info=%v err=%v", out, info, err) + } + req.SessionID, _ = info["sessionId"].(string) + must(json.Unmarshal([]byte(`[{"role":"assistant","content":"What changed?"},{"role":"user","content":"previous answer"}]`), &req.History)) + } + } + want := int32(1) + if name == "clarification" { + want = 6 + } + // Terminal submission may already have completed when the CLI + // requests a final acknowledgement. Only require the intended calls. + if calls.Load() < want { + t.Fatalf("model requests=%d want at least %d", calls.Load(), want) + } + }) + } +} + +func featureResponseText(text string) map[string]any { + return map[string]any{"id": "msg_fixture", "type": "message", "role": "assistant", "status": "completed", + "content": []any{map[string]any{"type": "output_text", "text": text, "annotations": []any{}}}} +} + +func featureResponseTool(t *testing.T, step int32, tools json.RawMessage, name, arguments string) map[string]any { + t.Helper() + if !strings.Contains(string(tools), `"name":"`+name+`"`) { + t.Errorf("session MCP tool %s is missing", name) + } + return map[string]any{"id": fmt.Sprintf("fc_%d", step), "type": "function_call", "call_id": fmt.Sprintf("call_%d", step), + "name": name, "namespace": "mcp__agentflow_session", "arguments": arguments, "status": "completed"} +} + +func writeFeatureResponses(w http.ResponseWriter, step int32, item map[string]any) { + id := fmt.Sprintf("resp_%d", step) + w.Header().Set("Content-Type", "text/event-stream") + emit := func(event string, fields map[string]any) { + fields["type"] = event + raw, _ := json.Marshal(fields) + fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event, raw) + } + emit("response.created", map[string]any{"response": map[string]any{"id": id, "status": "in_progress", "output": []any{}}}) + emit("response.output_item.added", map[string]any{"output_index": 0, "item": item}) + emit("response.output_item.done", map[string]any{"output_index": 0, "item": item}) + emit("response.completed", map[string]any{"response": map[string]any{ + "id": id, "object": "response", "status": "completed", "model": "fixture-model", "output": []any{item}, + "usage": map[string]int{"input_tokens": 10, "output_tokens": 3, "total_tokens": 13}, + }}) +} diff --git a/internal/httpapi/generic_oauth_cases_test.go b/internal/httpapi/generic_oauth_cases_test.go index 8dfbd305..276af5fb 100644 --- a/internal/httpapi/generic_oauth_cases_test.go +++ b/internal/httpapi/generic_oauth_cases_test.go @@ -86,6 +86,7 @@ func TestGongfengOAuthValidationBranches(t *testing.T) { cvBGongfengCallRound2(t, h.gongfengOAuthStart, "/api/auth/gongfeng/start", http.StatusServiceUnavailable) cvBGongfengCallRound2(t, h.gongfengOAuthCallback, "/api/auth/gongfeng/callback", http.StatusServiceUnavailable) + t.Setenv("AGENTFLOW_GONGFENG_HOST", "git.review.test") t.Setenv("AGENTFLOW_GONGFENG_OAUTH_CLIENT_ID", "id") t.Setenv("AGENTFLOW_GONGFENG_OAUTH_CLIENT_SECRET", "secret") t.Setenv("AGENTFLOW_GONGFENG_OAUTH_REDIRECT_URI", "http://example.test/callback") diff --git a/internal/httpapi/generic_workflows_test.go b/internal/httpapi/generic_workflows_test.go index 40bec4b5..9946d551 100644 --- a/internal/httpapi/generic_workflows_test.go +++ b/internal/httpapi/generic_workflows_test.go @@ -462,30 +462,53 @@ func TestGenericTemplateRunsDirectlyByReference(t *testing.T) { t.Fatal(err) } eng := engine.New(s, runtime.NewManager(filepath.Join(t.TempDir(), "ws"))) + eng.ConfigureExecution("template-admission-test", "", 0, false) h := New(s, eng, tracker.NewService(), "", "") - run := requestJSON[domain.Run](t, h, http.MethodPost, "/api/runs", - map[string]any{"workflowId": repo.GenericBackendDeliveryWorkflowID, "input": "x", "projectId": "alpha"}, - http.StatusCreated) - t.Cleanup(func() { - _ = eng.Cancel(run.ID) - // Wait for the run to fully stop so the workspace quiesces before - // TempDir RemoveAll — a still-running node goroutine recreates - // files underneath the cleanup and races it. - deadline := time.Now().Add(15 * time.Second) - for time.Now().Before(deadline) { - current, ok := s.Run(run.ID) - if !ok || current.Status != "running" { - return - } - time.Sleep(100 * time.Millisecond) + path := "/api/workflows/" + repo.GenericBackendDeliveryWorkflowID + "/executor-requirements?projectId=alpha" + requirements := requestEmptyJSON[[]engine.SOPExecutorRequirement](t, h, http.MethodGet, path, http.StatusOK) + if len(requirements) != 1 || requirements[0].Configured || requirements[0].Kind != "" { + t.Fatalf("unconfigured account should see a generic executor requirement: %+v", requirements) + } + runInput := map[string]any{"workflowId": repo.GenericBackendDeliveryWorkflowID, "input": "x", "projectId": "alpha"} + if err := s.PutProject(domain.Project{ID: "no-repo", Name: "No repository", OwnerID: 1}); err != nil { + t.Fatal(err) + } + pending := requestJSON[domain.Run](t, h, http.MethodPost, "/api/runs", + map[string]any{"workflowId": repo.GenericBackendDeliveryWorkflowID, "input": "x", "projectId": "no-repo"}, http.StatusCreated) + if len(pending.Repositories) != 0 || pending.Repository.RepositoryID != "" { + t.Fatalf("run should be admitted without a repository: %+v", pending.Repository) + } + for _, node := range pending.WorkflowSnapshot.Nodes { + if node.Type != "agent" { + continue } - }) + choice, deferred := pending.WorkflowSnapshot.ExecutorDefaults[node.ID] + if !deferred || choice.Executor != "" { + t.Fatalf("node %s should defer executor selection: %+v", node.ID, choice) + } + } + defaults := domain.AssistantDefaults{Executor: "codex", Model: "fixture-model", Effort: "low"} + baseURL := "http://127.0.0.1:1/v1" + if _, err := s.UpdateUserCredentials(1, repo.UserCredentialUpdate{CodexAPIKey: "fixture-key", CodexBaseURL: &baseURL, AssistantDefaults: &defaults}); err != nil { + t.Fatal(err) + } + requirements = requestEmptyJSON[[]engine.SOPExecutorRequirement](t, h, http.MethodGet, path, http.StatusOK) + if len(requirements) != 1 || requirements[0] != (engine.SOPExecutorRequirement{Kind: "codex", Name: "Codex", Configured: true}) { + t.Fatalf("preflight must find the configured executor: %+v", requirements) + } + run := requestJSON[domain.Run](t, h, http.MethodPost, "/api/runs", + runInput, http.StatusCreated) if run.WorkflowSnapshot.ID != repo.GenericBackendDeliveryWorkflowID || !run.WorkflowSnapshot.Generic { t.Fatalf("run should snapshot the catalog template, not the legacy row: %+v", run.WorkflowSnapshot) } if run.WorkflowSnapshot.SandboxProfileID != repo.GenericDockerSandboxID { t.Fatalf("direct generic run sandbox = %q, want %s", run.WorkflowSnapshot.SandboxProfileID, repo.GenericDockerSandboxID) } + for _, node := range run.WorkflowSnapshot.Nodes { + if node.Type == "agent" && run.WorkflowSnapshot.ExecutorDefaults[node.ID] != defaults { + t.Fatalf("run did not freeze the selected executor and model for %s: %+v", node.ID, run.WorkflowSnapshot.ExecutorDefaults) + } + } if run.ExecutionContext.ProjectID != "alpha" { t.Fatalf("run should belong to the requesting project: %+v", run.ExecutionContext) } diff --git a/internal/httpapi/git_token_verify.go b/internal/httpapi/git_token_verify.go index 03375d02..74273a15 100644 --- a/internal/httpapi/git_token_verify.go +++ b/internal/httpapi/git_token_verify.go @@ -12,6 +12,7 @@ import ( "time" "agentflow/internal/gitwork" + "agentflow/internal/gongfeng" "github.com/gin-gonic/gin" ) @@ -22,7 +23,7 @@ import ( // 不带令牌访问 /personal_access_tokens/self 返回 401,说明端点存在。 // 工蜂对能用的个人访问令牌也会在这个端点返回 404,不能据此判定令牌类型。 // 只有 /user 里的 private_token 与所填令牌相同,才是不能克隆仓库的私人令牌。 -var gongfengAPIBase = "https://git.example.com/api/v3" +var gongfengAPIBase string var requiredGitTokenScopes = []string{"read_repository", "write_repository"} @@ -118,10 +119,20 @@ func verifyGongfengToken(ctx context.Context, token string) gitTokenVerifyResult // 该端点对有效个人访问令牌也会返回 404。这时退回 /user:私人令牌会原样出现在 // private_token 字段里,应拒绝;其余能通过 /user 的令牌按 master 一样视为有效。 func gongfengTokenSelf(ctx context.Context, token string) ([]string, string, error) { - client := &http.Client{Timeout: 10 * time.Second} - resp, err := gongfengDo(ctx, client, gongfengAPIBase+"/personal_access_tokens/self", token) + base := gongfengAPIBase + if base == "" { + base = gongfeng.ConfigFromEnv().APIBase + } + if base == "" { + return nil, "", errors.New("服务端未配置工蜂主机,无法校验工蜂令牌") + } + client := &http.Client{ + Timeout: 10 * time.Second, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + } + resp, err := gongfengDo(ctx, client, base+"/personal_access_tokens/self", token) if err != nil { - return nil, "", fmt.Errorf("无法连接工蜂(git.example.com):%v", err) + return nil, "", fmt.Errorf("无法连接工蜂:%w", err) } defer resp.Body.Close() var info struct { @@ -133,7 +144,7 @@ func gongfengTokenSelf(ctx context.Context, token string) ([]string, string, err } `json:"user"` } if resp.StatusCode == http.StatusNotFound { - login, err := gongfengTokenUser(ctx, client, token) + login, err := gongfengTokenUser(ctx, client, base, token) if err != nil { return nil, "", err } @@ -154,10 +165,10 @@ func gongfengTokenSelf(ctx context.Context, token string) ([]string, string, err return info.Scopes, info.User.Username, nil } -func gongfengTokenUser(ctx context.Context, client *http.Client, token string) (string, error) { - resp, err := gongfengDo(ctx, client, gongfengAPIBase+"/user", token) +func gongfengTokenUser(ctx context.Context, client *http.Client, base, token string) (string, error) { + resp, err := gongfengDo(ctx, client, base+"/user", token) if err != nil { - return "", fmt.Errorf("无法连接工蜂(git.example.com):%v", err) + return "", fmt.Errorf("无法连接工蜂:%w", err) } defer resp.Body.Close() if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden { diff --git a/internal/httpapi/git_token_verify_test.go b/internal/httpapi/git_token_verify_test.go index 23d92244..a52bc16e 100644 --- a/internal/httpapi/git_token_verify_test.go +++ b/internal/httpapi/git_token_verify_test.go @@ -93,6 +93,7 @@ type gitTokenTestTransport func(*http.Request) (*http.Response, error) func (f gitTokenTestTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } func TestVerifyGongfengToken(t *testing.T) { + t.Setenv("AGENTFLOW_GONGFENG_HOST", "git.review.test") cases := []struct { name, selfBody, userBody string selfStatus, userStatus int diff --git a/internal/httpapi/gongfeng_oauth.go b/internal/httpapi/gongfeng_oauth.go index a5f7e5c9..5a3c6d43 100644 --- a/internal/httpapi/gongfeng_oauth.go +++ b/internal/httpapi/gongfeng_oauth.go @@ -16,6 +16,7 @@ import ( "strings" "time" + "agentflow/internal/config" "agentflow/internal/gongfeng" "github.com/gin-gonic/gin" @@ -35,13 +36,13 @@ type gongfengOAuthState struct { // gongfengOAuthStatus tells the settings page whether to offer "用工蜂授权". // Without a configured Gongfeng application the link only leads to an error. func (h *authHandlers) gongfengOAuthStatus(c *gin.Context) { - c.JSON(http.StatusOK, map[string]bool{"enabled": gongfeng.ConfigFromEnv().Enabled()}) + c.JSON(http.StatusOK, gin.H{"enabled": gongfeng.ConfigFromEnv().Enabled(), "host": config.GongfengHost()}) } func (h *authHandlers) gongfengOAuthStart(c *gin.Context) { cfg := gongfeng.ConfigFromEnv() if !cfg.Enabled() { - gongfengOAuthPage(c, http.StatusServiceUnavailable, "工蜂授权还没配好", "服务没有配置工蜂应用的 Client ID、Secret 和回调地址。") + gongfengOAuthPage(c, http.StatusServiceUnavailable, "工蜂授权还没配好", "请由管理员配置工蜂主机、OAuth 应用和回调地址。") return } user, ok := h.requestUser(c.Request, false) diff --git a/internal/httpapi/gongfeng_oauth_test.go b/internal/httpapi/gongfeng_oauth_test.go index ac1495b6..6db8426b 100644 --- a/internal/httpapi/gongfeng_oauth_test.go +++ b/internal/httpapi/gongfeng_oauth_test.go @@ -107,6 +107,7 @@ func TestGongfengOAuthCallbackStoresGrant(t *testing.T) { } func TestGongfengOAuthStartRedirects(t *testing.T) { + t.Setenv("AGENTFLOW_GONGFENG_HOST", "git.example.com") gin.SetMode(gin.TestMode) t.Setenv("AGENTFLOW_PREVIEW_LOCAL_LOGIN", "") st, err := repo.OpenTest() @@ -147,6 +148,7 @@ func TestGongfengOAuthStartRedirects(t *testing.T) { // land on a page telling it to sign in, and the settings page must be able to // tell whether the server has a Gongfeng application at all. func TestGongfengOAuthEntryPointsThroughAuthMiddleware(t *testing.T) { + t.Setenv("AGENTFLOW_GONGFENG_HOST", "git.example.com") gin.SetMode(gin.TestMode) t.Setenv("AGENTFLOW_PREVIEW_LOCAL_LOGIN", "") t.Setenv("AGENTFLOW_LOCAL_LOGIN_USER", "") @@ -183,13 +185,13 @@ func TestGongfengOAuthEntryPointsThroughAuthMiddleware(t *testing.T) { for _, key := range []string{"AGENTFLOW_GONGFENG_OAUTH_CLIENT_ID", "AGENTFLOW_GONGFENG_OAUTH_CLIENT_SECRET", "AGENTFLOW_GONGFENG_OAUTH_REDIRECT_URI"} { t.Setenv(key, "") } - if rec := get("/api/auth/gongfeng", true); rec.Code != http.StatusOK || strings.TrimSpace(rec.Body.String()) != `{"enabled":false}` { + if rec := get("/api/auth/gongfeng", true); rec.Code != http.StatusOK || strings.TrimSpace(rec.Body.String()) != `{"enabled":false,"host":"git.example.com"}` { t.Fatalf("unconfigured status = %d %s", rec.Code, rec.Body.String()) } t.Setenv("AGENTFLOW_GONGFENG_OAUTH_CLIENT_ID", "app-id") t.Setenv("AGENTFLOW_GONGFENG_OAUTH_CLIENT_SECRET", "app-secret") t.Setenv("AGENTFLOW_GONGFENG_OAUTH_REDIRECT_URI", "http://127.0.0.1:18767/api/auth/gongfeng/callback") - if rec := get("/api/auth/gongfeng", true); rec.Code != http.StatusOK || strings.TrimSpace(rec.Body.String()) != `{"enabled":true}` { + if rec := get("/api/auth/gongfeng", true); rec.Code != http.StatusOK || strings.TrimSpace(rec.Body.String()) != `{"enabled":true,"host":"git.example.com"}` { t.Fatalf("configured status = %d %s", rec.Code, rec.Body.String()) } if rec := get("/api/auth/gongfeng", false); rec.Code != http.StatusUnauthorized { diff --git a/internal/httpapi/issue_base_branch_test.go b/internal/httpapi/issue_base_branch_test.go index cd60660a..ad67bd12 100644 --- a/internal/httpapi/issue_base_branch_test.go +++ b/internal/httpapi/issue_base_branch_test.go @@ -278,7 +278,7 @@ func TestImportTAPDRejectsInvalidLinksBeforeMCP(t *testing.T) { h := New(st, engine.New(st, runtime.NewManager(filepath.Join(t.TempDir(), "workspaces"))), tracker.NewService(), "", "") for _, tc := range []struct{ text, errorPart string }{ {"只有标题,没有链接", "无法识别"}, - {"https://example.test/tapd_fe/10000000/story/detail/1010000000100001332", "tapd.example.com"}, + {"https://example.test/tapd_fe/10000000/story/detail/1010000000100001332", "www.tapd.cn"}, {"【两个工作项】\nhttps://tapd.example.com/tapd_fe/10000000/story/detail/1010000000100001332\nhttps://tapd.example.com/tapd_fe/10000000/task/detail/1010000000100001443", "多个不同"}, } { response := requestJSON[map[string]string](t, h, http.MethodPost, "/api/issues/import-tapd", map[string]any{ diff --git a/internal/httpapi/issue_routes_test.go b/internal/httpapi/issue_routes_test.go index 8f38632d..986338e0 100644 --- a/internal/httpapi/issue_routes_test.go +++ b/internal/httpapi/issue_routes_test.go @@ -96,7 +96,7 @@ func TestIssueRoutesCoverRegisteredPaths(t *testing.T) { t.Fatalf("%s: incomplete route", path) } } - if len(issueRoutes) != 12 { - t.Fatalf("expected 12 issue sub-routes, got %d", len(issueRoutes)) + if len(issueRoutes) != 13 { + t.Fatalf("expected 13 issue sub-routes, got %d", len(issueRoutes)) } } diff --git a/internal/httpapi/issues.go b/internal/httpapi/issues.go index 4778cba2..81907eb7 100644 --- a/internal/httpapi/issues.go +++ b/internal/httpapi/issues.go @@ -447,6 +447,7 @@ var issueRoutes = map[string]issueRoute{ "/api/issues/:id/runs": {handle: issuesHandlers.issueRuns, methods: []string{http.MethodGet}}, "/api/issues/:id/clarification": {handle: issuesHandlers.submitIssueClarification, methods: []string{http.MethodPost}}, "/api/issues/:id/chat-clarify": {handle: issuesHandlers.chatClarifyIssue, methods: []string{http.MethodGet, http.MethodPost}}, + "/api/issues/:id/clarify-models": {handle: issuesHandlers.clarifyModels, methods: []string{http.MethodGet}}, "/api/issues/:id/chat-clarify/cancel": {handle: issuesHandlers.cancelChatClarifyIssue, methods: []string{http.MethodPost}}, "/api/issues/:id/reopen": {handle: issuesHandlers.reopenIssue, methods: []string{http.MethodPost}}, "/api/issues/:id/close": {handle: issuesHandlers.closeIssue, methods: []string{http.MethodPost}}, @@ -477,6 +478,29 @@ func (h issuesHandlers) issue(c *gin.Context) { route.handle(h, c, issue) } +// Use the account that will execute the clarification. This catalog is only +// available to callers allowed to start the clarification. +func (h issuesHandlers) clarifyModels(c *gin.Context, issue domain.Issue) { + if !h.requireProjectWriter(c, issue.ProjectID) { + return + } + user, err := h.repo.ResponsibleUser(issue) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + ctx := c.Request.Context() + catalog := personalCodeBuddyCatalog(ctx, user) + catalog.Engines = assistantEngineOptions(user, false) + if user.AssistantDefaults != (domain.AssistantDefaults{}) { + catalog.Preferences = &user.AssistantDefaults + } + models, _ := assistantEngineModels(ctx, user, nil) + catalog.Models = append(selectableCodeBuddyModels(catalog.Models), models...) + c.Header("Cache-Control", "private, no-store") + c.JSON(http.StatusOK, catalog) +} + func actorLabel(user *auth.User) (string, int64) { if user == nil { return "", 0 diff --git a/internal/httpapi/notifications.go b/internal/httpapi/notifications.go index e11d1df8..b620ab0d 100644 --- a/internal/httpapi/notifications.go +++ b/internal/httpapi/notifications.go @@ -153,12 +153,16 @@ func (h *notificationHandlers) save(c *gin.Context, old *domain.NotificationBot) bot.InteractionEnabled = *req.InteractionEnabled } if req.Model != nil { - model := strings.TrimSpace(*req.Model) - if model == "" { - model = domain.DefaultNotificationReportModel + model, err := normalizeFeatureModel(*req.Model) + if err != nil { + c.JSON(400, gin.H{"error": err.Error()}) + return } - if assistantAllowedModel(model, assistantKnownCatalog()) != model { - c.JSON(400, gin.H{"error": "请选择有效的 CodeBuddy 模型"}) + // Preserve validation on the legacy, unqualified CodeBuddy field. + // Explicit CLI IDs are checked by their own model service at runtime. + if !assistantModelHasEnginePrefix(model) && !codeBuddyIsDefaultModel(model) && + (old == nil || old.Model != model) && !assistantCatalogLists(assistantKnownCatalog(), model) { + c.JSON(400, gin.H{"error": errFeatureModel.Error()}) return } bot.Model = model diff --git a/internal/httpapi/notifications_test.go b/internal/httpapi/notifications_test.go index a8c18719..a8451f34 100644 --- a/internal/httpapi/notifications_test.go +++ b/internal/httpapi/notifications_test.go @@ -135,7 +135,15 @@ func TestNotificationBotAPIAuthBindingAndSecrets(t *testing.T) { t.Fatal("model update lost target") } if rsp = request("owner", "PUT", "/bots/"+bot.ID, `{"name":"Bot","botId":"wecom","enabled":true,"model":"unknown-model"}`); rsp.Code != 400 { - t.Fatal("invalid model accepted") + t.Fatal("invalid legacy model accepted") + } + rsp = request("owner", "PUT", "/bots/"+bot.ID, `{"name":"Bot","botId":"wecom","enabled":true,"model":"codex:custom-model"}`) + if rsp.Code != 200 { + t.Fatalf("CLI-prefixed model rejected: %s", rsp.Body.String()) + } + bot, _ = s.NotificationBot(bot.ID) + if bot.Model != "codex:custom-model" || bot.Target == nil { + t.Fatal("CLI model update lost selection or target") } rsp = request("owner", "POST", "/bots/"+bot.ID+"/test", "") if rsp.Code != 200 || provider.sent != 1 { diff --git a/internal/httpapi/project_delete_test.go b/internal/httpapi/project_delete_test.go index 06927cc1..896b8a03 100644 --- a/internal/httpapi/project_delete_test.go +++ b/internal/httpapi/project_delete_test.go @@ -113,7 +113,7 @@ func TestProjectDeleteArchivesAndRestores(t *testing.T) { func TestAssistantTurnContextNamesTheChatProject(t *testing.T) { inProject := assistantTurnContext(assistantRequest{ProjectID: "skillhub"}) - for _, want := range []string{"本对话属于项目 skillhub", "不要说没有选中项目", "不归属当前项目", "projects_delete", "git.example.com/projects/new"} { + for _, want := range []string{"本对话属于项目 skillhub", "不要说没有选中项目", "不归属当前项目", "projects_delete", "提供完整仓库地址", "repositories_save"} { if !strings.Contains(inProject, want) { t.Errorf("project chat context missing %q", want) } diff --git a/internal/httpapi/project_write_access_test.go b/internal/httpapi/project_write_access_test.go index 477208cf..a0f649e5 100644 --- a/internal/httpapi/project_write_access_test.go +++ b/internal/httpapi/project_write_access_test.go @@ -6,6 +6,8 @@ import ( "agentflow/internal/repo" "agentflow/internal/runtime" "bytes" + "encoding/json" + "fmt" "net/http" "net/http/httptest" "testing" @@ -32,14 +34,17 @@ func TestProjectContentWritesRequireMembership(t *testing.T) { } return w.Result().Cookies()[0] } - call := func(cookie *http.Cookie, method, path, body string) int { + request := func(cookie *http.Cookie, method, path, body string) *httptest.ResponseRecorder { r := httptest.NewRequest(method, "http://localhost"+path, bytes.NewBufferString(body)) r.Header.Set("Content-Type", "application/json") r.Header.Set("Origin", "http://localhost") r.AddCookie(cookie) w := httptest.NewRecorder() h.ServeHTTP(w, r) - return w.Code + return w + } + call := func(cookie *http.Cookie, method, path, body string) int { + return request(cookie, method, path, body).Code } session("admin") owner, member, viewer, other := session("owner"), session("member"), session("viewer"), session("other") @@ -55,7 +60,7 @@ func TestProjectContentWritesRequireMembership(t *testing.T) { t.Fatal(err) } - issue := `{"id":"i1","projectId":"p1","title":"Fix login"}` + issue := fmt.Sprintf(`{"id":"i1","projectId":"p1","title":"Fix login","assigneeUserId":%d}`, ownerUser.ID) if code := call(other, "POST", "/api/issues", issue); code != 403 { t.Fatalf("non-member create issue: %d", code) } @@ -65,6 +70,30 @@ func TestProjectContentWritesRequireMembership(t *testing.T) { if code := call(member, "POST", "/api/issues", issue); code != 200 { t.Fatalf("member create issue: %d", code) } + t.Run("clarification catalog uses the responsible account", func(t *testing.T) { + const path = "/api/issues/i1/clarify-models" + models := []domain.CLIModel{{ID: "owner-model"}} + const key = "owner-test-key" + if _, err := s.UpdateUserCredentials(ownerUser.ID, repo.UserCredentialUpdate{CodexAPIKey: key, CodexModels: &models}); err != nil { + t.Fatal(err) + } + for _, cookie := range []*http.Cookie{other, viewer} { + if code := call(cookie, "GET", path, ""); code != 403 { + t.Fatalf("clarification catalog requires project write access: %d", code) + } + } + w := request(member, "GET", path, "") + if w.Code != 200 || bytes.Contains(w.Body.Bytes(), []byte(key)) { + t.Fatalf("invalid clarification catalog response: %d", w.Code) + } + var catalog assistantModelCatalog + if err := json.Unmarshal(w.Body.Bytes(), &catalog); err != nil { + t.Fatal(err) + } + if len(catalog.Models) != 1 || catalog.Models[0].ID != "codex:owner-model" { + t.Fatalf("want the project owner's model: %+v", catalog.Models) + } + }) if code := call(other, "PUT", "/api/issues", `{"id":"i1","projectId":"p1","title":"Hijacked"}`); code != 403 { t.Fatalf("non-member edit issue: %d", code) } diff --git a/internal/httpapi/run_eval.go b/internal/httpapi/run_eval.go index da7b11ed..cf280fca 100644 --- a/internal/httpapi/run_eval.go +++ b/internal/httpapi/run_eval.go @@ -94,8 +94,19 @@ func (h *runsHandlers) startRunEval(c *gin.Context) { return } user, ok := h.repo.User(current.ID) - if !ok || strings.TrimSpace(user.CodeBuddyAPIKey) == "" { - c.JSON(http.StatusBadRequest, map[string]string{"error": "请先在个人配置中配置自己的 CodeBuddy API Key"}) + if !ok { + c.JSON(http.StatusBadRequest, map[string]string{"error": "当前用户不可用"}) + return + } + var req struct { + Model string `json:"model"` + } + if c.Request.ContentLength != 0 && !decode(c, &req) { + return + } + model, err := resolveFeatureModel(user, req.Model) + if err != nil { + c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()}) return } if rec, busy := h.repo.ActiveRunEval(id); busy { @@ -110,20 +121,6 @@ func (h *runsHandlers) startRunEval(c *gin.Context) { // The row was saved as running, then startup failed before a job existed. h.failRunEval(rec, "上次评测没有真正启动") } - var req struct { - Model string `json:"model"` - } - if c.Request.ContentLength > 0 && !decode(c, &req) { - return - } - // Run evals run on CodeBuddy only: refuse a "codex:…" id instead of - // silently evaluating with the CodeBuddy default. - if engine, _ := assistantModelEngine(req.Model); engine != assistantEngineCodeBuddy { - c.JSON(http.StatusBadRequest, map[string]string{"error": "运行评测目前只支持 CodeBuddy 模型,请改选 CodeBuddy 模型"}) - return - } - catalog := assistantModelsForRequest(c.Request.Context(), user, req.Model) - model := assistantAllowedModel(req.Model, catalog) project, _ := h.repo.Project(run.ExecutionContext.ProjectID) rec := domain.RunEvalRecord{ ID: "eval-" + randomID(), @@ -487,7 +484,7 @@ func (h *runsHandlers) executeRunEval(ctx context.Context, rec domain.RunEvalRec _ = h.repo.PutRunEval(rec) emit("thought", map[string]string{"kind": "thinking", "text": "正在用 " + rec.Model + " 评测…"}) system, prompt := runeval.BuildPrompt(rec.Policy, facts) - raw, _, err := runAssistantCLI(ctx, assistantCLIRequest{Prompt: prompt, Model: rec.Model, SystemPrompt: system, UserID: user.ID}, user, func(ev assistantStreamEvent) { + raw, _, err := runAssistantCLI(ctx, assistantCLIRequest{Prompt: prompt, Model: rec.Model, SystemPrompt: system, UserID: user.ID, ReviewOnly: true}, user, func(ev assistantStreamEvent) { if emit == nil { return } diff --git a/internal/httpapi/schedule.go b/internal/httpapi/schedule.go index 89c676e2..0f23030e 100644 --- a/internal/httpapi/schedule.go +++ b/internal/httpapi/schedule.go @@ -249,6 +249,10 @@ func (h *scheduleHandlers) bindScheduleRunAs(c *gin.Context, job *domain.Schedul if !ok { return true } + model := scheduledAssistantDefault(h.repo, self, requestedModel) + if model != requestedModel && !scheduleRunConfigUnchanged(prior, *job) { + job.AssistantModel = model + } engine, _ := assistantModelEngine(job.AssistantModel) stopOnly := func() bool { if job.Enabled || !scheduleRunConfigUnchanged(prior, *job) { @@ -273,6 +277,10 @@ func (h *scheduleHandlers) bindScheduleRunAs(c *gin.Context, job *domain.Schedul if stopOnly() { return false } + if assistantModelUnspecified(model) { + c.JSON(400, gin.H{"error": errFeatureCredentials.Error()}) + return false + } c.JSON(400, gin.H{"error": scheduleMissingKeyError(engine)}) return false } @@ -315,10 +323,14 @@ func scheduleRunConfigUnchanged(prior, job domain.ScheduleJob) bool { // scheduleSharedRequestedModel treats the CLI-default placeholder as "no // model chosen", which the shared key resolves to its own default. func scheduleSharedRequestedModel(model string) string { - if model = strings.TrimSpace(model); model == assistantDefaultModel { - return "" + engine, id := assistantModelEngine(model) + if engine == assistantEngineCodeBuddy { + if codeBuddyIsDefaultModel(id) { + return "" + } + return id } - return model + return strings.TrimSpace(model) } func scheduleMissingKeyError(engine string) string { @@ -326,7 +338,7 @@ func scheduleMissingKeyError(engine string) string { return fmt.Sprintf("你还没有可用的 %s 凭据,请在默认执行机器启用账号登录(Runner %s 及以上),或在个人配置填写 API Key", assistantEngineLabel(engine), domain.RunnerVersionCLISettings) } if engine != assistantEngineCodeBuddy { - return fmt.Sprintf("你还没有配置 %s API Key,平台共享 Key 只支持 CodeBuddy 模型:请先在个人配置中填写,或改选 CodeBuddy 模型", assistantEngineLabel(engine)) + return assistantEngineMissingKey(engine) } return "你还没有配置 CodeBuddy API Key,平台也没有配置共享 Key,定时任务无法执行:请先在个人配置中填写自己的 Key,或联系平台管理员配置共享 Key" } @@ -556,7 +568,7 @@ func (h *scheduleHandlers) startBaselineAlignRun(job domain.ScheduleJob, repo do input := fmt.Sprintf(`对齐仓库 %s 的集成分支 %s 与默认分支 %s。冲突文件:%s。 ## 执行要求(严格,禁止只输出计划) -1. 在当前工作分支执行 git fetch origin %s && git merge origin/%s +1. 进入本次对齐仓库的检出目录,在当前工作分支执行 git fetch origin %s && git merge origin/%s 2. 逐个解决下方列出的冲突块:原则是保留双方有效实现;不确定取舍时选择对业务影响最小的方案并在提交说明里标注 3. 全部解决后 git add 并 git commit,提交说明必须列出冲突文件与每个文件的取舍 4. 不要 push(平台在校验通过后自动推送并创建基线 MR);不要改动默认分支 %s @@ -578,7 +590,7 @@ func (h *scheduleHandlers) startBaselineAlignRun(job domain.ScheduleJob, repo do return run.ID, nil } -const baselineAlignWorkflowVersion = 7 +const baselineAlignWorkflowVersion = 8 func alignWorkflowUsesPlatformAgent(wf domain.WorkflowDefinition) bool { for _, n := range wf.Nodes { @@ -643,7 +655,11 @@ func (h *scheduleHandlers) ensureBaselineAlignWorkflow(_ domain.ScheduleJob) boo SandboxProfileID: "local", Nodes: []domain.WorkflowNode{ {ID: "resolve", Name: "解决冲突", Type: "agent", AgentID: engine.BaselineAlignAgentID, MaxAttempts: 2, MaxReworks: 2, RejectTo: "resolve", Position: domain.Position{X: 80, Y: 80}}, - {ID: "verify", Name: "校验真实合并", Type: "script", ScriptLanguage: "shell", Script: baselineAlignVerifyScript, MaxAttempts: 1, MaxReworks: 2, OnFailure: "reject", RejectTo: "resolve", Position: domain.Position{X: 360, Y: 80}}, + { + ID: "verify", Name: "校验真实合并", Type: "script", + ScriptLanguage: "shell", Script: baselineAlignVerifyScript, ExecutionScope: domain.ExecutionScopeRepositories, + MaxAttempts: 1, MaxReworks: 2, OnFailure: "reject", RejectTo: "resolve", Position: domain.Position{X: 360, Y: 80}, + }, }, Edges: []domain.WorkflowEdge{ {ID: "e-align-1", Source: "resolve", Target: "verify"}, diff --git a/internal/httpapi/schedule_test.go b/internal/httpapi/schedule_test.go index a41a4867..21434463 100644 --- a/internal/httpapi/schedule_test.go +++ b/internal/httpapi/schedule_test.go @@ -454,6 +454,22 @@ func TestEnsureBaselineAlignWorkflowUpgradesExistingRevision(t *testing.T) { t.Fatal("confirm node must be removed") } } + if wf.Nodes[1].ExecutionScope != domain.ExecutionScopeRepositories { + t.Fatal("the merge verifier must run inside the repository checkout") + } + + wf.Version = 7 + wf.Nodes[1].ExecutionScope = "" + if err := st.PutWorkflow(wf); err != nil { + t.Fatal(err) + } + if !h.ensureBaselineAlignWorkflow(domain.ScheduleJob{ProjectID: "platform"}) { + t.Fatal("ensure should upgrade the previously installed v7 align SOP") + } + if upgraded, ok := st.Workflow(engine.BaselineAlignWorkflowID); !ok || upgraded.Version != baselineAlignWorkflowVersion || + len(upgraded.Nodes) != 2 || upgraded.Nodes[1].ExecutionScope != domain.ExecutionScopeRepositories { + t.Fatalf("installed align SOP still lacks repository-scoped verification: %+v", upgraded) + } } func TestScheduleJobRunAcceptedBeforeFinish(t *testing.T) { diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index d736e2a0..0760f29b 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -20,6 +20,7 @@ import ( apidocs "agentflow/docs/api" "agentflow/internal/application" "agentflow/internal/auth" + "agentflow/internal/config" "agentflow/internal/domain" "agentflow/internal/engine" "agentflow/internal/knowledge" @@ -384,6 +385,7 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Serv g.Any("/api/issues/:id/runs", api.issues.issue) g.Any("/api/issues/:id/clarification", api.issues.issue) g.Any("/api/issues/:id/chat-clarify", api.issues.issue) + g.GET("/api/issues/:id/clarify-models", api.issues.issue) g.Any("/api/issues/:id/chat-clarify/cancel", api.issues.issue) g.Any("/api/issues/:id/reopen", api.issues.issue) g.Any("/api/issues/:id/close", api.issues.issue) @@ -490,6 +492,7 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Serv g.POST("/api/workflows/:id/publish", api.catalog.workflow) g.GET("/api/workflows/:id/agents", api.catalog.workflow) g.PUT("/api/workflows/:id/agents", api.catalog.workflow) + g.GET("/api/workflows/:id/executor-requirements", api.catalog.workflow) g.POST("/api/workflows/:id/clone", api.catalog.workflow) g.GET("/api/workflow-metrics", api.runs.workflowMetrics) g.POST(insightIngestPath, api.insights.ingest) @@ -767,6 +770,13 @@ func (s *Server) bootstrap(c *gin.Context) { if current, ok := s.requestUser(c.Request, true); ok { currentUserID = current.ID } + var assistantDefaults domain.AssistantDefaults + for _, user := range users { + if user.ID == currentUserID { + assistantDefaults = user.AssistantDefaults + break + } + } mcpServers = domain.PublicMCPServers(withMarketIcons(visibleMCPServersForUser(mcpServers, currentUserID))) sharedModels := s.repo.SharedCodeBuddyModels() sponsoredModel := "" @@ -784,8 +794,10 @@ func (s *Server) bootstrap(c *gin.Context) { // Set when users without their own CodeBuddy API Key can still chat // and run SOPs on the platform's shared key, limited to these models // (sponsoredModel is the default). - "sponsoredModel": sponsoredModel, - "sponsoredModels": sharedModels, + "sponsoredModel": sponsoredModel, + "sponsoredModels": sharedModels, + "assistantDefaults": assistantDefaults, + "gongfengHost": config.GongfengHost(), }) } diff --git a/internal/httpapi/stream.go b/internal/httpapi/stream.go index 51299d0a..496665f1 100644 --- a/internal/httpapi/stream.go +++ b/internal/httpapi/stream.go @@ -221,10 +221,9 @@ func resolveCodeBuddyBin() (string, error) { if strings.TrimSpace(home) == "" { home = "/root" } - candidates := []string{ - filepath.Join(home, ".local", "bin", "codebuddy"), - "/usr/local/bin/codebuddy", - "/usr/bin/codebuddy", + candidates := []string{filepath.Join(home, ".local", "bin", "codebuddy")} + for _, dir := range assistantCLIGlobalDirs { + candidates = append(candidates, filepath.Join(dir, "codebuddy")) } for _, c := range candidates { if fileExecutable(c) { @@ -381,7 +380,7 @@ func clarifyRepositorySource(repository domain.Repository, selectedBaseBranch st } func (h *streamHandlers) runChatClarify(c *gin.Context, issue domain.Issue, request chatClarifyRequest) { - if err := clarifyModelEngineError(request.Model); err != nil { + if _, err := normalizeFeatureModel(request.Model); err != nil { c.JSON(400, map[string]string{"error": err.Error()}) return } @@ -420,6 +419,24 @@ func (h *streamHandlers) executeClarify(ctx context.Context, issue domain.Issue, if responsibleErr != nil { return nil, "", nil, responsibleErr } + modelID, err := resolveFeatureModel(responsible, request.Model) + if err != nil { + return nil, "", nil, err + } + cli, model := assistantModelEngine(modelID) + useCodeBuddy := cli == assistantEngineCodeBuddy + var bin, invocationRoot string + if useCodeBuddy { + bin, err = resolveCodeBuddyBin() + } else { + invocationRoot, err = os.MkdirTemp("", "agentflow-clarify-") + } + if err != nil { + return nil, "", nil, err + } + if invocationRoot != "" { + defer os.RemoveAll(invocationRoot) + } extras := clarifyRequestTexts(request) hydrateClarifyIssueFromText(&issue, extras...) workItemType := "需求" @@ -430,20 +447,16 @@ func (h *streamHandlers) executeClarify(ctx context.Context, issue domain.Issue, } modelCtx, cancelModel := context.WithCancel(ctx) defer cancelModel() - var toolSession *AgentToolSession - var toolFiles agentToolFiles if err := ensureClarifySessionDirs(responsible.ID); err != nil { return nil, "", nil, err } - sess, files, err := h.openClarifyToolSession(modelCtx, responsible, issue, cancelModel) + toolSession, toolFiles, err := h.openClarifyToolSession(modelCtx, responsible, issue, cancelModel) if err != nil { logAgentToolEvent("session-fallback", "mode=clarify", "err="+truncateRunes(err.Error(), 160)) return nil, "", nil, err } - toolSession = sess - toolFiles = files - defer sess.Close() - defer files.Cleanup() + defer toolSession.Close() + defer toolFiles.Cleanup() intro := fmt.Sprintf("你是研发工作项分析师,正在澄清一张已有的%s。这是多轮澄清:结合「对话」里已经问过和回答过的内容继续,不要重复已问过的问题。", workItemType) mcpStep := "2. 若下文列出了可用 MCP 工具:必须先用这些工具读取外部原单及其评论;正文或评论里的文档链接在对应工具可用时也要同步读取。不要声称看不到评论或文档。" if strings.TrimSpace(issue.ID) == "" { @@ -453,6 +466,9 @@ func (h *streamHandlers) executeClarify(ctx context.Context, issue domain.Issue, } } systemPrompt := clarifySystemPrompt(intro, mcpStep, focus) + if !useCodeBuddy { + systemPrompt = strings.Replace(systemPrompt, "用 Read/Grep/Glob 读取当前工作目录代码", "用 clarify_list_files 和 clarify_read_file 阅读本轮可用的仓库代码", 1) + } var prompt strings.Builder prompt.WriteString(systemPrompt) prompt.WriteString("\n\n## 需求\n标题:") @@ -482,10 +498,6 @@ func (h *streamHandlers) executeClarify(ctx context.Context, issue domain.Issue, } prompt.WriteString(clarifyRoundBudgetHint(clarifyAssistantRounds(request.History))) prompt.WriteString("\n请基于以上对话继续澄清,只围绕「## 需求」本身,完成后调用 submit_clarification。") - cbPath, cbErr := resolveCodeBuddyBin() - if cbErr != nil { - return nil, "", nil, cbErr - } workDir := "" repoInfo := map[string]any{"analyzed": false, "reason": "该 Issue 未绑定代码仓库"} // Resolve the analysis repository list: repositoryIds (multi-repository @@ -556,6 +568,11 @@ func (h *streamHandlers) executeClarify(ctx context.Context, issue domain.Issue, if sessionID == "" { sessionID = strings.TrimSpace(issue.Clarification.SessionID) } + // Other CLIs reconstruct each user turn from the supplied transcript. + // Only retries within this request reuse their temporary native session. + if !useCodeBuddy { + sessionID = "" + } resume := sessionID != "" if resume && !canResumeClarifySession(homeDir, sessionID, issue.Clarification.SessionUserID, responsible.ID) { emit("thought", map[string]string{"kind": "status", "text": "分析环境已变化,正在结合已有回答重新分析…"}) @@ -565,14 +582,25 @@ func (h *streamHandlers) executeClarify(ctx context.Context, issue domain.Issue, sessionID = newAssistantSessionID() resume = false } - if err := ensureClarifySessionDirs(responsible.ID); err != nil { - return nil, "", nil, err - } wsKey := strings.TrimSpace(issue.ID) if wsKey == "" { wsKey = "draft-" + sessionID } - if len(analyzedRepos) == 1 { + if !useCodeBuddy { + paths := make(map[string]string, len(analyzedRepos)) + for _, analysis := range analyzedRepos { + analysis.dirName = domain.NormalizeRepositoryDirName(domain.RepositoryContext{Name: analysis.name, RepositoryID: analysis.id}) + name := analysis.dirName + for i := 2; paths[name] != ""; i++ { + name = fmt.Sprintf("%s-%d", analysis.dirName, i) + } + paths[name] = analysis.dir + analysis.dirName = name + } + toolSession.mu.Lock() + toolSession.clarifyRepos = paths + toolSession.mu.Unlock() + } else if len(analyzedRepos) == 1 { workDir = analyzedRepos[0].dir } else if len(analyzedRepos) > 1 { // Multi-repository clarify: copy every analyzed repository into a @@ -607,25 +635,29 @@ func (h *streamHandlers) executeClarify(ctx context.Context, issue domain.Issue, // 1) 换成隔离的空工作目录,物理上杜绝读到垃圾; // 2) 在提示词里明确告知无代码可用,禁止声称已读代码,结论需注明未基于代码分析。 if len(analyzedRepos) == 0 { - if dir, mkErr := ensureClarifyWorkspace(responsible.ID, wsKey+"-empty"); mkErr == nil { - workDir = dir - } else { - workDir = homeDir + if useCodeBuddy { + if dir, mkErr := ensureClarifyWorkspace(responsible.ID, wsKey+"-empty"); mkErr == nil { + workDir = dir + } else { + workDir = homeDir + } } reason, _ := repoInfo["reason"].(string) - prompt.WriteString("\n\n## 重要限制\n本次未能读取代码仓库(原因:" + reason + ")。不要使用 Read/Grep/Glob,也不要假设或声称已阅读任何代码;请仅基于需求描述与对话历史进行澄清,并在 summary 开头注明「未基于代码分析」。") + prompt.WriteString("\n\n## 重要限制\n本次未能读取代码仓库(原因:" + reason + ")。不要调用代码读取工具,也不要假设或声称已阅读任何代码;请仅基于需求描述与对话历史进行澄清,并在 summary 开头注明「未基于代码分析」。") } // Multi-repository analysis: every selected repository is checked out as a // real sibling directory in the analysis workspace; the prompt lists each // directory plus the repos that could not be prepared. if len(analyzedRepos) > 1 { var b strings.Builder - b.WriteString("\n\n## 多仓库分析\n本次需求涉及多个仓库,均已检出供分析(每个仓库一个独立目录,工作目录为其上级):") + b.WriteString("\n\n## 多仓库分析\n以下仓库已检出供分析:") for _, a := range analyzedRepos { if a.dirName != "" { - fmt.Fprintf(&b, "\n- %s: 目录 ./%s", a.name, a.dirName) - } else { - fmt.Fprintf(&b, "\n- %s: 目录 %s", a.name, a.dir) + if useCodeBuddy { + fmt.Fprintf(&b, "\n- %s: 目录 ./%s", a.name, a.dirName) + } else { + fmt.Fprintf(&b, "\n- %s: repository=%s", a.name, a.dirName) + } } } b.WriteString("\n只澄清本需求实际要改动的仓库;summary 分别说明涉及的每个仓库各自需要什么,不涉及的仓库不必展开。") @@ -644,15 +676,20 @@ func (h *streamHandlers) executeClarify(ctx context.Context, issue domain.Issue, a := analyzedRepos[0] prompt.WriteString(fmt.Sprintf("\n\n## 多仓库范围\n本次需求还涉及其他仓库,但仅 %s 成功检出(当前工作目录),其余未能分析,请勿声称已阅读其代码。summary 需说明本需求涉及的其他仓库各自需要什么。", a.name)) } + if !useCodeBuddy && len(analyzedRepos) > 0 { + prompt.WriteString("\n用 clarify_list_files 获取可分析的仓库名及文件,再用 clarify_read_file 阅读相关代码。") + } if mcpHint := h.clarifyMCPInstructionsFor(issue, responsible, len(request.History) > 0, extras...); mcpHint != "" { prompt.WriteString(mcpHint) } userMsg := prompt.String() clarifyID := fmt.Sprintf("clarify-%d", time.Now().UnixNano()) - modelID := clarifyAllowedModel(modelCtx, responsible, request.Model) - credentials := runtime.RunCredentials{ - CodeBuddy: runtime.CodeBuddyCredential{APIKey: strings.TrimSpace(responsible.CodeBuddyAPIKey), InternetEnvironment: strings.TrimSpace(responsible.CodeBuddyInternetEnvironment)}, - GitHTTPCredentials: h.repo.GitHTTPCredentialSecrets(ctx, responsible.ID), + var credentials runtime.RunCredentials + if useCodeBuddy { + credentials = runtime.RunCredentials{ + CodeBuddy: runtime.CodeBuddyUserCredential(responsible), + GitHTTPCredentials: h.repo.GitHTTPCredentialSecrets(ctx, responsible.ID), + } } turnPrompt := userMsg if resume { @@ -674,11 +711,27 @@ func (h *streamHandlers) executeClarify(ctx context.Context, issue domain.Issue, emit("open", map[string]any{"repository": repoInfo, "model": modelID, "sessionId": sessionID}) emit("thought", map[string]string{"kind": "status", "text": "正在分析需求…"}) turnOpts := clarifyTurnOpts{Native: true, MCPConfig: toolFiles.MCPConfig, Settings: toolFiles.Settings} + runTurn := func(prompt string, resume bool) (string, string, error) { + if useCodeBuddy { + _, raw, captured, err := h.runClarifyTurn(modelCtx, workDir, bin, model, prompt, clarifyID, sessionID, homeDir, resume, credentials, emit, turnOpts) + return raw, captured, err + } + return runAssistantCLI(modelCtx, assistantCLIRequest{ + Prompt: prompt, SystemPrompt: systemPrompt, Model: modelID, UserID: responsible.ID, + SessionRoot: invocationRoot, SessionID: sessionID, Resume: resume, Native: true, MCPConfig: toolFiles.MCPConfig, + }, responsible, func(event assistantStreamEvent) { + if event.Kind == "tool" && event.Tool != "" { + emit("thought", map[string]string{"kind": "tool", "tool": event.Tool, "text": "正在调用 " + event.Tool}) + } else if event.Kind == "thinking" && event.Text != "" { + emit("thought", map[string]string{"kind": "thinking", "text": redactAssistantSecrets(event.Text, responsible)}) + } + }) + } jsonRetries := 0 var recoveredParsed any var recoveredRaw string - for follow := 0; ; follow++ { - _, turnRaw, captured, err := h.runClarifyTurn(modelCtx, workDir, cbPath, modelID, turnPrompt, clarifyID, sessionID, homeDir, resume, credentials, emit, turnOpts) + for { + turnRaw, captured, err := runTurn(turnPrompt, resume) if captured != "" { sessionID = captured repoInfo["sessionId"] = sessionID @@ -691,7 +744,7 @@ func (h *streamHandlers) executeClarify(ctx context.Context, issue domain.Issue, if turnPrompt != userMsg && !strings.Contains(sessionContext, turnPrompt) { fallbackPrompt = sessionContext + "\n" + turnPrompt } - _, turnRaw, captured, err = h.runClarifyTurn(modelCtx, workDir, cbPath, modelID, fallbackPrompt, clarifyID, sessionID, homeDir, false, credentials, emit, turnOpts) + turnRaw, captured, err = runTurn(fallbackPrompt, false) resume = false if captured != "" { sessionID = captured diff --git a/internal/httpapi/users.go b/internal/httpapi/users.go index 2171b406..6ff364b6 100644 --- a/internal/httpapi/users.go +++ b/internal/httpapi/users.go @@ -2,6 +2,7 @@ package httpapi import ( "encoding/json" + "errors" "net/http" "net/url" "strconv" @@ -52,7 +53,7 @@ func (h *usersHandlers) user(c *gin.Context) { } body.CodeBuddyInternetEnvironment = &environment } - baseURLs := []*string{body.CodexBaseURL, body.ClaudeCodeBaseURL} + baseURLs := []*string{body.CodeBuddyBaseURL, body.CodexBaseURL, body.ClaudeCodeBaseURL} for _, cred := range body.AgentCLICredentials { baseURLs = append(baseURLs, cred.BaseURL) } @@ -62,8 +63,40 @@ func (h *usersHandlers) user(c *gin.Context) { return } } + if defaults := body.AssistantDefaults; defaults != nil { + defaults.Executor = strings.TrimSpace(defaults.Executor) + defaults.Model = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(defaults.Model), defaults.Executor+":")) + defaults.Effort = strings.TrimSpace(defaults.Effort) + defaults.Approval = strings.TrimSpace(defaults.Approval) + if defaults.Model != "" && (!assistantValidEngineModel(defaults.Model) || defaults.Model == assistantDefaultModel || + defaults.Executor == assistantEngineCodeBuddy && codeBuddyIsDefaultModel(defaults.Model)) { + c.JSON(http.StatusBadRequest, gin.H{"error": "请选择具体的默认模型"}) + return + } + if defaults.Effort != "" { + if defaults.Model == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "请先选择默认模型"}) + return + } + user, _ := h.repo.User(id) + if err := validateAssistantEffort(c.Request.Context(), user, defaults.Executor+":"+defaults.Model, defaults.Effort); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + } + switch defaults.Approval { + case "", AssistantApprovalConfirm, AssistantApprovalAssisted, AssistantApprovalAuto: + default: + c.JSON(http.StatusBadRequest, gin.H{"error": "请选择有效的操作确认方式"}) + return + } + } saved, err := h.repo.UpdateUserCredentials(id, body) if err != nil { + if errors.Is(err, repo.ErrAssistantDefaultExecutorUnavailable) { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } respond(c, err) return } diff --git a/internal/managedcli/providers.go b/internal/managedcli/providers.go index 3097215e..affc4dc8 100644 --- a/internal/managedcli/providers.go +++ b/internal/managedcli/providers.go @@ -85,6 +85,9 @@ func EnabledProviders() ([]string, error) { selected[name] = struct{}{} } if len(selected) == 0 { + if os.Getenv("AGENTFLOW_SKIP_CODEBUDDY_INSTALL") == "1" { + return []string{"claude-code", "codex"}, nil + } return []string{"claude-code", "codebuddy", "codex"}, nil } providers := make([]string, 0, len(selected)) diff --git a/internal/notification/report.go b/internal/notification/report.go index 0f9479d4..3e9d27ec 100644 --- a/internal/notification/report.go +++ b/internal/notification/report.go @@ -11,9 +11,9 @@ import ( ) var ( - ErrReportCredentials = errors.New("本次 SOP 执行身份未配置 CodeBuddy 凭据") - ErrReportModel = errors.New("所选 CodeBuddy 模型不可用") - ErrReportCLI = errors.New("CodeBuddy CLI 调用失败,请检查 API 服务环境和日志") + ErrReportCredentials = errors.New("本次 SOP 执行身份未配置所选 CLI 的凭据") + ErrReportModel = errors.New("所选 CLI 模型不可用") + ErrReportCLI = errors.New("模型 CLI 调用失败,请检查 API 服务环境和日志") ErrReportFormat = errors.New("AI 未通过 submit_notification_report 提交有效报告") ) diff --git a/internal/observability/hooks.go b/internal/observability/hooks.go index 0eee9a11..9f5b225c 100644 --- a/internal/observability/hooks.go +++ b/internal/observability/hooks.go @@ -19,7 +19,8 @@ const ( AdapterLive = "anthropic-stream-v1" AdapterHooks = "agent-hooks-v1" AdapterLegacyHooks = "codebuddy-hooks-v1" - AdapterOTEL = "codebuddy-otel-v1" + AdapterOTEL = "otlp-v1" + AdapterLegacyOTEL = "codebuddy-otel-v1" ) const hookPython = `#!/usr/bin/env python3 @@ -343,9 +344,9 @@ func MatchAdapter(event domain.TelemetryEvent, view string) bool { case "hooks": return adapter == AdapterHooks || adapter == AdapterLegacyHooks case "otel": - return adapter == AdapterOTEL + return adapter == AdapterOTEL || adapter == AdapterLegacyOTEL case "live": - return adapter != AdapterHooks && adapter != AdapterLegacyHooks && adapter != AdapterOTEL + return adapter != AdapterHooks && adapter != AdapterLegacyHooks && adapter != AdapterOTEL && adapter != AdapterLegacyOTEL default: return adapter == view } diff --git a/internal/observability/otlp.go b/internal/observability/otlp.go index 158f48b9..77347756 100644 --- a/internal/observability/otlp.go +++ b/internal/observability/otlp.go @@ -149,6 +149,7 @@ func spanEvent(span otlpSpan, attrs map[string]string) domain.TelemetryEvent { if span.Status.Code == 2 { level = "error" } + provider := otlpProvider(attrs) return domain.TelemetryEvent{ Category: category, Name: eventName, @@ -157,11 +158,25 @@ func spanEvent(span otlpSpan, attrs map[string]string) domain.TelemetryEvent { Message: msg, Timestamp: end, ParentID: span.ParentSpanID, - Source: domain.TelemetrySource{Layer: "executor", Adapter: AdapterOTEL, Provider: "codebuddy", Protocol: "otlp"}, + Provider: provider, + Source: domain.TelemetrySource{Layer: "executor", Adapter: AdapterOTEL, Provider: provider, Protocol: "otlp"}, Attributes: attrAny, } } +func otlpProvider(attrs map[string]string) string { + if provider := firstNonEmpty(attrs["agentflow.executor_kind"], attrs["gen_ai.provider.name"], attrs["gen_ai.system"]); provider != "" { + return provider + } + if service := attrs["service.name"]; strings.HasPrefix(service, "agentflow-") { + return strings.TrimPrefix(service, "agentflow-") + } + if attrs["codebuddy.span_type"] != "" { + return "codebuddy" + } + return "" +} + func kvMap(kvs []otlpKV) map[string]string { out := map[string]string{} for _, kv := range kvs { diff --git a/internal/repo/catalog.go b/internal/repo/catalog.go index 369eb6c8..f337fa6e 100644 --- a/internal/repo/catalog.go +++ b/internal/repo/catalog.go @@ -26,7 +26,6 @@ func BaselineAlignResolverAgent() domain.AgentDefinition { Shared: true, Description: "全平台共用:把默认分支合入集成分支并解决冲突。不跑项目测试,不写修复报告,不发 MR。", Prompt: "你只做基线对齐,不是需求修复。\n1. 在当前工作分支执行 git fetch 并 merge 默认分支\n2. 逐块解决冲突,保留双方有效实现;拿不准时选对业务影响更小的一侧并在提交说明里写清\n3. git add 冲突文件并创建合并提交,提交说明列出冲突文件与取舍\n4. 不要 push,不要改默认分支,不要跑项目单测或 E2E,不要写 fix-plan.md / fix-report.md / review-report.md\n5. 结束后用几句话说明每个冲突文件的取舍即可", - ExecutorID: "codebuddy", } } diff --git a/internal/repo/git_http_credentials.go b/internal/repo/git_http_credentials.go index 203364ef..20a320a2 100644 --- a/internal/repo/git_http_credentials.go +++ b/internal/repo/git_http_credentials.go @@ -8,6 +8,7 @@ import ( "strings" "time" + "agentflow/internal/config" "agentflow/internal/domain" "agentflow/internal/gitwork" "agentflow/internal/gongfeng" @@ -36,6 +37,10 @@ func (row gitHTTPCredentialRow) secret() domain.GitHTTPCredentialSecret { // managedGitHost is the HTTPS host of the internal adapter's Git server. func managedGitHost() string { + if host := config.GongfengHost(); host != "" { + normalized, _ := gitwork.HTTPSHostScope(host) + return normalized + } host, _ := gitwork.HTTPSRemoteHost(gongfeng.ConfigFromEnv().APIBase) return host } diff --git a/internal/repo/gongfeng_credential.go b/internal/repo/gongfeng_credential.go index 21512d57..bc4ad829 100644 --- a/internal/repo/gongfeng_credential.go +++ b/internal/repo/gongfeng_credential.go @@ -49,7 +49,7 @@ func (r *UsersRepo) managedGitCredential(ctx context.Context, id int64) string { return formatManagedGitCredential(user) } cfg := gongfeng.ConfigFromEnv() - if !cfg.Enabled() { + if !cfg.RefreshEnabled() { return formatManagedGitCredential(user) } // Other callers for this user wait on the gate, and some pass diff --git a/internal/repo/gongfeng_credential_test.go b/internal/repo/gongfeng_credential_test.go index 5149db50..4ba6f701 100644 --- a/internal/repo/gongfeng_credential_test.go +++ b/internal/repo/gongfeng_credential_test.go @@ -13,6 +13,7 @@ import ( ) func TestGongfengOAuthSurvivesLoginAndRefreshes(t *testing.T) { + t.Setenv("AGENTFLOW_GONGFENG_HOST", "git.review.test") st, err := OpenTest() if err != nil { t.Fatal(err) diff --git a/internal/repo/models.go b/internal/repo/models.go index 3e711323..89300f68 100644 --- a/internal/repo/models.go +++ b/internal/repo/models.go @@ -38,6 +38,7 @@ type userConfigRow struct { GongfengRefreshToken *string `gorm:"column:gongfeng_refresh_token;type:text"` GongfengTokenExpiresAt *time.Time `gorm:"column:gongfeng_token_expires_at"` CodeBuddyAPIKey *string `gorm:"column:codebuddy_api_key;type:text"` + CodeBuddyBaseURL *string `gorm:"column:codebuddy_base_url;type:text"` CodeBuddyInternetEnvironment string `gorm:"column:codebuddy_internet_environment;size:64"` CodeBuddyModels *string `gorm:"column:codebuddy_models;type:text"` CodexAPIKey *string `gorm:"column:codex_api_key;type:text"` @@ -47,6 +48,7 @@ type userConfigRow struct { ClaudeCodeBaseURL *string `gorm:"column:claude_code_base_url;type:text"` ClaudeCodeModels *string `gorm:"column:claude_code_models;type:text"` AgentCLICredentials *string `gorm:"column:agent_cli_credentials;type:text"` + AssistantDefaults *string `gorm:"column:assistant_defaults;type:text"` Created *time.Time `gorm:"column:created_at"` Updated *time.Time `gorm:"column:updated_at"` } diff --git a/internal/repo/provider_credentials_test.go b/internal/repo/provider_credentials_test.go index 84cfd14a..6dc84d9c 100644 --- a/internal/repo/provider_credentials_test.go +++ b/internal/repo/provider_credentials_test.go @@ -3,6 +3,7 @@ package repo import ( "agentflow/internal/domain" "encoding/json" + "errors" "fmt" "os" "slices" @@ -11,6 +12,42 @@ import ( "time" ) +func TestAssistantDefaultsFollowCredentialChanges(t *testing.T) { + store, err := OpenTest() + if err != nil { + t.Fatal(err) + } + defer store.Close() + if err := store.PutUser(domain.User{LoginName: "assistant-defaults-owner"}); err != nil { + t.Fatal(err) + } + user, _ := store.UserByLoginName("assistant-defaults-owner") + update := func(change UserCredentialUpdate) domain.AssistantDefaults { + t.Helper() + if _, err := store.UpdateUserCredentials(user.ID, change); err != nil { + t.Fatal(err) + } + saved, _ := store.User(user.ID) + return saved.AssistantDefaults + } + if got := update(UserCredentialUpdate{CodexAPIKey: "fixture-key"}); got.Executor != "codex" { + t.Fatalf("the first configured CLI should be the default: %+v", got) + } + if got := update(UserCredentialUpdate{CodeBuddyAPIKey: "fixture-key"}); got.Executor != "codex" { + t.Fatalf("adding another credential changed the default: %+v", got) + } + chosen := domain.AssistantDefaults{Executor: "codebuddy", Model: "deepseek-v4.1-flash", Effort: "high", Approval: "assisted"} + if got := update(UserCredentialUpdate{AssistantDefaults: &chosen}); got != chosen { + t.Fatalf("explicit defaults were lost: %+v", got) + } + if got := update(UserCredentialUpdate{CodeBuddyAPIKeyClear: true}); got.Executor != "codex" || got.Model != "" || got.Effort != "" || got.Approval != "assisted" { + t.Fatalf("deleting the chosen CLI should select another available CLI: %+v", got) + } + if _, err := store.UpdateUserCredentials(user.ID, UserCredentialUpdate{AssistantDefaults: &chosen}); !errors.Is(err, ErrAssistantDefaultExecutorUnavailable) { + t.Fatalf("unconfigured CLI accepted: %v", err) + } +} + func TestAgentCLICredentialsRoundTrip(t *testing.T) { st, err := OpenTest() if err != nil { diff --git a/internal/repo/run_pages_test.go b/internal/repo/run_pages_test.go index 3fdb9b02..d97e1f3c 100644 --- a/internal/repo/run_pages_test.go +++ b/internal/repo/run_pages_test.go @@ -78,13 +78,17 @@ func TestQueryRunTelemetryFiltersAdapter(t *testing.T) { } } -func TestAdapterSQLKeepsLegacyAndCrossCLIHookEventsVisible(t *testing.T) { +func TestAdapterSQLKeepsLegacyHooksAndOTLPVisible(t *testing.T) { hooks := adapterSQLFilter("hooks") if hooks.clause != " AND adapter IN (?, ?)" || len(hooks.args) != 2 { t.Fatalf("hooks SQL filter = %+v", hooks) } + otel := adapterSQLFilter("otel") + if otel.clause != " AND adapter IN (?, ?)" || len(otel.args) != 2 { + t.Fatalf("OTLP SQL filter = %+v", otel) + } live := adapterSQLFilter("live") - if live.clause != " AND adapter NOT IN (?, ?, ?)" || len(live.args) != 3 { + if live.clause != " AND adapter NOT IN (?, ?, ?, ?)" || len(live.args) != 4 { t.Fatalf("live SQL filter = %+v", live) } } diff --git a/internal/repo/runners.go b/internal/repo/runners.go index 7b3a20bc..bdc15fea 100644 --- a/internal/repo/runners.go +++ b/internal/repo/runners.go @@ -670,6 +670,7 @@ func scrubRunnerTaskCredentials(task *domain.RunnerTask) { return } task.Invocation.CodeBuddyAPIKey = "" + task.Invocation.CodeBuddyBaseURL = "" task.Invocation.CodeBuddyInternetEnvironment = "" task.Invocation.CodexAPIKey = "" task.Invocation.CodexBaseURL = "" diff --git a/internal/repo/runs.go b/internal/repo/runs.go index 18a3c576..c38c0cf0 100644 --- a/internal/repo/runs.go +++ b/internal/repo/runs.go @@ -1702,9 +1702,9 @@ func adapterSQLFilter(adapter string) sqlFilter { case "hooks": return sqlFilter{clause: " AND adapter IN (?, ?)", args: []any{observability.AdapterHooks, observability.AdapterLegacyHooks}} case "otel": - return sqlFilter{clause: " AND adapter=?", args: []any{observability.AdapterOTEL}} + return sqlFilter{clause: " AND adapter IN (?, ?)", args: []any{observability.AdapterOTEL, observability.AdapterLegacyOTEL}} case "live": - return sqlFilter{clause: " AND adapter NOT IN (?, ?, ?)", args: []any{observability.AdapterHooks, observability.AdapterLegacyHooks, observability.AdapterOTEL}} + return sqlFilter{clause: " AND adapter NOT IN (?, ?, ?, ?)", args: []any{observability.AdapterHooks, observability.AdapterLegacyHooks, observability.AdapterOTEL, observability.AdapterLegacyOTEL}} default: return sqlFilter{clause: " AND adapter=?", args: []any{strings.TrimSpace(adapter)}} } diff --git a/internal/repo/user_assistant_defaults.go b/internal/repo/user_assistant_defaults.go new file mode 100644 index 00000000..9e2717cc --- /dev/null +++ b/internal/repo/user_assistant_defaults.go @@ -0,0 +1,18 @@ +package repo + +import ( + "errors" + + "agentflow/internal/domain" +) + +var ErrAssistantDefaultExecutorUnavailable = errors.New("请选择已配置的执行器") + +func firstAssistantExecutor(user domain.User) string { + for _, executor := range append([]string{"codebuddy", "codex", "claude-code"}, domain.AgentCLIExecutorKinds...) { + if user.HasExecutorCredential(executor) { + return executor + } + } + return "" +} diff --git a/internal/repo/users.go b/internal/repo/users.go index f1fdba34..1de1c75e 100644 --- a/internal/repo/users.go +++ b/internal/repo/users.go @@ -32,6 +32,7 @@ type userWithConfig struct { GongfengRefreshToken *string `gorm:"column:gongfeng_refresh_token"` GongfengTokenExpiresAt *time.Time `gorm:"column:gongfeng_token_expires_at"` CodeBuddyAPIKey *string `gorm:"column:codebuddy_api_key"` + CodeBuddyBaseURL *string `gorm:"column:codebuddy_base_url"` CodeBuddyInternetEnvironment string `gorm:"column:codebuddy_internet_environment"` CodeBuddyModels *string `gorm:"column:codebuddy_models"` CodexAPIKey *string `gorm:"column:codex_api_key"` @@ -41,6 +42,7 @@ type userWithConfig struct { ClaudeCodeBaseURL *string `gorm:"column:claude_code_base_url"` ClaudeCodeModels *string `gorm:"column:claude_code_models"` AgentCLICredentials *string `gorm:"column:agent_cli_credentials"` + AssistantDefaults *string `gorm:"column:assistant_defaults"` Created *time.Time `gorm:"column:created_at"` Updated *time.Time `gorm:"column:updated_at"` } @@ -50,9 +52,10 @@ const userSelectColumns = `u.id, u.staff_id, u.login_name, u.chinese_name, u.dep c.git_token, EXISTS (SELECT 1 FROM user_git_ssh_keys k WHERE k.user_id = u.id) AS git_ssh_key_configured, EXISTS (SELECT 1 FROM user_git_http_credentials h WHERE h.user_id = u.id) AS git_http_credentials_configured, EXISTS (SELECT 1 FROM user_git_http_credentials h WHERE h.user_id = u.id AND h.host = 'github.com') AS github_credential_configured, - c.gongfeng_refresh_token, c.gongfeng_token_expires_at, c.codebuddy_api_key, COALESCE(c.codebuddy_internet_environment, '') AS codebuddy_internet_environment, c.codebuddy_models, + c.gongfeng_refresh_token, c.gongfeng_token_expires_at, c.codebuddy_api_key, c.codebuddy_base_url, + COALESCE(c.codebuddy_internet_environment, '') AS codebuddy_internet_environment, c.codebuddy_models, c.codex_api_key, c.codex_base_url, c.codex_models, c.claude_code_api_key, c.claude_code_base_url, c.claude_code_models, - c.agent_cli_credentials, + c.agent_cli_credentials, c.assistant_defaults, u.created_at, u.updated_at` func (r userWithConfig) toDomain() domain.User { @@ -77,6 +80,9 @@ func (r userWithConfig) toDomain() domain.User { if r.CodeBuddyAPIKey != nil { u.CodeBuddyAPIKey = *r.CodeBuddyAPIKey } + if r.CodeBuddyBaseURL != nil { + u.CodeBuddyBaseURL = *r.CodeBuddyBaseURL + } if r.CodexAPIKey != nil { u.CodexAPIKey = *r.CodexAPIKey } @@ -94,6 +100,9 @@ func (r userWithConfig) toDomain() domain.User { if r.AgentCLICredentials != nil { _ = json.Unmarshal([]byte(*r.AgentCLICredentials), &u.AgentCLICredentials) } + if r.AssistantDefaults != nil { + _ = json.Unmarshal([]byte(*r.AssistantDefaults), &u.AssistantDefaults) + } if r.Created != nil { u.CreatedAt = *r.Created } @@ -172,6 +181,7 @@ func (r *UsersRepo) PutUser(v domain.User) error { v.CodexAPIKey, v.CodexBaseURL, v.CodexModels = old.CodexAPIKey, old.CodexBaseURL, old.CodexModels v.ClaudeCodeAPIKey, v.ClaudeCodeBaseURL, v.ClaudeCodeModels = old.ClaudeCodeAPIKey, old.ClaudeCodeBaseURL, old.ClaudeCodeModels v.CodeBuddyAPIKey = old.CodeBuddyAPIKey + v.CodeBuddyBaseURL = old.CodeBuddyBaseURL v.CodeBuddyInternetEnvironment = old.CodeBuddyInternetEnvironment v.CodeBuddyModels = old.CodeBuddyModels v.AgentCLICredentials = old.AgentCLICredentials @@ -241,6 +251,7 @@ func userHasConfig(user domain.User) bool { return user.GitToken != "" || user.GongfengRefreshToken != "" || user.CodeBuddyAPIKey != "" || + user.CodeBuddyBaseURL != "" || user.CodeBuddyInternetEnvironment != "" || len(user.CodeBuddyModels) > 0 || user.CodexAPIKey != "" || @@ -253,18 +264,20 @@ func userHasConfig(user domain.User) bool { } type UserCredentialUpdate struct { - CodeBuddyAPIKey string `json:"codeBuddyApiKey"` - CodeBuddyAPIKeyClear bool `json:"codeBuddyApiKeyClear"` - CodeBuddyInternetEnvironment *string `json:"codeBuddyInternetEnvironment"` - CodeBuddyModels *[]domain.CLIModel `json:"codeBuddyModels"` - CodexAPIKey string `json:"codexApiKey"` - CodexAPIKeyClear bool `json:"codexApiKeyClear"` - CodexBaseURL *string `json:"codexBaseUrl"` - CodexModels *[]domain.CLIModel `json:"codexModels"` - ClaudeCodeAPIKey string `json:"claudeCodeApiKey"` - ClaudeCodeAPIKeyClear bool `json:"claudeCodeApiKeyClear"` - ClaudeCodeBaseURL *string `json:"claudeCodeBaseUrl"` - ClaudeCodeModels *[]domain.CLIModel `json:"claudeCodeModels"` + AssistantDefaults *domain.AssistantDefaults `json:"assistantDefaults"` + CodeBuddyAPIKey string `json:"codeBuddyApiKey"` + CodeBuddyAPIKeyClear bool `json:"codeBuddyApiKeyClear"` + CodeBuddyBaseURL *string `json:"codeBuddyBaseUrl"` + CodeBuddyInternetEnvironment *string `json:"codeBuddyInternetEnvironment"` + CodeBuddyModels *[]domain.CLIModel `json:"codeBuddyModels"` + CodexAPIKey string `json:"codexApiKey"` + CodexAPIKeyClear bool `json:"codexApiKeyClear"` + CodexBaseURL *string `json:"codexBaseUrl"` + CodexModels *[]domain.CLIModel `json:"codexModels"` + ClaudeCodeAPIKey string `json:"claudeCodeApiKey"` + ClaudeCodeAPIKeyClear bool `json:"claudeCodeApiKeyClear"` + ClaudeCodeBaseURL *string `json:"claudeCodeBaseUrl"` + ClaudeCodeModels *[]domain.CLIModel `json:"claudeCodeModels"` // AgentCLICredentials updates the agent CLIs by kind; absent fields keep // the stored value. CodeBuddy, Codex and Claude Code stay on their own columns. AgentCLICredentials map[string]AgentCLICredentialUpdate `json:"agentCliCredentials"` @@ -309,11 +322,19 @@ func (r *UsersRepo) updateUserCredentials(id int64, update UserCredentialUpdate) if !ok { return domain.User{}, errors.New("user not found") } + previousDefaults := user.AssistantDefaults + if user.AssistantDefaults.Executor == "" { + user.AssistantDefaults.Executor = firstAssistantExecutor(user) + } if update.CodeBuddyAPIKeyClear { user.CodeBuddyAPIKey = "" + user.CodeBuddyBaseURL = "" } else if value := strings.TrimSpace(update.CodeBuddyAPIKey); value != "" { user.CodeBuddyAPIKey = value } + if update.CodeBuddyBaseURL != nil && !update.CodeBuddyAPIKeyClear { + user.CodeBuddyBaseURL = strings.TrimSpace(*update.CodeBuddyBaseURL) + } if update.CodeBuddyInternetEnvironment != nil { user.CodeBuddyInternetEnvironment = strings.TrimSpace(*update.CodeBuddyInternetEnvironment) } @@ -357,10 +378,29 @@ func (r *UsersRepo) updateUserCredentials(id int64, update UserCredentialUpdate) if err := applyAgentCLICredentialUpdates(&user, update.AgentCLICredentials); err != nil { return domain.User{}, err } + if update.AssistantDefaults != nil { + if !user.HasExecutorCredential(update.AssistantDefaults.Executor) { + return domain.User{}, ErrAssistantDefaultExecutorUnavailable + } + user.AssistantDefaults = *update.AssistantDefaults + } else if !user.HasExecutorCredential(user.AssistantDefaults.Executor) { + user.AssistantDefaults.Executor = firstAssistantExecutor(user) + user.AssistantDefaults.Model = "" + user.AssistantDefaults.Effort = "" + } user.UpdatedAt = time.Now().UTC() if err := r.writeUserConfig(user); err != nil { return domain.User{}, err } + if user.AssistantDefaults != previousDefaults { + value, err := json.Marshal(user.AssistantDefaults) + if err != nil { + return domain.User{}, err + } + if err := r.DB.Model(&userConfigRow{}).Where("user_id = ?", id).Update("assistant_defaults", string(value)).Error; err != nil { + return domain.User{}, err + } + } return user, nil } @@ -387,6 +427,7 @@ func (r *UsersRepo) writeUserConfig(v domain.User) error { "git_token": nullableString(v.GitToken), "gongfeng_refresh_token": nullableString(v.GongfengRefreshToken), "gongfeng_token_expires_at": timePtr(v.GongfengTokenExpiresAt), "codebuddy_api_key": nullableString(v.CodeBuddyAPIKey), + "codebuddy_base_url": nullableString(v.CodeBuddyBaseURL), "codebuddy_internet_environment": v.CodeBuddyInternetEnvironment, "codebuddy_models": encodeCLIModels(v.CodeBuddyModels), "codex_api_key": nullableString(v.CodexAPIKey), "codex_base_url": nullableString(v.CodexBaseURL), "codex_models": encodeCLIModels(v.CodexModels), diff --git a/internal/runeval/facts_test.go b/internal/runeval/facts_test.go index f0ba9f7d..fee41687 100644 --- a/internal/runeval/facts_test.go +++ b/internal/runeval/facts_test.go @@ -72,6 +72,7 @@ func TestBuildFactsDetectsReworkAndToolStorm(t *testing.T) { func TestParseModelResultScoresByWeight(t *testing.T) { raw := `{ + "score": 96.75, "summary": "返工过多,建议提高 maxAttempts 并收紧门禁。", "dimensions": {"control":40,"latency":80,"tools":50,"tokens":70,"recovery":30,"delivery":90}, "findings":[{"severity":"error","dimension":"control","nodeId":"fix","message":"返工 2 次"}], diff --git a/internal/runeval/prompt.go b/internal/runeval/prompt.go index 03bd52e7..c7132aee 100644 --- a/internal/runeval/prompt.go +++ b/internal/runeval/prompt.go @@ -13,7 +13,7 @@ func BuildPrompt(policy domain.RunEvalPolicy, facts domain.RunEvalFacts) (system var b strings.Builder b.WriteString("你是 AgentFlow 的 SOP Run 评测员。根据提供的结构化 facts 和压缩 trace digest,按平台规则给这次 run 打分,并给出可落地的改进建议。\n") b.WriteString("只输出一个 JSON 对象,不要 Markdown。字段:\n") - b.WriteString(`{"score":0,"dimensions":{`) + b.WriteString(`{"dimensions":{`) for i, dim := range policy.Dimensions { if i > 0 { b.WriteString(",") @@ -22,7 +22,7 @@ func BuildPrompt(policy domain.RunEvalPolicy, facts domain.RunEvalFacts) (system } b.WriteString(`},"findings":[{"severity":"warn","dimension":"control","nodeId":"","ruleId":"","message":"","evidence":""}],"summary":"","recommendations":[]}` + "\n") b.WriteString("规则:\n") - b.WriteString(fmt.Sprintf("- 准入线 %d 分。dimensions 每维 0-100,必须覆盖全部维度。score 可省略,服务端会按权重重算。\n", policy.Threshold)) + b.WriteString(fmt.Sprintf("- 准入线 %d 分。dimensions 每维填写 0-100 的整数,必须覆盖全部维度。总分由服务端按权重计算。\n", policy.Threshold)) b.WriteString("- findings 用中文,指向具体 nodeId 和 digest seq / event。severity 只能是 info/warn/error。\n") b.WriteString("- summary 必须包含这次 run 的质量结论,以及如果没有可应用补丁时应该怎么改。\n") b.WriteString("- recommendations 可为空。可应用时 action 只能是:update_node、upsert_gate、remove_gate、append_task_prompt(追加到角色 prompt)。\n") @@ -44,7 +44,6 @@ func ParseModelResult(raw string, policy domain.RunEvalPolicy) (domain.RunEvalRe return domain.RunEvalResult{}, fmt.Errorf("model did not return JSON") } var parsed struct { - Score int `json:"score"` Summary string `json:"summary"` Dimensions map[string]int `json:"dimensions"` Findings []domain.RunEvalFinding `json:"findings"` diff --git a/internal/runner/daemon.go b/internal/runner/daemon.go index 9df44f2a..46734471 100644 --- a/internal/runner/daemon.go +++ b/internal/runner/daemon.go @@ -1126,6 +1126,7 @@ func bindInvocationCredentials(inv *domain.RunnerInvocation, bindings []runtime. return nil, nil, errors.New("CodeBuddy 个人 API Key 未配置") } env["CODEBUDDY_API_KEY"] = key + env["CODEBUDDY_BASE_URL"] = strings.TrimSpace(inv.CodeBuddyBaseURL) if net := strings.TrimSpace(inv.CodeBuddyInternetEnvironment); net != "" { env["CODEBUDDY_INTERNET_ENVIRONMENT"] = net } @@ -1447,7 +1448,7 @@ func (d *Daemon) defaultWorkspace(taskID string) string { } // runnerVersion is reported at registration; it matches the module build. -var runnerVersion = domain.RunnerVersionGitSSHKnownHosts +var runnerVersion = domain.RunnerVersionCodeBuddyBaseURL // Version returns the runner build version reported at registration. func Version() string { return runnerVersion } diff --git a/internal/runner/daemon_test.go b/internal/runner/daemon_test.go index c9d83734..6442b22a 100644 --- a/internal/runner/daemon_test.go +++ b/internal/runner/daemon_test.go @@ -21,6 +21,17 @@ import ( ) func TestBindInvocationCredentials(t *testing.T) { + t.Run("personal codebuddy overrides the runner endpoint", func(t *testing.T) { + inv := &domain.RunnerInvocation{CredentialSource: domain.RuntimeAuthPersonal, CodeBuddyAPIKey: "fixture-key", CodeBuddyBaseURL: "https://gateway.example/v1", CodeBuddyInternetEnvironment: "ioa"} + for _, baseURL := range []string{inv.CodeBuddyBaseURL, ""} { + inv.CodeBuddyBaseURL = baseURL + _, env, err := bindInvocationCredentials(inv, []runtime.CredentialBinding{runtime.BindCodeBuddy}, []string{"codebuddy", "-p", "prompt"}) + boundURL, present := env["CODEBUDDY_BASE_URL"] + if err != nil || !present || boundURL != baseURL || env["CODEBUDDY_INTERNET_ENVIRONMENT"] != "ioa" { + t.Fatalf("unexpected CodeBuddy endpoint binding: %q, %v", boundURL, err) + } + } + }) t.Run("local login leaves codex invocation unchanged", func(t *testing.T) { argv := []string{"codex", "exec", "prompt"} gotArgv, env, err := bindInvocationCredentials(&domain.RunnerInvocation{CredentialSource: domain.RuntimeAuthLocal}, []runtime.CredentialBinding{runtime.BindCodex}, argv) diff --git a/internal/runtime/command_binding.go b/internal/runtime/command_binding.go index c6776888..f23df5d2 100644 --- a/internal/runtime/command_binding.go +++ b/internal/runtime/command_binding.go @@ -45,6 +45,7 @@ func bindCommand(ctx context.Context, sandbox Sandbox, workspace string, command // Known host credentials are cleared for every child by default. A provider // receives them only by explicitly requesting a controlled binding. bound.environment["CODEBUDDY_API_KEY"] = "" + bound.environment["CODEBUDDY_BASE_URL"] = "" bound.environment["CODEBUDDY_INTERNET_ENVIRONMENT"] = "" bound.environment["AGENTFLOW_GIT_TOKEN"] = "" bound.environment["GH_TOKEN"] = "" @@ -107,13 +108,13 @@ func bindCommand(ctx context.Context, sandbox Sandbox, workspace string, command for _, binding := range command.CredentialBindings { switch binding { case BindCodeBuddy: - // Empty values are intentional: a responsible user without credentials must - // not inherit either variable from the AgentFlow host process. + // Clearing an endpoint restores CodeBuddy's official address for this edition. bound.environment["CODEBUDDY_API_KEY"] = strings.TrimSpace(credentials.CodeBuddy.APIKey) if bound.environment["CODEBUDDY_API_KEY"] == "" { return CommandSpec{}, fmt.Errorf("需求责任人未配置 CodeBuddy API Key,请在个人配置中配置") } bound.environment["CODEBUDDY_INTERNET_ENVIRONMENT"] = strings.TrimSpace(credentials.CodeBuddy.InternetEnvironment) + bound.environment["CODEBUDDY_BASE_URL"] = strings.TrimSpace(credentials.CodeBuddy.BaseURL) case BindGit: if err := bindWorkspaceGitEnvironment(ctx, sandbox, workspace, bound.environment, credentials); err != nil { return CommandSpec{}, err @@ -185,27 +186,37 @@ func bindCommand(ctx context.Context, sandbox Sandbox, workspace string, command if command.HookOutput != "" { bound.environment["AGENTFLOW_HOOK_OUTPUT"] = command.HookOutput } - bindTelemetryEnvironment(bound.environment, command.Telemetry) + bindTelemetryEnvironment(bound.environment, command.Telemetry, command.Provider) return bound, nil } // bindTelemetryEnvironment points the child CLI's OpenTelemetry exporter at // the AgentFlow collector and tags its spans with the run and node. A nil // telemetry leaves env untouched. -func bindTelemetryEnvironment(env map[string]string, telemetry *InvocationOptions) { +func bindTelemetryEnvironment(env map[string]string, telemetry *InvocationOptions, provider string) { if telemetry == nil { return } runID, nodeID := telemetry.RunID, telemetry.NodeID env["AGENTFLOW_RUN_ID"] = runID env["AGENTFLOW_NODE_ID"] = nodeID - env["CODEBUDDY_CODE_ENABLE_TELEMETRY"] = "1" - env["CLAUDE_CODE_ENABLE_TELEMETRY"] = "1" + switch provider { + case "codebuddy": + env["CODEBUDDY_CODE_ENABLE_TELEMETRY"] = "1" + case "claude-code": + env["CLAUDE_CODE_ENABLE_TELEMETRY"] = "1" + } env["OTEL_TRACES_EXPORTER"] = "otlp" env["OTEL_EXPORTER_OTLP_PROTOCOL"] = "http/protobuf" env["OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"] = observability.CollectorTracesURL() env["OTEL_LOG_TOOL_DETAILS"] = "1" - env["OTEL_RESOURCE_ATTRIBUTES"] = fmt.Sprintf("agentflow.run_id=%s,agentflow.node_id=%s,service.name=agentflow-codebuddy", runID, nodeID) + attributes := fmt.Sprintf("agentflow.run_id=%s,agentflow.node_id=%s", runID, nodeID) + if provider == "" { + attributes += ",service.name=agentflow" + } else { + attributes += fmt.Sprintf(",agentflow.executor_kind=%s,service.name=agentflow-%s", provider, provider) + } + env["OTEL_RESOURCE_ATTRIBUTES"] = attributes } // CodexUserProviderArgv inserts a dedicated "agentflow_user" model provider diff --git a/internal/runtime/command_binding_telemetry_test.go b/internal/runtime/command_binding_telemetry_test.go index bddc9ec2..5ec0c516 100644 --- a/internal/runtime/command_binding_telemetry_test.go +++ b/internal/runtime/command_binding_telemetry_test.go @@ -4,7 +4,7 @@ import "testing" func TestBindTelemetryEnvironmentNilLeavesEnvUntouched(t *testing.T) { env := map[string]string{"KEEP": "1"} - bindTelemetryEnvironment(env, nil) + bindTelemetryEnvironment(env, nil, "codebuddy") if len(env) != 1 || env["KEEP"] != "1" { t.Fatalf("nil telemetry changed env: %#v", env) } @@ -13,17 +13,16 @@ func TestBindTelemetryEnvironmentNilLeavesEnvUntouched(t *testing.T) { func TestBindTelemetryEnvironmentSetsCollectorAndRunTags(t *testing.T) { t.Setenv("AGENTFLOW_OTEL_TRACES_ENDPOINT", "http://collector.test/v1/traces") env := map[string]string{} - bindTelemetryEnvironment(env, &InvocationOptions{RunID: "run-1", NodeID: "node-a"}) + bindTelemetryEnvironment(env, &InvocationOptions{RunID: "run-1", NodeID: "node-a"}, "claude-code") want := map[string]string{ "AGENTFLOW_RUN_ID": "run-1", "AGENTFLOW_NODE_ID": "node-a", - "CODEBUDDY_CODE_ENABLE_TELEMETRY": "1", "CLAUDE_CODE_ENABLE_TELEMETRY": "1", "OTEL_TRACES_EXPORTER": "otlp", "OTEL_EXPORTER_OTLP_PROTOCOL": "http/protobuf", "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT": "http://collector.test/v1/traces", "OTEL_LOG_TOOL_DETAILS": "1", - "OTEL_RESOURCE_ATTRIBUTES": "agentflow.run_id=run-1,agentflow.node_id=node-a,service.name=agentflow-codebuddy", + "OTEL_RESOURCE_ATTRIBUTES": "agentflow.run_id=run-1,agentflow.node_id=node-a,agentflow.executor_kind=claude-code,service.name=agentflow-claude-code", } if len(env) != len(want) { t.Fatalf("env = %#v, want %#v", env, want) diff --git a/internal/runtime/conversation_process.go b/internal/runtime/conversation_process.go index c954ff89..e519759f 100644 --- a/internal/runtime/conversation_process.go +++ b/internal/runtime/conversation_process.go @@ -286,8 +286,8 @@ func (p *ConversationProcessPool) Handle(ctx context.Context, root, workspace st defer stopWrite() if req.EOF { err = input.Close() - // Process cleanup can close stdin before the final EOF arrives. - if errors.Is(err, os.ErrClosed) { + // A short-lived CLI can exit before the client relays its final EOF. + if errors.Is(err, os.ErrClosed) || errors.Is(err, io.ErrClosedPipe) { err = nil } } else { diff --git a/internal/runtime/remote_sandbox_test.go b/internal/runtime/remote_sandbox_test.go index 7941a1ef..c7aff71a 100644 --- a/internal/runtime/remote_sandbox_test.go +++ b/internal/runtime/remote_sandbox_test.go @@ -74,3 +74,16 @@ func TestWithSandboxCredentialsRefreshesExplicitBindings(t *testing.T) { t.Fatalf("unrequested credentials inherited: %q %v", output, err) } } + +func TestCodeBuddyBaseURLIsBoundPerInvocation(t *testing.T) { + t.Setenv("CODEBUDDY_BASE_URL", "https://ambient.example/v1") + const gateway = "https://personal.example/v1" + command := CommandSpec{Argv: []string{"sh", "-c", `printf '%s' "$CODEBUDDY_BASE_URL"`}, Provider: "codebuddy", CredentialBindings: []CredentialBinding{BindCodeBuddy}} + for _, baseURL := range []string{gateway, ""} { + credentials := RunCredentials{CodeBuddy: CodeBuddyCredential{APIKey: "fixture-key", BaseURL: baseURL}} + output, err := ExecuteLocalCommand(context.Background(), t.TempDir(), command, credentials, nil) + if err != nil || strings.TrimSpace(output) != baseURL { + t.Fatalf("CodeBuddy received %q, want %q: %v", output, baseURL, err) + } + } +} diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index 173ba2f6..dec6cdb3 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -40,6 +40,7 @@ const ( type CodeBuddyCredential struct { APIKey string + BaseURL string `json:",omitempty"` InternetEnvironment string // Sponsored is set when the responsible user has no key of their own and // the platform's shared key is used; such runs are limited to @@ -48,6 +49,13 @@ type CodeBuddyCredential struct { SponsoredModels []string } +func CodeBuddyUserCredential(user domain.User) CodeBuddyCredential { + return CodeBuddyCredential{ + APIKey: user.CodeBuddyAPIKey, BaseURL: user.CodeBuddyBaseURL, + InternetEnvironment: user.CodeBuddyInternetEnvironment, + } +} + // RunCredentials lives only on the in-memory run sandbox handle. It is never // serialized into domain objects, run-context.json, or workspace files. type RunCredentials struct { diff --git a/internal/runtime/sandbox_docker.go b/internal/runtime/sandbox_docker.go index 2289d50e..9abaf864 100644 --- a/internal/runtime/sandbox_docker.go +++ b/internal/runtime/sandbox_docker.go @@ -628,7 +628,7 @@ func DockerImageCached(ctx context.Context, dockerfile domain.DockerfileDefiniti if image := isolatedRuntimeImage(dockerfile); image != "" { return dockerImageExists(ctx, image) } - return dockerImageExists(ctx, cachedDockerImageName(dockerfile)) + return dockerImageExists(ctx, cachedDockerImageName(effectiveIsolatedDockerfile(dockerfile))) } func reclaimCachedDockerImages(ctx context.Context, keep map[string]struct{}) (int, error) { @@ -906,6 +906,7 @@ func ensureDockerImage(ctx context.Context, workspace string, dockerfile domain. } return image, nil } + dockerfile = effectiveIsolatedDockerfile(dockerfile) image := cachedDockerImageName(dockerfile) if dockerImageExists(ctx, image) { return image, nil @@ -972,15 +973,28 @@ func dockerBuildWatch(dockerfile domain.DockerfileDefinition) procwatch.Options } func isolatedRuntimeImage(dockerfile domain.DockerfileDefinition) string { - if dockerfile.Content != IsolatedDockerfile || len(dockerfile.Files) != 0 { + if !isBuiltInIsolatedDockerfile(dockerfile) { return "" } return strings.TrimSpace(os.Getenv("AGENTFLOW_ISOLATED_IMAGE")) } -// IsolatedDockerfile matches the public "generic-backend" environment so both -// share one cached image. -const IsolatedDockerfile = "FROM node:22-bookworm\nRUN apt-get update && apt-get install -y --no-install-recommends git openssh-client python3 ripgrep ca-certificates curl && rm -rf /var/lib/apt/lists/*\nRUN npm install -g @openai/codex @anthropic-ai/claude-code @tencent-ai/codebuddy-code\nWORKDIR /workspace\n" +const isolatedDockerfileBase = "FROM node:22-bookworm\nRUN apt-get update && apt-get install -y --no-install-recommends git openssh-client python3 ripgrep ca-certificates curl && rm -rf /var/lib/apt/lists/*\n" +const legacyIsolatedDockerfile = isolatedDockerfileBase + "RUN npm install -g @openai/codex @anthropic-ai/claude-code @tencent-ai/codebuddy-code\nWORKDIR /workspace\n" + +// IsolatedDockerfile is the fallback for profiles without a custom image. +const IsolatedDockerfile = isolatedDockerfileBase + "RUN npm install -g @openai/codex @anthropic-ai/claude-code\nARG CODEBUDDY_PACKAGE=@tencent-ai/codebuddy-code\nRUN if [ -n \"$CODEBUDDY_PACKAGE\" ]; then npm install -g \"$CODEBUDDY_PACKAGE\"; fi\nWORKDIR /workspace\n" + +func isBuiltInIsolatedDockerfile(dockerfile domain.DockerfileDefinition) bool { + return len(dockerfile.Files) == 0 && (dockerfile.Content == IsolatedDockerfile || dockerfile.Content == legacyIsolatedDockerfile) +} + +func effectiveIsolatedDockerfile(dockerfile domain.DockerfileDefinition) domain.DockerfileDefinition { + if os.Getenv("AGENTFLOW_SKIP_CODEBUDDY_INSTALL") == "1" && isBuiltInIsolatedDockerfile(dockerfile) { + dockerfile.Content = strings.Replace(IsolatedDockerfile, "ARG CODEBUDDY_PACKAGE=@tencent-ai/codebuddy-code", "ARG CODEBUDDY_PACKAGE=", 1) + } + return dockerfile +} // PrebuildIsolatedImage warms the shared sandbox image in the background so // the first SOP on a fresh container install does not wait for the build. diff --git a/internal/runtime/sandbox_process.go b/internal/runtime/sandbox_process.go index f41bcef3..0f4a77ac 100644 --- a/internal/runtime/sandbox_process.go +++ b/internal/runtime/sandbox_process.go @@ -53,7 +53,7 @@ func appendEnvironment(base []string, overlays ...map[string]string) []string { func controlledBaseEnvironment(base []string) []string { blocked := []string{ - "CODEBUDDY_API_KEY=", + "CODEBUDDY_API_KEY=", "CODEBUDDY_BASE_URL=", "OPENAI_API_KEY=", "CODEX_API_KEY=", "OPENAI_BASE_URL=", "ANTHROPIC_API_KEY=", "ANTHROPIC_AUTH_TOKEN=", "ANTHROPIC_BASE_URL=", "CLAUDE_CODE_OAUTH_TOKEN=", "CODEX_HOME=", "CLAUDE_CONFIG_DIR=", diff --git a/internal/tracker/catalog.go b/internal/tracker/catalog.go index bbb9e7d7..b7d9585b 100644 --- a/internal/tracker/catalog.go +++ b/internal/tracker/catalog.go @@ -17,7 +17,7 @@ type mcpBinding struct { Source string } -func bindTrackerMCP(kind string, cfg domain.SyncConfig, servers []domain.MCPServerDefinition, envToken, codebuddyAuth string) mcpBinding { +func bindTrackerMCP(kind string, cfg domain.SyncConfig, servers []domain.MCPServerDefinition, envToken string) mcpBinding { kind = strings.ToLower(strings.TrimSpace(kind)) cfgURL := strings.TrimSpace(cfg.GongfengMCPURL) exact := []string{"gongfeng-delivery", "gongfeng"} @@ -59,12 +59,13 @@ func bindTrackerMCP(kind string, cfg domain.SyncConfig, servers []domain.MCPServ return out } if !headerHas(out.Headers, "Authorization") { - out.Headers = applyAuthFallback(out.Headers, envToken, codebuddyAuth) + token := strings.TrimSpace(envToken) + if token != "" { + out.Headers["Authorization"] = bearerHeader(token) + } if out.Source == "" { - if strings.TrimSpace(envToken) != "" { + if token != "" { out.Source = "env:AGENTFLOW_MCP_TOKEN" - } else if strings.TrimSpace(codebuddyAuth) != "" { - out.Source = "codebuddy:mcp.json" } else { out.Source = "none" } @@ -97,7 +98,7 @@ func bindProjectUserTrackerMCP(kind string, cfg domain.SyncConfig, servers []dom projectServers = append(projectServers, server) } } - binding := bindTrackerMCP(kind, cfg, projectServers, "", "") + binding := bindTrackerMCP(kind, cfg, projectServers, "") if strings.TrimSpace(binding.URL) == "" { return binding, fmt.Errorf("项目 %s 未配置 %s MCP 地址", projectID, trackerDisplayName(kind)) } @@ -168,26 +169,6 @@ func findCatalogHTTP(servers []domain.MCPServerDefinition, exactIDs, needles []s return matches[0], true } -func applyAuthFallback(hdrs map[string]string, envToken, codebuddyAuth string) map[string]string { - out := hdrs - if out == nil { - out = map[string]string{} - } else { - out = maps.Clone(out) - } - if headerHas(out, "Authorization") { - return out - } - if token := strings.TrimSpace(envToken); token != "" { - out["Authorization"] = bearerHeader(token) - return out - } - if auth := strings.TrimSpace(codebuddyAuth); auth != "" { - out["Authorization"] = bearerHeader(auth) - } - return out -} - func bearerHeader(value string) string { value = strings.TrimSpace(value) if strings.HasPrefix(strings.ToLower(value), "bearer ") { diff --git a/internal/tracker/catalog_test.go b/internal/tracker/catalog_test.go index 5dc4c8ba..4ea50ed9 100644 --- a/internal/tracker/catalog_test.go +++ b/internal/tracker/catalog_test.go @@ -49,14 +49,14 @@ func TestBindTrackerMCPPrefersCatalogHeadersOverEnvToken(t *testing.T) { URL: "https://mcp-gateway.example.com/gongfeng", Headers: map[string]string{"Authorization": "Bearer catalog-pat"}, }} - gf := bindTrackerMCP("gongfeng", cfg, servers, "expired-env-token", "Bearer expired-oauth") + gf := bindTrackerMCP("gongfeng", cfg, servers, "expired-env-token") if gf.Source != "catalog:gongfeng-delivery" { t.Fatalf("gongfeng source=%q", gf.Source) } if gf.Headers["Authorization"] != "Bearer catalog-pat" { t.Fatalf("gongfeng auth=%q", gf.Headers["Authorization"]) } - tapd := bindTrackerMCP("tapd", cfg, servers, "expired-env-token", "Bearer expired-oauth") + tapd := bindTrackerMCP("tapd", cfg, servers, "expired-env-token") if tapd.Source != "catalog:gongfeng-delivery+tapd-url" { t.Fatalf("tapd source=%q", tapd.Source) } @@ -74,7 +74,7 @@ func TestBindTrackerMCPUsesDedicatedTAPDCatalog(t *testing.T) { {ID: "gongfeng-delivery", Transport: "http", URL: "https://mcp-gateway.example.com/gongfeng", Headers: map[string]string{"Authorization": "Bearer gf"}}, {ID: "tapd-delivery", Transport: "http", URL: "https://mcp-gateway.example.com/tapd/", Headers: map[string]string{"Authorization": "Bearer tapd"}}, } - got := bindTrackerMCP("tapd", cfg, servers, "env", "") + got := bindTrackerMCP("tapd", cfg, servers, "env") if got.Source != "catalog:tapd-delivery" || got.Headers["Authorization"] != "Bearer tapd" { t.Fatalf("got %+v", got) } @@ -82,15 +82,15 @@ func TestBindTrackerMCPUsesDedicatedTAPDCatalog(t *testing.T) { func TestBindTrackerMCPFallsBackWhenCatalogMissing(t *testing.T) { cfg := domain.SyncConfig{GongfengMCPURL: "https://mcp-gateway.example.com/gongfeng"} - got := bindTrackerMCP("gongfeng", cfg, nil, "env-token", "") + got := bindTrackerMCP("gongfeng", cfg, nil, "env-token") if got.Source != "env:AGENTFLOW_MCP_TOKEN" { t.Fatalf("source=%q", got.Source) } if got.Headers["Authorization"] != "Bearer env-token" { t.Fatalf("auth=%q", got.Headers["Authorization"]) } - got = bindTrackerMCP("gongfeng", cfg, nil, "", "Bearer oauth") - if got.Source != "codebuddy:mcp.json" || !strings.Contains(got.Headers["Authorization"], "oauth") { + got = bindTrackerMCP("gongfeng", cfg, nil, "") + if got.Source != "none" || got.Headers["Authorization"] != "" { t.Fatalf("got %+v", got) } } diff --git a/internal/tracker/mcp_client.go b/internal/tracker/mcp_client.go index b2fa7cb1..0d2e6afc 100644 --- a/internal/tracker/mcp_client.go +++ b/internal/tracker/mcp_client.go @@ -1,12 +1,6 @@ package tracker -import ( - "encoding/json" - "os" - "path/filepath" - - "agentflow/internal/mcpclient" -) +import "agentflow/internal/mcpclient" // MCPClient is a Streamable HTTP MCP client used by issue/MR sync. type MCPClient = mcpclient.Client @@ -14,30 +8,3 @@ type MCPClient = mcpclient.Client func NewMCPClient(url string, headers map[string]string) *MCPClient { return mcpclient.New(url, headers) } - -// LoadAuthFromCodeBuddy reads ~/.codebuddy/mcp.json and extracts the -// Authorization bearer token for a named MCP server. Returns "" if not found. -// CodeBuddy stores per-server OAuth tokens here; they auto-refresh on expiry. -func LoadAuthFromCodeBuddy(serverName string) string { - home, err := os.UserHomeDir() - if err != nil { - return "" - } - path := filepath.Join(home, ".codebuddy", "mcp.json") - data, err := os.ReadFile(path) - if err != nil { - return "" - } - var cfg struct { - MCPServers map[string]struct { - Headers map[string]string `json:"headers"` - } `json:"mcpServers"` - } - if json.Unmarshal(data, &cfg) != nil { - return "" - } - if srv, ok := cfg.MCPServers[serverName]; ok { - return srv.Headers["Authorization"] - } - return "" -} diff --git a/internal/tracker/mr_delivery_sync.go b/internal/tracker/mr_delivery_sync.go index 212d9d03..e327b105 100644 --- a/internal/tracker/mr_delivery_sync.go +++ b/internal/tracker/mr_delivery_sync.go @@ -202,7 +202,7 @@ func (s *Service) discoverPromoteMRs(store MRDeliveryStore) { if mr.IID <= 0 { continue } - url := "https://git.example.com/" + project + "/merge_requests/" + strconv.Itoa(mr.IID) + url := domain.GongfengMRURL(project, mr.IID) if err := store.EnsureMRDeliveryState(project, mr.IID, url, domain.BaselinePromoteIssueID); err != nil { log.Printf("mr-delivery ensure promote %s!%d: %v", project, mr.IID, err) continue diff --git a/internal/tracker/service.go b/internal/tracker/service.go index 7edf45f7..8df2c74e 100644 --- a/internal/tracker/service.go +++ b/internal/tracker/service.go @@ -90,8 +90,7 @@ func NewService() *Service { } // Configure updates the sync config and recreates MCP clients. -// Prefer catalog HTTP MCP Headers (the same assets Agent steps use). Fall back -// to AGENTFLOW_MCP_TOKEN, then ~/.codebuddy/mcp.json OAuth. +// Prefer the catalog MCP headers, then the deployment's AGENTFLOW_MCP_TOKEN. func (s *Service) Configure(cfg domain.SyncConfig) { s.ConfigureWithCatalog(cfg, nil) } @@ -99,8 +98,8 @@ func (s *Service) Configure(cfg domain.SyncConfig) { // ConfigureWithCatalog binds Gongfeng/TAPD clients from catalog MCP assets. func (s *Service) ConfigureWithCatalog(cfg domain.SyncConfig, servers []domain.MCPServerDefinition) { s.cfg.Set(cfg) - gf := bindTrackerMCP("gongfeng", cfg, servers, s.authToken, LoadAuthFromCodeBuddy("gongfeng")) - tapd := bindTrackerMCP("tapd", cfg, servers, s.authToken, LoadAuthFromCodeBuddy("tapd")) + gf := bindTrackerMCP("gongfeng", cfg, servers, s.authToken) + tapd := bindTrackerMCP("tapd", cfg, servers, s.authToken) s.gfSource, s.tapdSource = gf.Source, tapd.Source if gf.URL != "" { s.gongfeng = NewMCPClient(gf.URL, gf.Headers) @@ -1187,7 +1186,7 @@ func (s *Service) upsertTAPDRecord(store IssueStoreAdapter, projectID, workspace ExternalRef: &domain.ExternalRef{ Source: "tapd", ExternalID: st.ID, - ExternalURL: fmt.Sprintf("https://tapd.example.com/tapd_fe/%s/%s/detail/%s", workspaceID, externalType, st.ID), + ExternalURL: tapdWorkItemURL(workspaceID, externalType, st.ID), ExternalState: st.Status, ExternalType: externalType, SyncedAt: time.Now().UTC(), @@ -1348,7 +1347,7 @@ func (s *Service) CreateTAPDStory(store IssueStoreAdapter, issue domain.Issue) ( issue.ExternalRef = &domain.ExternalRef{ Source: "tapd", ExternalID: st.ID, - ExternalURL: fmt.Sprintf("https://tapd.example.com/tapd_fe/%s/story/detail/%s", workspaceID, st.ID), + ExternalURL: tapdWorkItemURL(workspaceID, "story", st.ID), ExternalState: st.Status, ExternalType: "story", SyncedAt: time.Now().UTC(), diff --git a/internal/tracker/tapd_import_test.go b/internal/tracker/tapd_import_test.go index 788817f7..82b14199 100644 --- a/internal/tracker/tapd_import_test.go +++ b/internal/tracker/tapd_import_test.go @@ -51,6 +51,7 @@ func TestImportTAPDStoryFromTitleAndLink(t *testing.T) { svc.Configure(domain.SyncConfig{TAPDMCPURL: gateway.URL}) store := &memIssueStore{projects: map[string]domain.Project{"dp": {ID: "dp"}}} const link = "https://tapd.example.com/tapd_fe/10000000/story/detail/1010000000100001554" + const canonical = "https://www.tapd.cn/tapd_fe/10000000/story/detail/1010000000100001554" issue, err := svc.ImportTAPDStory(store, "dp", "【DP】用户复制的标题\n"+link, 0) if err != nil { t.Fatal(err) @@ -58,11 +59,11 @@ func TestImportTAPDStoryFromTitleAndLink(t *testing.T) { if issue.Title != "TAPD 中的最新标题" { t.Fatalf("title should come from TAPD, got %q", issue.Title) } - if issue.ExternalRef == nil || issue.ExternalRef.ExternalURL != link { + if issue.ExternalRef == nil || issue.ExternalRef.ExternalURL != canonical { t.Fatalf("external reference should contain only the canonical URL, got %+v", issue.ExternalRef) } stored, ok := store.Issue(issue.ID) - if !ok || stored.ExternalRef == nil || stored.ExternalRef.ExternalURL != link { + if !ok || stored.ExternalRef == nil || stored.ExternalRef.ExternalURL != canonical { t.Fatalf("stored issue has invalid external reference: %+v", stored) } } diff --git a/internal/tracker/tapd_task_import_test.go b/internal/tracker/tapd_task_import_test.go index 8d60f47d..791842b2 100644 --- a/internal/tracker/tapd_task_import_test.go +++ b/internal/tracker/tapd_task_import_test.go @@ -13,7 +13,7 @@ import ( "agentflow/internal/repo" ) -const testTAPDTaskURL = "https://tapd.example.com/tapd_fe/10000000/task/detail/1010000000100000444" +const testTAPDTaskURL = "https://www.tapd.cn/tapd_fe/10000000/task/detail/1010000000100000444" func TestParseTAPDTaskURL(t *testing.T) { want := TAPDStoryRef{WorkspaceID: "10000000", StoryID: "1010000000100000444", Kind: "task"} diff --git a/internal/tracker/tapd_url.go b/internal/tracker/tapd_url.go index 11b35b39..9d5f5cda 100644 --- a/internal/tracker/tapd_url.go +++ b/internal/tracker/tapd_url.go @@ -5,6 +5,8 @@ import ( "net/url" "regexp" "strings" + + "agentflow/internal/config" ) // TAPDStoryRef is a TAPD record identified from a pasted web URL. @@ -18,12 +20,21 @@ type TAPDStoryRef struct { var ( // Capture complete URLs before looking for bare TAPD hosts, so a TAPD URL // inside another host's path or query cannot pass the host check. - tapdPastedURLRe = regexp.MustCompile("(?i)(?:[a-z][a-z0-9+.-]*://|//|(?:tapd\\.example\\.com|(?:www\\.)?tapd\\.cn)/)[^\\s\\p{Z}<>\\[\\](){}\"'`,。;:!?、()【】《》「」『』]+") + tapdPastedURLRe = tapdURLPattern("www.tapd.cn") tapdWorkspacePathRe = regexp.MustCompile(`^/(?:tapd_fe/)?(\d{2,12})(?:/|$)`) tapdDetailPathRe = regexp.MustCompile(`/(story/detail|stories/view|bug/detail|bugs/view|task/detail|tasks/view)/(\d+)/?$`) tapdPreviewIDRe = regexp.MustCompile(`^(story|bug|task)_(\d+)$`) ) +func tapdURLPattern(host string) *regexp.Regexp { + return regexp.MustCompile("(?i)(?:[a-z][a-z0-9+.-]*://|//|(?:tapd\\.example\\.com|(?:www\\.)?tapd\\.cn|" + + regexp.QuoteMeta(host) + ")/)[^\\s\\p{Z}<>\\[\\](){}\"'`,。;:!?、()【】《》「」『』]+") +} + +func tapdWorkItemURL(workspace, kind, id string) string { + return fmt.Sprintf("https://%s/tapd_fe/%s/%s/detail/%s", config.TAPDWebHost(), workspace, kind, id) +} + // ParseTAPDStoryURL extracts one TAPD record from a URL or pasted title and // link. Repeated links to the same record are harmless; different records must // be imported separately to avoid silently choosing the wrong requirement. @@ -34,7 +45,11 @@ func ParseTAPDStoryURL(raw string) (TAPDStoryRef, error) { } var found TAPDStoryRef var firstErr error - for _, match := range tapdPastedURLRe.FindAllStringIndex(raw, -1) { + pattern := tapdPastedURLRe + if host := config.TAPDWebHost(); host != "www.tapd.cn" { + pattern = tapdURLPattern(host) + } + for _, match := range pattern.FindAllStringIndex(raw, -1) { candidate := raw[match[0]:match[1]] // A bare host must stand on its own, rather than be a suffix of a // foreign hostname or e-mail address. @@ -74,8 +89,10 @@ func parseTAPDStoryLink(raw string) (TAPDStoryRef, error) { return TAPDStoryRef{}, fmt.Errorf("无法识别 TAPD 链接") } host := strings.ToLower(parsed.Hostname()) - if (parsed.Scheme != "https" && parsed.Scheme != "http") || (host != "tapd.example.com" && host != "www.tapd.cn" && host != "tapd.cn") { - return TAPDStoryRef{}, fmt.Errorf("请粘贴 tapd.example.com 或 tapd.cn 的需求详情链接") + configuredHost := config.TAPDWebHost() + if (parsed.Scheme != "https" && parsed.Scheme != "http") || parsed.User != nil || + (host != "tapd.example.com" && host != "www.tapd.cn" && host != "tapd.cn" && !strings.EqualFold(parsed.Host, configuredHost)) { + return TAPDStoryRef{}, fmt.Errorf("请粘贴 %s 的 TAPD 工作项详情链接", configuredHost) } path := parsed.Path ref := TAPDStoryRef{Kind: "story"} diff --git a/internal/tracker/tapd_url_test.go b/internal/tracker/tapd_url_test.go index 5e62d7f5..9cfc5b00 100644 --- a/internal/tracker/tapd_url_test.go +++ b/internal/tracker/tapd_url_test.go @@ -5,6 +5,18 @@ import ( "testing" ) +func TestTAPDConfiguredWebHost(t *testing.T) { + t.Setenv("AGENTFLOW_TAPD_HOST", "tapd.review.test:8443") + const detail = "tapd.review.test:8443/tapd_fe/10000000/story/detail/1010000000100001554" + ref, err := ParseTAPDStoryURL("测试工作项\n" + detail) + if err != nil || ref.WorkspaceID != "10000000" || ref.StoryID != "1010000000100001554" || ref.Kind != "story" { + t.Fatalf("managed work item = %+v, %v", ref, err) + } + if got := tapdWorkItemURL(ref.WorkspaceID, ref.Kind, ref.StoryID); got != "https://"+detail { + t.Fatalf("managed work item URL = %s", got) + } +} + func TestParseTAPDStoryURLPastedText(t *testing.T) { const storyURL = "https://tapd.example.com/tapd_fe/10000000/story/detail/1010000000100001554" want := TAPDStoryRef{WorkspaceID: "10000000", StoryID: "1010000000100001554", Kind: "story"} diff --git a/internal/tracker/tracker_cases_test.go b/internal/tracker/tracker_cases_test.go index 63a38202..98093560 100644 --- a/internal/tracker/tracker_cases_test.go +++ b/internal/tracker/tracker_cases_test.go @@ -280,28 +280,27 @@ func TestTAPDParsingAndMessages(t *testing.T) { } } -func TestCodeBuddyAuthLoading(t *testing.T) { +func TestTrackerDoesNotUseHostCodeBuddyCredentials(t *testing.T) { home := t.TempDir() t.Setenv("HOME", home) dir := filepath.Join(home, ".codebuddy") if err := os.MkdirAll(dir, 0o700); err != nil { t.Fatal(err) } - path := filepath.Join(dir, "mcp.json") - if err := os.WriteFile(path, []byte(`{"mcpServers":{"gongfeng":{"headers":{"Authorization":"Bearer token"}}}}`), 0o600); err != nil { + data := []byte(`{"mcpServers":{"gongfeng":{"headers":{"Authorization":"Bearer fixture-gf"}},"tapd":{"headers":{"Authorization":"Bearer fixture-tapd"}}}}`) + if err := os.WriteFile(filepath.Join(dir, "mcp.json"), data, 0o600); err != nil { t.Fatal(err) } - if got := LoadAuthFromCodeBuddy("gongfeng"); got != "Bearer token" { - t.Fatalf("auth = %q", got) - } - if got := LoadAuthFromCodeBuddy("missing"); got != "" { - t.Fatalf("missing auth = %q", got) - } - if err := os.WriteFile(path, []byte(`{`), 0o600); err != nil { - t.Fatal(err) + svc := NewService() + cfg := domain.SyncConfig{GongfengMCPURL: "https://mcp.example.test/gongfeng", TAPDMCPURL: "https://mcp.example.test/tapd"} + svc.Configure(cfg) + if svc.gongfeng == nil || svc.tapd == nil || svc.gfSource != "none" || svc.tapdSource != "none" { + t.Fatal("the configured endpoints should not inherit host credentials") } - if got := LoadAuthFromCodeBuddy("gongfeng"); got != "" { - t.Fatalf("malformed auth = %q", got) + svc.SetAuthToken("explicit-fixture-token") + svc.Configure(cfg) + if svc.gfSource != "env:AGENTFLOW_MCP_TOKEN" || svc.tapdSource != "env:AGENTFLOW_MCP_TOKEN" { + t.Fatalf("explicit token source = %q / %q", svc.gfSource, svc.tapdSource) } } @@ -442,7 +441,7 @@ func TestCatalogBindingHelpers(t *testing.T) { {ID: "gongfeng", Transport: "http", URL: "https://mcp.example/gf"}, {ID: "ignored", Transport: "stdio", URL: "https://ignored"}, } - binding := bindTrackerMCP("tapd", domain.SyncConfig{}, servers, "token", "") + binding := bindTrackerMCP("tapd", domain.SyncConfig{}, servers, "token") if binding.URL == "" || !headerHas(binding.Headers, "authorization") { t.Fatalf("binding = %#v", binding) } diff --git a/scripts/test-runtime-image.sh b/scripts/test-runtime-image.sh index 8a5d81bc..69f374c3 100755 --- a/scripts/test-runtime-image.sh +++ b/scripts/test-runtime-image.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash set -euo pipefail image="${1:?Usage: bash scripts/test-runtime-image.sh IMAGE}" -docker run --rm -i --network none --read-only --tmpfs /tmp:rw,exec,nosuid,size=128m --entrypoint sh "$image" -eu <<'CHECK' +docker run --rm -i --network none -e LOOPFORGE_EXPECT_CODEBUDDY --read-only --tmpfs /tmp:rw,exec,nosuid,size=128m --entrypoint sh "$image" -eu <<'CHECK' export HOME=/tmp/home mkdir -p "$HOME" cd /tmp @@ -23,7 +23,11 @@ ssh -V unzip -v >/dev/null codex --version if command -v claude >/dev/null; then printf 'Claude Code must not be bundled; it installs on first use.\n' >&2; exit 1; fi -codebuddy --version +case "${LOOPFORGE_EXPECT_CODEBUDDY:-optional}" in + 1) codebuddy --version ;; + 0) if command -v codebuddy >/dev/null; then printf 'CodeBuddy should be absent.\n' >&2; exit 1; fi ;; + *) if command -v codebuddy >/dev/null; then codebuddy --version; fi ;; +esac dsh --version wecom-cli --version printf 'Runtime image compatibility checks passed.\n' diff --git a/web/app.js b/web/app.js index ba285fe2..5df678da 100644 --- a/web/app.js +++ b/web/app.js @@ -941,6 +941,7 @@ async function boot(){ history.pushState({assetFrom:assetViewHash(state.assetType)},'',assetDetailHash); return; } + if(name==='settings'&&routePart(1)==='executors'){gotoCredential('executors');return} if(activeViewName()!==name){ if(name==='flow')await applyFlowRoute(); if(name==='projects')syncProjectAdminRouteState(); @@ -964,7 +965,8 @@ async function boot(){ }); if(view==='projects')syncProjectAdminRouteState(); renderAll(); - switchView(view); + if(view==='settings'&&routePart(1)==='executors')gotoCredential('executors'); + else switchView(view); settleBootLoader(); if(!['approvals','issues','runs','sops'].includes(state.currentView))preloadApprovalBadge(); restoreRequirementComposer(); @@ -1002,6 +1004,7 @@ window.addEventListener('storage',event=>{if(!event.key||event.key===THEME_KEY)a function bind(){ prepareMCPFormHints(); + $('#returnToQuickAccess')?.addEventListener('click',returnToQuickAccess); $$('.nav[data-view]').forEach(btn=>btn.onclick=async()=>{ if(!(await confirmAssetLeave()))return; if(btn.dataset.view==='projects'&&state.projectAdminDetailId){ @@ -1492,6 +1495,25 @@ function postNativeChatProject(frame){ // requirement already @-mentioned. It waits here until the chat frame can // take it: in the frame URL on first mount, otherwise once the chat is ready. let pendingChatIssueMention=null; +let pendingQuickAccessReturn=false; +const QUICK_ACCESS_EXECUTOR_SETTINGS='#/settings/executors/quick-access'; +let quickAccessExecutorSettingsActive=false; +function postQuickAccessReturn(frame){ + if(!pendingQuickAccessReturn||!nativeChatReady||!frame?.contentWindow)return; + pendingQuickAccessReturn=false; + frame.contentWindow.postMessage({type:'agentflow-chat-resume-quick-access'},location.origin); +} +function returnToQuickAccess(){ + if(location.hash!==QUICK_ACCESS_EXECUTOR_SETTINGS)return; + if(history.state?.quickAccessExecutorReturn){history.back();return} + const chat=new URL('/chatbot/',location.origin),params=new URLSearchParams(location.search); + chat.searchParams.set('quickAccess','1'); + const projectId=params.get('projectId'); + const session=params.get('chatSession'); + if(projectId)chat.searchParams.set('projectId',projectId); + if(session)chat.searchParams.set('session',session); + location.replace(chat); +} function postPendingChatIssueMention(frame){ if(!pendingChatIssueMention||!nativeChatReady||frame?.dataset.src!=='native')return; frame.contentWindow?.postMessage({type:'agentflow-chat-mention-issue',...pendingChatIssueMention},location.origin); @@ -1527,6 +1549,7 @@ function mountNativeChat(){ nativeChatReady=true; postPendingChatIssueMention(frame); postNativeChatProject(frame); + postQuickAccessReturn(frame); finishBootLoader(); } if(message.type==='agentflow-chat-session'){ @@ -1554,6 +1577,14 @@ function mountNativeChat(){ else reloadShellProjects().then(follow).catch(()=>{}); } if(message.type==='agentflow-projects-changed')reloadShellProjects().catch(()=>{}); + if(message.type==='agentflow-credentials-changed'){ + const userId=state.currentUser?.id; + api('/api/users',{silent:true}).then(users=>{ + if(state.currentUser?.id!==userId)return; + const saved=users.find(user=>Number(user.id)===Number(userId)); + if(saved)storeCredentialUser(saved); + }).catch(()=>{}); + } if(message.type==='agentflow-quick-access-completed'){ api('/api/bootstrap',{silent:true}).then(shell=>{ Object.assign(state.data,shell); @@ -1566,7 +1597,12 @@ function mountNativeChat(){ }).catch(()=>{}); } if(message.type==='agentflow-chat-open-view'&&['settings','runners','sops','projects','runs','agents','environments','dockerfiles','sandboxes','flow','mcp'].includes(message.view)){ - if(message.view==='settings'&&CREDENTIAL_FIELDS[message.credential])gotoCredential(message.credential,message.sshRemote); + if(message.view==='settings'&&message.credential){ + if(message.credential==='executors'&&message.returnToQuickAccess===true&&activeViewName()==='collaboration'&&location.hash!==QUICK_ACCESS_EXECUTOR_SETTINGS){ + history.pushState({quickAccessExecutorReturn:true},'',QUICK_ACCESS_EXECUTOR_SETTINGS); + } + gotoCredential(message.credential,message.sshRemote); + } else if(message.view==='sandboxes'&&message.action==='create')createConversationSandbox(message.projectId).catch(error=>toast(error.message)); else if(message.view==='runs'&&/^run-[\w-]+$/.test(message.runId||''))location.hash='#/runs/'+encodeURIComponent(message.runId); else switchView(message.view); @@ -1575,6 +1611,7 @@ function mountNativeChat(){ } if(frame.dataset.src!=='native'){ frame.dataset.src='native'; + nativeChatReady=false; const topParams=new URL(location.href).searchParams; const projectId=nativeChatProjectId(); const sessionId=topParams.get('chatSession')||''; @@ -1889,6 +1926,7 @@ function syncRunHash(id){ function persistView(name,push=false){ localStorage.setItem('agentflow.activeView',name); let next=`#/${name}`; + if(name==='settings'&&location.hash===QUICK_ACCESS_EXECUTOR_SETTINGS)next=QUICK_ACCESS_EXECUTOR_SETTINGS; if(name==='runs'){ const linked=runRouteId(); if(linked)next=runViewHash(linked); @@ -1924,6 +1962,14 @@ function switchView(name){ // 手敲 #/platform 或者从别的账号留下的 localStorage 恢复进来,都要挡住。 if(name==='platform'&&!isPlatformAdmin())name='collaboration'; const previous=activeViewName(); + if(name!=='settings')cancelCredentialFocus(); + if(previous==='settings'&&name!=='settings'){ + window.HuiPopover?.closeAll?.(); + window.HuiTooltip?.hide?.(); + closeCredentialWizard(true); + $('#gitHTTPCredentialDialog')?.close(); + $('#gitSSHKeyDialog')?.close(); + } if(previous==='agents'&&name!=='agents')$('#agentModal')?.classList.remove('open'); if(!settingsRouteApplying){ const crossingSettings=previous!==name&&((previous==='collaboration'&&isSettingsManagementView(name))||(isSettingsManagementView(previous)&&name==='collaboration')); @@ -1963,6 +2009,15 @@ function switchView(name){ //(staying)不压;hashchange 后退触发的调用 prevView 非空且 hash 已是目标值, // persistView 内部会短路,不会重复压栈。 persistView(name,!staying&&!!prevView); + const resumeQuickAccess=name==='collaboration'&&quickAccessExecutorSettingsActive; + quickAccessExecutorSettingsActive=name==='settings'&&location.hash===QUICK_ACCESS_EXECUTOR_SETTINGS; + const quickAccessReturnButton=$('#returnToQuickAccess'); + if(quickAccessReturnButton)quickAccessReturnButton.hidden=!quickAccessExecutorSettingsActive; + if(name!=='collaboration')pendingQuickAccessReturn=false; + if(resumeQuickAccess){ + pendingQuickAccessReturn=true; + postQuickAccessReturn($('#chatNextFrame')); + } const nav=$('.platform-sidebar nav'); if(nav){ if(['dashboard','issues','approvals'].includes(name)){ diff --git a/web/app/access.js b/web/app/access.js index cba9aa2d..beae42a7 100644 --- a/web/app/access.js +++ b/web/app/access.js @@ -42,9 +42,10 @@ function accessPublicBaseURL(configured, page){ } function accessViewActive(){return !!$('#guideView')?.classList.contains('active')} let credentialFocusRequest=0; +function cancelCredentialFocus(){credentialFocusRequest++} function gotoCredential(name,sshRemote){ const request=++credentialFocusRequest; - if(!CREDENTIAL_FIELDS[name]){switchView('settings');return} + if(name!=='executors'&&!Object.hasOwn(CREDENTIAL_FIELDS,name)){switchView('settings');return} if(name==='gitSshKey')return openGitSSHKeys(sshRemote); if(name==='gitHttpCredentials')return openGitHTTPCredentials(); switchView('settings'); @@ -62,9 +63,17 @@ function gotoCredential(name,sshRemote){ } if(performance.now()syncAgentTabIndicators()).catch(()=>{}); function pickerHTML(items,selected,prefix){return `${(items||[]).map(x=>``).join('')||'暂无可用资产,请先到对应的资产管理页面添加'}`} function bindPickerFilters(root){(root||document).querySelectorAll('[data-picker-filter]').forEach(input=>input.oninput=()=>{const q=input.value.trim().toLowerCase();input.parentElement.querySelectorAll('.asset-check').forEach(row=>row.hidden=!!q&&!row.textContent.toLowerCase().includes(q))})} -function executorOptions(selected){const allowed=new Set(['codebuddy','codex','claude','opencode','cursor','agy','kimi','pi','dsh','zcode']),items=(state.data.executors||[]).filter(x=>allowed.has(x.id)),legacy=selected&&!allowed.has(selected)?``:'';return legacy+items.map(x=>``).join('')} +function executorOptions(selected){ + const allowed=new Set(['codebuddy','codex','claude','opencode','cursor','agy','kimi','pi','dsh','zcode']); + const items=(state.data.executors||[]).filter(executor=>allowed.has(executor.id)); + const inherited=``; + const legacy=selected&&!allowed.has(selected) + ?``:''; + return inherited+legacy+items.map(executor=>``).join(''); +} +function storedAgentExecutorId(agent){ + return agent?.executorId||(agent?.model||agent?.effort?'codebuddy':''); +} const AGENT_CUSTOM_MODEL='__custom__'; let executorModelCatalogUser, executorModelCatalogRequest, agentModelRevision=0; function executorModelCatalogs(){ @@ -140,7 +150,7 @@ function loadExecutorModelCatalogs(){ return request.pending; } function agentModelAPI(){return window.AgentFlowAssistantModels} -function currentAgentExecutorId(){return $('#agentForm')?.elements?.executorId?.value||'codebuddy'} +function currentAgentExecutorId(){return $('#agentForm')?.elements?.executorId?.value||''} function agentModelItems(executorId,current){ const cat=executorModelCatalogs()[executorId]||{},items=(cat.models||[]).filter(item=>item.id!=='default'); if(current&¤t!=='default'&¤t!==AGENT_CUSTOM_MODEL&&!items.some(m=>m.id===current))items.push({id:current,name:`${current}(历史模型)`,family:'other'}); @@ -197,16 +207,25 @@ function renderAgentEffortPicker(modelChanged=false){ paintAgentPicker('#agentEffortPicker',items.find(x=>x.id===current)||{id:current,name:current,icon:false}); } function applyAgentModelUI(executorId,model,effort,pickFirst=false){ - const picker=$('#agentModelPicker');if(!picker||!$('#agentEffortPicker'))return; + const picker=$('#agentModelPicker'),effortPicker=$('#agentEffortPicker');if(!picker||!effortPicker)return; + for(const control of [picker,effortPicker]){ + const toggle=control.querySelector('[data-model-toggle]'); + if(!toggle)continue; + toggle.disabled=!executorId; + if(!executorId){ + control.querySelector('.ai-model-menu').hidden=true; + toggle.setAttribute('aria-expanded','false'); + } + } const cat=executorModelCatalogs()[executorId]||{}; // Keep cached models available for manual picks while the catalog refreshes. - let choice=model||(pickFirst&&!executorModelCatalogRequest?(cat.models||[]).find(item=>item.id!=='default')?.id:'')||''; + let choice=executorId?(model||(pickFirst&&!executorModelCatalogRequest?(cat.models||[]).find(item=>item.id!=='default')?.id:'')||''):''; if(choice&&choice!=='default'&&!(cat.models||[]).some(m=>m.id===choice)&&cat.customModel)choice=AGENT_CUSTOM_MODEL; picker.querySelector('[name="modelChoice"]').value=choice; const customInput=$('#agentModelCustomField')?.querySelector('input[name="model"]'); if(customInput&&choice===AGENT_CUSTOM_MODEL)customInput.value=model||''; renderAgentModelPicker(); - $('#agentEffortPicker').querySelector('[name="effort"]').value=effort||''; + effortPicker.querySelector('[name="effort"]').value=executorId?effort||'':''; renderAgentEffortPicker(); } function bindAgentPicker(pickerId,render){ @@ -242,11 +261,15 @@ function selectAgent(a,rerender=true){ const f=$('#agentForm'); ['id','name','description'].forEach(k=>{if(f.elements[k])f.elements[k].value=a[k]||''}); if(f.elements.shared)f.elements.shared.checked=!!a.shared; - if(f.elements.executorId)f.elements.executorId.innerHTML=executorOptions(a.executorId||'codebuddy'); + const prefs=state.data.assistantDefaults; + const preferredId=prefs?.executor==='claude-code'?'claude':prefs?.executor; + const selectedId=storedAgentExecutorId(a)||(!a.id?preferredId:'')||''; + if(f.elements.executorId)f.elements.executorId.innerHTML=executorOptions(selectedId); const modelRevision=++agentModelRevision; const modelUser=state.currentUser?.id; const refreshModels=loadExecutorModelCatalogs(); - applyAgentModelUI(currentAgentExecutorId(),a.model||'',a.effort||'',!a.id); + const personalModel=!a.id&&preferredId===selectedId&&!a.model?prefs?.model:''; + applyAgentModelUI(currentAgentExecutorId(),a.model||personalModel||'',a.effort||(personalModel?prefs.effort:''),!a.id); refreshModels.then(()=>{ if(modelRevision!==agentModelRevision||modelUser!==state.currentUser?.id)return; const model=agentEffectiveModel(f); @@ -254,7 +277,7 @@ function selectAgent(a,rerender=true){ renderAgentModelPicker(); renderAgentEffortPicker(); }else{ - applyAgentModelUI(currentAgentExecutorId(),model,f.elements.effort?.value,!a.id||currentAgentExecutorId()!==(a.executorId||'codebuddy')); + applyAgentModelUI(currentAgentExecutorId(),model,f.elements.effort?.value,!a.id||currentAgentExecutorId()!==storedAgentExecutorId(a)); } if(state.agentModalMode==='create'&&state.agentCreateStep===3)renderAgentCreateReview(); }); @@ -291,7 +314,9 @@ function openAgentWizard(agent=null,initialStep=1,{loaded=false}={}){ const presetHost=$('#agentPresetHost');if(presetHost)presetHost.dataset.ready=''; setAgentModalMode(a?.id?'edit':'create'); if(state.agentModalMode==='create'){state.agentCreatePreset='blank';state.agentIdAuto=true;state.agentIdSuffix=agentSlugSuffix()} - selectAgent(a||{id:'',name:'',version:1,projectId:state.projectFilter||'',shared:false,description:'',prompt:'',rules:[],skills:[],mcpServers:[],hooks:[],loop:{enabled:false,maxIterations:3,onExhausted:'fail'},interventions:[],artifactOutputs:[],verification:[]},false); + const preference=state.data.assistantDefaults||{}; + const executorId=preference.executor==='claude-code'?'claude':preference.executor; + selectAgent(a||{id:'',name:'',version:1,projectId:state.projectFilter||'',shared:false,description:'',prompt:'',executorId,model:preference.model,effort:preference.effort,rules:[],skills:[],mcpServers:[],hooks:[],loop:{enabled:false,maxIterations:3,onExhausted:'fail'},interventions:[],artifactOutputs:[],verification:[]},false); resetAgentIdentityErrors(); if(state.agentModalMode==='create'){syncAgentSlug();setAgentCreateStep(1)} else setAgentTab(AGENT_TABS[Math.max(1,Math.min(4,Number(initialStep)||1))-1]); @@ -429,9 +454,10 @@ function saveAgent(e){ } async function persistAgent(f){ const creating=state.agentModalMode==='create'; - const changedExecutor=currentAgentExecutorId()!==(agentWizardSubject()?.executorId||'codebuddy'); + const executorId=currentAgentExecutorId(); + const changedExecutor=executorId!==storedAgentExecutorId(agentWizardSubject()); const model=agentEffectiveModel(f); - if((creating||changedExecutor||f.elements.modelChoice?.value===AGENT_CUSTOM_MODEL)&&(!model||model==='default')){ + if(executorId&&(creating||changedExecutor||f.elements.modelChoice?.value===AGENT_CUSTOM_MODEL)&&(!model||model==='default')){ toast('请选择模型或填写模型 ID','err'); if(creating)setAgentCreateStep(2); else setAgentTab('identity'); diff --git a/web/app/assistant-models.js b/web/app/assistant-models.js index ee9f6daa..1b7e7095 100644 --- a/web/app/assistant-models.js +++ b/web/app/assistant-models.js @@ -1,7 +1,6 @@ // Shared AI model catalog for the classic SPA. The SOP preview, role, Bot, // scheduler, run-eval and requirement-clarification pickers all read // window.AgentFlowAssistantModels, so this file must load before them. -// Pickers for entries that only run on CodeBuddy use renderCodeBuddyList. // Only the picker chrome lives here; per-feature selections stay in the // callers (localStorage keys, hidden inputs, form fields). (() => { @@ -66,11 +65,22 @@ if (listed) return listed.engine || 'codebuddy'; const value = String(id || ''); const prefix = value.slice(0, Math.max(0, value.indexOf(':'))); - return (source.engines || []).some(e => e.id === prefix) ? prefix : 'codebuddy'; + return Object.hasOwn(CLI_ICON, prefix) ? prefix : 'codebuddy'; } function modelMeta(id) { const value = id || DEFAULT_MODEL; - return catalog.models.find(m => m.id === value) || {id: value, family: familyOf(value), name: value === DEFAULT_MODEL ? '默认' : value}; + const listed = catalog.models.find(m => m.id === value || ('codebuddy:' + m.id === value && !m.engine)); + if (listed) return {...listed, id: value}; + return {id: value, family: familyOf(value), name: value === DEFAULT_MODEL ? '默认' : value}; + } + function concreteModelId(id) { + const value = String(id || '').trim(); + const separator = value.indexOf(':'); + const prefix = value.slice(0, Math.max(0, separator)); + const qualified = Object.hasOwn(CLI_ICON, prefix); + const engine = qualified ? prefix : 'codebuddy'; + const model = qualified ? value.slice(separator + 1) : value; + return model === DEFAULT_MODEL || (engine === 'codebuddy' && model === 'default-model') || !model ? '' : value; } function fillModelIcon(el, family, id) { if (!el) return; @@ -120,6 +130,7 @@ const opt = document.createElement('button'); opt.type = 'button'; opt.setAttribute('role', 'option'); + opt.setAttribute('aria-selected', String(item.id === selectedId)); opt.className = 'ai-model-option' + (item.id === selectedId ? ' is-active' : ''); opt.dataset.id = item.id; if (item.icon !== false) { @@ -149,25 +160,94 @@ function renderList(menu, selectedId, onPick) { renderOptions(menu, catalog.models || [], selectedId, onPick); } - // Requirement clarification, Bot replies, run evals and the SOP preview - // build run on CodeBuddy only, so their pickers list CodeBuddy models and - // never offer a "codex:…" id the server would have to refuse. - function codeBuddyModels() { - return (catalog.models || []).filter(m => (m.engine || 'codebuddy') === 'codebuddy'); + function featurePickerHTML(modelName = '') { + return ` + `; } - function renderCodeBuddyList(menu, selectedId, onPick) { - renderOptions(menu, codeBuddyModels(), selectedId, onPick); + function qualifiedModel(engine, id) { + return id.startsWith(engine + ':') ? id : engine + ':' + id; } - // codeBuddyModel keeps a CodeBuddy id and turns an empty id, or a saved id - // of another CLI, into the CLI default the server resolves itself. - function codeBuddyModel(id) { - const value = String(id || '').trim(); - // The catalog may not have landed yet; the built-in CLI prefixes still count. - if (!value || /^(codex|claude-code):/.test(value) || engineOf(value) !== 'codebuddy') return DEFAULT_MODEL; - return value; + function featureExecutors(source) { + const engines = (source.engines || []).filter(engine => engine.personal ?? engine.configured) + .map(engine => ({...engine, models: []})); + for (const model of source.models || []) { + if (!concreteModelId(model.id)) continue; + const engine = engines.find(engine => engine.id === engineOf(model.id, source)); + if (engine) engine.models.push({...model, id: qualifiedModel(engine.id, model.id)}); + } + return engines; + } + function preferredFeatureModel(source, executor, models) { + if (!executor) return ''; + const preferred = source.preferences?.executor === executor && concreteModelId(source.preferences.model); + const providerDefault = executor === 'codebuddy' && concreteModelId(source.default); + for (const id of [preferred, providerDefault]) { + if (id && models.some(item => item.id === qualifiedModel(executor,id))) return qualifiedModel(executor,id); + } + return models[0]?.id || ''; + } + function bindFeaturePicker(host, {model = '', legacyModel = '', readOnly = false, keepSaved = false, onChange, loadCatalog = load} = {}) { + if (!host || host.modelPickerReady) return host?.modelPickerReady; + const executor = host.querySelector('[data-feature-executor]'); + const models = host.querySelector('[data-feature-model]'); + if (!executor || !models) return; + host.modelPickerReady = loadCatalog().then(source => { + if (!host.isConnected) return; + const engines = featureExecutors(source); + let selected = concreteModelId(model || (!source.preferences?.executor && legacyModel)); + const savedExecutor = selected && engineOf(selected, source); + let engine = engines.find(item => item.id === savedExecutor); + if (keepSaved && savedExecutor && !engine) { + const saved = source.engines?.find(item => item.id === savedExecutor); + if (saved) { + engine = {...saved, models: []}; + engines.push(engine); + } + } + if (engine) selected = qualifiedModel(engine.id, selected); + if (keepSaved && selected && engine && !engine.models.some(item => item.id === selected)) { + engine.models.push({id: selected, name: modelMeta(selected).name}); + } + if (!engine?.models.some(item => item.id === selected)) { + selected = ''; + engine = engines.find(item => item.id === source.preferences?.executor && item.models.length) || + engines.find(item => item.models.length) || engines[0]; + } + executor.replaceChildren(...engines.map(item => { + const option = new Option(item.name, item.id); + option.disabled = !item.models.length; + return option; + })); + if (!engine) executor.prepend(new Option('暂无可用执行器', '')); + executor.value = engine?.id || ''; + executor.disabled = readOnly || !engines.some(item => item.models.length); + + const remembered = new Map(); + const paintModels = (current, value) => { + const items = current?.models || []; + const next = value || preferredFeatureModel(source, current?.id, items); + models.replaceChildren(...items.map(item => new Option(item.name || item.id, item.id))); + if (!items.length) models.append(new Option('暂无可选模型', '')); + models.value = next; + models.disabled = readOnly || !items.length; + }; + paintModels(engine, selected); + executor.onchange = () => { + if (engine) remembered.set(engine.id, models.value); + engine = engines.find(item => item.id === executor.value); + paintModels(engine, remembered.get(engine?.id)); + onChange?.(models.value); + }; + models.onchange = () => onChange?.(models.value); + }).catch(() => { + if (!host.isConnected) return; + executor.options[0].text = '暂无可用执行器'; + models.options[0].text = '暂无可选模型'; + }); + return host.modelPickerReady; } - async function fetchCatalog() { - const resp = await fetch('/api/assistant/models', {headers: {Accept: 'application/json'}, credentials: 'same-origin'}); + async function fetchCatalog(path = '/api/assistant/models') { + const resp = await fetch(path, {headers: {Accept: 'application/json'}, credentials: 'same-origin'}); if (!resp.ok) throw new Error(`模型列表加载失败(${resp.status})`); return resp.json(); } @@ -176,8 +256,8 @@ if (!loading) { loading = fetchCatalog().then(data => { if (Array.isArray(data?.models)) { - const models = data.models.filter(m => m.id !== DEFAULT_MODEL && m.id !== `${m.engine}:default`); - catalog = {default: data.default || DEFAULT_MODEL, models, engines: data.engines || []}; + const models = data.models.filter(m => concreteModelId(m.id)); + catalog = {default: data.default || DEFAULT_MODEL, models, engines: data.engines || [], preferences: data.preferences}; } return catalog; }).catch(() => catalog).finally(() => { loading = null; }); @@ -188,13 +268,16 @@ DEFAULT: DEFAULT_MODEL, catalog: () => catalog, cliIcon: id => Object.hasOwn(CLI_ICON, id) ? '/images/credentials/' + CLI_ICON[id] : '', - codeBuddyModel, - codeBuddyModels, + bindFeaturePicker, + concreteModelId, engineOf, + featureExecutors, + featurePickerHTML, + fetchCatalog, load, paint, paintItem, - renderCodeBuddyList, + preferredFeatureModel, renderList, renderOptions }; diff --git a/web/app/bots.js b/web/app/bots.js index 3dd63320..eab8ba1c 100644 --- a/web/app/bots.js +++ b/web/app/bots.js @@ -1,27 +1,8 @@ function loadBotModels(){return window.AgentFlowAssistantModels?.load?.()||Promise.resolve()} -function botModelPickerHTML(bot){return `
    `} -function closeBotModelPicker(){const picker=document.querySelector('#botModelPicker');if(!picker)return;picker.querySelector('.ai-model-menu').hidden=true;picker.querySelector('[data-model-toggle]').setAttribute('aria-expanded','false')} -function bindBotModelPicker(host){ - const picker=host.querySelector('#botModelPicker'),models=window.AgentFlowAssistantModels; - if(!picker||!models)return; - const toggle=picker.querySelector('[data-model-toggle]'),menu=picker.querySelector('.ai-model-menu'),value=picker.querySelector('[name="model"]'); - models.paint(toggle,value.value); - toggle.onclick=event=>{ - event.stopPropagation();if(toggle.disabled||toggle.closest('fieldset')?.disabled)return; - const open=menu.hidden;closeBotModelPicker();if(!open)return; - models.renderCodeBuddyList(menu,value.value,id=>{value.value=id;models.paint(toggle,id);captureBotDraft(host);closeBotModelPicker()}); - const rect=toggle.getBoundingClientRect(),width=Math.min(Math.max(rect.width,320),window.innerWidth-24),height=Math.min(320,window.innerHeight-24),below=window.innerHeight-rect.bottom-12,above=rect.top-12; - menu.style.width=width+'px';menu.style.left=Math.max(12,Math.min(rect.left,window.innerWidth-width-12))+'px'; - const down=below>=Math.min(height,above);const available=down?below:above; - menu.style.maxHeight=Math.min(height,available)+'px';menu.style.top=(down?rect.bottom+6:Math.max(12,rect.top-Math.min(height,available)-6))+'px'; - menu.hidden=false;toggle.setAttribute('aria-expanded','true'); - }; - host.querySelector('fieldset').onscroll=closeBotModelPicker; - if(!bindBotModelPicker.docBound){bindBotModelPicker.docBound=true;document.addEventListener('click',event=>{if(!event.target.closest('#botModelPicker'))closeBotModelPicker()});document.addEventListener('keydown',event=>{if(event.key==='Escape')closeBotModelPicker()});window.addEventListener('resize',closeBotModelPicker)} -} +function botModelPickerHTML(){return `
    ${globalThis.AgentFlowAssistantModels?.featurePickerHTML('model')||''}
    `} // Project-scoped enterprise chat notifications. const botUI={projectId:'',items:[],deliveries:[],selected:null,sessions:[],query:'',loading:false,error:'',busy:false,busyAction:'',revision:0,tab:'list',step:1,recordsTab:'deliveries',interactionBotId:'',interaction:null,interactionLoading:false,interactionError:'',testResult:'',flashId:'',motion:null,animations:[],shownCount:null,shownError:'',watchTimer:0,watchCount:0,deletingId:''}; -const BOT_TABS=['list','edit','records'],BOT_STEPS=[[1,'填写凭据'],[2,'选择接收会话'],[3,'发送测试']],BOT_DEFAULT_MODEL='glm-5.3-flash-ioa'; +const BOT_TABS=['list','edit','records'],BOT_STEPS=[[1,'填写凭据'],[2,'选择接收会话'],[3,'发送测试']]; // In-progress states breathe; terminal states stay still. const BOT_LIVE_STATES=['pending','sending','connecting','reconnecting','queued','running','ready']; const BOT_CONNECTION={connected:['已连接','success'],connecting:['连接中','info'],reconnecting:['重连中','info'],error:['连接异常','error'],offline:['未连接','neutral']}; @@ -39,7 +20,12 @@ function canManageBot(bot){ function botStepAllowed(bot,step){return step===1||(step===2&&!!bot?.id)||(step===3&&!!bot?.id&&!!bot?.target&&!bot._targetChanged)} function botStepDone(bot,step){return step===1?!!bot?.id:step===2?botStepAllowed(bot,3):false} function botStoredBot(bot){return bot?.id?botUI.items.find(b=>b.id===bot.id):null} -function botCredentialsDirty(bot){const stored=botStoredBot(bot);if(!stored)return !!bot;return !!bot._secret||(bot.name||'')!==(stored.name||'')||(bot.botId||'')!==(stored.botId||'')||(bot.model||BOT_DEFAULT_MODEL)!==(stored.model||BOT_DEFAULT_MODEL)||!!bot.enabled!==!!stored.enabled||!!bot.interactionEnabled!==!!stored.interactionEnabled} +function botCredentialsDirty(bot){ + const stored=botStoredBot(bot); + if(!stored)return !!bot; + const modelID=value=>(value||'').replace(/^codebuddy:/,''); + return !!bot._secret||(bot.name||'')!==(stored.name||'')||(bot.botId||'')!==(stored.botId||'')||modelID(bot.model)!==modelID(stored.model)||!!bot.enabled!==!!stored.enabled||!!bot.interactionEnabled!==!!stored.interactionEnabled; +} function botIcon(name){return ``} // Harness StatusBadge: in-progress states breathe, settled states carry a glyph so colour is never the only cue. @@ -75,7 +61,8 @@ function botPanelHeadHTML(){ function botTargetHTML(target){return target?`${botTypeLabel(target.type)}${escapeHTML(target.name)}`:'尚未选择接收会话'} function botRowHTML(bot){ const id=escapeHTML(bot.id),name=escapeHTML(bot.name),manage=canManageBot(bot),target=botTargetHTML(bot.target); - const sub=escapeHTML(bot.model||BOT_DEFAULT_MODEL)+(bot.interactionEnabled?' · 已启用对话':''); + const model=globalThis.AgentFlowAssistantModels?.concreteModelId(bot.model)??bot.model; + const sub=[escapeHTML(model||''),bot.interactionEnabled?'已启用对话':''].filter(Boolean).join(' · '); return `
    ${botIcon('robot')}${name}${sub}${target}
    ${target}${botEnabledBadge(bot.enabled)}${botHealthBadge(bot.health)}
    ${manage?``:''}
    `; } function botListHTML(items){ @@ -97,7 +84,7 @@ function botEditTabHTML(bot){ return `
    ${botStepsHTML(bot,step)}
    ${pane}
    ${!manage?'

    仅创建者或项目管理员可修改凭据和接收目标。

    ':''}
    `; } function botCredentialPaneHTML(bot,manage){ - return `

    首次对话请按 Bot 提示关联平台账号;新单聊和群聊会自动建立上下文。发送 /new 或“开启新会话”开始新的对话。

    `; + return `
    执行器与模型${botModelPickerHTML()}

    首次对话请按 Bot 提示关联平台账号;新单聊和群聊会自动建立上下文。发送 /new 或“开启新会话”开始新的对话。

    `; } function botTargetPaneHTML(bot,manage){ const changed=!!bot._targetChanged; @@ -119,7 +106,7 @@ function botRecordsHTML(){ const deliveries=botUI.recordsTab!=='interactions'; return `
    ${botRecordTabsHTML(botUI.recordsTab)}${deliveries?'保留最近 100 条':''}
    ${deliveries?botDeliveryHTML():botInteractionPanelHTML()}
    `; } -function botDeliveryExtraHTML(item){return `${item.reportModel?`CodeBuddy · ${escapeHTML(item.reportModel)}`:''}${item.reportError?`${escapeHTML(item.reportError)}`:''}${item.lastError?`${escapeHTML(item.lastError)}`:''}`} +function botDeliveryExtraHTML(item){return `${item.reportModel?`${escapeHTML(item.reportModel)}`:''}${item.reportError?`${escapeHTML(item.reportError)}`:''}${item.lastError?`${escapeHTML(item.lastError)}`:''}`} function botDeliveryActionHTML(item){const bot=botUI.items.find(b=>b.id===item.botId);return ['failed','awaiting_authorization','target_unavailable'].includes(item.status)&&item.contentSource!=='invalid'&&bot&&canManageBot(bot)?``:''} function botDeliveryHTML(){ if(!botUI.deliveries.length)return '

    暂无发送记录。Agent 节点触发通知后,会在这里展示发送状态。

    '; @@ -315,19 +302,28 @@ function bindBots(host){ host.querySelector('#botInteractionBot')?.addEventListener('change',event=>{botUI.interactionBotId=event.target.value;botUI.interaction=null;botMotion('entries');loadBotInteractions();renderBots()}); host.querySelector('#botRefreshInteractions')?.addEventListener('click',()=>{loadBotInteractions();renderBots()}); } -function captureBotDraft(host){const form=host.querySelector('#botForm');if(!form||!botUI.selected)return;botUI.selected.name=form.elements.name.value;botUI.selected.botId=form.elements.botId.value;botUI.selected.enabled=form.elements.enabled.checked;botUI.selected.model=form.elements.model.value;botUI.selected.interactionEnabled=form.elements.interactionEnabled.checked;botUI.selected._secret=form.elements.secret.value} +function captureBotDraft(host){const form=host.querySelector('#botForm');if(!form||!botUI.selected)return;botUI.selected.name=form.elements.name.value;botUI.selected.botId=form.elements.botId.value;botUI.selected.enabled=form.elements.enabled.checked;botUI.selected.model=form.elements.model?.value||botUI.selected.model||'';botUI.selected.interactionEnabled=form.elements.interactionEnabled.checked;botUI.selected._secret=form.elements.secret.value} function botSaveSelected(saved){const index=botUI.items.findIndex(b=>b.id===saved.id);if(index<0)botUI.items.push(saved);else botUI.items[index]=saved;botUI.selected=structuredClone(saved);botUI.error='';nodeBotCache.delete(botUI.projectId)} function bindBotEditor(host){ host.querySelector('#botDelete')?.addEventListener('click',()=>botDelete(botStoredBot(botUI.selected)||botUI.selected,null)); const form=host.querySelector('#botForm'); if(form){ - bindBotModelPicker(host); + const ready=window.AgentFlowAssistantModels?.bindFeaturePicker(form.querySelector('#botModelPicker'),{ + model:botUI.selected?.model,keepSaved:true,readOnly:form.querySelector('fieldset').disabled + }); form.oninput=event=>{event.target.removeAttribute?.('aria-invalid');captureBotDraft(host)};form.onchange=()=>captureBotDraft(host); form.onsubmit=async event=>{ - event.preventDefault();if(botUI.busy)return;captureBotDraft(host); + event.preventDefault(); + await ready; + if(!form.isConnected||botUI.busy)return; + captureBotDraft(host); const bot=botUI.selected,projectId=botUI.projectId,revision=botUI.revision,creating=!bot.id; const missing=['name','botId',...(creating?['secret']:[])].map(name=>form.elements[name]).filter(input=>!input.value.trim()); if(missing.length){botShake(missing);toast(creating?'请填写名称、Bot ID 和 Secret':'请填写名称和 Bot ID','warn');return} + if(bot.interactionEnabled&&!botStoredBot(bot)?.interactionEnabled&&!window.AgentFlowAssistantModels?.concreteModelId(bot.model)){ + form.querySelector('#botModelPicker [data-feature-model]')?.focus(); + toast('请先选择模型','warn');return; + } const payload={projectId,name:bot.name,botId:bot.botId,enabled:bot.enabled,model:bot.model,interactionEnabled:bot.interactionEnabled,secret:form.elements.secret.value}; if(bot.id&&!payload.secret&&bot.botId===botStoredBot(bot)?.botId&&bot._targetChanged)payload.targetId=bot.target?.id||''; if(bot._targetChanged&&(payload.secret||!bot.id)){toast('请先保存凭据,再刷新并选择目标','warn');return} diff --git a/web/app/flows.js b/web/app/flows.js index 52359ff7..f036534d 100644 --- a/web/app/flows.js +++ b/web/app/flows.js @@ -3,48 +3,48 @@ function workflowPreviewContract(wf){ } const PREVIEW_BUILD_NODE_ID='af-preview-build'; const PREVIEW_BUILD_AGENT_ID='af-preview-builder'; -const PREVIEW_MODEL_FALLBACK=[ - {id:'default',name:'GLM-5.3-Flash'}, - {id:'glm-5.3-ioa',name:'GLM-5.3'}, - {id:'gpt-5.6-terra',name:'GPT-5.6-Terra'}, - {id:'gpt-5.6-luna',name:'GPT-5.6-Luna'}, - {id:'gpt-6-sol',name:'GPT-6-Sol'}, - {id:'claude-sonnet-4.6',name:'Claude-Sonnet-4.6'}, - {id:'kimi-k3-ioa',name:'Kimi-K3'}, - {id:'deepseek-v4.1-flash',name:'DeepSeek-V4.1-Flash'} -]; function isPreviewBuildNode(id){return id===PREVIEW_BUILD_NODE_ID} +function workflowPreviewExecutor(wf){ + const preview=workflowPreviewContract(wf); + const model=preview?.model?.trim(); + return preview?.executorId?.trim()||(model&&!['default','default-model'].includes(model)?'codebuddy':''); +} function workflowPreviewModel(wf){ - const api=window.AgentFlowAssistantModels; - const fallback=(api&&api.DEFAULT)||'default'; - const model=(workflowPreviewContract(wf)||{}).model; - return (model&&String(model).trim())||fallback; -} -function previewModelChoices(){ - const api=window.AgentFlowAssistantModels; - // The preview build node runs on CodeBuddy (executorId codebuddy). - const models=api?.codeBuddyModels?.()||api?.catalog?.()?.models; - if(models&&models.length)return models.map(m=>({id:m.id,name:m.name||m.id})); - return PREVIEW_MODEL_FALLBACK.slice(); -} -function fillPreviewModelSelect(sel, selected){ - if(!sel)return; - const items=previewModelChoices(); - const keep=selected||items[0]?.id||'default'; - if(keep&&!items.some(m=>m.id===keep))items.unshift({id:keep,name:keep}); - sel.innerHTML=items.map(m=>``).join(''); + const model=String(workflowPreviewContract(wf)?.model||'').trim(); + return model==='default'||(model==='default-model'&&workflowPreviewExecutor(wf)==='codebuddy')?'':model; +} +function previewModelOptions(executorId){ + return (executorModelCatalogs()[executorId]?.models||[]).filter(m=>m.id!=='default'&&(executorId!=='codebuddy'||m.id!=='default-model')); +} +function defaultPreviewModel(executorId, items=previewModelOptions(executorId)){ + const prefs=state.data.assistantDefaults; + const preferenceExecutor=prefs?.executor==='claude-code'?'claude':prefs?.executor; + if(preferenceExecutor===executorId&&items.some(item=>item.id===prefs.model))return prefs.model; + const preferred=executorModelCatalogs()[executorId]?.default; + return items.find(item=>item.id===preferred)?.id||items[0]?.id||''; +} +function fillPreviewModelSelect(sel, selected, executorId){ + if(!executorId){ + sel.innerHTML=''; + sel.disabled=true; + return ''; + } + const items=previewModelOptions(executorId); + const model=selected||defaultPreviewModel(executorId,items); + if(model&&!items.some(m=>m.id===model))items.push({id:model,name:model}); + sel.innerHTML=items.length?items.map(m=>``).join(''):''; + sel.disabled=flowReadOnly()||!items.length; + return model; } function ensurePreviewContract(){ const wf=state.workflow;if(!wf)return null; const prev=workflowPreviewContract(wf)||{}; - const api=window.AgentFlowAssistantModels; - const model=(prev.model&&String(prev.model).trim())||(api&&api.DEFAULT)||'default'; wf.preview={ ...prev, enabled:true, kind:'static', - executorId:'codebuddy', - model, + executorId:workflowPreviewExecutor(wf), + model:prev.model??'', sourcePath:prev.sourcePath||'dist', indexFile:prev.indexFile||'index.html', spaFallback:prev.spaFallback!==false, @@ -81,7 +81,7 @@ function syncPreviewBuildGraph(){ name:'构建静态站点', type:'agent', agentId:PREVIEW_BUILD_AGENT_ID, - executorId:'codebuddy', + executorId:workflowPreviewExecutor(wf), executionScope:'run', onFailure:'fail', retryStrategy:'targeted_fix', @@ -196,7 +196,7 @@ function addNode(type,opts={}){ if(existing){openNodeDrawer(existing.id);return toast('预览节点已存在,可拖拽连线调整它的位置')} flowHistory.record(); ensurePreviewContract(); - state.workflow.nodes.push({id:PREVIEW_BUILD_NODE_ID,name:'构建静态站点',type:'agent',agentId:PREVIEW_BUILD_AGENT_ID,executorId:'codebuddy',executionScope:'run',onFailure:'fail',retryStrategy:'targeted_fix',maxAttempts:2,maxReworks:1,position:at,artifactOutputs:[{name:'frontend-preview',path:'dist/index.html',required:true}]}); + state.workflow.nodes.push({id:PREVIEW_BUILD_NODE_ID,name:'构建静态站点',type:'agent',agentId:PREVIEW_BUILD_AGENT_ID,executorId:workflowPreviewExecutor(state.workflow),executionScope:'run',onFailure:'fail',retryStrategy:'targeted_fix',maxAttempts:2,maxReworks:1,position:at,artifactOutputs:[{name:'frontend-preview',path:'dist/index.html',required:true}]}); dirty();openNodeDrawer(PREVIEW_BUILD_NODE_ID); return; } @@ -283,7 +283,10 @@ function flowNodeTint(n){ } function flowNodeEl(id){return document.querySelector(`#nodes .flow-node[data-id="${CSS.escape(id)}"]`)} function nodeMeta(n){ - if(isPreviewBuildNode(n.id))return {kind:'preview',subtitle:'CodeBuddy 静态站点构建',tags:[{text:workflowPreviewModel(state.workflow)}]}; + if(isPreviewBuildNode(n.id)){ + const model=workflowPreviewModel(state.workflow); + return {kind:'preview',subtitle:'静态站点构建',tags:model?[{text:model}]:[]}; + } if(n.type==='agent'){ const a=workflowAgent(n.agentId),generic=catalogGeneric(state.workflow); const e=(state.data.executors||[]).find(x=>x.id===(a?.executorId||n.executorId)); @@ -389,7 +392,7 @@ function flowDiagnostics(){ const nodes=state.workflow.nodes||[],edges=state.workflow.edges||[],incoming=new Map(nodes.map(n=>[n.id,0])),items=[];edges.forEach(e=>incoming.has(e.target)&&incoming.set(e.target,incoming.get(e.target)+1)); const starts=nodes.filter(n=>incoming.get(n.id)===0);items.push({level:!nodes.length?'error':starts.length===1?'ok':'warn',title:'流程入口',detail:!nodes.length?'至少添加一个节点':starts.length===1?`从「${starts[0].name}」开始`:`检测到 ${starts.length} 个入口;这些节点会并行启动`}); items.push({level:state.data.sandboxes?.some(s=>s.id===state.workflow.sandboxProfileId)?'ok':'error',title:'运行沙箱',detail:state.workflow.sandboxProfileId?`整条流程使用 ${state.workflow.sandboxProfileId}`:'尚未选择 Workflow 运行沙箱'}); - nodes.forEach(n=>{if(isPreviewBuildNode(n.id)){const inDeg=edges.filter(e=>e.target===n.id).length;items.push({level:inDeg?'ok':'warn',title:n.name,detail:inDeg?`插在流程中间:CodeBuddy ${workflowPreviewModel(state.workflow)} 构建静态站点,运行成功后归档预览`:'还没有前序依赖,会作为流程入口直接运行;请从上游节点连线到此'});return}if(n.type==='agent'){const missing=[];const agent=workflowAgent(n.agentId);const generic=catalogGeneric(state.workflow);if(!n.agentId)missing.push('角色');else if(!agent)missing.push(generic?'通用模板角色未加载':'角色不属于当前项目或未共享');else if(!generic&&!(agent.executorId||n.executorId))missing.push('角色未选模型');if(!(n.artifactOutputs||[]).length&&!(agent?.artifactOutputs||[]).length)missing.push('角色产物契约');items.push({level:missing.length?'warn':'ok',title:n.name,detail:missing.length?`尚未配置:${missing.join('、')}`:generic?'已绑定通用模板角色;任务书与门禁在角色定义中':'已绑定角色;任务书与门禁在角色定义中'})}if(n.type==='sop'){const missing=[];const wf=sopWorkflowChoices(state.workflow.id).find(w=>w.id===n.sopWorkflowId)||(state.data.workflows||[]).find(w=>w.id===n.sopWorkflowId);if(!n.sopWorkflowId)missing.push('要跑的 SOP');else if(!wf)missing.push('引用的 SOP 不存在');if(n.sopWorkflowId===state.workflow.id)missing.push('不能引用自己');items.push({level:missing.length?'error':'ok',title:n.name,detail:missing.length?`尚未配置:${missing.join('、')}`:`引用「${wf.name}」,产物交给下一步`})}if(n.rejectTo&&!nodes.some(x=>x.id===n.rejectTo))items.push({level:'error',title:n.name,detail:'失败打回目标不存在'})}); + nodes.forEach(n=>{if(isPreviewBuildNode(n.id)){const inDeg=edges.filter(e=>e.target===n.id).length;items.push({level:inDeg?'ok':'warn',title:n.name,detail:inDeg?`插在流程中间:${workflowPreviewModel(state.workflow)} 构建静态站点,运行成功后归档预览`:'还没有前序依赖,会作为流程入口直接运行;请从上游节点连线到此'});return}if(n.type==='agent'){const missing=[];const agent=workflowAgent(n.agentId);const generic=catalogGeneric(state.workflow);if(!n.agentId)missing.push('角色');else if(!agent)missing.push(generic?'通用模板角色未加载':'角色不属于当前项目或未共享');else if(!generic&&!(agent.executorId||n.executorId))missing.push('角色未选模型');if(!(n.artifactOutputs||[]).length&&!(agent?.artifactOutputs||[]).length)missing.push('角色产物契约');items.push({level:missing.length?'warn':'ok',title:n.name,detail:missing.length?`尚未配置:${missing.join('、')}`:generic?'已绑定通用模板角色;任务书与门禁在角色定义中':'已绑定角色;任务书与门禁在角色定义中'})}if(n.type==='sop'){const missing=[];const wf=sopWorkflowChoices(state.workflow.id).find(w=>w.id===n.sopWorkflowId)||(state.data.workflows||[]).find(w=>w.id===n.sopWorkflowId);if(!n.sopWorkflowId)missing.push('要跑的 SOP');else if(!wf)missing.push('引用的 SOP 不存在');if(n.sopWorkflowId===state.workflow.id)missing.push('不能引用自己');items.push({level:missing.length?'error':'ok',title:n.name,detail:missing.length?`尚未配置:${missing.join('、')}`:`引用「${wf.name}」,产物交给下一步`})}if(n.rejectTo&&!nodes.some(x=>x.id===n.rejectTo))items.push({level:'error',title:n.name,detail:'失败打回目标不存在'})}); if(nodes.length>1&&edges.length===0)items.push({level:'warn',title:'成功路径',detail:'多个节点之间没有依赖关系,将同时启动'});if(!items.some(x=>x.level==='error'))items.push({level:'ok',title:'结构校验',detail:'未发现阻止保存或试运行的结构错误'});return items; } function setFlowView(mode){$$('.canvas-view-toggle button').forEach(b=>b.classList.toggle('active',b.dataset.flowView===mode));$('#canvas').hidden=mode!=='canvas';$('#flowCheckPanel').hidden=mode!=='check';$('#flowStageWrap')?.classList.toggle('check-mode',mode==='check');if(mode==='check')$('#flowCheckPanel').innerHTML=`

    配置检查

    运行前检查入口、CLI、产物契约和返工路径。

    ${flowDiagnostics().map(x=>`
    ${escapeHTML(x.title)}

    ${escapeHTML(x.detail)}

    `).join('')}
    `;else flowViewport.renderMinimap()} @@ -976,7 +979,13 @@ function agentBindCard(n){ if(!agent)return `

    ${hint}

    先选一个已定义的角色。画布只编排顺序和打回,不改编排角色内部的任务。

    `; const arts=effectiveNodeArtifacts(n,agent),gates=roleGates(agent); const duty=String(agent.description||'').trim(),taskHint=duty?(duty.length>48?`${duty.slice(0,48)}…`:duty):'还没写职责,可在角色定义里补'; - const model=agent.model||exec?.model||exec?.name||'未选模型'; + const source=(state.workflow?.tags||[]).find(tag=>tag.startsWith('generic-source:'))?.slice('generic-source:'.length); + const template=(state.data.workflows||[]).find(w=>w.id===source&&catalogGeneric(w)); + const fromTemplate=generic||template?.nodes?.some(node=>node.agentId&&(node.agentId===agent.id||`${node.agentId}-${projectId}`===agent.id)); + const legacyTemplate=fromTemplate&&(agent.projectId||'')===(state.workflow?.projectId||'')&&agent.executorId==='codebuddy'; + const inheritsExecutor=!n.executorId&&(!agent.executorId||legacyTemplate)&& + !String(agent.model||'').trim()&&!String(agent.effort||'').trim(); + const model=inheritsExecutor?'跟随责任人':agent.model||exec?.model||exec?.name||'未选模型'; return `

    ${hint}

    ${escapeHTML(flowPalette.initial(agent.name))}${escapeHTML(agent.name)}${escapeHTML(taskHint)}${boundRoleLink(agent)}
    ${escapeHTML(model)}模型
    ${arts.length}产物
    ${gates.length}门禁
    ${agent.loop?.enabled?`${agent.loop.maxIterations||1} 轮`:'单轮'}Loop
    `; } @@ -992,20 +1001,36 @@ function flowFold(id,title,sub,body,defaultOpen){ return `
    ${title}${sub?`${sub}`:''}${flowPalette.icon('chev',14)}
    ${body}
    `; } function renderPreviewBuildProperties(host,n){ - const model=workflowPreviewModel(state.workflow); const spa=state.workflow.preview?.spaFallback!==false; host.innerHTML=`${flowDrawerHead(n,'preview','系统步骤 · 前端预览')}
    主配置

    运行到该节点时用所选模型构建静态站点,不必再手写脚本节点;Run 成功后平台归档预览。它只有成功出口。

    -
    +
    +
    从左侧「成功」出口连到下一步;预览节点没有失败出口
    `; - fillPreviewModelSelect($('#previewNodeModel'), model); - const sel=$('#previewNodeModel'); - if(sel)sel.onchange=()=>{flowHistory.record();updatePreviewContract({model:sel.value});dirty();renderCanvas();}; + const executor=$('#previewNodeExecutor'),sel=$('#previewNodeModel'); + const fill=()=>{ + const model=fillPreviewModelSelect(sel,workflowPreviewModel(state.workflow),executor.value); + if(!sel.disabled&&model&&state.workflow.preview?.model===''){ + updatePreviewContract({model}); + renderCanvas(); + } + }; + fill(); + loadExecutorModelCatalogs().then(()=>{if(executor.isConnected)fill()}); + executor.onchange=()=>{ + flowHistory.record(); + updatePreviewContract({executorId:executor.value,model:''}); + n.executorId=executor.value; + fill(); + dirty(); + renderCanvas(); + }; + sel.onchange=()=>{flowHistory.record();updatePreviewContract({model:sel.value});dirty();renderCanvas();}; const spaBox=$('#previewNodeSpa'); if(spaBox)spaBox.onchange=()=>{flowHistory.record();updatePreviewContract({spaFallback:spaBox.checked});dirty();}; } @@ -1112,6 +1137,17 @@ async function discardWorkflow(){ async function saveWorkflow(){ if(catalogGeneric(state.workflow)&&!isPlatformAdmin()){toast('通用模板为只读,请先「复制到本项目」再修改');throw new Error('generic sop is read-only')} if(catalogForeign(state.workflow?.projectId)){toast('这是其他项目的共享 SOP,请先复制到本项目再改');throw new Error('shared sop is read-only')} + if(state.workflow?.preview?.enabled&&workflowPreviewExecutor(state.workflow)&&state.workflow.preview.model===''){ + const workflow=state.workflow; + await loadExecutorModelCatalogs(); + if(state.workflow!==workflow)throw new Error('SOP 已切换,请重新保存'); + if(!workflow.preview.model)workflow.preview.model=defaultPreviewModel(workflowPreviewExecutor(workflow)); + if(!workflow.preview.model){ + const message='请选择构建静态站点的模型'; + toast(message); + throw new Error(message); + } + } try{const saved=await api('/api/workflows',{method:'PUT',body:JSON.stringify(state.workflow)});state.workflow=clone(saved);const i=state.data.workflows.findIndex(w=>w.id===saved.id);if(i>=0)state.data.workflows[i]=clone(saved);else state.data.workflows.unshift(clone(saved));markWorkflowClean();renderWorkflowMeta();renderSOPCatalog();renderCanvas();renderProperties();toast('SOP 草稿已保存');return saved}catch(e){if(e.message.includes('revision conflict')){toast('保存冲突:其他人已更新该 SOP,请重新选择后合并')}else if(e.message!=='shared sop is read-only'&&e.message!=='generic sop is read-only')toast(e.message);throw e}} function sopSandboxChoices(){ return (state.data.sandboxes||[]).filter(s=>s.id&&catalogVisible(s.projectId,s.shared)); diff --git a/web/app/git-http-credentials.js b/web/app/git-http-credentials.js index 082b0b2f..1ca8bad9 100644 --- a/web/app/git-http-credentials.js +++ b/web/app/git-http-credentials.js @@ -12,7 +12,7 @@ function gitHTTPDefaultUsername(platform) { return platform === 'gitlab' ? 'oauth2' : 'x-access-token'; } -function openGitHTTPCredentials() { +function openGitHTTPCredentials(options = {}) { const user = state.currentUser; if (!user?.id || user.isGuest) return; @@ -69,7 +69,7 @@ function openGitHTTPCredentials() { name.maxLength = 80; username.maxLength = 128; token.maxLength = 4096; - host.required = name.required = true; + host.required = true; function setStatus(message = '', error = false) { status.textContent = message; @@ -106,8 +106,9 @@ function openGitHTTPCredentials() { form.querySelector('h3').textContent = cred ? '编辑令牌' : '添加令牌'; host.value = cred?.host || ''; host.readOnly = !!cred; - platform.value = cred?.platform || 'github'; + platform.value = cred?.platform || options.platform || 'github'; name.value = cred?.name || ''; + name.placeholder = '例如 公司 GitLab'; username.value = cred?.username || ''; username.placeholder = gitHTTPDefaultUsername(platform.value); token.required = !cred; @@ -138,7 +139,7 @@ function openGitHTTPCredentials() { method, silent:true, ...(body ? {body:JSON.stringify(body)} : {}), }); storeCredentialUser({...credentialUser(), id:user.id, gitHttpCredentialsConfigured:creds.length > 0, gitHubCredentialConfigured:creds.some(credential=>credential.host==='github.com')}); - renderCredentialPanel(); + renderCredentialGitGroup(); notifyCredentialsChanged(); deleting = ''; renderList(); @@ -188,13 +189,13 @@ function openGitHTTPCredentials() { if (scope === 'github.com') platform.value = 'github'; else if (/(^|\.)gitlab\./.test(scope)) platform.value = 'gitlab'; username.placeholder = gitHTTPDefaultUsername(platform.value); - if (!name.value.trim()) name.value = scope; + name.placeholder = scope || '例如 公司 GitLab'; }); platform.addEventListener('change', () => { username.placeholder = gitHTTPDefaultUsername(platform.value); }); form.onsubmit = event => { event.preventDefault(); const body = { - host:host.value, platform:platform.value, name:name.value, + host:host.value, platform:platform.value, name:name.value.trim() || gitHTTPHostScope(host.value), username:username.value.trim() || gitHTTPDefaultUsername(platform.value), token:token.value, }; @@ -208,8 +209,7 @@ function openGitHTTPCredentials() { dialog.addEventListener('close', () => { form.reset(); dialog.remove(); - if (opener?.isConnected) opener.focus({preventScroll:true}); - else $('#credentialPanel [data-credential-row="gitHttpCredentials"] [data-credential-act="setup"]')?.focus({preventScroll:true}); + (opener?.isConnected ? opener : $('#credentialPanel [data-credential-add-menu="platform"]'))?.focus({preventScroll:true}); }); document.body.append(dialog); dialog.showModal(); @@ -220,5 +220,8 @@ function openGitHTTPCredentials() { add.disabled = false; setStatus(creds.length ? '' : '还没有配置 Git 访问令牌'); renderList(); + const selected = creds.find(cred => cred.id === options.id); + if (selected && !selected.managed) openForm(selected); + else if (options.add) openForm(null); }).catch(error => setStatus(error.message, true)); } diff --git a/web/app/git-ssh-keys.js b/web/app/git-ssh-keys.js index f0228225..b6ccf8e5 100644 --- a/web/app/git-ssh-keys.js +++ b/web/app/git-ssh-keys.js @@ -45,7 +45,7 @@ window.addEventListener('focus', () => { refreshGitSSHWarnings(); }); -function openGitSSHKeys(remote = '') { +function openGitSSHKeys(remote = '', options = {}) { const user = state.currentUser; if (!user?.id || user.isGuest) return; @@ -149,7 +149,7 @@ function openGitSSHKeys(remote = '') { }); gitSSHKeyCache = {userId:user.id, keys, pending:null}; storeCredentialUser({...credentialUser(), id:user.id, gitSshKeyConfigured:keys.length > 0}); - renderCredentialPanel(); + renderCredentialGitGroup(); notifyCredentialsChanged(); refreshGitSSHWarnings(); deleting = ''; @@ -192,8 +192,7 @@ function openGitSSHKeys(remote = '') { dialog.addEventListener('close', () => { form.reset(); dialog.remove(); - if (opener?.isConnected) opener.focus({preventScroll:true}); - else $('#credentialPanel [data-credential-row="gitSshKey"] [data-credential-act="setup"]')?.focus({preventScroll:true}); + (opener?.isConnected ? opener : $('#credentialPanel [data-credential-add-menu="platform"]'))?.focus({preventScroll:true}); }); document.body.append(dialog); dialog.showModal(); @@ -207,6 +206,9 @@ function openGitSSHKeys(remote = '') { if (repository) { const existing = keys.find(key => globalThis.LoopForgeGitSSHHost(key.host) === repository.host); openForm(existing || null, repository); + } else { + const selected = keys.find(key => key.id === options.id); + if (selected || options.add) openForm(selected || null, null); } }).catch(error => setStatus(error.message, true)); } diff --git a/web/app/git-ssh.js b/web/app/git-ssh.js index 01ba6ebd..886b0ac2 100644 --- a/web/app/git-ssh.js +++ b/web/app/git-ssh.js @@ -53,3 +53,34 @@ globalThis.LoopForgeGitHTTPS = function parseHTTPSRepository(raw) { return {provider:'https',host,project:host+'/'+parts.join('/').replace(/\.git$/,''),name,cloneUrl,webUrl:cloneUrl.replace(/\.git$/,'')}; }catch{return null} }; + +// The managed host is supplied by the deployment. Explicit old links remain +// readable so existing repositories can be opened and edited. +globalThis.LoopForgeGongfengRepository = function parseManagedRepository(raw, host = '') { + const legacyHost = 'git.example.com'; + const managedHost = host || legacyHost; + let value = String(raw || '').trim().replace(/^['"]+|['"]+$/g, ''); + if (/^git\s+clone\s+/i.test(value)) { + value = value.replace(/^git\s+clone\s+/i, '').split(/\s+/)[0].replace(/^['"]+|['"]+$/g, ''); + } + if (!value || /[\s"'<>\\?#]/.test(value)) return null; + const ssh = /^(?:git@|ssh:\/\/git@)/i.test(value); + const remote = value.replace(/^(?:https?:\/\/|ssh:\/\/)?(?:git@)?/i, ''); + const lower = remote.toLowerCase(); + const matched = [managedHost.toLowerCase(), legacyHost].find(candidate => + lower.startsWith(candidate + '/') || lower.startsWith(candidate + ':')); + if (!matched) return null; + const separator = remote[matched.length]; + let path = remote.slice(matched.length + 1); + if (separator === ':') path = path.replace(/^\d+\//, ''); + for (const marker of ['/-/', '/tree/', '/blob/', '/commit/', '/commits/', '/merge_requests/', '/issues/', '/snippets/', '/wikis/', '/releases/', '/tags/']) { + const at = path.indexOf(marker); + if (at !== -1) path = path.slice(0, at); + } + path = path.replace(/\/+$/, '').replace(/\.git$/i, ''); + const segments = path.split('/'); + if (segments.length < 2 || path.includes('..') || segments.some(segment => !segment)) return null; + const webUrl = `https://${managedHost}/${path}`; + const cloneUrl = ssh && !managedHost.includes(':') ? `git@${managedHost}:${path}.git` : webUrl + '.git'; + return {provider:'gongfeng', project:path, name:segments.at(-1), webUrl, cloneUrl}; +}; diff --git a/web/app/hui-controls.css b/web/app/hui-controls.css index f2a64db2..1cdf727b 100644 --- a/web/app/hui-controls.css +++ b/web/app/hui-controls.css @@ -68,6 +68,8 @@ .hui-select-option.is-selected, .hui-select-option.is-selected:hover { background: var(--hui-accent-soft); } .hui-select-option-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; } +.hui-select-option-brand { width: 16px; height: 16px; margin-right: 8px; object-fit: contain; vertical-align: -3px; } +html[data-theme="dark"] .hui-select-option-brand.is-monochrome { filter: invert(1); } .hui-select-option-meta { margin-left: auto; display: inline-flex; align-items: center; gap: 6px; color: var(--hui-tertiary); font-size: 12px; } .hui-select-check { color: var(--hui-accent); } .hui-select-group { flex: none; padding: 8px 10px 4px; color: var(--hui-tertiary); font: 500 11.5px/1.3 var(--hui-sans); cursor: default; user-select: none; } diff --git a/web/app/hui-select.js b/web/app/hui-select.js index ef06975a..e37203b6 100644 --- a/web/app/hui-select.js +++ b/web/app/hui-select.js @@ -202,7 +202,19 @@ button.disabled = !!(option.disabled || group?.disabled); button.huiIndex = i; button.searchText = optionSearch(option); - button.appendChild(el('span', 'hui-select-option-label', option.text)); + const label = el('span', 'hui-select-option-label', option.text); + const brand = option.getAttribute('data-brand'); + if (brand && /^[-a-z0-9]+\.(svg|png)$/.test(brand)) { + const logo = el('img', 'hui-select-option-brand'); + logo.src = '/images/credentials/' + brand; + logo.alt = ''; + if (option.hasAttribute('data-brand-monochrome')) logo.classList.add('is-monochrome'); + label.prepend(logo); + } else { + const glyph = option.getAttribute('data-option-icon'); + if (glyph) label.prepend(icon(glyph, 'hui-select-option-brand is-glyph')); + } + button.appendChild(label); const meta = el('span', 'hui-select-option-meta', optionMeta(option)); if (i === index) meta.appendChild(icon('check', 'hui-select-check')); button.appendChild(meta); @@ -247,7 +259,7 @@ panel.classList.add('is-open'); anchor.setAttribute('aria-expanded', 'true'); anchor.setAttribute('aria-controls', panel.id); - place(anchor, panel); + place(anchor, panel, {align: select.getAttribute('data-align'), minWidth: Number(select.getAttribute('data-min-width')) || undefined}); if (mode === 'inline') { watcher = new MutationObserver(() => { if (select.disabled || !connected(select)) close(false); @@ -255,8 +267,19 @@ }); watcher.observe(select, { childList: true, subtree: true, attributes: true, characterData: true }); } - if (!searchBar.hidden && via !== 'touch') search.focus(); - else focusOption(); + if (searchBar.hidden || via === 'touch') { + focusOption(); + } else { + search.focus({ preventScroll: true }); + // Keep a saved value visible in a long list while leaving search ready to type. + if (select.getAttribute('data-reveal-selected') !== null) { + const selected = buttons.find(button => button.huiIndex === selectedIndex()); + if (selected) { + list.scrollTop += selected.getBoundingClientRect().top - list.getBoundingClientRect().top + - (list.clientHeight - selected.offsetHeight) / 2; + } + } + } } function close(focusAnchor) { if (!open) return; @@ -392,7 +415,8 @@ trigger.addEventListener('click', event => { event.stopPropagation?.(); - if (selector.isOpen()) selector.close(true); else selector.show(); + if (selector.isOpen()) selector.close(true); + else selector.show(event.pointerType === 'touch' ? 'touch' : undefined); }); trigger.addEventListener('keydown', event => { if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { diff --git a/web/app/issue-drawer.js b/web/app/issue-drawer.js index c51400f5..4968c12f 100644 --- a/web/app/issue-drawer.js +++ b/web/app/issue-drawer.js @@ -223,7 +223,7 @@ function renderIssueDetailTab(){ if(!wasSelected)b.classList.add('selected'); } }); - host.querySelectorAll('[data-clarify-model]').forEach(bindClarifyModelPicker); + host.querySelectorAll('[data-clarify-model]').forEach(picker=>bindClarifyModelPicker(picker,issue)); bindWaitingActions(host); if(state.issueDetailTab==='clarify'&&issueClarifying(issue.id))restoreIssueClarifyThinking(issue.id); if(clarifyDraft)restoreIssueClarifyDraft(host,clarifyDraft); @@ -271,8 +271,8 @@ function openIssueClarification(autoStart=false,restart=false){ } renderIssueDetailTab(); if(autoStart&&issue.clarification.status==='analyzing')attachIssueClarifyStream(issue.id); - else if(autoStart&&clarifyKickoffPending(issue))setTimeout(()=>sendIssueClarification(CLARIFY_AUTO_PROMPTS[0]),0); - else if(restart)setTimeout(()=>sendIssueClarification(CLARIFY_AUTO_PROMPTS[1]),0); + else if(autoStart&&clarifyKickoffPending(issue))void sendIssueClarification(CLARIFY_AUTO_PROMPTS[0]); + else if(restart)void sendIssueClarification(CLARIFY_AUTO_PROMPTS[1]); } function collectIssueClarifyReply(){ const parts=[]; @@ -289,7 +289,6 @@ function collectIssueClarifyReply(){ } function retryIssueClarifyTurn(){ const issue=state.issueDetailData?.issue;if(!issue)return; - if(issue.clarification)issue.clarification.lastError=''; const last=(issue.clarification?.history||[]).filter(h=>h.role==='user').pop(); sendIssueClarification(last?.content||CLARIFY_AUTO_PROMPTS[0]); } @@ -409,6 +408,12 @@ async function sendIssueClarification(initialMessage=''){ attachIssueClarifyStream(issueId); return; } + const picker=$('#issueDetailBody [data-clarify-model]'); + await picker?.modelPickerReady; + if(state.issueDetailData?.issue?.id!==issueId||issueClarifyJobs.get(issueId)?.attached)return; + if(picker&&!picker.isConnected&&(!initialMessage||!state.drawerOpen||state.issueDetailTab!=='clarify'))return; + const model=picker?.querySelector('[data-feature-model]')?.value||undefined; + if(!model&&!initialMessage)return toast('暂无可选模型,请检查个人配置中的执行器'); const msg=initialMessage||collectIssueClarifyReply(); if(!msg)return toast('请先选择或填写答案'); const c=issue.clarification||(issue.clarification={}); @@ -425,7 +430,7 @@ async function sendIssueClarification(initialMessage=''){ renderIssueDetailTab(); renderIssues(); try{ - const resp=await fetch(`/api/issues/${encodeURIComponent(issueId)}/chat-clarify`,{method:'POST',headers:{'Content-Type':'application/json','Accept':'text/event-stream'},body:JSON.stringify({message:msg,history,model:selectedClarifyModel()}),signal:abort.signal}); + const resp=await fetch(`/api/issues/${encodeURIComponent(issueId)}/chat-clarify`,{method:'POST',headers:{'Content-Type':'application/json','Accept':'text/event-stream'},body:JSON.stringify({message:msg,history,model}),signal:abort.signal}); if(!resp.ok){let em=`HTTP ${resp.status}`;try{const d=await resp.json();em=d.error||em}catch{}throw new Error(em)} const data=(resp.headers.get('Content-Type')||'').includes('text/event-stream')?await consumeIssueClarifyStream(resp,issueId):await resp.json(); await applyIssueClarifyDone(issueId,data); diff --git a/web/app/issue-model.js b/web/app/issue-model.js index 92809972..165b80ce 100644 --- a/web/app/issue-model.js +++ b/web/app/issue-model.js @@ -354,7 +354,7 @@ function deliveryMRLinked(i){return deliveryMRList(i).length>0} function pendingDeliveryMRCount(i){return deliveryMRList(i).filter(m=>['opened','reopened'].includes(String(m.state||'').toLowerCase())).length} // 多仓库交付每个仓库一个 MR;旧数据只有 deliveryMrUrl。 function deliveryMRList(i){ - const withRef=m=>{const hit=String(m.url).match(/git\.example\.com\/(.+?)(?:\/-)?\/merge_requests\/(\d+)/);return{...m,project:m.project||hit?.[1]||'',iid:m.iid||Number(hit?.[2])||0}}; + const withRef=m=>{const hit=String(m.url).match(/^https?:\/\/[^/]+\/(.+?)(?:\/-)?\/merge_requests\/(\d+)/);return{...m,project:m.project||hit?.[1]||'',iid:m.iid||Number(hit?.[2])||0}}; const list=(i?.deliveryMrs||[]).filter(m=>String(m?.url||'').trim()); if(list.length)return list.map(withRef); const url=String(i?.deliveryMrUrl||'').trim(); diff --git a/web/app/issues.js b/web/app/issues.js index ec57b47b..a42695e0 100644 --- a/web/app/issues.js +++ b/web/app/issues.js @@ -540,47 +540,22 @@ function issueFromForm(){ } // ParseGongfengRepoURL 与后端 domain.ParseGongfengRepoURL 保持一致:把粘贴的 -// 工蜂链接(web / ssh / scp / 纯项目路径)解析成统一的仓库信息,让"粘一个链接" -// 就能完成仓库配置。 +// 将完整的仓库链接和克隆地址解析成统一的仓库信息。 // repoDisplayPath shows host/path for a parsed repository, e.g. github.com/owner/name. function repoDisplayPath(info,fallback=''){return info?.provider==='ssh'?(info.project||info.cloneUrl||fallback):info?.webUrl?String(info.webUrl).replace(/^https?:\/\//,''):String(fallback||'')} -function repoProviderLabel(info){return info?.provider==='ssh'?'Git SSH':info?.provider==='github'?'GitHub':'工蜂'} +function repoProviderLabel(info){ + const labels={ssh:'Git SSH',https:'Git HTTPS',github:'GitHub',gongfeng:'工蜂'}; + return labels[info?.provider]||'Git'; +} function parseGongfengRepoURL(raw){ - const httpsInfo=globalThis.LoopForgeGitHTTPS?.(raw);if(httpsInfo)return httpsInfo; const sshInfo=globalThis.LoopForgeGitSSH?.(raw);if(sshInfo)return sshInfo; + const managed=globalThis.LoopForgeGongfengRepository?.(raw,state.data?.gongfengHost);if(managed)return managed; + const httpsInfo=globalThis.LoopForgeGitHTTPS?.(raw);if(httpsInfo)return httpsInfo; let publicURL=String(raw||'').trim().replace(/^git clone /,'').replace(/^github:/,'https://github.com/').replace(/^(?:git@github\.com:|ssh:\/\/git@github\.com(?::22)?\/)/,'https://github.com/'); if(publicURL.startsWith('github.com/'))publicURL='https://'+publicURL; try{const u=new URL(publicURL);if(u.hostname==='github.com'&&!u.username&&!u.password&&['http:','https:'].includes(u.protocol)){const parts=u.pathname.split('/').filter(Boolean),owner=parts[0],name=(parts[1]||'').replace(/\.git$/,'');if(parts.length>=2&&/^[A-Za-z0-9_.-]+$/.test(owner)&&/^[A-Za-z0-9_.-]+$/.test(name)&&!['.','..'].includes(owner)&&!['.','..'].includes(name))return {project:'github:'+owner+'/'+name,name,webUrl:'https://github.com/'+owner+'/'+name,cloneUrl:'https://github.com/'+owner+'/'+name+'.git',provider:'github'}}}catch(_){} - let original=String(raw||'').trim().replace(/^['"]+|['"]+$/g,''); - if(!original)return null; - const strippedClone=/^git\s+clone\s+/i.test(original); - let s=original.replace(/^git\s+clone\s+/i,'').trim().replace(/^['"]+|['"]+$/g,''); - if(strippedClone&&/\s/.test(s))s=s.split(/\s+/)[0]; - if(!s||/[\s"'<>()\\]/.test(s))return null; - const ssh=/^(git@|ssh:\/\/)/i.test(s); - s=s.replace(/\/+$/,''); - const hadScheme=s.includes('://'),hadAt=s.includes('@'); - let rest=s; - if(hadScheme)rest=rest.slice(rest.indexOf('://')+3); - if(rest.includes('@'))rest=rest.slice(rest.lastIndexOf('@')+1); - let path=''; - if(!hadScheme&&!hadAt&&!rest.includes(':')){ - path=rest; - }else if(rest.includes('/')){ - const cut=rest.search(/[:\/]/),host=rest.slice(0,cut); - if(host.toLowerCase()!=='git.example.com')return null; - path=rest.slice(cut+1); - if(rest[cut]===':'){const j=path.indexOf('/');if(j>=0&&/^\d+$/.test(path.slice(0,j)))path=path.slice(j+1)} - }else return null; - path=path.replace(/^git\.example\.com\//i,'').replace(/\.git$/i,''); - for(const marker of ['/-/','/tree/','/blob/','/commit/','/commits/','/merge_requests/','/issues/','/snippets/','/wikis/','/releases/','/tags/']){ - const i=path.indexOf(marker);if(i>=0)path=path.slice(0,i); - } - path=path.replace(/^\/+|\/+$/g,''); - if(!path||path.includes('..')||path.split('/').some(seg=>!seg||/[\s\\?#]/.test(seg)))return null; - const name=path.slice(path.lastIndexOf('/')+1); - return {project:path,name,webUrl:`https://git.example.com/${path}`,cloneUrl:ssh?`git@git.example.com:${path}.git`:`https://git.example.com/${path}.git`}; + return null; } // fillRepositoryFromLink 把解析结果填进空缺字段;显式填过的字段不覆盖。 function fillRepositoryFromLink(url,fill){ diff --git a/web/app/notification-editor.js b/web/app/notification-editor.js index e9a94cdd..5a83dbbd 100644 --- a/web/app/notification-editor.js +++ b/web/app/notification-editor.js @@ -21,7 +21,7 @@ function sopNotificationFieldButtons(fields){return fields.map(([key,label,descr const recommendedSOPNotificationTemplate='需求「{{issue.title}}」已完成\n\n{{ai.body}}\n\n{{url}}'; function sopNotificationHTML(bindings,options){ const cached=nodeBotCache.get(options.projectId),bots=cached?.bots||[],binding=bindings[0]; - return `
    ${cached?.error?escapeHTML(cached.error):!cached?'正在获取本项目 Bot…':'选中后自动提醒失败、待人工处理,并在 SOP 完成后发送汇报。'}
    ${binding?`

    SOP 完成后使用所选 Bot 配置的 CodeBuddy 模型单独生成整体报告,凭据沿用本次 SOP 执行身份。缺少凭据或生成失败时发送标准完成消息。

    自定义完成汇报(选填)
    完成消息

    直接写想说的话,点击下面的内容即可插入。按钮会插入英文占位符,发送时自动替换为实际内容,不需要手动记忆或输入。留空则使用默认汇报。

    ${sopNotificationFieldButtons(sopNotificationFields.slice(0,4))}
    更多可插入内容
    ${sopNotificationFieldButtons(sopNotificationFields.slice(4,10))}

    项目名称是当前项目,简短摘要是完成汇报的精简内容,节点执行结果会汇总各步骤的输出。

    接收者看到的消息示例示例数据 · 不发送通知
    展开后加载示例…

    以示例需求「登录校验优化」展示。实际内容会替换为本次需求和执行结果;AI 编写要求在实际执行时生效。

    独立 AI 汇总所有节点的输出、验证信息和历史产物,提炼需求的整体成果。以上设置仅影响完成汇报,失败与待人工提醒始终使用标准消息。

    `:''}`; + return `
    ${cached?.error?escapeHTML(cached.error):!cached?'正在获取本项目 Bot…':'选中后自动提醒失败、待人工处理,并在 SOP 完成后发送汇报。'}
    ${binding?`

    SOP 完成后使用所选 Bot 配置的 CLI 模型单独生成整体报告,凭据沿用本次 SOP 执行身份。缺少凭据或生成失败时发送标准完成消息。

    自定义完成汇报(选填)
    完成消息

    直接写想说的话,点击下面的内容即可插入。按钮会插入英文占位符,发送时自动替换为实际内容,不需要手动记忆或输入。留空则使用默认汇报。

    ${sopNotificationFieldButtons(sopNotificationFields.slice(0,4))}
    更多可插入内容
    ${sopNotificationFieldButtons(sopNotificationFields.slice(4,10))}

    项目名称是当前项目,简短摘要是完成汇报的精简内容,节点执行结果会汇总各步骤的输出。

    接收者看到的消息示例示例数据 · 不发送通知
    展开后加载示例…

    以示例需求「登录校验优化」展示。实际内容会替换为本次需求和执行结果;AI 编写要求在实际执行时生效。

    独立 AI 汇总所有节点的输出、验证信息和历史产物,提炼需求的整体成果。以上设置仅影响完成汇报,失败与待人工提醒始终使用标准消息。

    `:''}`; } function mountSOPNotificationEditor(host,bindings,options,onChange){ const revision=(host._notificationEditorRevision||0)+1;host._notificationEditorRevision=revision; diff --git a/web/app/runs.js b/web/app/runs.js index 4838622d..51c0e8d2 100644 --- a/web/app/runs.js +++ b/web/app/runs.js @@ -371,9 +371,10 @@ function logLineHTML(l){ const repository=l.attributes?.repositoryName||l.attributes?.repositoryDir||l.attributes?.repositoryId||''; return `
    ${escapeHTML(l.stream||'worker')}${escapeHTML(l.context?.nodeId||'run')}${repository?` · ${escapeHTML(repository)}`:''}
    ${escapeHTML(body)}
    `; } +function isOTLPAdapter(adapter){return adapter==='otlp-v1'||adapter==='codebuddy-otel-v1'} function isHookAdapter(adapter){return adapter==='agent-hooks-v1'||adapter==='codebuddy-hooks-v1'} function hookTraceDetails(e){const a=e.attributes||{},facts=[["ID",a.hookId],["事件",a.hook],["仓库",a.repositoryName||a.repositoryDir||a.repositoryId],["阶段",a.executionPhase],["语言",a.language],["Matcher",a.matcher],["耗时",a.durationMs!=null?`${a.durationMs} ms`:""],["退出码",a.exitCode!=null?String(a.exitCode):""]].filter(x=>x[1]!==''&&x[1]!=null);return `${facts.length?`
    ${facts.map(([k,v])=>`
    ${k}
    ${escapeHTML(v)}
    `).join('')}
    `:''}${a.stdout?`
    stdout
    ${escapeHTML(a.stdout)}
    `:''}${a.stderr?`
    stderr
    ${escapeHTML(a.stderr)}
    `:''}`} -function telemetryItemHTML(e){const hook=isHookAdapter(e.source?.adapter),tag=hook?'Hook':e.source?.adapter==='codebuddy-otel-v1'?'OTEL':'',title=hook?(e.attributes?.hookName||e.attributes?.hookId||e.name):e.name,repository=e.attributes?.repositoryName||e.attributes?.repositoryDir||e.attributes?.repositoryId||'';return `
    ${telemetryLabel(e)}${tag?`${tag}`:''}
    ${escapeHTML(title)}

    ${escapeHTML(e.message||'')}

    ${hook?hookTraceDetails(e):''}${escapeHTML(e.nodeId||'run')}${repository?` · ${escapeHTML(repository)}`:''}${hook&&e.source?.provider?` · ${escapeHTML(e.source.provider)}`:''}${e.model?` · ${escapeHTML(e.model)}`:''}${e.toolCallId?` · ${escapeHTML(e.toolCallId)}`:''}
    `} +function telemetryItemHTML(e){const hook=isHookAdapter(e.source?.adapter),tag=hook?'Hook':isOTLPAdapter(e.source?.adapter)?'OTEL':'',title=hook?(e.attributes?.hookName||e.attributes?.hookId||e.name):e.name,repository=e.attributes?.repositoryName||e.attributes?.repositoryDir||e.attributes?.repositoryId||'';return `
    ${telemetryLabel(e)}${tag?`${tag}`:''}
    ${escapeHTML(title)}

    ${escapeHTML(e.message||'')}

    ${hook?hookTraceDetails(e):''}${escapeHTML(e.nodeId||'run')}${repository?` · ${escapeHTML(repository)}`:''}${hook&&e.source?.provider?` · ${escapeHTML(e.source.provider)}`:''}${e.model?` · ${escapeHTML(e.model)}`:''}${e.toolCallId?` · ${escapeHTML(e.toolCallId)}`:''}
    `} async function loadRunLogs(runId,nodeId,more=false){ if(!more&&state.runLogs?.runId===runId&&state.runLogs?.nodeId===nodeId&&state.runLogs.loading)return; const params=new URLSearchParams({limit:'100'}); @@ -419,12 +420,12 @@ function matchTelemetryAdapter(e,view){ const a=e?.source?.adapter||''; if(!view||view==='all')return true; if(view==='hooks')return isHookAdapter(a); - if(view==='otel')return a==='codebuddy-otel-v1'; - if(view==='live')return !isHookAdapter(a)&&a!=='codebuddy-otel-v1'; + if(view==='otel')return isOTLPAdapter(a); + if(view==='live')return !isHookAdapter(a)&&!isOTLPAdapter(a); return a===view; } function telemetrySectionTitle(adapter){return ({live:'节点实时轨迹',hooks:'Hook 轨迹',otel:'OTEL 轨迹'})[adapter]||'节点轨迹'} -function telemetryEmptyHint(adapter){return ({live:'该节点没有实时轨迹',hooks:'还没有 Hook 事件。角色级 Hook 在 Claude Code、Codex 或 CodeBuddy 触发后会写到这里。',otel:'还没有 OTEL span。需要 CodeBuddy 打开原生 OTLP 导出。'})[adapter]||'该节点没有轨迹'} +function telemetryEmptyHint(adapter){return ({live:'该节点没有实时轨迹',hooks:'还没有 Hook 事件。角色级 Hook 在 Claude Code、Codex 或 CodeBuddy 触发后会写到这里。',otel:'还没有 OTEL span。请检查所用 CLI 的 OTLP 导出配置。'})[adapter]||'该节点没有轨迹'} function telemetrySourceTabs(adapter,attr){ return `
    ${[['live','实时'],['hooks','Hook'],['otel','OTEL']].map(([id,label])=>``).join('')}
    `; } @@ -1277,10 +1278,6 @@ function defaultRunEval(){return{enabled:true,version:1,threshold:70,dimensions: {id:'recovery',name:'错误恢复',question:'相同错误是否反复出现?',weight:10}, {id:'delivery',name:'交付完整',question:'终态、产物和验证信号是否齐全?',weight:10} ]}} -// Run evals run on CodeBuddy only; a saved "codex:…" id falls back. -function runEvalModel(){const api=window.AgentFlowAssistantModels,stored=state.runEvalModel||localStorage.getItem('agentflow.runEvalModel')||'';if(api?.codeBuddyModel)return api.codeBuddyModel(stored);return stored||(api&&api.DEFAULT)||'default'} -function setRunEvalModel(id){state.runEvalModel=id;localStorage.setItem('agentflow.runEvalModel',id)} -function runEvalHasKey(){return !!(userById(state.currentUser?.id)||state.currentUser||{}).codeBuddyApiKeyConfigured} function runEvalApplyable(rec){if(!rec||rec.status==='applied')return false;const action=((rec.target||'')+'.'+(rec.action||'')).replace(/^\./,'').toLowerCase();const full=rec.action&&rec.action.includes('.')?rec.action.toLowerCase():action;return ['workflow.update_node','agent.upsert_gate','agent.remove_gate','agent.append_instructions','agent.append_task_prompt'].includes(full)} function runEvalPaneHTML(run){ const rec=state.runEval?.runId===run.id?state.runEval:null,busy=!!state.runEvalBusy,thoughts=state.runEvalThoughts||[]; @@ -1299,16 +1296,10 @@ function runEvalPaneHTML(run){
    -
    评测大模型
    +
    评测执行器与模型
    -
    - - - +
    + ${window.AgentFlowAssistantModels?.featurePickerHTML()||''}
    `:(can?``:'仅建议')}`; } function bindRunEvalPane(run,host){ - bindRunEvalModelPicker(host.querySelector('#runEvalModelPicker')); + bindRunEvalModelPicker(host.querySelector('#runEvalModelPicker'),run.id); host.querySelectorAll('[data-run-eval]').forEach(b=>b.onclick=()=>{ state.runDetailTab='eval'; host.querySelectorAll('[data-run-tab]').forEach(x=>x.classList.toggle('active',x.dataset.runTab==='eval')); @@ -1364,30 +1355,19 @@ function bindRunEvalPane(run,host){ host.querySelectorAll('[data-apply-eval]').forEach(b=>b.onclick=()=>applyRunEvalRec(run,b.dataset.applyEval)); host.querySelectorAll('[data-open-eval-target]').forEach(b=>b.onclick=()=>openRunEvalTarget(b.dataset.openEvalTarget,b.dataset.openEvalId)); } -function bindRunEvalModelPicker(host){ - if(!host)return; - const api=window.AgentFlowAssistantModels,toggle=host.querySelector('[data-model-toggle]'),menu=host.querySelector('.ai-model-menu'); - if(!api||!toggle||!menu)return; - const paint=()=>{const keep=runEvalModel();const inp=host.querySelector('[name=runEvalModel]');if(inp)inp.value=keep;api.paint(toggle,keep)}; - paint(); - api.load?.().then(paint).catch(paint); - if(host.dataset.bound)return; - host.dataset.bound='1'; - toggle.onclick=e=>{ - e.stopPropagation(); - const open=menu.hidden; - menu.hidden=!open; - toggle.setAttribute('aria-expanded',open?'true':'false'); - if(open)api.renderCodeBuddyList(menu,runEvalModel(),id=>{setRunEvalModel(id);paint();menu.hidden=true;toggle.setAttribute('aria-expanded','false')}); - }; - document.addEventListener('click',e=>{if(host.contains(e.target))return;menu.hidden=true;toggle.setAttribute('aria-expanded','false')}); +let runEvalModelChoice; +function bindRunEvalModelPicker(host,runId){ + window.AgentFlowAssistantModels?.bindFeaturePicker(host,{ + model:runEvalModelChoice?.runId===runId?runEvalModelChoice.model:'', + legacyModel:localStorage.getItem('agentflow.runEvalModel'), + onChange:model=>{runEvalModelChoice={runId,model}} + }); } async function loadRunEval(runId,background){ try{ const rec=await api(`/api/runs/${encodeURIComponent(runId)}/eval`,{silent:true}); if((state.activeRun?.id||state.selectedRun)!==runId&&state.activeRun?.id!==runId)return; state.runEval={...rec,runId}; - if(rec?.model)setRunEvalModel(rec.model); if(rec?.status==='running'&&!state.runEvalStream)attachRunEvalStream(runId); if(!background){ const host=$('#runDetail'); @@ -1398,12 +1378,21 @@ async function loadRunEval(runId,background){ } async function startRunEval(run){ if(!['succeeded','failed','cancelled'].includes(run.status))return toast('请等 SOP 跑完后再评测'); - if(!runEvalHasKey()){toast('请先在个人配置中配置自己的 CodeBuddy API Key','err');switchView('settings');return} + let picker=$('#runEvalModelPicker'); + await picker?.modelPickerReady; + if(picker&&!picker.isConnected&&state.activeRun?.id===run.id){ + // Loading the last evaluation can replace the picker while its catalog is loading. + picker=$('#runEvalModelPicker'); + await picker?.modelPickerReady; + } + if(!picker?.isConnected||state.runEvalBusy)return; + const model=picker.querySelector('[data-feature-model]')?.value; + if(!model)return toast('暂无可选模型,请检查个人配置中的执行器'); state.runEvalBusy=true;state.runEvalThoughts=['正在提交评测…']; const host=$('#runDetail'),pane=host?.querySelector('[data-run-pane="eval"]'); if(pane){pane.innerHTML=runEvalPaneHTML(run);bindRunEvalPane(run,host)} try{ - const rec=await api(`/api/runs/${encodeURIComponent(run.id)}/eval`,{method:'POST',body:JSON.stringify({model:runEvalModel()})}); + const rec=await api(`/api/runs/${encodeURIComponent(run.id)}/eval`,{method:'POST',body:JSON.stringify({model})}); state.runEval={...rec,runId:run.id}; attachRunEvalStream(run.id); }catch(e){state.runEvalBusy=false;toast(e.message,'err');if(pane){pane.innerHTML=runEvalPaneHTML(run);bindRunEvalPane(run,host)}} diff --git a/web/app/sops.js b/web/app/sops.js index 0a125d6d..c6502cfe 100644 --- a/web/app/sops.js +++ b/web/app/sops.js @@ -86,18 +86,27 @@ function genericRequirementChips(w){ if(!rows.length)return ''; return `
    ${rows.map(r=>sopBadge(r.label,r.ok?'success':'warn',r.ok?'check':'alert',r.hint)).join('')}
    `; } -// Agent nodes run with the executor credentials of the requirement owner; a -// bound repository only matters for templates that check out project code. -function sopRunRequirements(w){ - const nodes=w?.nodes||[],user=userById(state.currentUser?.id)||{}; +function sopResourceRequirements(w){ const project=(state.data?.projects||[]).find(p=>p.id===(w?.projectId||state.projectFilter))||(state.data?.projects||[]).find(p=>p.id===state.projectFilter); const driver=((state.data?.sandboxes||[]).find(sb=>sb.id===w?.sandboxProfileId)||{}).driver||(/docker/i.test(w?.sandboxProfileId||'')?'docker':''); const usesRepo=(catalogGeneric(w)||(w?.tags||[]).some(t=>String(t).startsWith('generic-source:')))&&!!project?.defaultRepositoryId; const rows=[]; - const providers=new Set(); - for(const node of nodes.filter(n=>n.type==='agent')){ + if(usesRepo)rows.push({key:'run-repo',label:'GitHub 仓库(已绑定)',ok:true,hint:'使用项目已绑定的仓库。访问私有仓库或推送代码时需要在个人配置中配置 GitHub Token;未绑定仓库时可在任务工作区直接运行。'}); + if(driver==='docker')rows.push({key:'run-docker',label:'Docker',ok:state.data?.capabilities?.docker!==false,hint:state.data?.capabilities?.docker===false?'平台连不上 Docker,这个 SOP 现在跑不了。重新运行 scripts/install.sh 会自动安装并挂载 Docker。':'在隔离的 Docker 沙箱里运行,首次运行会构建镜像,需要几分钟。'}); + return rows; +} +function sopRunRequirements(w){ + const nodes=w?.nodes||[],user=userById(state.currentUser?.id)||{}; + const resources=sopResourceRequirements(w); + if(catalogGeneric(w)||(w?.tags||[]).some(tag=>tag.startsWith('generic-source:')))return resources; + const rows=[]; + const executorIds=nodes.filter(n=>n.type==='agent'&&!isPreviewBuildNode(n.id)).map(node=>{ const role=(state.data?.agents||[]).find(a=>a.id===node.agentId); - const id=role?.executorId||node.executorId||'codebuddy'; + return role?.executorId||node.executorId||'codebuddy'; + }); + if(w?.preview?.enabled)executorIds.push(workflowPreviewExecutor(w)); + const providers=new Set(); + for(const id of executorIds){ const kind=(state.data?.executors||[]).find(e=>e.id===id)?.kind||id; if(['codebuddy','codex','claude','claude-code','opencode','cursor','agy','kimi','pi','dsh','zcode'].includes(kind))providers.add(kind==='claude'?'claude-code':kind); } @@ -109,15 +118,13 @@ function sopRunRequirements(w){ rows.push({key:'run-key-'+kind,field,fix:'settings',fixLabel:'去个人配置配置',label:label+' API Key',ok:!!user.agentCliCredentials?.[kind]?.apiKeyConfigured,hint:lfT('Agent 节点使用 '+label+',请在个人配置里配置对应 API Key。','Agent nodes use '+label+'. Configure its API key in Settings.')}); continue; } - rows.push({key:'run-key-'+kind,field,fix:'settings',fixLabel:'去个人配置配置',label:label+' API Key',ok:!!user[flag],hint:lfT('Agent 节点使用 '+label+',请在个人配置里配置对应 API Key。','Agent nodes use '+label+'. Configure its API key in Settings.')}); + rows.push({key:'run-key-'+kind,field,fix:'settings',fixLabel:'去个人配置配置',label:label+' API Key',ok:!!user[flag]||!!window.AgentFlowAssistantModels?.catalog().engines?.find(engine=>engine.id===kind&&engine.configured),hint:lfT('Agent 节点使用 '+label+',请在个人配置里配置对应 API Key。','Agent nodes use '+label+'. Configure its API key in Settings.')}); } - if(usesRepo)rows.push({key:'run-repo',fix:'',label:'GitHub 仓库(已绑定)',ok:true,hint:'使用项目已绑定的仓库。访问私有仓库或推送代码时需要在个人配置中配置 GitHub Token;未绑定仓库时可在任务工作区直接运行。'}); - if(driver==='docker')rows.push({key:'run-docker',label:'Docker',ok:state.data?.capabilities?.docker!==false,hint:state.data?.capabilities?.docker===false?'平台连不上 Docker,这个 SOP 现在跑不了。重新运行 scripts/install.sh 会自动安装并挂载 Docker。':'在隔离的 Docker 沙箱里运行,首次运行会构建镜像,需要几分钟。'}); - return rows; + return [...rows,...resources]; } function sopRunRequirementChips(w){ const rows=sopRunRequirements(w); - if(!rows.length)return `
    ${sopBadge('无需 Key 或仓库','success','check','只包含脚本和人工审批节点')}
    `; + if(!rows.length)return ''; return `
    ${rows.map(r=>sopBadge((r.ok?'':'需要 ')+r.label,r.ok?'success':'warn',r.ok?'check':'alert',r.hint)).join('')}
    `; } // --- 流程模板卡片 ------------------------------------------------------------- @@ -396,10 +403,18 @@ function bindSOPCatalogEvents(root){ activateSOPCard(e.target); }); } -function renderGenericRequirementRows(w){ +function renderGenericRequirementRows(w,executors,loading=false){ const host=$('#genericTemplateRequirements');if(!host)return; - const rows=[...sopRunRequirements(w).map(r=>({...r,fix:r.ok?'':r.fix||''})),...genericRequirementRows(w)]; - host.innerHTML=rows.map(r=>`
    ${r.ok?'✓':'!'}
    ${escapeHTML(r.label)}

    ${escapeHTML(r.hint)}${r.nodeId?` · 节点「${escapeHTML(workflowNodeName(w,r.nodeId))}」`:''}

    ${r.ok?'已配置':'未配置'}${r.fix?``:''}
    `).join('')||'
    ✓
    无额外依赖

    复制到本项目后即可直接运行。

    '; + const executorRows=executors?.map(ex=>({ + key:'run-executor',label:ex.name?`执行器 · ${ex.name}`:'执行器',ok:ex.configured, + hint:ex.configured?'角色节点使用任务责任人的执行器配置。':ex.name?`配置运行此 SOP 所需的 ${ex.name}。`:'在个人配置中添加当前执行环境可用的执行器,即可运行角色节点。', + fix:ex.configured?'':'settings',fixLabel:'配置执行器' + }))??[{ + label:'执行器',status:loading?'检查中':'暂时无法检查', + hint:loading?'正在检查任务责任人的执行器配置。':'请关闭后重新打开,重试执行器检查。' + }]; + const rows=[...executorRows,...sopResourceRequirements(w),...genericRequirementRows(w)]; + host.innerHTML=rows.map(r=>`
    ${r.status?'…':r.ok?'✓':'!'}
    ${escapeHTML(r.label)}

    ${escapeHTML(r.hint)}${r.nodeId?` · 节点「${escapeHTML(workflowNodeName(w,r.nodeId))}」`:''}

    ${r.status||(r.ok?'已配置':'未配置')}${r.fix?``:''}
    `).join('')||'
    ✓
    无额外依赖

    复制到本项目后即可直接运行。

    '; host.querySelectorAll('[data-fix-requirement]').forEach(btn=>btn.onclick=()=>openGenericRequirementTarget(btn.dataset.fixRequirement)); } async function openGenericTemplateEditor(id){ @@ -411,7 +426,8 @@ async function openGenericTemplateEditor(id){ renderWorkflowMeta();renderCanvas();renderProperties();switchView('flow'); await refreshGenericWorkflowRoles(); } -function openGenericTemplateModal(id){ +let genericRequirementRequest=0; +async function openGenericTemplateModal(id){ const w=(state.data?.workflows||[]).find(x=>x.id===id&&catalogGeneric(x)); if(!w)return toast('通用模板不存在或已下架'); state.genericTemplateId=id; @@ -419,17 +435,22 @@ function openGenericTemplateModal(id){ $('#genericTemplateIntro').textContent=w.description||'平台提供的通用流程模板,复制后归本项目所有。'; const nodes=w.nodes||[],agentCount=nodes.filter(n=>n.type==='agent').length,gates=nodes.filter(n=>n.type==='approval').length; $('#genericTemplateStructure').innerHTML=`${nodes.length} 个节点${agentCount} 个角色节点${gates} 个人工门禁${nodes.some(n=>n.id==='mr')?'含「发起 PR」节点':''}复制=归本项目、可自由修改、不再跟随平台更新直接运行=始终使用平台最新版`; - renderGenericRequirementRows(w); - $('#genericTemplateModal').classList.add('open'); + const request=++genericRequirementRequest,modal=$('#genericTemplateModal'); + const needsExecutor=agentCount>0||w.preview?.enabled; + renderGenericRequirementRows(w,needsExecutor?null:[],true); + modal.classList.add('open'); + if(!needsExecutor)return; + try{ + const executors=await api(`/api/workflows/${encodeURIComponent(id)}/executor-requirements${projectQuery()}`,{silent:true}); + if(request===genericRequirementRequest&&modal.classList.contains('open'))renderGenericRequirementRows(w,executors); + }catch{ + if(request===genericRequirementRequest&&modal.classList.contains('open'))renderGenericRequirementRows(w,null); + } } function openGenericRequirementTarget(key){ - if(key==='run-key'||key.startsWith('run-key-')||key==='run-repo'){ - const w=(state.data?.workflows||[]).find(x=>x.id===state.genericTemplateId); - const row=sopRunRequirements(w).find(r=>r.key===key); + if(key==='run-executor'){ $('#genericTemplateModal').classList.remove('open'); - if(row?.fix==='repository')return openRepositoryModal(); - gotoCredential(row?.field||(key==='run-key'?'codeBuddyApiKey':'gitHttpCredentials')); - return; + return gotoCredential('executors'); } const meta=GENERIC_REQUIREMENT_CHECKS[key];if(!meta)return; $('#genericTemplateModal').classList.remove('open'); diff --git a/web/app/sync-schedule.js b/web/app/sync-schedule.js index f910c7a8..909e0007 100644 --- a/web/app/sync-schedule.js +++ b/web/app/sync-schedule.js @@ -98,56 +98,19 @@ function scheduleIssueStatusValues(job){ return ['backlog','todo']; } function scheduleModelAPI(){return window.AgentFlowAssistantModels} -function selectedClarifyModel(){ - const api=window.AgentFlowAssistantModels; - const stored=localStorage.getItem('agentflow.clarifyModel')||''; - // Clarification runs on CodeBuddy only; a saved "codex:…" id falls back. - if(api?.codeBuddyModel)return api.codeBuddyModel(stored); - return stored||(api&&api.DEFAULT)||'default'; -} -function setClarifyModel(id){ - if(!id)return; - localStorage.setItem('agentflow.clarifyModel',id); - $$('[data-clarify-model-value]').forEach(el=>{el.value=id}); -} function clarifyModelPickerHTML(disabled){ - const id=escapeHTML(selectedClarifyModel()); - return `
    `; -} -function bindClarifyModelPicker(host){ - if(!host)return; - const api=window.AgentFlowAssistantModels,toggle=host.querySelector('[data-model-toggle]'),menu=host.querySelector('.ai-model-menu'); - if(!api||!toggle||!menu)return; - const paint=()=>{const keep=selectedClarifyModel();const hidden=host.querySelector('[data-clarify-model-value]');if(hidden)hidden.value=keep;api.paint(toggle,keep)}; - api.load?.().then(paint).catch(paint); - if(!bindClarifyModelPicker.docBound){ - bindClarifyModelPicker.docBound=true; - document.addEventListener('click',e=>{ - $$('[data-clarify-model]').forEach(el=>{ - if(el.contains(e.target))return; - const m=el.querySelector('.ai-model-menu'),t=el.querySelector('[data-model-toggle]'); - if(m)m.hidden=true; - if(t)t.setAttribute('aria-expanded','false'); - }); - }); - } - if(host.dataset.bound)return; - host.dataset.bound='1'; - toggle.onclick=e=>{ - e.stopPropagation(); - if(toggle.disabled)return; - const open=menu.hidden; - menu.hidden=!open; - toggle.setAttribute('aria-expanded',open?'true':'false'); - if(open){ - api.renderCodeBuddyList(menu, selectedClarifyModel(), id=>{ - setClarifyModel(id); - api.paint(toggle, id); - menu.hidden=true; - toggle.setAttribute('aria-expanded','false'); - }); - } - }; + return `
    ${scheduleModelAPI()?.featurePickerHTML()||''}
    `; +} +let clarifyModelChoice; +function bindClarifyModelPicker(host, issue){ + const models=scheduleModelAPI(); + return models?.bindFeaturePicker(host,{ + model:clarifyModelChoice?.issueId===issue.id?clarifyModelChoice.model:'', + legacyModel:localStorage.getItem('agentflow.clarifyModel'), + readOnly:host.hasAttribute('data-picker-readonly'), + onChange:model=>{clarifyModelChoice={issueId:issue.id,model}}, + loadCatalog:()=>models.fetchCatalog(`/api/issues/${encodeURIComponent(issue.id)}/clarify-models`) + }); } // The AI 定时任务 model picker: a CLI select narrows the model list to that // CLI, like the chat composer's CLI switch. The menu is fixed-positioned so the @@ -159,6 +122,13 @@ function scheduleModelCatalog(){ function scheduleEngineModels(engine){ return (scheduleModelCatalog().models||[]).filter(m=>(m.engine||'codebuddy')===engine); } +function scheduleDefaultModel(engine){ + const models=scheduleEngineModels(engine); + const prefs=scheduleModelCatalog().preferences; + const saved=prefs?.executor===engine&&models.find(item=>item.id===prefs.model||item.id===engine+':'+prefs.model); + const preferred=engine==='codebuddy'&&models.find(item=>item.id===scheduleModelCatalog().default); + return saved?.id||preferred?.id||models[0]?.id||''; +} function scheduleModelEngine(id){ return scheduleModelAPI()?.engineOf?.(id,scheduleModelCatalog())||'codebuddy'; } @@ -167,8 +137,10 @@ function paintScheduleEngines(selected){ if(!select)return; const current=scheduleModelEngine(selected); const engines=scheduleModelCatalog().engines||[]; - const list=engines.length?[...engines]:[{id:'codebuddy',name:'CodeBuddy'}]; - if(!list.some(e=>e.id===current))list.push({id:current,name:current}); + const list=engines.filter(engine=>engine.configured||scheduleEngineModels(engine.id).length); + if(!list.some(e=>e.id===current)&&(scheduleModelAPI()?.concreteModelId(selected)||$('#scheduleJobForm')?.elements.id.value)){ + list.push(engines.find(e=>e.id===current)||{id:current,name:current}); + } // CodeBuddy can run on its native default with no concrete model in the // list. A saved task keeps its CLI selectable during edits. select.replaceChildren(...list.map(e=>{ @@ -177,7 +149,9 @@ function paintScheduleEngines(selected){ option.disabled=!usable; return option; })); - select.value=current; + if(!list.length)select.add(new Option('暂无可用执行器','')); + select.value=list.some(item=>item.id===current)?current:list[0]?.id||''; + select.disabled=!list.length; } function closeScheduleModelMenu(){ const host=$('#scheduleModelPicker'); @@ -227,8 +201,7 @@ function bindScheduleModelPicker(){ const engine=$('#scheduleEngine'); if(engine)engine.onchange=()=>{ const api=scheduleModelAPI(); - const models=scheduleEngineModels(engine.value); - const next=models[0]?.id||(engine.value==='codebuddy'?(scheduleModelCatalog().default||api?.DEFAULT):''); + const next=scheduleDefaultModel(engine.value)||(engine.value==='codebuddy'?(scheduleModelCatalog().default||api?.DEFAULT):''); if(next)paintScheduleModel(next); }; document.addEventListener('click',e=>{if(!host.contains(e.target))closeScheduleModelMenu()}); @@ -240,12 +213,23 @@ function bindScheduleModelPicker(){ async function loadScheduleModels(){ const picker=scheduleModelAPI(); if(!picker)return; + const version=scheduleModalVersion; + let catalog; try{ - scheduleCatalog=await api('/api/assistant/models?schedule=1',{silent:true}); + catalog=await api('/api/assistant/models?schedule=1',{silent:true}); }catch{ - scheduleCatalog=await picker.load(); + catalog=await picker.load(); } - paintScheduleModel($('#scheduleJobForm')?.elements.assistantModel.value||picker.DEFAULT); + if(version!==scheduleModalVersion)return; + scheduleCatalog=catalog; + const form=$('#scheduleJobForm'); + const selected=form.elements.assistantModel.value; + const configured=(catalog?.engines||[]).filter(engine=>engine.configured); + const preferred=configured.find(engine=>engine.id===catalog.preferences?.executor); + const fallback=!form.elements.id.value&&!picker.concreteModelId(selected) + ?(preferred&&scheduleDefaultModel(preferred.id))||configured.map(engine=>scheduleDefaultModel(engine.id)).find(Boolean) + :''; + paintScheduleModel(fallback||selected||picker.DEFAULT); } function paintScheduleModel(selected){ const api=scheduleModelAPI(); @@ -372,6 +356,7 @@ async function openScheduleJobModal(kind='dispatch',job){ scheduleModalOpener=document.activeElement; if(scheduleModalOpener?.closest('#issueHeadingMenu'))scheduleModalOpener=$('#issueHeadingMore'); const f=$('#scheduleJobForm'); + f.modelPickerReady=null; f.inert=false; f.querySelector('[type="submit"]').disabled=false; if(scheduleEditorKind==='assistant')fillScheduleJobForm(job||{}); @@ -379,7 +364,8 @@ async function openScheduleJobModal(kind='dispatch',job){ $('#scheduleModal').classList.add('open'); if(scheduleEditorKind==='assistant'){ f.elements.name.focus(); - await Promise.all([refreshAISchedules(),loadScheduleModels(),loadSharedScheduleEditor(job||{},version,projectId)]); + f.modelPickerReady=loadScheduleModels(); + await Promise.all([refreshAISchedules(),f.modelPickerReady,loadSharedScheduleEditor(job||{},version,projectId)]); }else{ // Load the saved project config before allowing edits or a first save. f.inert=true; @@ -467,7 +453,7 @@ function renderScheduleJobs(){ const disabled='本实例不执行定时任务;任务可在主实例自动运行。'; $('#scheduleRuntimeHint').textContent=canRun?'每个项目使用一份触发配置,修改后保存即可生效。立即运行在服务端执行,关闭页面不会中断。':disabled; const triggerHint=$('#aiScheduleTriggerHint');if(triggerHint)triggerHint.textContent=canRun?'按计划扫描本项目选定状态、尚未跑过 SOP 的需求,通过基线门禁后派发 SOP。每个项目使用一份触发配置。':disabled; - $('#aiScheduleRuntimeHint').textContent=!state.projectFilter?'请先在顶栏选择项目,再管理 AI 定时任务。':canRun?'以最后保存任务的人的身份和完全权限执行。默认执行机器离线时使用该用户的 API Key。CodeBuddy 缺少个人 Key 时可使用平台共享 Key。关闭页面不会中断执行。':disabled; + $('#aiScheduleRuntimeHint').textContent=!state.projectFilter?'请先在顶栏选择项目,再管理 AI 定时任务。':canRun?'任务以最后保存人的身份和完全权限执行。关闭页面后,任务会继续运行。':disabled; $('#aiScheduleProjectName').textContent=currentProject()?.name||'当前项目'; $('#aiScheduleCount').textContent=`${assistant.length} 个任务`; $('#newAISchedule').disabled=!state.projectFilter; @@ -597,6 +583,11 @@ function renderScheduleJobList(list,jobs,kind,canRun){ async function saveScheduleJob(e){ e.preventDefault(); const f=e.currentTarget,cron=f.elements.scheduleMode.value==='cron',assistant=f.elements.jobKind.value==='assistant'; + const version=scheduleModalVersion; + if(assistant&&f.modelPickerReady){ + await f.modelPickerReady; + if(version!==scheduleModalVersion)return; + } const payload={ id:f.elements.id.value, name:f.elements.name.value.trim()||(assistant?'':'触发配置'), @@ -625,7 +616,7 @@ async function saveScheduleJob(e){ if(!assistant&&!payload.issueStatuses.length)return toast('请至少选择一个触发状态'); if(!assistant&&payload.maxDispatch!==undefined&&(!Number.isInteger(payload.maxDispatch)||payload.maxDispatch<1||payload.maxDispatch>10))return toast('单次最多触发需求数必须为 1–10,或留空使用默认值 10'); if(cron&&!payload.cron)return toast('请填写 Cron 表达式'); - const version=scheduleModalVersion,projectId=state.projectFilter,button=f.querySelector?.('[type="submit"]'),label=button?.textContent; + const projectId=state.projectFilter,button=f.querySelector?.('[type="submit"]'),label=button?.textContent; if(button?.disabled)return; if(button){button.disabled=true;button.textContent='保存中…'} try{ diff --git a/web/app/workbench.js b/web/app/workbench.js index e3b2c7d0..93e456df 100644 --- a/web/app/workbench.js +++ b/web/app/workbench.js @@ -29,8 +29,8 @@ function updateApprovalBadge(){ // ================= 个人凭证 ================= // One table drives the list rows, the inline editors and the add wizard. const CREDENTIAL_GROUPS=[ - {id:'platform',name:'平台集成',sub:'代码仓库与统一认证',icon:'key'}, - {id:'model',name:'模型与执行',sub:'AI 对话与编码 CLI',icon:'sparkles'}, + {id:'platform',name:'Git 配置'}, + {id:'model',name:'执行器配置'}, ]; // 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. @@ -69,11 +69,12 @@ 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 账号所在的网络环境:国际站、国内站或 iOA'],['登录该站点的 API Key 页面,新建 API Key',codeBuddyKeyURL,codeBuddyKeyLinkLabel],['复制以 ck_ 开头的密钥粘贴到下方;DeepSeek、OpenAI 等第三方模型的 Key 不能填在这里']], + guide:[['使用官方地址时,选择 CodeBuddy 账号所在的网络环境'],['登录该站点的 API Key 页面,新建 API Key',codeBuddyKeyURL,codeBuddyKeyLinkLabel],['使用自定义网关时,填写网关提供的 Base URL 和 API Key']], placeholder:'请输入个人 ck_ key', extra:{name:'codeBuddyInternetEnvironment',label:'网络环境',options:CODEBUDDY_ENVIRONMENTS}, + baseURL:'codeBuddyBaseUrl', models:{name:'codeBuddyModels',engine:'codebuddy'}, - impact:'AI 对话将只能使用默认模型,CodeBuddy 执行器节点会失败。'}, + impact:'CodeBuddy 会使用可用的共享配置。其他 CLI 继续使用各自的凭据。'}, {key:'codexApiKey',group:'model',name:'Codex',short:'Codex API Key',logo:'codex',monochrome:true, use:'AI 对话选择 Codex 执行器,以及以 Codex 运行的 SOP 节点', description:'AI 对话切换到 Codex 后可选用模型目录里的模型,SOP 在执行机器上以 Codex 运行的节点也使用它。目录为空时,未填 Base URL 使用 Codex 自带模型,填写后跟随服务发布的模型;也可以自己挑选、排序和命名。', @@ -236,7 +237,7 @@ function credentialCatalogDetailHTML(mode,kind,protocol){ return mode!=='remote'?escapeHTML(copy.detail):`目录为空时,AI 对话列出 Base URL 的 ${escapeHTML(credentialModelsEndpoint(kind,protocol))} 返回的模型。`; } function credentialCatalogHTML(kind,user,{runnerLogin=false,label='模型目录'}={}){ - const baseUrl=kind.extra?.url?credentialValue(user,kind.extra.name):'',protocol=credentialProtocol(kind,user); + const baseUrl=credentialValue(user,kind.baseURL||(kind.extra?.url?kind.extra.name:'')),protocol=credentialProtocol(kind,user); const cursorAutomatic=kind.agentCli==='cursor'&&!user?.agentCliCredentials?.cursor?.modelsCustomized; const models=credentialCatalogModels(cursorAutomatic?[]:credentialValue(user,kind.models.name)),empty=!models.length; const mode=runnerLogin?'runner':!String(baseUrl||'').trim()?'official':'remote'; @@ -268,7 +269,7 @@ function credentialCatalogRowModel(row){ function credentialCatalogFilledRows(catalog){return credentialCatalogRows(catalog).filter(row=>credentialCatalogModels([credentialCatalogRowModel(row)]).length)} function readCredentialCatalog(catalog){return credentialCatalogModels(credentialCatalogRows(catalog).map(credentialCatalogRowModel))} function credentialCatalogMode(catalog){ - const form=catalog?.closest('.credential-editor-form'),extra=form?.querySelector('input[name="extra"]'); + const form=catalog?.closest('.credential-editor-form'),extra=form?.querySelector('input[name="baseUrl"], input[name="extra"]'); if(!extra||catalog.dataset.catalogMode==='runner')return catalog.dataset.catalogMode; return extra.value.trim()?'remote':'official'; } @@ -380,8 +381,8 @@ function closeCredentialCatalogProbe(catalog){ } async function probeCredentialCatalog(row,catalog,button){ const kind=credentialKind(row.dataset.credentialRow),form=row.querySelector('.credential-editor-form'),panel=catalog.querySelector('[data-catalog-probe]'); - const extra=form?.querySelector('input[name="extra"]'),secret=form?.querySelector('[name="secret"]')?.value.trim()||'',protocol=form?.querySelector('select[name="protocol"]')?.value,environment=form?.querySelector('select[name="extra"]')?.value; - const extraError=extra?credentialExtraError(kind,extra.value,protocol):''; + const extra=form?.querySelector('input[name="baseUrl"], input[name="extra"]'),secret=form?.querySelector('[name="secret"]')?.value.trim()||'',protocol=form?.querySelector('select[name="protocol"]')?.value,environment=form?.querySelector('select[name="extra"]')?.value; + const extraError=extra?(extra.name==='baseUrl'?credentialBaseURLError(extra.value):credentialExtraError(kind,extra.value,protocol)):''; if(extraError){toast(extraError,'err');extra.focus();return} const token=(catalog.probeToken||0)+1;catalog.probeToken=token;catalog.probe=null; panel.hidden=false; @@ -494,7 +495,11 @@ function credentialKind(key){return CREDENTIAL_KINDS.find(kind=>kind.key===key)| function credentialDialog(key){return credentialKind(key)?.dialog||null} function credentialConfigured(kind,user){if(kind.key==='gitToken')return !!user.gitHubCredentialConfigured;return !!credentialValue(user,kind.agentCli?kind.key+'.apiKeyConfigured':kind.key+'Configured')} function credentialUser(){return userById(state.currentUser?.id)||{}} -function credentialUI(){return state.credentialUI||(state.credentialUI={open:null,filter:'all',closed:{}})} +function credentialUI(){ + const userId=state.currentUser?.id; + if(!state.credentialUI||state.credentialUI.userId!==userId)state.credentialUI={userId,open:null,catalog:null}; + return state.credentialUI; +} function credentialGlyph(name,size=16,cls=''){return ``} function credentialSpinner(size=14){return credentialGlyph('arc-spinner',size,'credential-spin')} function credentialLogo(kind,cls=''){ @@ -502,14 +507,13 @@ function credentialLogo(kind,cls=''){ return `${kind.icon?credentialGlyph(kind.icon,18):``}`; } function hydrateCredentialIcons(root){if(root)window.AgentFlowHarnessIcons?.hydrate?.(root)} -function credentialNextKind(user){return CREDENTIAL_RECOMMENDED.map(credentialKind).find(kind=>!credentialConfigured(kind,user))||null} 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){ +function credentialSecretWarning(kind,value,baseUrl=''){ const text=String(value||'').trim(); - if(kind?.key!=='codeBuddyApiKey'||!text||text.startsWith('ck_'))return ''; + if(kind?.key!=='codeBuddyApiKey'||String(baseUrl||'').trim()||!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'; @@ -541,9 +545,19 @@ function refreshCredentialEnvironmentLinks(scope,value){ function credentialExtraError(kind,value,protocol){ const text=String(value||'').trim(); if(!text&&kind.extra?.required?.(protocol))return '请填写 Base URL'; - if(!kind.extra?.url||!text)return ''; - try{const url=new URL(text);if(url.protocol==='http:'||url.protocol==='https:')return ''}catch{} - return '请填写以 http:// 或 https:// 开头的地址'; + return kind.extra?.url?credentialBaseURLError(text):''; +} +function credentialBaseURLError(value){ + const text=String(value||'').trim(); + if(!text)return ''; + try{ + const url=new URL(text); + if(/^https?:\/\//i.test(text)&&url.hostname&&!url.username&&!url.password&&!/[?#]/.test(text))return ''; + }catch{} + return '请填写以 http:// 或 https:// 开头的地址,地址内不可包含账号密码、查询参数或片段'; +} +function credentialBaseURLFieldHTML(value){ + return credentialFieldHTML({label:'Base URL',note:'可选 · 留空使用网络环境的官方地址',name:'baseUrl',type:'url',value,placeholder:'https://gateway.example.com/v1'}); } // Only the fields of one credential are sent; the server leaves the rest alone. function credentialSavePayload(kind,values={}){ @@ -557,6 +571,7 @@ function credentialSavePayload(kind,values={}){ } const payload={[kind.key]:String(values.secret||'').trim()}; if(kind.extra&&values.extra!==undefined)payload[kind.extra.name]=String(values.extra||'').trim()||(kind.extra.fallback||''); + if(kind.baseURL&&values.baseUrl!==undefined)payload[kind.baseURL]=String(values.baseUrl||'').trim(); if(kind.models&&values.models!==undefined)payload[kind.models.name]=credentialCatalogStored(values.models); return payload; } @@ -595,7 +610,7 @@ function credentialSubline(kind,user){ const dot='',use=`${escapeHTML(kind.use)}`; if(!credentialConfigured(kind,user))return use; if(kind.key==='gitToken'){ - const verify=gitTokenVerifyFor({id:state.currentUser?.id}),result=verify?.result,source=`${user.gitTokenOAuth?'工蜂授权':'个人访问令牌'}`; + const verify=gitTokenVerifyFor({id:state.currentUser?.id}),result=verify?.result,source='https://github.com'; if(verify?.busy)return source+dot+'正在校验…'; if(!result)return source+dot+use; if(result.error)return source+dot+`${escapeHTML(result.error)}`; @@ -603,13 +618,14 @@ function credentialSubline(kind,user){ return source+dot+'令牌有效'+(result.scopes?.length?dot+`${escapeHTML(result.scopes.join(' · '))}`:''); } if(kind.key==='codeBuddyApiKey'){ - const raw=String(user.codeBuddyInternetEnvironment||'').trim(),env=codeBuddyEnvironment(raw); - return `网络环境${env?`${escapeHTML(env.label)}`:`「${escapeHTML(raw)}」无法识别,按国际站连接`}${dot}${use}`; + const raw=String(user.codeBuddyInternetEnvironment||'').trim(),env=codeBuddyEnvironment(raw),baseUrl=user.codeBuddyBaseUrl; + if(baseUrl)return `${escapeHTML(baseUrl)}`; + return `网络环境${env?`${escapeHTML(env.label)}`:`「${escapeHTML(raw)}」无法识别,按国际站连接`}`; } if(kind.extra){ const models=kind.models&&credentialCatalogModels(credentialValue(user,kind.models.name)).length,baseUrl=credentialValue(user,kind.extra.name); const protocol=kind.protocol?kind.protocol.options.find(([id])=>id===credentialProtocol(kind,user))?.[1]:''; - return (baseUrl?`${escapeHTML(baseUrl)}`:'官方地址')+(protocol?dot+`${escapeHTML(protocol)}`:'')+(models?dot+`${models} 个自定义模型`:'')+dot+use; + return `${escapeHTML(baseUrl||'官方服务')}${protocol?` · ${escapeHTML(protocol)}`:''}${models?` · ${models} 个自定义模型`:''}`; } return use; } @@ -664,7 +680,7 @@ function credentialEditorHTML(kind,user){ const extraStored=kind.extra?credentialValue(user,kind.extra.name):''; const extraValue=kind.extra?credentialExtraValue(kind,extraStored):''; const extraField=!kind.extra?'' - :kind.extra.options?credentialSelectFieldHTML(kind,extraStored,'与 Key 所在站点一致') + :kind.extra.options?credentialSelectFieldHTML(kind,extraStored,'官方地址使用') :credentialFieldHTML({label:kind.extra.label,note:kind.extra.note||(kind.extra.url?'留空使用官方地址':''),name:'extra',type:kind.extra.url?'url':'text',value:extraValue,placeholder:kind.extra.placeholder,hint:null}); const protocolValue=kind.protocol?credentialProtocol(kind,user):''; const protocolField=kind.protocol?credentialProtocolHTML(kind,protocolValue):''; @@ -672,77 +688,300 @@ function credentialEditorHTML(kind,user){ return `
    ${credentialFieldHTML({label:kind.short,note:'已配置 · 留空则不改',name:'secret',placeholder:'输入新值以替换',hint:kind.hint||''})} ${extraField} + ${kind.baseURL?credentialBaseURLFieldHTML(credentialValue(user,kind.baseURL)):''} ${protocolField} ${kind.models?credentialCatalogHTML(kind,user):''}
    - +
    `; } function credentialRowMainHTML(kind,user){ const managed=!!kind.dialog,on=credentialConfigured(kind,user),open=on&&credentialUI().open===kind.key,status=credentialStatus(kind,user); const end=on&&!managed - ?`${credentialBadgeHTML(status)}${kind.key==='gitToken'?``:''}${credentialGlyph('chevron-down',16)}` + ?`${kind.key==='gitToken'?`${credentialBadgeHTML(status)}`:''}` :`${credentialBadgeHTML(status)}`; const interaction=managed?'':` role="button" tabindex="0"${on?` aria-expanded="${open}"`:''}`; - return `
    ${credentialLogo(kind,on?'':'is-dim')}
    ${escapeHTML(kind.name)}${escapeHTML(kind.short)}${credentialSubline(kind,user)}
    ${end}
    `; + const preferred=credentialDefaultsExecutor(credentialUI().catalog); + const executor=on&&kind.models?.engine; + const active=executor&&executor===preferred?.id; + return `
    ${credentialLogo(kind,on?'':'is-dim')}
    ${escapeHTML(kind.name)}${active?'默认':''}${credentialSubline(kind,user)}
    ${end}
    `; } function credentialRowHTML(kind,user){ const on=credentialConfigured(kind,user),open=on&&credentialUI().open===kind.key; const editor=on&&!kind.dialog?credentialEditorHTML(kind,user):''; - return `
    ${credentialRowMainHTML(kind,user)}
    ${editor}
    `; + return `
    ${credentialRowMainHTML(kind,user)}
    ${editor}
    `; +} +const GIT_ADD_OPTIONS=[ + {id:'gitToken',name:'GitHub',logo:'github',monochrome:true}, + {id:'gitlab',name:'GitLab',logo:'gitlab',monochrome:true}, + {id:'github',name:'GitHub Enterprise',logo:'github',monochrome:true}, + {id:'other',name:'其他 Git',icon:'globe'}, + {id:'gitSshKey',name:'Git SSH',icon:'key'}, +]; +function credentialOptionHTML({id,name,logo,monochrome,icon},selected){ + const file=logo&&(logo.endsWith('.png')?logo:logo+'.svg'); + return ``; +} +function credentialAddMenu(group,user){ + const git=group.id==='platform'; + const label=git?'新增 Git 配置':'新增执行器'; + const options=git?GIT_ADD_OPTIONS:CREDENTIAL_KINDS.filter(kind=>kind.group==='model'&&!credentialConfigured(kind,user)) + .map(kind=>({id:kind.key,name:kind.name,logo:kind.logo,monochrome:kind.monochrome})); + if(!options.length)return ''; + return `
    + +
    `; } function credentialGroupHTML(group,user){ - const kinds=CREDENTIAL_KINDS.filter(kind=>kind.group===group.id),done=kinds.filter(kind=>credentialConfigured(kind,user)).length,closed=!!credentialUI().closed[group.id]; - return `
    ${kinds.map(kind=>credentialRowHTML(kind,user)).join('')}
    `; + const git=group.id==='platform'; + const kinds=CREDENTIAL_KINDS.filter(kind=>kind.group===group.id&&!kind.dialog&&credentialConfigured(kind,user)); + const scope=git&&(kinds.length||user.gitHttpCredentialsConfigured||user.gitSshKeyConfigured); + return `
    +
    +

    ${group.name}

    + ${git?`

    按仓库地址的协议、主机和端口匹配

    `:''} +
    +
    +
    ${kinds.map(kind=>credentialRowHTML(kind,user)).join('')}${git?'
    ':''}
    + ${credentialAddMenu(group,user)} + ${git?'':` + ${credentialLogo({icon:'monitor'})} + + 使用已有订阅 + Claude Code、Codex 和 Antigravity 可用账号登录 + + 配置执行机器${credentialGlyph('arrow-right',14)} + `} +
    +
    `; } -function credentialProgressHTML(user){ - const done=CREDENTIAL_KINDS.filter(kind=>credentialConfigured(kind,user)).length,next=credentialNextKind(user); - return `${done} / ${CREDENTIAL_KINDS.length} 已配置` - +(next?`下一步`:`${credentialGlyph('check',15)}推荐凭证已全部就绪`); +function credentialPanelHTML(user){ + const hasCLI=CREDENTIAL_KINDS.some(kind=>kind.group==='model'&&credentialConfigured(kind,user)); + return `
    + ${CREDENTIAL_GROUPS.map(group=>credentialGroupHTML(group,user)).join('')} + ${hasCLI?`
    ${credentialDefaultsHeader()}

    正在读取执行器…

    `:''} +
    `; } -function credentialFilterHTML(user){ - const done=CREDENTIAL_KINDS.filter(kind=>credentialConfigured(kind,user)).length,filter=credentialUI().filter; - return [['all','全部',CREDENTIAL_KINDS.length],['configured','已配置',done],['missing','未配置',CREDENTIAL_KINDS.length-done]].map(([id,label,count])=>``).join(''); +function credentialGitRowsHTML(http,ssh,showGitHub){ + return [...http.filter(item=>item.host!=='github.com'||!showGitHub).map(item=>({...item,kind:'http'})),...ssh.map(item=>({...item,kind:'ssh'}))].map(item=>{ + const isSSH=item.kind==='ssh'; + const platform=GIT_ADD_OPTIONS.find(type=>type.id===(isSSH?'gitSshKey':item.platform))||GIT_ADD_OPTIONS.find(type=>type.id==='other'); + const endpoint=`${isSSH?'ssh':'https'}://${item.host}`; + return `
    + ${credentialLogo(platform)}
    ${escapeHTML(item.name)}${platform.name} · ${escapeHTML(endpoint)}
    +
    +
    `; + }).join(''); } -function credentialPanelHTML(user){ - return `

    个人凭证

    SOP 使用需求责任人(未指定时为项目 Owner)的个人凭证,保存后对下一次任务生效。

    -
    - ${credentialGlyph('monitor',16)} -
    使用已有订阅 -

    绑定已登录 Claude Code、Codex 或 Antigravity 的机器,选「账号登录」即可用订阅额度运行对话和 SOP,无需 API Key。

    - 配置执行机器${credentialGlyph('arrow-right',14)} -
    -
    ${credentialProgressHTML(user)}
    -
    ${credentialFilterHTML(user)}
    -
    ${CREDENTIAL_GROUPS.map(group=>credentialGroupHTML(group,user)).join('')}
    `; -} -function applyCredentialFilter(panel,user){ - const filter=credentialUI().filter; - panel.querySelectorAll('[data-credential-row]').forEach(row=>{ - const on=credentialConfigured(credentialKind(row.dataset.credentialRow),user); - row.classList.toggle('is-filtered',(filter==='configured'&&!on)||(filter==='missing'&&on)); - }); - panel.querySelectorAll('[data-credential-group]').forEach(group=>{ - const empty=group.querySelector('.credential-empty'),visible=group.querySelectorAll('[data-credential-row]:not(.is-filtered)').length; - empty.hidden=!!visible; - empty.textContent=filter==='configured'?'这一组还没有配置凭证':'这一组已全部配置'; +async function loadCredentialGitRows(panel,user){ + const host=panel.querySelector('[data-credential-git-rows]'); + if(!host||!user.id)return; + const http=api(`/api/users/${user.id}/git-http-credentials`,{silent:true}); + const ssh=user.gitSshKeyConfigured?loadGitSSHKeys():[]; + const [httpRows,sshRows]=await Promise.allSettled([http,ssh]); + if(!host.isConnected||state.currentUser?.id!==user.id)return; + const listed=entry=>entry.status==='fulfilled'&&Array.isArray(entry.value)?entry.value:[]; + host.innerHTML=credentialGitRowsHTML(listed(httpRows),listed(sshRows),user.gitHubCredentialConfigured); + const note=panel.querySelector('[data-credential-group="platform"] .credential-group-note'); + if(note)note.hidden=!user.gitHubCredentialConfigured&&!host.firstElementChild; + hydrateCredentialIcons(host); +} +function credentialMenuReady(panel){ + panel.querySelectorAll('[data-credential-add-menu]').forEach(select=>{ + const menu=window.HuiSelect?.enhance(select); + menu?.trigger.classList.add('credential-add-trigger'); + menu?.panel.classList.add('credential-add-panel'); }); } +function credentialDefaultsExecutor(catalog){ + if(!catalog)return null; + const engines=window.AgentFlowAssistantModels?.featureExecutors(catalog)||[]; + return engines.find(engine=>engine.id===catalog.preferences?.executor)||engines.find(engine=>engine.models.length)||engines[0]||null; +} +const ASSISTANT_APPROVAL_CHOICES=[['confirm','请求批准'],['assisted','帮我批准'],['auto','完全权限']]; +const DEFAULT_EFFORT_LABELS={none:'关闭',minimal:'极低',low:'低',medium:'中',high:'高',xhigh:'极高',max:'最大',ultra:'Ultra',ultracode:'Ultracode',thinking:'开启'}; +function credentialDefaultOptions(options,value){ + return options.map(([id,name])=>credentialOptionHTML({id,name},value)).join(''); +} +function credentialDefaultsHeader(){ + return `
    +

    AI 默认设置

    + +
    `; +} +function credentialDefaultField(label,name,icon,options=''){ + const id=`credentialDefault-${name}`; + return `
    + + +
    `; +} +function credentialDefaultValues(form){ + const {executor,model,effort,approval}=form.elements; + return {executor:executor.value,model:model.value.replace(executor.value+':',''),effort:effort.value,approval:approval.value}; +} +function syncCredentialDefaultActions(form){ + form.querySelector('[data-default-actions]').hidden=JSON.stringify(credentialDefaultValues(form))===form.dataset.initial; + form.querySelector('[data-default-error]').hidden=true; +} +function paintCredentialDefaultEffort(form,engine,value){ + const model=engine?.models.find(item=>item.id===form.elements.model.value); + const options=(model?.efforts||[]).map(level=>[level,DEFAULT_EFFORT_LABELS[level]||level]); + form.elements.effort.innerHTML=credentialDefaultOptions([['','默认'],...options],value); + form.elements.effort.disabled=!options.length; +} +function paintCredentialDefaults(host,catalog){ + const models=window.AgentFlowAssistantModels; + const engines=models.featureExecutors(catalog),engine=credentialDefaultsExecutor(catalog); + if(!engine)return; + const prefs=catalog.preferences||{}; + const executorOptions=engines.map(item=>credentialOptionHTML({...credentialKind(item.credential),id:item.id,name:item.name},engine.id)).join(''); + host.innerHTML=`${credentialDefaultsHeader()} +
    +
    +
    + ${credentialDefaultField('默认执行器','executor','terminal',executorOptions)} + ${credentialDefaultField('默认模型','model','sparkles')} + ${credentialDefaultField('思考强度','effort','brain')} + ${credentialDefaultField('操作确认方式','approval','gate',credentialDefaultOptions(ASSISTANT_APPROVAL_CHOICES,prefs.approval||'confirm'))} +
    + +
    + +
    `; + const form=host.querySelector('form'); + const feedback=host.querySelector('[data-default-feedback]'); + const selectedExecutor=()=>engines.find(item=>item.id===form.elements.executor.value); + const syncEffort=()=>{ + const {executor,model}=form.elements; + const savedModel=executor.value===prefs.executor&&model.value===`${prefs.executor}:${prefs.model}`; + paintCredentialDefaultEffort(form,selectedExecutor(),savedModel?prefs.effort:''); + }; + const fillModels=()=>{ + const selected=selectedExecutor(); + if(!selected)return; + const model=models.preferredFeatureModel(catalog,selected.id,selected.models); + const options=selected.models.map(item=>[item.id,item.name||item.id]); + form.elements.model.innerHTML=credentialDefaultOptions(options.length?options:[['','暂无可选模型']],model); + form.elements.model.disabled=!options.length; + syncEffort(); + }; + fillModels(); + for(const select of form.querySelectorAll('.credential-default-select')){ + const menu=window.HuiSelect?.enhance(select); + if(!menu)continue; + menu.panel.classList.add('credential-default-panel'); + const value=menu.trigger.querySelector('.hui-select-value'); + value.id=`${select.id}-value`; + menu.trigger.setAttribute('aria-labelledby',`${select.id}-label ${value.id}`); + } + form.dataset.initial=JSON.stringify(credentialDefaultValues(form)); + form.onchange=event=>{ + feedback.textContent=''; + if(event.target===form.elements.executor)fillModels(); + if(event.target===form.elements.model)syncEffort(); + syncCredentialDefaultActions(form); + }; + form.onreset=event=>{ + event.preventDefault(); + form.elements.executor.value=engine.id; + form.elements.approval.value=prefs.approval||'confirm'; + fillModels(); + syncCredentialDefaultActions(form); + form.elements.executor.focus({preventScroll:true}); + }; + form.onsubmit=event=>{event.preventDefault();void saveCredentialDefaults(form,host)}; + hydrateCredentialIcons(host); +} +async function loadCredentialDefaults(panel){ + const host=panel.querySelector('[data-credential-defaults]'); + const models=window.AgentFlowAssistantModels; + if(!host||!models)return; + const ui=credentialUI(); + try{ + const catalog=await models.fetchCatalog(); + if(!host.isConnected||credentialUI()!==ui)return; + ui.catalog=catalog; + state.data.assistantDefaults=catalog.preferences||{}; + if(!credentialDefaultsExecutor(catalog)){ + host.querySelector('.credential-default-status').textContent='当前账号暂无可用执行器'; + return; + } + paintCredentialDefaults(host,catalog); + CREDENTIAL_KINDS.filter(kind=>kind.group==='model').forEach(kind=>repaintCredentialRow(kind.key)); + }catch(error){ + if(host.isConnected){const status=host.querySelector('.credential-default-status');if(status)status.textContent=error.message} + } +} +async function saveCredentialDefaults(form,host){ + const ui=credentialUI(),catalog=ui.catalog,userId=ui.userId; + const defaults=credentialDefaultValues(form); + if(!catalog||ui.savingDefaults||JSON.stringify(defaults)===form.dataset.initial)return; + const fields=form.querySelector('fieldset'),button=form.querySelector('[data-save-ai-defaults]'); + const error=form.querySelector('[data-default-error]'); + ui.savingDefaults=true; + fields.disabled=true; + error.hidden=true; + setCredentialButtonBusy(button,'保存中'); + try{ + await api(`/api/users/${userId}/credentials`,{method:'PUT',body:JSON.stringify({assistantDefaults:defaults})}); + if(credentialUI()!==ui)return; + ui.catalog={...catalog,preferences:defaults}; + state.data.assistantDefaults=defaults; + if(host.isConnected){ + paintCredentialDefaults(host,ui.catalog); + CREDENTIAL_KINDS.filter(kind=>kind.group==='model').forEach(kind=>repaintCredentialRow(kind.key)); + const executor=host.querySelector('.credential-default-field .hui-select-trigger, [name="executor"]:not(.hui-select-native)'); + executor?.focus({preventScroll:true}); + host.querySelector('[data-default-feedback]').textContent='已保存'; + } + notifyCredentialsChanged(); + }catch(failure){ + if(error.isConnected){error.textContent=failure.message;error.hidden=false} + }finally{ + ui.savingDefaults=false; + if(form.isConnected){fields.disabled=false;setCredentialButtonBusy(button,'')} + } +} function renderCredentialPanel(){ const panel=$('#credentialPanel');if(!panel)return; const user=credentialUser(); + if(!CREDENTIAL_KINDS.some(kind=>kind.group==='model'&&credentialConfigured(kind,user))){ + credentialUI().catalog=null; + state.data.assistantDefaults={}; + } panel.innerHTML=credentialPanelHTML(user); if(typeof hydrateGitHubConnections==='function')hydrateGitHubConnections(panel); - applyCredentialFilter(panel,user); + credentialMenuReady(panel); hydrateCredentialIcons(panel); + void loadCredentialGitRows(panel,user); + void loadCredentialDefaults(panel); +} +function renderCredentialGitGroup(panel=$('#credentialPanel'),user=credentialUser()){ + const group=panel?.querySelector('[data-credential-group="platform"]'); + if(!group)return; + const holder=document.createElement('div'); + holder.innerHTML=credentialGroupHTML(CREDENTIAL_GROUPS[0],user); + group.replaceWith(holder.firstElementChild); + if(typeof hydrateGitHubConnections==='function')hydrateGitHubConnections(panel); + credentialMenuReady(panel); + hydrateCredentialIcons(panel); + void loadCredentialGitRows(panel,user); } function repaintCredentialRow(key){ const row=$(`#credentialPanel [data-credential-row="${key}"]`),kind=credentialKind(key);if(!row||!kind)return; const user=credentialUser(),holder=document.createElement('div'); holder.innerHTML=credentialRowMainHTML(kind,user); - row.querySelector('.credential-row-main').replaceWith(holder.firstElementChild); + const previous=row.querySelector('.credential-row-main'),main=holder.firstElementChild; + const restoreFocus=document.activeElement===previous; + previous.replaceWith(main); if(key==='gitToken'){ // Only the read-only parts are replaced: an open replace form keeps what was typed. const failure=gitTokenFailure(gitTokenVerifyFor({id:state.currentUser?.id})?.result),detail=row.querySelector('[data-git-detail]'),warning=row.querySelector('.git-token-pat-warning'),replace=row.querySelector('[data-credential-act="replace"]'); @@ -752,6 +991,7 @@ function repaintCredentialRow(key){ } row.querySelector('.credential-status')?.classList.add('is-swap'); hydrateCredentialIcons(row); + if(restoreFocus)main.focus({preventScroll:true}); } function flashCredentialRow(key){ const row=$(`#credentialPanel [data-credential-row="${key}"]`);if(!row)return; @@ -761,7 +1001,13 @@ function flashCredentialRow(key){ function setCredentialRowOpen(key,open){ const row=$(`#credentialPanel [data-credential-row="${key}"]`);if(!row)return; row.classList.toggle('is-open',open); - row.querySelector('.credential-row-main')?.setAttribute('aria-expanded',String(open)); + const main=row.querySelector('.credential-row-main'); + const editor=row.querySelector('.credential-editor'); + main?.setAttribute('aria-expanded',String(open)); + const fold=main?.querySelector('[data-credential-fold-label]'); + if(fold)fold.textContent=open?'收起':'编辑'; + if(!open&&editor?.contains(document.activeElement))main?.focus({preventScroll:true}); + if(editor)editor.inert=!open; if(!open){ resetCredentialEditor(row); showCredentialPane(row,'bar'); @@ -771,6 +1017,8 @@ function resetCredentialEditor(row){ row.querySelectorAll('[name="secret"]').forEach(input=>{input.value='';if(input.tagName==='INPUT')input.type='password'}); const form=row.querySelector('.credential-editor-form');if(!form)return; const extra=form.querySelector('[name="extra"]');if(extra)extra.value=form.dataset.original||''; + const baseUrl=form.querySelector('[name="baseUrl"]'); + if(baseUrl){baseUrl.value=baseUrl.defaultValue;setCredentialHint(form,'baseUrl','')} if(extra?.tagName==='SELECT')refreshCredentialEnvironmentLinks(form,extra.value); const protocol=form.querySelector('select[name="protocol"]');if(protocol)protocol.value=form.dataset.originalProtocol||''; resetCredentialCatalog(row); @@ -785,8 +1033,6 @@ function toggleCredentialRow(key,open){ if(ui.open&&ui.open!==key)setCredentialRowOpen(ui.open,false); ui.open=next?key:null; setCredentialRowOpen(key,next); - // 代码仓库 opens on its read-only detail; the token input only appears after 手动更换令牌. - if(next&&key!=='gitToken')setTimeout(()=>$(`#credentialPanel [data-credential-row="${key}"] [name="secret"]`)?.focus({preventScroll:true}),200); } const CREDENTIAL_PANE_FOCUS={form:'[name="secret"]',confirm:'[data-credential-act="undelete"]'}; // 代码仓库 swaps bar / form / confirm; the other kinds swap foot / confirm. Unknown names fall back to the first pane. @@ -798,7 +1044,9 @@ function showCredentialPane(row,name,focus=CREDENTIAL_PANE_FOCUS[name]){ } function updateCredentialEditorDirty(form){ const secret=form.querySelector('[name="secret"]')?.value.trim()||'',extra=form.querySelector('[name="extra"]'),protocol=form.querySelector('select[name="protocol"]'),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||''))&&!(protocol&&protocol.value!==(form.dataset.originalProtocol||''))&&!credentialCatalogDirty(form.querySelector('[data-credential-catalog]')); + const baseUrl=form.querySelector('[name="baseUrl"]'); + const baseChanged=baseUrl&&baseUrl.value.trim()!==baseUrl.defaultValue; + if(save&&!save.dataset.busy)save.disabled=!secret&&!baseChanged&&!form.dataset.legacy&&!(extra&&extra.value.trim()!==(form.dataset.original||''))&&!(protocol&&protocol.value!==(form.dataset.originalProtocol||''))&&!credentialCatalogDirty(form.querySelector('[data-credential-catalog]')); } function setCredentialHint(scope,name,text,tone=''){ const hint=scope.querySelector(`[data-credential-hint="${name}"]`),box=scope.querySelector(`[name="${name}"]`)?.closest('.credential-input'); @@ -869,16 +1117,21 @@ async function refreshGitTokenStatus(options={}){ } function credentialSaved(key,message){ credentialUI().open=null; - renderCredentialPanel(); + const group=credentialKind(key)?.group; + if(group==='platform')renderCredentialGitGroup();else renderCredentialPanel(); flashCredentialRow(key); + const row=$(`#credentialPanel [data-credential-row="${key}"] .credential-row-main`); + (row||$(`#credentialPanel [data-credential-add-menu="${group}"]`))?.focus({preventScroll:true}); toast(message,'ok'); } async function submitCredentialEditor(row,button){ const key=row.dataset.credentialRow,kind=credentialKind(key),form=row.querySelector('.credential-editor-form'); const secret=form.querySelector('[name="secret"]').value.trim(),extra=form.querySelector('[name="extra"]'),protocol=form.querySelector('[name="protocol"]'); const secretError=credentialSecretError(kind,secret),extraError=extra?credentialExtraError(kind,extra.value,protocol?.value):''; + const baseUrl=form.querySelector('[name="baseUrl"]'),baseValue=baseUrl?.value.trim(),baseError=credentialBaseURLError(baseValue); if(secretError){setCredentialHint(form,'secret',secretError,'err');return} if(extraError){toast(extraError,'err');extra.focus();return} + if(baseError){setCredentialHint(form,'baseUrl',baseError,'err');baseUrl.focus();return} const catalog=form.querySelector('[data-credential-catalog]'),models=credentialCatalogPayload(catalog); if(!validateCredentialCatalog(catalog,models))return; setCredentialButtonBusy(button,key==='gitToken'?'校验中':'保存中'); @@ -895,8 +1148,8 @@ async function submitCredentialEditor(row,button){ credentialSaved(key,'Git Token 校验通过,已保存'); return; } - await saveCredential(key,{secret,...(extra?{extra:extra.value}:{}),...(protocol?{protocol:protocol.value}:{}),...(models?{models}:{})}); - credentialSaved(key,`${kind.short} 已保存`); + await saveCredential(key,{secret,extra:extra?.value,baseUrl:baseValue!==baseUrl?.defaultValue?baseValue:undefined,protocol:protocol?.value,models}); + credentialSaved(key,`${kind.name} 配置已保存`); }catch(err){toast(err.message,'err');setCredentialButtonBusy(button,'')} } async function confirmDeleteCredential(row,button){ @@ -928,17 +1181,6 @@ function credentialRowAction(action,row,button){ if(action==='confirm-delete')return confirmDeleteCredential(row,button); if(action==='save')return submitCredentialEditor(row,button); } -function setCredentialFilter(panel,filter){ - credentialUI().filter=filter; - panel.querySelectorAll('[data-credential-filter]').forEach(tab=>{const on=tab.dataset.credentialFilter===filter;tab.classList.toggle('active',on);tab.setAttribute('aria-selected',String(on))}); - applyCredentialFilter(panel,credentialUser()); -} -function toggleCredentialGroup(head){ - const id=head.closest('[data-credential-group]').dataset.credentialGroup,ui=credentialUI(); - ui.closed[id]=!ui.closed[id]; - head.setAttribute('aria-expanded',String(!ui.closed[id])); - head.nextElementSibling.classList.toggle('is-closed',!!ui.closed[id]); -} function activateCredentialRow(row){ const key=row.dataset.credentialRow; const dialog=credentialDialog(key);if(dialog)return dialog(); @@ -947,10 +1189,8 @@ function activateCredentialRow(row){ function bindCredentialPanel(panel){ panel.onclick=event=>{ const target=event.target; - if(target.closest('[data-credential-add]'))return openCredentialWizard(); - const setup=target.closest('[data-credential-setup]');if(setup)return openCredentialWizard(setup.dataset.credentialSetup); - const filter=target.closest('[data-credential-filter]');if(filter)return setCredentialFilter(panel,filter.dataset.credentialFilter); - const head=target.closest('.credential-group-head');if(head)return toggleCredentialGroup(head); + const git=target.closest('[data-credential-git-kind]'); + if(git)return git.dataset.credentialGitKind==='ssh'?openGitSSHKeys('',{id:git.dataset.credentialGitId}):openGitHTTPCredentials({id:git.dataset.credentialGitId}); const eye=target.closest('[data-credential-eye]');if(eye)return toggleCredentialSecret(eye); const row=target.closest('[data-credential-row]');if(!row)return; const catalogAction=target.closest('[data-catalog-act]'); @@ -960,6 +1200,19 @@ function bindCredentialPanel(panel){ if(target.closest('.credential-editor'))return; if(target.closest('.credential-row-main'))activateCredentialRow(row); }; + panel.onchange=event=>{ + const select=event.target.closest('[data-credential-add-menu]'); + if(select){ + const key=select.value; + select.value=''; + if(!key)return; + select.focus(); + if(select.dataset.credentialAddMenu==='model'||key==='gitToken')openCredentialWizard(key); + else if(key==='gitSshKey')openGitSSHKeys('',{add:true}); + else if(key)openGitHTTPCredentials({platform:key,add:true}); + return; + } + }; panel.onkeydown=event=>{ const main=event.target.closest?.('.credential-row-main[role="button"]'); if(main&&event.target===main&&(event.key==='Enter'||event.key===' ')){event.preventDefault();activateCredentialRow(main.closest('[data-credential-row]'))} @@ -981,11 +1234,15 @@ function bindCredentialPanel(panel){ event.target.closest('.credential-input')?.classList.remove('is-bad'); syncCredentialCatalogEfforts(event.target.closest('[data-catalog-row]')); } - if(event.target.name==='extra'||event.target.name==='protocol'){const catalogBox=form.querySelector('[data-credential-catalog]');if(catalogBox)syncCredentialCatalog(catalogBox)} - 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); + if(['extra','baseUrl','protocol'].includes(event.target.name)){const catalogBox=form.querySelector('[data-credential-catalog]');if(catalogBox)syncCredentialCatalog(catalogBox)} + if(event.target.name==='secret'||event.target.name==='baseUrl'){ + const kind=credentialKind(form.closest('[data-credential-row]').dataset.credentialRow),secret=form.querySelector('[name="secret"]').value,baseUrl=form.querySelector('[name="baseUrl"]')?.value; + const error=credentialSecretError(kind,secret),warning=credentialSecretWarning(kind,secret,baseUrl); setCredentialHint(form,'secret',error||warning||(kind.key==='gitToken'?GIT_TOKEN_REPLACE_HINT:kind.hint||''),error?'err':warning?'warn':''); } + if(event.target.name==='baseUrl'){ + const error=credentialBaseURLError(event.target.value);setCredentialHint(form,'baseUrl',error,error?'err':''); + } if(event.target.name==='extra'&&event.target.tagName==='SELECT')refreshCredentialEnvironmentLinks(form,event.target.value); updateCredentialEditorDirty(form); }; @@ -993,11 +1250,13 @@ function bindCredentialPanel(panel){ // gotoCredential lands here for configured credentials. function revealCredentialRow(key){ const panel=$('#credentialPanel'),row=panel?.querySelector(`[data-credential-row="${key}"]`);if(!row)return; - if(row.classList.contains('is-filtered'))setCredentialFilter(panel,'all'); - const group=row.closest('[data-credential-group]'),head=group?.querySelector('.credential-group-head'); - if(head&&credentialUI().closed[group.dataset.credentialGroup])toggleCredentialGroup(head); if(credentialUI().open!==key)toggleCredentialRow(key,true); - else if(key!=='gitToken')setTimeout(()=>row.querySelector('[name="secret"]')?.focus({preventScroll:true}),200); + if(key!=='gitToken'){ + const focus=document.activeElement; + setTimeout(()=>{ + if(row.isConnected&&row.classList.contains('is-open')&&document.activeElement===focus)row.querySelector('[name="secret"]')?.focus({preventScroll:true}); + },200); + } row.scrollIntoView({block:'center',behavior:'smooth'}); row.classList.add('credential-highlight'); setTimeout(()=>row.classList.remove('credential-highlight'),2400); @@ -1006,6 +1265,7 @@ function revealCredentialRow(key){ // ---- 添加凭证向导 ---- let credentialWizard=null; function credentialWizardDefaults(kind,user){return kind?.extra?credentialExtraValue(kind,credentialValue(user,kind.extra.name)):''} +function isDirectExecutorForm(wizard=credentialWizard){return wizard?.direct&&wizard.step===2&&credentialKind(wizard.kind)?.group==='model'} function openCredentialWizard(key){ const user=credentialUser(); if(!state.currentUser||state.currentUser.isGuest||!$('#credentialPanel'))return; @@ -1015,7 +1275,7 @@ function openCredentialWizard(key){ const kind=preset||CREDENTIAL_RECOMMENDED.map(credentialKind).find(k=>!credentialConfigured(k,user))||CREDENTIAL_KINDS.find(k=>!credentialConfigured(k,user))||null; if(credentialWizard)closeCredentialWizard(true); credentialUI().open&&toggleCredentialRow(credentialUI().open,false); - credentialWizard={step:preset?2:1,kind:kind?.key||null,direct:!!preset,secret:'',extra:credentialWizardDefaults(kind,user),protocol:credentialProtocol(kind||{},user),saving:false,error:'',done:false,guide:{},returnFocus:document.activeElement}; + credentialWizard={step:preset?2:1,kind:kind?.key||null,direct:!!preset,secret:'',extra:credentialWizardDefaults(kind,user),baseUrl:credentialValue(user,kind?.baseURL)||'',protocol:credentialProtocol(kind||{},user),saving:false,error:'',done:false,guide:{},returnFocus:document.activeElement}; let scrim=$('#credentialWizard'); if(scrim?.closeTimer){clearTimeout(scrim.closeTimer);scrim.closeTimer=0} if(!scrim){ @@ -1048,17 +1308,22 @@ function closeCredentialWizard(immediate=false){ // The secret input is removed with the dialog so nothing typed stays in the DOM. scrim.querySelectorAll('input').forEach(input=>{input.value=''}); if(immediate)remove();else scrim.closeTimer=setTimeout(remove,260); - if(wizard.done)flashCredentialRow(wizard.kind); - if(wizard.returnFocus?.isConnected)wizard.returnFocus.focus({preventScroll:true}); + if(wizard.done){ + flashCredentialRow(wizard.kind); + const row=$('#credentialPanel [data-credential-row="'+wizard.kind+'"] .credential-row-main'); + row?.scrollIntoView?.({block:'nearest'}); + row?.focus({preventScroll:true}); + }else if(wizard.returnFocus?.isConnected)wizard.returnFocus.focus({preventScroll:true}); } function credentialWizardValid(wizard=credentialWizard){ const kind=credentialKind(wizard.kind);if(!kind)return {ok:false}; const secret=String(wizard.secret||'').trim(),error=credentialSecretError(kind,secret)||(kind.extra?credentialExtraError(kind,wizard.extra,wizard.protocol):''); - return {ok:!!secret&&!error,error}; + const baseError=kind.baseURL?credentialBaseURLError(wizard.baseUrl):''; + return {ok:!!secret&&!error&&!baseError,error,baseError}; } 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'}; + const warning=credentialSecretWarning(kind,wizard.secret,wizard.baseUrl);if(warning)return {text:warning,tone:'warn'}; return validity.ok?{text:'格式正确',tone:'ok'}:{text:kind.hint||'只在你负责的任务运行时注入,保存后不再明文展示',tone:''}; } function credentialWizardStepOneHTML(user){ @@ -1088,23 +1353,33 @@ function credentialWizardStepTwoHTML(kind){ :credentialFieldHTML({label:kind.extra.label,note:kind.extra.note||(kind.extra.url?'可选 · 留空使用官方地址':''),name:'extra',type:kind.extra.url?'url':'text',value:wizard.extra,placeholder:kind.extra.placeholder,hint:''}); const protocolField=kind.protocol?credentialProtocolHTML(kind,wizard.protocol||credentialProtocol(kind,{})):''; // The network environment decides where the key comes from, so it is chosen first. + const baseField=kind.baseURL?credentialBaseURLFieldHTML(wizard.baseUrl):''; + const fields=(kind.extra?.options?extraField+secretField:secretField+extraField+protocolField)+baseField; + if(isDirectExecutorForm(wizard)){ + const error=wizard.error?``:''; + return `
    ${credentialLogo(kind)}

    新增 ${escapeHTML(kind.name)}

    +
    ${fields}
    +
    如何获取密钥
      ${guide}
    ${error}`; + } return `
    ${credentialLogo(kind,'is-mini')}${github?'使用访问令牌':'配置 '+escapeHTML(kind.short)}${escapeHTML(kind.description)}
    ${methods}
      ${guide}
    - ${kind.extra?.options?extraField+secretField:secretField+extraField+protocolField} + ${fields}
    `; } function credentialWizardStepThreeHTML(kind){ const wizard=credentialWizard; if(wizard.done)return `

    ${escapeHTML(kind.short)} 已保存

    下一次运行你负责的任务时生效,可随时在列表中展开编辑。

    `; const extra=kind.extra?`
    ${escapeHTML(kind.extra.label)}
    ${escapeHTML(credentialExtraLabel(kind,wizard.extra))}`:''; - const warning=credentialSecretWarning(kind,wizard.secret); + const base=kind.baseURL&&wizard.baseUrl?`
    Base URL
    ${escapeHTML(wizard.baseUrl)}
    `:''; + const warning=credentialSecretWarning(kind,wizard.secret,wizard.baseUrl); const line=wizard.error?`` :wizard.saving&&kind.key==='gitToken'?`

    ${credentialSpinner(13)}正在校验令牌有效性与权限…

    ` :kind.key==='gitToken'?`

    ${credentialGlyph('lock',13)}保存前会先校验令牌有效性与权限

    ` :warning?`

    ${credentialGlyph('alert',13)}${escapeHTML(warning)}

    `:''; - return `
    ${credentialGlyph('check',16)}确认并保存密钥只在任务运行时注入,不写入 Agent 资产
    ${credentialGlyph('key',14)}${escapeHTML(kind.name)}
    凭证
    ${escapeHTML(kind.short)}
    密钥
    已填写 ••••••••
    ${extra}
    生效
    下一次任务
    ${line}`; + return `
    ${credentialGlyph('check',16)}确认并保存密钥只在任务运行时注入,不写入 Agent 资产
    ${credentialGlyph('key',14)}${escapeHTML(kind.name)}
    凭证
    ${escapeHTML(kind.short)}
    密钥
    已填写 ••••••••
    ${extra}${base}
    生效
    下一次任务
    ${line}`; } function credentialWizardFootHTML(){ const wizard=credentialWizard; + if(isDirectExecutorForm(wizard))return ``; if(wizard.step===2&&wizard.kind==='gitToken'&&wizard.githubMethod!=='manual')return 'Esc 关闭仅为当前账号授权'; if(wizard.done)return ``; const back=wizard.step===1||(wizard.direct&&wizard.step===2) @@ -1125,6 +1400,7 @@ function credentialWizardPaneHTML(){ } function paintCredentialWizard(direction){ const scrim=$('#credentialWizard'),wizard=credentialWizard;if(!scrim||!wizard)return; + scrim.classList.toggle('is-executor-form',isDirectExecutorForm(wizard)); const body=scrim.querySelector('.credential-dialog-body'),before=body.offsetHeight,old=body.querySelector('.credential-pane:not(.is-leaving)'); const pane=document.createElement('div'); pane.className='credential-pane'+(direction>0?' is-forward':direction<0?' is-back':''); @@ -1137,6 +1413,8 @@ function paintCredentialWizard(direction){ scrim.querySelectorAll('.credential-dots span').forEach((dot,index)=>{dot.className=wizard.done||index+1!el.disabled&&!el.closest('.credential-pane.is-leaving, [hidden]')&&el.getClientRects().length); + return [...dialog.querySelectorAll('button, a[href], input, select, summary')].filter(el=>!el.matches(':disabled')&&!el.closest('.credential-pane.is-leaving, [hidden]')&&el.getClientRects().length); } function markCredentialGuide(index){ const wizard=credentialWizard;if(!wizard||wizard.guide[index])return; @@ -1172,12 +1450,14 @@ function credentialWizardInput(event){ const wizard=credentialWizard,input=event.target;if(!wizard||!input.name)return; const kind=credentialKind(wizard.kind),pane=input.closest('.credential-pane'); if(input.name==='extra')wizard.extra=input.value; + if(input.name==='baseUrl')wizard.baseUrl=input.value; if(input.name==='protocol')wizard.protocol=input.value; if(input.name==='secret')wizard.secret=input.value; 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,wizard.protocol);setCredentialHint(pane,'extra',extraError,extraError?'err':'')} + if(input.name==='baseUrl')setCredentialHint(pane,'baseUrl',valid.baseError,valid.baseError?'err':''); if(valid.ok)kind.guide.forEach((_,index)=>markCredentialGuide(index)); const next=$('#credentialWizard [data-wizard-next]');if(next)next.disabled=!valid.ok; } @@ -1198,6 +1478,7 @@ function selectCredentialWizardKind(key){ // A secret typed for one kind must never be submitted as another kind's credential. wizard.kind=key;wizard.secret='';wizard.guide={};wizard.error=''; wizard.extra=credentialWizardDefaults(credentialKind(key),credentialUser()); + wizard.baseUrl=credentialValue(credentialUser(),credentialKind(key)?.baseURL)||''; wizard.protocol=credentialProtocol(credentialKind(key),credentialUser()); } function credentialWizardClick(event){ @@ -1229,8 +1510,13 @@ async function advanceCredentialWizard(){ wizard.step=2;paintCredentialWizard(1);setTimeout(focusCredentialWizard,220);return; } if(wizard.step===2){ - if(!credentialWizardValid().ok){const pane=$('#credentialWizard .credential-pane:not(.is-leaving)');if(pane)setCredentialHint(pane,'secret',credentialWizardValid().error||'请先填写密钥','err');return} - wizard.step=3;wizard.error='';paintCredentialWizard(1);setTimeout(focusCredentialWizard,220);return; + const validity=credentialWizardValid(); + if(!validity.ok){ + const pane=$('#credentialWizard .credential-pane:not(.is-leaving)'); + if(pane)setCredentialHint(pane,validity.baseError?'baseUrl':'secret',validity.baseError||validity.error||'请先填写密钥','err'); + return; + } + if(!isDirectExecutorForm(wizard)){wizard.step=3;wizard.error='';paintCredentialWizard(1);setTimeout(focusCredentialWizard,220);return} } const kind=credentialKind(wizard.kind),secret=String(wizard.secret).trim(); wizard.saving=true;wizard.error='';paintCredentialWizard(0);focusCredentialWizard(); @@ -1238,13 +1524,17 @@ async function advanceCredentialWizard(){ if(kind.key==='gitToken'){ const outcome=await verifyAndSaveGitToken(secret); if(!outcome.saved){wizard.error=`${gitTokenFailure(outcome.result)||'Git Token 校验未通过'}(未保存)`;return} - }else await saveCredential(kind.key,{secret,...(kind.extra?{extra:wizard.extra}:{}),...(kind.protocol?{protocol:wizard.protocol}:{})}); + }else await saveCredential(kind.key,{secret,extra:wizard.extra,baseUrl:wizard.baseUrl,protocol:wizard.protocol}); wizard.done=true;wizard.secret=''; - renderCredentialPanel(); - toast(kind.key==='gitToken'?'Git Token 校验通过,已保存':`${kind.short} 已保存`,'ok'); + if(kind.group==='platform')renderCredentialGitGroup();else renderCredentialPanel(); + toast(kind.key==='gitToken'?'Git Token 校验通过,已保存':`${kind.name} 配置已保存`,'ok'); }catch(err){wizard.error=err.message} finally{ - if(credentialWizard===wizard){wizard.saving=false;paintCredentialWizard(0);focusCredentialWizard()} + if(credentialWizard===wizard){ + wizard.saving=false; + if(wizard.done&&isDirectExecutorForm(wizard))closeCredentialWizard(true); + else{paintCredentialWizard(0);focusCredentialWizard()} + } } } @@ -1265,20 +1555,17 @@ async function refreshGongfengGrant(){ const users=await api('/api/users',{silent:true}); const fresh=(Array.isArray(users)?users:[]).find(u=>Number(u.id)===Number(user.id)); const panel=$('#credentialPanel'),row=panel?.querySelector('[data-credential-row="gitToken"]'); - if(!fresh||!row||Number(state.currentUser?.id)!==Number(user.id))return; + if(!fresh||!panel||Number(state.currentUser?.id)!==Number(user.id))return; storeCredentialUser(fresh); state.gitTokenVerify=null; - if(credentialWizard?.kind==='gitToken'&&fresh.gitHubCredentialConfigured)closeCredentialWizard(true); - if(row.classList.contains('is-configured')!==!!fresh.gitHubCredentialConfigured){ - const holder=document.createElement('div'); - holder.innerHTML=credentialRowHTML(credentialKind('gitToken'),fresh); - row.replaceWith(holder.firstElementChild); - panel.querySelector('.credential-progress').innerHTML=credentialProgressHTML(fresh); - panel.querySelector('.credential-filter').innerHTML=credentialFilterHTML(fresh); - applyCredentialFilter(panel,fresh); - hydrateCredentialIcons(panel); + if(credentialWizard?.kind==='gitToken'&&(fresh.gitTokenOAuth||fresh.gitHubCredentialConfigured))closeCredentialWizard(true); + if(!!row!==!!fresh.gitHubCredentialConfigured)renderCredentialGitGroup(panel,fresh); + else void loadCredentialGitRows(panel,fresh); + notifyCredentialsChanged(); + if(!fresh.gitHubCredentialConfigured){ + if(fresh.gitTokenOAuth)toast('工蜂授权已保存','ok'); + return; } - if(!fresh.gitHubCredentialConfigured){repaintCredentialRow('gitToken');return} state.gitTokenAnnounceVerify=true; toast('工蜂授权已保存,正在校验授权有效性…'); await refreshGitTokenStatus(); @@ -1286,7 +1573,9 @@ async function refreshGongfengGrant(){ async function renderPersonalSettings(){ const host=$('#personalSettingsContent');if(!host)return; + const account=$('#personalSettingsAccount'); const user=state.currentUser; + if(account)account.hidden=!user||!!user.isGuest; if(!user||user.isGuest){ host.innerHTML='

    登录账号

    登录后即可管理自己的 Git Token 和 API Key。

    '; host.querySelector('#settingsLogin').onclick=()=>{window.location.href=state.loginUrl||'/login.html'}; @@ -1303,7 +1592,12 @@ async function renderPersonalSettings(){ toast('工蜂授权已保存,正在校验授权有效性…'); } if(credentialWizard)closeCredentialWizard(true); - host.innerHTML=`
    `; + if(account){ + const name=user.chineseName||user.loginName||userDisplay(user); + const login=user.loginName&&user.loginName!==name?`${escapeHTML(user.loginName)}`:''; + account.innerHTML=`${userAvatarHTML(user,150)}
    ${escapeHTML(name)}${login}
    `; + } + host.innerHTML='
    '; const panel=host.querySelector('#credentialPanel'); bindCredentialPanel(panel); renderCredentialPanel(); @@ -1976,7 +2270,7 @@ function renderUserProfilePopover() { ⚠️ 认证换票未通过
    此前统一认证票据已失效,请点击下方按钮重新登录。
    ` : ` -

    当前以访客身份访问平台。登录后可在左侧「个人配置」配置 GitHub Git Token 和 CodeBuddy API Key。

    +

    登录后可在「个人配置」添加 Git 凭据和执行器。

    `}
    diff --git a/web/assistant-models.css b/web/assistant-models.css index e6e29062..350e8fb3 100644 --- a/web/assistant-models.css +++ b/web/assistant-models.css @@ -41,6 +41,9 @@ } .ai-model-option{padding:8px 10px;gap:8px} .ai-model-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.feature-model-picker{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.4fr);gap:6px;min-width:0} +.feature-model-picker .select{width:100%;min-width:0} +@media(max-width:420px){.feature-model-picker{grid-template-columns:minmax(0,1fr)}} .ai-model-credits{flex-shrink:0;color:var(--muted-2);font-size:11px;font-variant-numeric:tabular-nums;font-weight:500} .ai-model-credits:empty{display:none!important} .ai-model-option.is-active{background:var(--blue-soft);color:var(--blue)} diff --git a/web/assistant_models_test.js b/web/assistant_models_test.js index b45b2f6a..86d04c1c 100644 --- a/web/assistant_models_test.js +++ b/web/assistant_models_test.js @@ -1,9 +1,4 @@ -// Regression: the clarification model picker (and every other classic-SPA -// picker) needs window.AgentFlowAssistantModels. A refactor once deleted the -// only definition, bindClarifyModelPicker() returned early at -// `if(!api||!toggle||!menu)return;`, and the 澄清 tab's 「选择模型」 button -// silently stopped opening. This test boots the shared module plus the real -// picker helpers from the bundle and clicks through a selection. +// Shared catalog rendering and the linked executor/model selectors. 'use strict'; const assert = require('node:assert/strict'); const fs = require('node:fs'); @@ -42,46 +37,47 @@ function createElement(tag) { return node; } -// host > button.ai-model-toggle([data-model-toggle], .ai-model-icon, [data-model-label]) -// + input[data-clarify-model-value] + .ai-model-menu -const host = createElement('div'); const toggle = createElement('button'); -toggle.className = 'ai-model-toggle'; -toggle.setAttribute('data-model-toggle', ''); const icon = createElement('span'); icon.className = 'ai-model-icon'; -const label = createElement('span'); label.setAttribute('data-model-label', ''); label.textContent = '选择模型'; -const caret = createElement('span'); caret.className = 'ai-model-caret'; -toggle.append(icon, label, caret); -const input = createElement('input'); input.setAttribute('data-clarify-model-value', ''); -const menu = createElement('div'); menu.className = 'ai-model-menu'; menu.hidden = true; -host.append(toggle, input, menu); +const label = createElement('span'); label.setAttribute('data-model-label', ''); +toggle.append(icon, label); + +function pickerFixture() { + const field = () => ({ + options: [], value: '', disabled: true, + replaceChildren(...options) { this.options = options; }, + append(option) { this.options.push(option); }, + prepend(option) { this.options.unshift(option); }, + }); + const executor = field(), model = field(); + const host = { + isConnected: true, + querySelector(selector) { return selector === '[data-feature-executor]' ? executor : model; }, + }; + return {host, executor, model}; +} -const store = new Map([['agentflow.clarifyModel', 'model-a']]); const ctx = { console, setTimeout, clearTimeout, Promise, document: { addEventListener() {}, querySelectorAll: () => [], createElement }, - localStorage: { - getItem: key => (store.has(key) ? store.get(key) : null), - setItem: (key, value) => store.set(key, String(value)), - removeItem: key => store.delete(key), - }, + Option: class Option { constructor(text, value) { this.text = text; this.value = value; } }, fetch: async () => ({ ok: true, json: async () => ({ default: 'model-b', models: [ { id: 'default', name: 'CLI 默认模型', family: 'other' }, + { id: 'default-model', name: '旧版默认', family: 'other' }, + { id: 'codex:default', name: 'Codex 默认', engine: 'codex' }, { id: 'model-a', name: 'Model A', family: 'claude', credits: 'x1.00' }, { id: 'model-b', name: 'Model B', family: 'glm', credits: 'x0.06' }, { id: 'codex:gpt-5.5', name: 'GPT-5.5', family: 'gpt', engine: 'codex' }, ], - engines: [{ id: 'codebuddy', name: 'CodeBuddy' }, { id: 'codex', name: 'Codex' }], + engines: [{ id: 'codebuddy', name: 'CodeBuddy', configured: true, personal: true }, { id: 'codex', name: 'Codex', configured: true, personal: true }], }), }), }; ctx.window = ctx; -// bindClarifyModelPicker uses $$ for the outside-click closer and setClarifyModel. -ctx.$$ = selector => (selector === '[data-clarify-model]' ? [host] : [input]); vm.createContext(ctx); vm.runInContext(moduleSource, ctx); @@ -123,49 +119,50 @@ vm.runInContext(moduleSource, ctx); assert.equal(icon.dataset.family, family); assert.ok(icon.innerHTML.includes(`/images/credentials/${family}.svg`)); } - // Pickers keep painting before the catalog lands, so the built-in fallback - // must already render a usable label. - assert.equal(api.codeBuddyModel('codex:gpt-5.5'), 'default', 'codex ids fall back before the catalog loads'); - api.paint(toggle, api.DEFAULT); - assert.equal(label.textContent, '默认'); - assert.equal(icon.dataset.family, 'other'); - assert.equal(api.codeBuddyModels().length, 0, 'the placeholder is not selectable before loading'); - + assert.equal(api.engineOf('codex:gpt-5.5'), 'codex'); + assert.equal(api.concreteModelId('codebuddy:default-model'), ''); await api.load(); assert.equal(api.catalog().default, 'model-b'); - assert.equal(api.catalog().models.length, 3, 'catalog adopts /api/assistant/models'); - // Issue #228: clarification runs on CodeBuddy only, so CodeBuddy-only - // pickers hide other CLIs and a saved "codex:…" id falls back. - assert.deepEqual(api.codeBuddyModels().map(m => m.id), ['model-a', 'model-b']); - assert.equal(api.codeBuddyModel('codex:gpt-5.5'), 'default'); - assert.equal(api.codeBuddyModel(''), 'default'); - assert.equal(api.codeBuddyModel('model-a'), 'model-a'); + assert.equal(api.catalog().models.length, 3, 'catalog adopts concrete models'); + assert.match(bundle, /bindClarifyModelPicker/); - // Pull the real picker helpers out of the bundle and bind them to the stub host. - for (const name of ['selectedClarifyModel', 'setClarifyModel', 'bindClarifyModelPicker']) { - const start = bundle.search(new RegExp('^function ' + name + '\\(', 'm')); - assert.ok(start >= 0, `${name} is missing from the app bundle`); - const rest = bundle.slice(start); - const next = /\n(?:async )?function \w+\(/.exec(rest); - vm.runInContext(next ? rest.slice(0, next.index) : rest, ctx); - } - ctx.bindClarifyModelPicker(host); - assert.equal(host.dataset.bound, '1', 'clarify picker must bind once the model API exists'); - - toggle.onclick({ stopPropagation() {} }); - assert.equal(menu.hidden, false, 'clicking 选择模型 must open the menu'); - assert.equal(menu.children.length, 2, 'menu lists only CodeBuddy models'); - assert.ok(!menu.children.some(opt => opt.dataset.id.startsWith('codex:')), 'clarify menu hides Codex models'); - assert.ok(menu.children[0].className.includes('is-active'), 'stored model is marked active'); + const pair = pickerFixture(); + const changes = []; + await api.bindFeaturePicker(pair.host, {model: 'default', onChange: id => changes.push(id)}); + assert.equal(pair.executor.value, 'codebuddy'); + assert.equal(pair.model.value, 'codebuddy:model-b'); + assert.deepEqual(pair.model.options.map(option => option.value), ['codebuddy:model-a', 'codebuddy:model-b']); + pair.model.value = 'codebuddy:model-a'; + pair.model.onchange(); + pair.executor.value = 'codex'; + pair.executor.onchange(); + assert.equal(pair.model.value, 'codex:gpt-5.5'); + assert.deepEqual(pair.model.options.map(option => option.text), ['GPT-5.5']); + pair.executor.value = 'codebuddy'; + pair.executor.onchange(); + assert.equal(pair.model.value, 'codebuddy:model-a'); + assert.deepEqual(changes, ['codebuddy:model-a', 'codex:gpt-5.5', 'codebuddy:model-a']); - menu.children[1].onclick(); - assert.equal(store.get('agentflow.clarifyModel'), 'model-b'); - assert.equal(input.value, 'model-b'); - assert.equal(menu.hidden, true); - assert.equal(label.textContent, 'Model B'); + const codexOnly = pickerFixture(); + await api.bindFeaturePicker(codexOnly.host, { + model: 'model-b', + loadCatalog: async () => ({ + ...api.catalog(), + engines: [ + {id: 'codebuddy', name: 'CodeBuddy', configured: true, personal: false}, + {id: 'codex', name: 'Codex', configured: true, personal: true}, + ], + }), + }); + assert.equal(codexOnly.executor.value, 'codex'); + assert.deepEqual(codexOnly.executor.options.map(item => item.value), ['codex']); + assert.equal(codexOnly.model.value, 'codex:gpt-5.5'); - // A Codex id saved before this fix must not reach chat-clarify. - store.set('agentflow.clarifyModel', 'codex:gpt-5.5'); - assert.equal(ctx.selectedClarifyModel(), 'default'); + const saved = pickerFixture(); + await api.bindFeaturePicker(saved.host, {model: 'claude-code:old-model', keepSaved: true, loadCatalog: async () => ({ + engines: [{id: 'claude-code', name: 'Claude Code', configured: false}], models: [], + })}); + assert.equal(saved.executor.value, 'claude-code'); + assert.equal(saved.model.value, 'claude-code:old-model'); console.log('assistant models ok'); })().catch(err => { console.error(err); process.exit(1); }); diff --git a/web/bots.css b/web/bots.css index 6e719532..1bb0e92d 100644 --- a/web/bots.css +++ b/web/bots.css @@ -26,7 +26,6 @@ .sop-message-compose .sop-notification-example>div:first-child{flex-wrap:wrap} @media(max-width:850px){.sop-message-compose{grid-template-columns:1fr}} -.bot-model-field .ai-model-menu{position:fixed;right:auto;bottom:auto;min-width:0;max-width:calc(100vw - 24px);z-index:100} /* Bot management (#botsView): one integrated panel, guided editor and records. * --hui-* tokens, buttons, badges, panel and inputs come from app/harness-ui.css. Motion only references the --bot-* tokens below. */ @@ -170,13 +169,12 @@ @keyframes bot-draw{from{stroke-dashoffset:1}} .bot-step-fold{position:relative} .bot-fields{display:grid;grid-template-columns:1fr 1fr;gap:16px 18px;max-width:820px} -.bot-fields label{display:flex;flex-direction:column;gap:6px;min-width:0;color:var(--hui-secondary);font-size:12px;font-weight:500} +.bot-fields :is(label,.bot-model-field){display:flex;flex-direction:column;gap:6px;min-width:0;color:var(--hui-secondary);font-size:12px;font-weight:500} .bot-fields label small{color:var(--hui-tertiary);font-weight:400;line-height:1.6} .bot-fields .bot-check{flex-direction:row;align-items:center;gap:10px;color:var(--hui-text);font-size:13px;font-weight:400;cursor:pointer} #botsContent fieldset{border:0;padding:0;margin:0;min-width:0} #botsContent .input{box-sizing:border-box;height:36px;min-height:36px;padding:0 11px;font:400 13px var(--hui-sans)} #botsContent .input[aria-invalid="true"]{border-color:var(--bot-err)} -#botsContent .bot-model-field .ai-model-toggle{min-height:36px;border-color:var(--hui-border-strong);border-radius:8px;background:var(--hui-surface)} #botsContent .select{box-sizing:border-box;height:32px;padding:0 10px;font-size:13px;line-height:30px} .bot-shake{animation:bot-shake var(--bot-t-shake) var(--bot-ease-ui)} @keyframes bot-shake{20%,60%{transform:translateX(-4px)}40%,80%{transform:translateX(4px)}} diff --git a/web/bots_test.go b/web/bots_test.go index 5c0d5216..04bbfed6 100644 --- a/web/bots_test.go +++ b/web/bots_test.go @@ -11,7 +11,20 @@ func TestBotSessionSearchAndTypes(t *testing.T) { if err != nil { t.Skip("node not installed") } - script := `const assert=require('node:assert/strict'),vm=require('node:vm'),fs=require('node:fs');const ctx={};vm.createContext(ctx);vm.runInContext(fs.readFileSync('app/bots.js','utf8'),ctx);const sessions=[{name:'研发群',type:'group'},{name:'Alice',type:'single'}];assert.equal(ctx.filteredBotSessions(sessions,'研发')[0].type,'group');assert.equal(ctx.filteredBotSessions(sessions,'ALICE')[0].type,'single');assert.equal(ctx.filteredBotSessions(sessions,'不存在').length,0);assert.equal(ctx.botTypeLabel('group'),'群聊');assert.equal(ctx.botTypeLabel('single'),'单聊');assert.equal(ctx.filteredBotSessions(sessions,'').length,2);ctx.escapeHTML=x=>String(x);assert.match(ctx.botModelPickerHTML({model:'gpt-6.1-sol'}),/name="model" value="gpt-6.1-sol"/);assert.match(fs.readFileSync('app/bots.js','utf8'),/name="model"/);` + script := ` +const assert=require('node:assert/strict'),vm=require('node:vm'),fs=require('node:fs'); +const ctx={};ctx.window=ctx;vm.createContext(ctx); +vm.runInContext(fs.readFileSync('app/assistant-models.js','utf8'),ctx); +vm.runInContext(fs.readFileSync('app/bots.js','utf8'),ctx); +const sessions=[{name:'研发群',type:'group'},{name:'Alice',type:'single'}]; +assert.equal(ctx.filteredBotSessions(sessions,'研发')[0].type,'group'); +assert.equal(ctx.filteredBotSessions(sessions,'ALICE')[0].type,'single'); +assert.equal(ctx.filteredBotSessions(sessions,'不存在').length,0); +assert.equal(ctx.botTypeLabel('group'),'群聊'); +assert.equal(ctx.botTypeLabel('single'),'单聊'); +assert.equal(ctx.filteredBotSessions(sessions,'').length,2); +assert.match(ctx.botModelPickerHTML(), /]*data-feature-executor/); +assert.match(ctx.botModelPickerHTML(), /]*data-feature-model[^>]*name="model"/);` out, err := exec.Command(node, "-e", script).CombinedOutput() if err != nil { t.Fatalf("search: %v %s", err, out) @@ -44,7 +57,7 @@ assert.match(list,/群聊<\/span>glm-5.3-flash-ioa<\/small>/,'a bot without a model has no model label'); assert.equal((list.match(/data-bot-delete=/g)||[]).length,2); assert.match(list,/class="hui-icon-btn" data-bot-edit="b1" aria-label="编辑 研发通知" title="编辑"/); assert.match(list,/class="hui-icon-btn is-danger" data-bot-delete="b1" aria-label="删除 研发通知" title="删除"/); diff --git a/web/git_token_verify_test.go b/web/git_token_verify_test.go index b2811e80..e66c809e 100644 --- a/web/git_token_verify_test.go +++ b/web/git_token_verify_test.go @@ -54,7 +54,7 @@ const api=async(path,options={})=>{ }; const verifyCalls=()=>calls.filter(c=>c.path.endsWith('/git-token/verify')); const putCalls=()=>calls.filter(c=>c.method==='PUT'); -const panel={innerHTML:'',classList:{remove(){}},querySelectorAll:()=>[]}; +const panel={innerHTML:'',classList:{remove(){}},querySelector:()=>null,querySelectorAll:()=>[]}; const host={innerHTML:'',querySelector(selector){return {'#credentialPanel':panel}[selector]??null},querySelectorAll:()=>[]}; const posted=[]; const $=selector=>({'#personalSettingsContent':host,'#credentialPanel':panel,'#chatNextFrame':{contentWindow:{postMessage:m=>posted.push(m)}}}[selector]??null); diff --git a/web/gongfeng_oauth_notify_test.go b/web/gongfeng_oauth_notify_test.go index 8dd3f8d5..d53dcdf4 100644 --- a/web/gongfeng_oauth_notify_test.go +++ b/web/gongfeng_oauth_notify_test.go @@ -8,8 +8,8 @@ import ( ) // The OAuth tab and the settings page must agree on the channel and message, -// and the settings listener must be registered once. The quick-access wizard -// asks for a GitHub token and still refreshes the user when focus returns. +// and the settings page must register its listener once. The wizard refreshes +// credentials when settings reports a save and when focus returns. func TestGongfengOAuthCompletionChannelIsShared(t *testing.T) { read := func(name string) string { data, err := os.ReadFile(name) @@ -21,7 +21,7 @@ func TestGongfengOAuthCompletionChannelIsShared(t *testing.T) { for name, wants := range map[string][]string{ "gongfeng-oauth-done.js": {"'agentflow-gongfeng-oauth'", "type:'gongfeng-oauth-completed'"}, "app/workbench.js": {"'agentflow-gongfeng-oauth'", "'gongfeng-oauth-completed'", "function listenForGongfengOAuth()"}, - "../chatbot/src/QuickAccessWizard.jsx": {`window.addEventListener("focus", refreshUser)`}, + "../chatbot/src/QuickAccessWizard.jsx": {`window.addEventListener("focus", refresh)`, `"agentflow-credentials-changed"`}, } { code := read(name) for _, want := range wants { @@ -30,11 +30,8 @@ func TestGongfengOAuthCompletionChannelIsShared(t *testing.T) { } } } - if wizard := read("../chatbot/src/QuickAccessWizard.jsx"); strings.Contains(wizard, "agentflow-gongfeng-oauth") || strings.Contains(wizard, "BroadcastChannel") { - t.Error("the quick-access wizard must not offer the legacy OAuth flow") - } if n := strings.Count(read("app.js"), "listenForGongfengOAuth()"); n != 1 { - t.Fatalf("settings listener must be registered exactly once at startup, found %d calls", n) + t.Fatalf("settings must register the shared listener once, found %d calls", n) } } @@ -55,11 +52,12 @@ const calls=[]; const api=async(path)=>{calls.push(path);if(path==='/api/users')return [{id:1,gitHubCredentialConfigured:true,gitTokenOAuth:true}];if(path.endsWith('/git-token/verify'))return {valid:true,scopes:['read_repository','write_repository']};return {}}; const channels=[]; class BroadcastChannel{constructor(name){this.name=name;channels.push(this)}close(){}} -let panelRenders=0,replacedRow='',progress='',filter=''; +let panelRenders=0,replacedRow=''; const unsaved={value:'typed-but-unsaved'}; const main={replaceWith(){}}; const row={classList:{contains:name=>name==='is-configured'&&!!replacedRow},replaceWith(next){replacedRow=next.html},querySelector(s){return s==='.credential-row-main'?main:null}}; -const panel={set innerHTML(v){panelRenders++},querySelector(s){return {'[data-credential-row="gitToken"]':row,'.credential-progress':{set innerHTML(v){progress=v}},'.credential-filter':{set innerHTML(v){filter=v}}}[s]??null},querySelectorAll:()=>[]}; +const group={replaceWith(next){replacedRow=next.html}}; +const panel={set innerHTML(v){panelRenders++},querySelector(s){return {'[data-credential-row="gitToken"]':replacedRow?row:null,'[data-credential-group="platform"]':group}[s]??null},querySelectorAll:()=>[]}; const $=s=>({'#credentialPanel':panel,'[data-credential-row="gitToken"]':row,'#credentialPanel [data-credential-row="gitToken"]':row}[s]??null); const document={createElement(){const holder={set innerHTML(v){holder.firstElementChild={html:v}}};return holder},querySelectorAll:()=>[]}; const window={}; @@ -79,8 +77,7 @@ eval(code.slice(code.indexOf('const CREDENTIAL_GROUPS='),code.indexOf('// 谁能 assert.equal(unsaved.value,'typed-but-unsaved'); assert.equal(view,'settings'); assert.ok(replacedRow.includes('is-configured')&&replacedRow.includes('工蜂授权'),'the Gongfeng row switches to the configured grant'); - assert.ok(progress.includes('1')); - assert.ok(filter.includes('已配置1')); + assert.ok(replacedRow.includes('新增 Git 配置')); assert.equal(state.data.users[0].gitTokenOAuth,true); assert.equal(state.gitTokenVerify.result.valid,true); assert.ok(toasts.some(t=>t.message.includes('工蜂授权已保存'))); diff --git a/web/i18n-en.js b/web/i18n-en.js index cff28928..8ea2757d 100644 --- a/web/i18n-en.js +++ b/web/i18n-en.js @@ -243,6 +243,15 @@ Object.assign(window.LF_I18N_EN,{ Object.assign(window.LF_I18N_EN,{ "使用已有订阅":"Use your existing subscription", + "Claude Code、Codex 和 Antigravity 可用「账号登录」运行对话和 SOP。":"Use Account login for Claude Code, Codex, or Antigravity to run chats and SOPs.", + "Git 配置":"Git credentials", + "执行器配置":"Executors", + "新增 Git 配置":"Add Git credential", + "新增执行器":"Add executor", + "按仓库地址的协议、主机和端口匹配":"Matched by repository protocol, host, and port", + "AI 默认设置":"AI defaults", + "默认执行器":"Default executor", + "操作确认方式":"Approval mode", "绑定已登录 Claude Code、Codex 或 Antigravity 的机器,选「账号登录」即可用订阅额度运行对话和 SOP,无需 API Key。":"Connect a machine where you are signed in to Claude Code, Codex, or Antigravity. Select Account login to use your subscription for chats and SOPs without an API key.", "配置执行机器":"Configure runners", "Claude Code、Codex 和 Antigravity 可用账号登录":"Account login for Claude Code, Codex and Antigravity", diff --git a/web/images/credentials/README.md b/web/images/credentials/README.md index 3415f9cd..b3d876ec 100644 --- a/web/images/credentials/README.md +++ b/web/images/credentials/README.md @@ -1,7 +1,7 @@ # Credential artwork -`github.svg` is copied from `chatbot/src/assets/provider-logos/github.svg`. -Its source is [Simple Icons](https://github.com/simple-icons/simple-icons), +`github.svg` and `gitlab.svg` are copied from `chatbot/src/assets/provider-logos/`. +Their source is [Simple Icons](https://github.com/simple-icons/simple-icons), distributed under CC0 1.0. See the bundled provider-logo README and SOURCE.md for the existing artwork attribution. Brand names and marks belong to their respective owners. diff --git a/web/images/credentials/gitlab.svg b/web/images/credentials/gitlab.svg new file mode 100644 index 00000000..e4a29630 --- /dev/null +++ b/web/images/credentials/gitlab.svg @@ -0,0 +1 @@ +GitLab \ No newline at end of file diff --git a/web/index.html b/web/index.html index 7d34e632..c5eca185 100644 --- a/web/index.html +++ b/web/index.html @@ -12,7 +12,7 @@ - + @@ -185,10 +185,17 @@

    设置

    -
    -

    个人中心

    个人配置

    管理个人账号与执行凭据。

    +
    + +
    +

    个人配置

    + +
    +
    -
    @@ -939,7 +946,7 @@

    新建需求

    - + @@ -1098,21 +1105,20 @@

    触发配置

    可填写 1–10,留空默认 10;其余需求在后续执行时继续触发。