From e39777770597648a5d0e105126129b1b71075cf5 Mon Sep 17 00:00:00 2001 From: roberttwang Date: Sat, 21 Nov 2026 01:09:50 +0800 Subject: [PATCH 01/25] Make CodeBuddy optional across platform model workflows --- .github/workflows/platform.yml | 2 +- Dockerfile | 4 +- README.md | 4 +- README.zh-CN.md | 4 +- chatbot/src/QuickAccessWizard.jsx | 68 +++-- chatbot/src/engines.js | 11 +- chatbot/src/useChat.js | 15 +- compose.dev.yaml | 1 + compose.yaml | 3 + docs/api/openapi.yaml | 7 +- docs/deployment.md | 23 +- e2e/README.md | 4 +- e2e/lib/env.mjs | 2 +- e2e/local.sh | 51 +++- internal/application/operations.go | 2 +- internal/domain/domain_cases_test.go | 1 - internal/domain/preview.go | 24 +- internal/domain/preview_build.go | 22 +- internal/domain/preview_build_test.go | 27 +- internal/domain/user.go | 14 ++ internal/domain/workflow.go | 33 +-- internal/engine/engine_test.go | 48 +++- internal/engine/node_execute.go | 14 +- internal/engine/preview_finalizer_test.go | 2 +- internal/engine/run_events.go | 6 +- internal/engine/run_ops.go | 1 + internal/engine/run_start.go | 10 +- internal/engine/runner_dispatch.go | 4 +- internal/engine/workspace_preparation.go | 2 +- internal/httpapi/agent_tool_catalog.go | 4 + internal/httpapi/agent_tool_mcp.go | 3 + internal/httpapi/agent_tool_session.go | 1 + internal/httpapi/assistant.go | 48 ++-- internal/httpapi/assistant_approval_review.go | 18 +- internal/httpapi/assistant_engine_cli.go | 5 +- internal/httpapi/assistant_engines.go | 53 ++-- internal/httpapi/assistant_failure.go | 2 +- internal/httpapi/assistant_generation.go | 7 +- internal/httpapi/assistant_mcp.go | 5 + internal/httpapi/assistant_models.go | 10 +- .../httpapi/assistant_notification_report.go | 17 +- internal/httpapi/bot_interactions.go | 34 ++- internal/httpapi/bot_interactions_test.go | 2 +- internal/httpapi/catalog.go | 45 ++-- internal/httpapi/clarify_engine_test.go | 71 ++++-- internal/httpapi/clarify_mcp.go | 19 -- internal/httpapi/clarify_mcp_test.go | 13 - internal/httpapi/clarify_source.go | 144 +++++++++++ internal/httpapi/feature_model.go | 66 +++++ internal/httpapi/feature_model_test.go | 238 ++++++++++++++++++ internal/httpapi/misc_cases_test.go | 11 + internal/httpapi/notifications.go | 9 +- internal/httpapi/run_eval.go | 31 ++- internal/httpapi/schedule.go | 6 +- internal/httpapi/stream.go | 118 ++++++--- internal/managedcli/providers.go | 3 + internal/notification/report.go | 6 +- internal/observability/hooks.go | 7 +- internal/observability/otlp.go | 17 +- internal/repo/catalog.go | 33 ++- internal/repo/run_pages_test.go | 8 +- internal/repo/runs.go | 4 +- internal/runtime/command_binding.go | 20 +- .../runtime/command_binding_telemetry_test.go | 7 +- internal/runtime/sandbox_docker.go | 24 +- internal/tracker/service.go | 14 +- .../040_inherit_stock_sop_executors.sql | 47 ++++ migrations/seed/001_public_catalog.sql | 12 +- scripts/test-runtime-image.sh | 8 +- web/app/agents.js | 14 +- web/app/assistant-models.js | 37 ++- web/app/bots.js | 6 +- web/app/flows.js | 57 ++--- web/app/notification-editor.js | 2 +- web/app/runs.js | 20 +- web/app/sops.js | 12 +- web/app/sync-schedule.js | 4 +- web/app/workbench.js | 2 +- web/assistant_models_test.js | 31 +-- web/orchestrate.js | 13 +- web/sop_catalog_test.js | 1 + webtest/tests/assets-agents.test.mjs | 38 ++- webtest/tests/flows-editor.test.mjs | 13 +- 83 files changed, 1324 insertions(+), 525 deletions(-) create mode 100644 internal/httpapi/clarify_source.go create mode 100644 internal/httpapi/feature_model.go create mode 100644 internal/httpapi/feature_model_test.go create mode 100644 migrations/040_inherit_stock_sop_executors.sql 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 c33b826e..ab03f869 100644 --- a/Dockerfile +++ b/Dockerfile @@ -28,9 +28,11 @@ 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 + && npm install -g @openai/codex@0.162.1 @deepseek-ai/dsh@0.2.2-rc.1 \ + && 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 fcdd9f9d..b5ba9a7c 100644 --- a/README.md +++ b/README.md @@ -111,11 +111,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. SOP roles can pin an executor or inherit the default selected for the responsible account. Scheduled prompts use the CLI selected on the schedule. The platform can run without a CodeBuddy installation or key. [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 06c049f9..844082c7 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -111,11 +111,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、未配置其 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/QuickAccessWizard.jsx b/chatbot/src/QuickAccessWizard.jsx index e4570b35..caa73bee 100644 --- a/chatbot/src/QuickAccessWizard.jsx +++ b/chatbot/src/QuickAccessWizard.jsx @@ -22,6 +22,7 @@ import { codeBuddyKeyWarning, openCredentialSettings, } from "./credentials"; +import { EXECUTORS, personalEngineConfigured } from "./engines.js"; import "./quick-access-wizard.css"; const DEFAULT_SOP_ID = "generic-backend-delivery"; @@ -700,7 +701,6 @@ async function provisionFallbackProjectSOP(projectId, workflowId, owner) { name: role.name, projectId, version: 1, - executorId: "codebuddy", description: role.description, prompt: role.prompt, artifactOutputs: [ @@ -1209,6 +1209,9 @@ export default function QuickAccessWizard({ const codeBuddyEnvInfo = codeBuddyEnvironment(codeBuddyEnv) || CODEBUDDY_ENVIRONMENTS[0]; const codeBuddyWarning = codeBuddyKeyWarning(codeBuddyApiKey); + const readyCLIs = EXECUTORS.filter(cli => personalEngineConfigured(storedUser, cli.id) || + (cli.id === "codebuddy" && codeBuddyReady)); + const cliReady = readyCLIs.length > 0 || Boolean(sponsoredModel); const nodes = activeWorkflow?.nodes?.filter((node) => node.type === "agent") || FALLBACK_NODES; @@ -1287,10 +1290,6 @@ export default function QuickAccessWizard({ if (saving) return; setError(""); if (activeStep.id === "auth") { - if (!gitReady && !hasSSHKeys && !codeBuddyReady && !sponsoredModel) { - setError("请先配置 GitHub Git Token、Git SSH 密钥或 CodeBuddy API Key。"); - return; - } setSaving(true); try { await saveTypedCredentials(); @@ -1519,10 +1518,7 @@ export default function QuickAccessWizard({ workflow: provisionedWorkflow || activeWorkflow, rolesCount: roles.length, gitReady: Boolean(boundRepo?.provider === "ssh" ? hasSSHKey(parseGongfengRepo(boundRepo.cloneUrl)) : latestUser?.gitHubCredentialConfigured), - codeBuddyReady: Boolean( - latestUser?.codeBuddyApiKeyConfigured || - storedUser?.codeBuddyApiKeyConfigured, - ), + cliNames: EXECUTORS.filter(cli => personalEngineConfigured(latestUser || storedUser, cli.id)).map(cli => cli.label), }); setPhase("success"); await onCompleted?.(targetProject?.id || ""); @@ -1699,28 +1695,13 @@ export default function QuickAccessWizard({ : "未配置,克隆/推送私有仓库前可在个人配置补齐"} -
  • - +
  • + - CodeBuddy API Key: - {completedSummary?.codeBuddyReady - ? "已配置" - : sponsoredModel - ? `未配置。对话和 SOP 都会使用平台共享 Key(可用模型:${sharedModelNames(sponsoredModels, sponsoredModel)}),可以直接开始;配置自己的 Key 后可选用任意模型` - : "未配置。对话可用平台默认模型,但运行 SOP 时节点需要它调模型,请先在个人配置补齐"} + 模型 CLI · {completedSummary?.cliNames?.join("、") || + (sponsoredModel + ? `平台共享模型(${sharedModelNames(sponsoredModels, sponsoredModel)})` + : "可在个人配置或执行机器设置中准备")}
  • @@ -1897,7 +1878,22 @@ export default function QuickAccessWizard({
    - CodeBuddy API Key + 模型 CLI + {readyCLIs.length ? readyCLIs.map(cli => cli.label).join("、") : "可在个人配置中选择 CLI 或在执行机器上登录"} +
    + +
    +
    + +
    +
    +
    +
    +
    + CodeBuddy API Key(可选) {sponsoredModel ? "可选:未配置时对话和 SOP 使用平台共享模型,配置后可选用其他模型" @@ -2346,16 +2342,12 @@ export default function QuickAccessWizard({
    凭据
    {sshRepository ? "Git SSH" : "GitHub"} {(sshRepository ? sshReady : gitReady) ? "已配置" : "未配置"} · - CodeBuddy{" "} - {codeBuddyReady - ? "已配置" - : sponsoredModel - ? "使用平台共享模型" - : "未配置"} + CLI · {readyCLIs.length ? readyCLIs.map(cli => cli.label).join("、") : + sponsoredModel ? "使用平台共享模型" : "未配置"}
    diff --git a/chatbot/src/engines.js b/chatbot/src/engines.js index 63ba8745..8890863f 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/useChat.js b/chatbot/src/useChat.js index cc6cfc51..4d47a66e 100644 --- a/chatbot/src/useChat.js +++ b/chatbot/src/useChat.js @@ -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 { personalEngineConfigured, EXECUTORS, concreteModel, conversationEngine, engineModels, engineOfModel } from "./engines.js"; import { readComposerPreference, useComposerOptions, writeComposerPreference } from "./composer-preferences.js"; import { enqueue, @@ -100,6 +100,7 @@ export function useChat() { new URLSearchParams(location.search).get("issueId") || "", ), [models, setModels] = useState([]), + [catalogEngines, setCatalogEngines] = useState([]), [modelCatalogRefresh, requestModelCatalogRefresh] = useState(0), [sessions, setSessions] = useState([]), [session, setSession] = useState(null), @@ -251,6 +252,7 @@ export function useChat() { } const applyModelCatalog = useCallback((catalog) => { setModels(catalog.models || []); + setCatalogEngines(catalog.engines || []); setCodeBuddyDefault({ id: catalog.default || "default", name: "默认", efforts: catalog.defaultEfforts }); setSponsoredModels(sponsoredModelList(catalog)); }, []); @@ -630,6 +632,17 @@ 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] || ""; + useEffect(() => { + if (!user || user.isGuest || activeId || submitting || !catalogEngines.length || + readComposerPreference("executor")) return; + const choices = catalogEngines.filter(engine => engine.configured); + // Account-authenticated runners advertise their runtime independently of + // the personal API catalog. Keep a selected CLI if that machine can run it. + const machine = executionMachines.machines.find(item => item.id === executionMachines.defaultRunnerId); + if (machine?.runtimes?.some(runtime => runtime.provider === executor && runtime.authMode !== "personal")) return; + const next = choices.find(engine => personalEngineConfigured(user, engine.id)) || choices[0]; + if (next && next.id !== executor) setSelection({ executor: next.id, model: null, effort: null }); + }, [user, activeId, submitting, catalogEngines, executor, executionMachines.machines, executionMachines.defaultRunnerId]); function resolveComposerModel( { executor, model, effort }, conversation, draft, catalogs = providerCatalogs, machines = executionMachines.machines, 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..214cce21 100644 --- a/compose.yaml +++ b/compose.yaml @@ -36,6 +36,9 @@ services: AGENTFLOW_ASSISTANT_SESSION_DIR: /data/assistant AGENTFLOW_CONVERSATION_DIR: ${LOOPFORGE_DATA_DIR}/conversations AGENTFLOW_CLARIFY_SESSION_DIR: /data/clarify + AGENTFLOW_DEFAULT_EXECUTOR: ${AGENTFLOW_DEFAULT_EXECUTOR:-} + AGENTFLOW_SKIP_CODEBUDDY_INSTALL: ${AGENTFLOW_SKIP_CODEBUDDY_INSTALL:-} + AGENTFLOW_TRACKER_CODEBUDDY_AUTH: ${AGENTFLOW_TRACKER_CODEBUDDY_AUTH:-} 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 6d4f25c7..f0b5bd12 100644 --- a/docs/api/openapi.yaml +++ b/docs/api/openapi.yaml @@ -65,7 +65,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 @@ -403,7 +403,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: @@ -436,7 +436,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": @@ -3048,6 +3048,7 @@ paths: post: tags: [Runs] operationId: startRunEval + description: Evaluates a finished run using the requesting account's personal CLI credentials. requestBody: required: false content: diff --git a/docs/deployment.md b/docs/deployment.md index f68dacd2..6d573843 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. Set `AGENTFLOW_MANAGED_CLI_ROOT` to a persistent absolute directory to enable the daily CLI updater on platform processes that execute runs (`worker` or `all`). By default it checks Claude Code, CodeBuddy, and Codex. Set `AGENTFLOW_MANAGED_CLIS` to the full comma-separated list you want to update, for example `claude-code,codebuddy,codex,pi`. The additional provider IDs are `agy`, `cursor`, `dsh`, `kimi`, `opencode`, and `pi`. The updater ignores empty entries, including trailing commas. A list with no names uses the default, and any unknown ID rejects the update. This list applies to scheduled checks, the bulk CLI update command, and managed CLI updates on Runners. Existing installations and rollback remain available. Set the same list on API and worker processes that share a managed root. The API uses the list when resolving CodeBuddy and workers claim the daily check once per root. @@ -33,6 +31,15 @@ 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 and run evaluation 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` follows a configured personal CLI. A concrete model is passed unchanged to its CLI. +- 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 preview builds can specify a CLI. An unset executor inherits the run's default. `AGENTFLOW_DEFAULT_EXECUTOR` sets the deployment default using a built-in executor ID such as `codex` or `claude`. When unset, the first compatible CLI with personal credentials or the responsible account's runner login is chosen in catalog order. Installations relying on the shared CodeBuddy credential keep the historical default. The default is recorded in new run snapshots. +- On existing databases, operators can apply `migrations/040_inherit_stock_sop_executors.sql` to move stock version-one templates and the stock baseline resolver to inheritance. Operators can also select inheritance in the role editor for existing project copies. Explicit role executors and models continue to work. New installs use the updated seed. +- 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 takes headers from the catalog or `AGENTFLOW_MCP_TOKEN`. Installations that rely on host CodeBuddy OAuth can opt in with `AGENTFLOW_TRACKER_CODEBUDDY_AUTH=1`. + ## Container installation ```bash @@ -155,9 +162,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 6239884d..126d33a8 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -34,7 +34,9 @@ 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_EXECUTOR` | 执行器,默认 `codebuddy` | +| `AGENTFLOW_E2E_CLI_KEY` | 本地实测时所选 CLI 的个人凭据 | +| `AGENTFLOW_E2E_CLI_BASE_URL` | 本地实测可选的自定义模型网关 | +| `AGENTFLOW_E2E_EXECUTOR` | 执行器,默认 `codex` | | `AGENTFLOW_E2E_SANDBOX` | 沙箱,默认 `local`,仅对可信的验收任务使用 | | `AGENTFLOW_E2E_MODEL_SANDBOX` | 真实模型用例使用的沙箱,镜像里要有执行器 CLI;默认同 `AGENTFLOW_E2E_SANDBOX` | | `AGENTFLOW_E2E_REPO_CLONE_URL` | 带代码仓库的用例克隆这个仓库(只读,不推送)。不设置就跳过这些用例;`local.sh` 会自动设成本机裸仓库 | diff --git a/e2e/lib/env.mjs b/e2e/lib/env.mjs index c3c20df5..212a0763 100644 --- a/e2e/lib/env.mjs +++ b/e2e/lib/env.mjs @@ -38,7 +38,7 @@ export const cfg = { projectId: process.env.AGENTFLOW_E2E_PROJECT || 'e2e-auto', // Real-model scenarios are opt-in because they consume model credits. model: flag('AGENTFLOW_E2E_MODEL', false), - executor: process.env.AGENTFLOW_E2E_EXECUTOR || 'codebuddy', + executor: process.env.AGENTFLOW_E2E_EXECUTOR || 'codex', modelID: process.env.AGENTFLOW_E2E_MODEL_ID || '', sandbox: process.env.AGENTFLOW_E2E_SANDBOX || 'local', keep: flag('AGENTFLOW_E2E_KEEP', false), diff --git a/e2e/local.sh b/e2e/local.sh index 2fa5660a..7c2c62eb 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 codex) +# 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,41 @@ 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 +if [ -z "${AGENTFLOW_E2E_EXECUTOR:-}" ] && [ -n "${AGENTFLOW_E2E_CODEBUDDY_API_KEY:-}" ]; then + export AGENTFLOW_E2E_EXECUTOR=codebuddy fi +export AGENTFLOW_E2E_EXECUTOR=${AGENTFLOW_E2E_EXECUTOR:-codex} +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 +171,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/internal/application/operations.go b/internal/application/operations.go index 52183bb7..a7c4839a 100644 --- a/internal/application/operations.go +++ b/internal/application/operations.go @@ -95,7 +95,7 @@ func PublicOperations() []Operation { {Name: "runs_start", Description: "Start an SOP Run", Method: "POST", Path: "/api/runs"}, {Name: "runs_get", Description: "Get one Run", Method: "GET", Path: "/api/runs/{id}", 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}, 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/preview.go b/internal/domain/preview.go index 23465294..ad9c0d32 100644 --- a/internal/domain/preview.go +++ b/internal/domain/preview.go @@ -35,7 +35,6 @@ const ( PreviewBuildNodeID = "af-preview-build" PreviewBuildAgentID = "af-preview-builder" - PreviewBuildExecutor = "codebuddy" PreviewDefaultModel = "default" PreviewDefaultSource = "dist" PreviewBuildEdgeID = "af-preview-build-edge" @@ -43,14 +42,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"` // optional CLI executor; empty inherits the workflow default + 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 +94,11 @@ func (c *PreviewContract) SourceOrDist() string { return PreviewDefaultSource } -func (c *PreviewContract) ExecutorOrCodeBuddy() string { +func (c *PreviewContract) Executor() string { if c == nil { - return PreviewBuildExecutor + return "" } - if id := strings.TrimSpace(c.ExecutorID); id != "" { - return id - } - return PreviewBuildExecutor + return strings.TrimSpace(c.ExecutorID) } func (c *PreviewContract) ModelOrDefault() string { @@ -135,7 +131,7 @@ func (c *PreviewContract) Normalize() { return } c.Kind = c.KindOrStatic() - c.ExecutorID = c.ExecutorOrCodeBuddy() + c.ExecutorID = c.Executor() c.Model = c.ModelOrDefault() c.SourcePath = c.SourceOrDist() c.IndexFile = c.Index() @@ -152,12 +148,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..102a1f33 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.Executor() { + wf.Nodes = append([]WorkflowNode(nil), wf.Nodes...) + wf.Nodes[i].ExecutorID = wf.Preview.Executor() + } return wf, nil } } @@ -65,7 +75,7 @@ func PreviewBuildNode(wf WorkflowDefinition) WorkflowNode { Name: "构建静态站点", Type: "agent", AgentID: PreviewBuildAgentID, - ExecutorID: PreviewBuildExecutor, + ExecutorID: contract.Executor(), ExecutionScope: ExecutionScopeRun, ArtifactOutputs: []ArtifactContract{PreviewBuildArtifact(contract)}, OnFailure: "fail", @@ -82,8 +92,8 @@ func PreviewBuildAgent(contract *PreviewContract) AgentDefinition { return AgentDefinition{ ID: PreviewBuildAgentID, Name: "构建静态站点", - Description: "系统步骤:用 CodeBuddy 产出可托管的静态站点,再由预览收尾归档。", - ExecutorID: PreviewBuildExecutor, + Description: "系统步骤:构建可托管的静态站点并归档为预览。", + ExecutorID: contract.Executor(), Model: contract.ModelOrDefault(), Prompt: PreviewBuildPrompt(contract), ArtifactOutputs: []ArtifactContract{PreviewBuildArtifact(contract)}, @@ -109,7 +119,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/user.go b/internal/domain/user.go index d5502629..bcae25ae 100644 --- a/internal/domain/user.go +++ b/internal/domain/user.go @@ -45,6 +45,20 @@ type User struct { UpdatedAt time.Time `json:"updatedAt"` } +// CLIAPIKey returns the personal credential for a CLI provider kind. +func (u User) CLIAPIKey(kind string) string { + switch kind { + case "codebuddy": + return strings.TrimSpace(u.CodeBuddyAPIKey) + case "codex": + return strings.TrimSpace(u.CodexAPIKey) + case "claude-code": + return strings.TrimSpace(u.ClaudeCodeAPIKey) + default: + return strings.TrimSpace(u.AgentCLICredentials[kind].APIKey) + } +} + 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..559b8f69 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. @@ -177,6 +177,9 @@ type WorkflowDefinition struct { // the resolved profile plus Dockerfile/environment payload so retries can // reconstruct the original environment after catalog definitions change. SandboxSnapshot *RunnerSandboxSpec `json:"sandboxSnapshot,omitempty"` + // DefaultExecutorID freezes the executor inherited by unconfigured SOP + // roles. It is assigned by the engine when creating a run snapshot. + DefaultExecutorID string `json:"defaultExecutorId,omitempty"` // Preview is the optional frontend delivery contract. It is frozen into // the run snapshot so later SOP edits cannot change an in-flight archive. Preview *PreviewContract `json:"preview,omitempty"` diff --git a/internal/engine/engine_test.go b/internal/engine/engine_test.go index 57d1b8ac..35b6df62 100644 --- a/internal/engine/engine_test.go +++ b/internal/engine/engine_test.go @@ -2804,6 +2804,46 @@ func TestRecoverMisplacedArtifactsCopiesHostLeakIntoSandbox(t *testing.T) { } } +func TestRunFreezesInheritedExecutorForRolesAndPreview(t *testing.T) { + t.Setenv("AGENTFLOW_DEFAULT_EXECUTOR", "") + store, err := repo.OpenTest() + if err != nil { + t.Fatal(err) + } + defer store.Close() + responsible := domain.User{ID: 701, LoginName: "codex-worker", CodexAPIKey: "test-only"} + if err := store.PutUser(responsible); err != nil { + t.Fatal(err) + } + role := domain.AgentDefinition{ID: "inherited-role", Name: "Inherited role"} + if err := store.PutAgent(role); err != nil { + t.Fatal(err) + } + eng := New(store, runtime.NewManager(t.TempDir())) + eng.ConfigureExecution("", "", 0, false) + wf := domain.WorkflowDefinition{ + ID: "inherit-executor", Name: "Inherited executor", SandboxProfileID: "local", + Nodes: []domain.WorkflowNode{{ID: "work", Name: "Work", Type: "agent", AgentID: role.ID}}, + Preview: &domain.PreviewContract{Enabled: true}, + } + run, err := eng.startWorkflowDefinition(wf, "", nil, domain.TelemetryContext{ProjectID: "platform", ResponsibleUserID: responsible.ID}, false) + if err != nil { + t.Fatal(err) + } + t.Setenv("AGENTFLOW_DEFAULT_EXECUTOR", "claude") + snapshot := run.WorkflowSnapshot + if snapshot.DefaultExecutorID != "codex" { + t.Fatalf("stored default = %q", snapshot.DefaultExecutorID) + } + for _, node := range snapshot.Nodes { + agent, _ := workflowAgent(store, snapshot, node.AgentID) + ex, err := resolveNodeExecutor(store, node, agent, snapshot.DefaultExecutorID) + if err != nil || ex.Kind != "codex" { + t.Fatalf("node %s resolved to %q: %v", node.ID, ex.Kind, err) + } + } +} + func TestResolveNodeExecutorPrefersAgentModel(t *testing.T) { t.Parallel() s, err := repo.OpenTest() @@ -2812,7 +2852,7 @@ func TestResolveNodeExecutorPrefersAgentModel(t *testing.T) { } defer s.Close() agent := domain.AgentDefinition{ID: "analyst", Name: "Analyst", ExecutorID: "codebuddy", Model: "agent-model"} - got, err := resolveNodeExecutor(s, domain.WorkflowNode{AgentID: "analyst", ExecutorID: "mock"}, agent) + got, err := resolveNodeExecutor(s, domain.WorkflowNode{AgentID: "analyst", ExecutorID: "mock"}, agent, "") if err != nil { t.Fatal(err) } @@ -2823,7 +2863,7 @@ func TestResolveNodeExecutorPrefersAgentModel(t *testing.T) { t.Fatalf("model = %s, want agent override", got.Model) } agentEffort := domain.AgentDefinition{ID: "analyst", Name: "Analyst", ExecutorID: "codex", Effort: "xhigh"} - withEffort, err := resolveNodeExecutor(s, domain.WorkflowNode{AgentID: "analyst"}, agentEffort) + withEffort, err := resolveNodeExecutor(s, domain.WorkflowNode{AgentID: "analyst"}, agentEffort, "") if err != nil { t.Fatal(err) } @@ -2833,14 +2873,14 @@ func TestResolveNodeExecutorPrefersAgentModel(t *testing.T) { if err := s.PutExecutor(domain.ExecutorDefinition{ID: "legacy-codex", Name: "Legacy Codex", Kind: "codex", Binary: "custom-codex", Args: []string{"unsafe"}, Model: "legacy-model"}); err != nil { t.Fatal(err) } - legacy, err := resolveNodeExecutor(s, domain.WorkflowNode{ExecutorID: "legacy-codex"}, domain.AgentDefinition{ID: "legacy"}) + legacy, err := resolveNodeExecutor(s, domain.WorkflowNode{ExecutorID: "legacy-codex"}, domain.AgentDefinition{ID: "legacy"}, "") if err != nil { t.Fatal(err) } if legacy.ID != "codex" || legacy.Binary != "codex" || legacy.Model != "legacy-model" { t.Fatalf("legacy executor was not safely mapped to the built-in CLI: %+v", legacy) } - _, err = resolveNodeExecutor(s, domain.WorkflowNode{ExecutorID: "custom"}, domain.AgentDefinition{ID: "legacy"}) + _, err = resolveNodeExecutor(s, domain.WorkflowNode{ExecutorID: "custom"}, domain.AgentDefinition{ID: "legacy"}, "") if err == nil || !strings.Contains(err.Error(), "not found") { t.Fatalf("custom executor must be rejected: %v", err) } diff --git a/internal/engine/node_execute.go b/internal/engine/node_execute.go index 5ca17b72..53db3418 100644 --- a/internal/engine/node_execute.go +++ b/internal/engine/node_execute.go @@ -186,12 +186,16 @@ func (e *Engine) execute(ctx context.Context, runID string) { } } -func resolveNodeExecutor(st *repo.Store, node domain.WorkflowNode, agent domain.AgentDefinition) (domain.ExecutorDefinition, error) { - executorID := agent.ExecutorID +func resolveNodeExecutor(st *repo.Store, node domain.WorkflowNode, agent domain.AgentDefinition, defaultExecutorID string) (domain.ExecutorDefinition, error) { + executorID := strings.TrimSpace(agent.ExecutorID) if executorID == "" { - executorID = node.ExecutorID + executorID = strings.TrimSpace(node.ExecutorID) } if executorID == "" { + executorID = defaultExecutorID + } + if executorID == "" { + // Runs created before the inherited executor was frozen used CodeBuddy. executorID = "codebuddy" } ex, found := repo.BuiltInExecutor(executorID) @@ -233,7 +237,7 @@ 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 := resolveNodeExecutor(st, node, agent, wf.DefaultExecutorID) if err != nil { return runtime.SandboxRequirements{}, err } @@ -689,7 +693,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 := resolveNodeExecutor(e.repo, node, agent, wf.DefaultExecutorID) if errResolve != nil { err = errResolve break diff --git a/internal/engine/preview_finalizer_test.go b/internal/engine/preview_finalizer_test.go index 055e7ece..cdf1f03f 100644 --- a/internal/engine/preview_finalizer_test.go +++ b/internal/engine/preview_finalizer_test.go @@ -208,7 +208,7 @@ func TestStartInjectsPreviewBuildNode(t *testing.T) { t.Fatalf("catalog SOP must stay without the injected node: %+v", stored.Nodes) } agent, ok := workflowAgent(store, run.WorkflowSnapshot, domain.PreviewBuildAgentID) - if !ok || agent.ExecutorID != domain.PreviewBuildExecutor || agent.Model != "gpt-5.6-terra" { + if !ok || agent.ExecutorID != "" || agent.Model != "gpt-5.6-terra" { t.Fatalf("synthetic agent = %+v ok=%v", agent, ok) } } diff --git a/internal/engine/run_events.go b/internal/engine/run_events.go index 95041e20..f66ac7de 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++ } diff --git a/internal/engine/run_ops.go b/internal/engine/run_ops.go index 24c1af67..2e86ce6e 100644 --- a/internal/engine/run_ops.go +++ b/internal/engine/run_ops.go @@ -844,6 +844,7 @@ 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 + latest.DefaultExecutorID = r.WorkflowSnapshot.DefaultExecutorID var err error latest, err = domain.AttachPreviewBuild(latest) if err != nil { diff --git a/internal/engine/run_start.go b/internal/engine/run_start.go index 7899fff5..22fd0ffc 100644 --- a/internal/engine/run_start.go +++ b/internal/engine/run_start.go @@ -2,6 +2,7 @@ package engine import ( "agentflow/internal/domain" + "agentflow/internal/repo" "context" "fmt" "strings" @@ -110,9 +111,6 @@ func (e *Engine) startWorkflowDefinition(wf domain.WorkflowDefinition, input str if err != nil { return domain.Run{}, err } - if _, err := workflowSandboxRequirements(e.repo, wf); err != nil { - return domain.Run{}, err - } now := time.Now().UTC() id := fmt.Sprintf("run-%d", now.UnixNano()) assignWorkBranches(repositories, func() string { @@ -148,6 +146,12 @@ func (e *Engine) startWorkflowDefinition(wf domain.WorkflowDefinition, input str } else { executionContext.ExecutionMode = domain.ExecutionModeCloud } + responsible, _ := e.repo.User(executionContext.ResponsibleUserID) + runner, _ := e.repo.Runner(executionContext.ExecutionRunnerID) + wf.DefaultExecutorID = repo.DefaultExecutorID(responsible, runner) + if _, err := workflowSandboxRequirements(e.repo, wf); err != nil { + return domain.Run{}, err + } if err := e.requireWorkBranchCapabilities(executionContext.ExecutionRunnerID, repositories); err != nil { return domain.Run{}, err } diff --git a/internal/engine/runner_dispatch.go b/internal/engine/runner_dispatch.go index 066fbbb2..efa732ea 100644 --- a/internal/engine/runner_dispatch.go +++ b/internal/engine/runner_dispatch.go @@ -523,11 +523,11 @@ 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 := resolveNodeExecutor(e.repo, node, agent, run.WorkflowSnapshot.DefaultExecutorID) if err != nil { return fmt.Errorf("无法重连原执行环境:%w", err) } diff --git a/internal/engine/workspace_preparation.go b/internal/engine/workspace_preparation.go index a599845a..e9fd9db8 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 := resolveNodeExecutor(st, node, agent, wf.DefaultExecutorID) if err != nil { continue } diff --git a/internal/httpapi/agent_tool_catalog.go b/internal/httpapi/agent_tool_catalog.go index 31405676..b7ecd540 100644 --- a/internal/httpapi/agent_tool_catalog.go +++ b/internal/httpapi/agent_tool_catalog.go @@ -312,9 +312,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 45985a97..f31d4d50 100644 --- a/internal/httpapi/agent_tool_mcp.go +++ b/internal/httpapi/agent_tool_mcp.go @@ -364,6 +364,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 7969f6a0..4e6e58ee 100644 --- a/internal/httpapi/agent_tool_session.go +++ b/internal/httpapi/agent_tool_session.go @@ -93,6 +93,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 55d70ff3..e50b83b7 100644 --- a/internal/httpapi/assistant.go +++ b/internal/httpapi/assistant.go @@ -110,7 +110,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 @@ -120,8 +120,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 @@ -172,6 +170,7 @@ func (h *assistantHandlers) chat(c *gin.Context) { } req.ExecutionTarget = target } + req.Model = assistantChatRequestModel(req, old, stored) cliEngine, _ := assistantModelEngine(req.Model) loginRunner := h.assistantLoginRunner(stored.ID, req.ExecutionTarget, cliEngine) runnerLogin := loginRunner.ID != "" @@ -219,9 +218,10 @@ func (h *assistantHandlers) chat(c *gin.Context) { return } catalogEngine, _ := assistantModelEngine(req.Model) - catalog := assistantChatCatalog(c.Request.Context(), user.CodeBuddyInternetEnvironment, nil) + 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) @@ -278,7 +278,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 { @@ -1486,6 +1488,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 @@ -1498,7 +1508,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 @@ -1525,23 +1535,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 @@ -1551,7 +1546,7 @@ 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} + 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} switch engine { case assistantEngineClaude: if !req.RunnerLogin { @@ -1571,7 +1566,7 @@ 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}) + 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}) inv.credentials = runtime.RunCredentials{CodeBuddy: runtime.CodeBuddyCredential{APIKey: user.CodeBuddyAPIKey, InternetEnvironment: user.CodeBuddyInternetEnvironment}} inv.sessionRef = sessionID } @@ -1588,9 +1583,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 diff --git a/internal/httpapi/assistant_approval_review.go b/internal/httpapi/assistant_approval_review.go index c98929aa..51e20b43 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, id := assistantModelEngine(selected) + var models []string + if id != "" && !codeBuddyIsDefaultModel(id) || engine != assistantEngineCodeBuddy { + models = []string{selected} + } else if h.reviewCatalog != nil { + models = assistantApprovalReviewModels(h.reviewCatalog(user.CodeBuddyInternetEnvironment)) } else { - catalog = h.chatCatalog(context.Background(), 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_engine_cli.go b/internal/httpapi/assistant_engine_cli.go index 44bd4e82..6e2d5fd7 100644 --- a/internal/httpapi/assistant_engine_cli.go +++ b/internal/httpapi/assistant_engine_cli.go @@ -41,6 +41,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 } @@ -208,7 +209,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 { @@ -312,4 +313,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 16d15be8..d11fd894 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), }) } @@ -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 @@ -666,11 +665,25 @@ 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 assistantChatRequestModel(req assistantRequest, saved domain.AssistantSession, user domain.User) string { + if strings.TrimSpace(req.Executor) == "" && (strings.TrimSpace(req.Model) == "" || req.Model == assistantDefaultModel) { + if saved.Model != "" || saved.Executor != "" { + return assistantRequestModel(saved.Executor, saved.Model) + } + 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 a1aa525f..2799943c 100644 --- a/internal/httpapi/assistant_failure.go +++ b/internal/httpapi/assistant_failure.go @@ -151,7 +151,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 4b919943..ab97549b 100644 --- a/internal/httpapi/assistant_generation.go +++ b/internal/httpapi/assistant_generation.go @@ -46,7 +46,6 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) { if !requireAssistantApprovalUser(c, current.ID, req.ApprovalUserID) { 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 @@ -85,6 +84,7 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) { return } } + req.Model = assistantChatRequestModel(req, old, stored) cliEngine, _ := assistantModelEngine(req.Model) loginRunner := h.assistantLoginRunner(stored.ID, req.ExecutionTarget, cliEngine) runnerLogin := loginRunner.ID != "" @@ -123,9 +123,10 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) { return } catalogEngine, _ := assistantModelEngine(req.Model) - catalog := assistantChatCatalog(c.Request.Context(), user.CodeBuddyInternetEnvironment, nil) + 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) 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 32f5b881..f7d0ec5a 100644 --- a/internal/httpapi/assistant_models.go +++ b/internal/httpapi/assistant_models.go @@ -180,9 +180,8 @@ func cachedCLIModels(environment string) []string { return 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) @@ -236,7 +235,7 @@ 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(c.Request.Context(), key.InternetEnvironment, 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) @@ -247,6 +246,9 @@ func (h *assistantHandlers) models(c *gin.Context) { catalog.Models = listed } } + case signedIn: + // Do not probe a CLI the user has not configured. + catalog.Default = assistantDefaultModel default: catalog = assistantChatCatalog(c.Request.Context(), "", nil) } diff --git a/internal/httpapi/assistant_notification_report.go b/internal/httpapi/assistant_notification_report.go index aaf39210..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 := loadAssistantModels(ctx, user.CodeBuddyInternetEnvironment) - 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/bot_interactions.go b/internal/httpapi/bot_interactions.go index c48d0b06..4768c0ba 100644 --- a/internal/httpapi/bot_interactions.go +++ b/internal/httpapi/bot_interactions.go @@ -7,6 +7,7 @@ import ( "context" "errors" "fmt" + "os" "strings" ) @@ -71,15 +72,12 @@ 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 - } - if assistantAllowedModel(model, loadAssistantModels(ctx, user.CodeBuddyInternetEnvironment)) != model { - return "所选模型不可用,请在 Bot 管理中重新选择。", nil + model, err := resolveFeatureModel(user, bot.Model) + if err != nil { + if errors.Is(err, errFeatureModel) { + return err.Error(), nil + } + return "你的平台账号尚未配置对应的模型凭据。" + err.Error(), nil } if err = ensureAssistantSessionDirs(user.ID); err != nil { return "", err @@ -94,13 +92,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 +128,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 +142,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 21136cb3..4ffeb8ad 100644 --- a/internal/httpapi/bot_interactions_test.go +++ b/internal/httpapi/bot_interactions_test.go @@ -132,7 +132,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 cbc41fc3..27811d69 100644 --- a/internal/httpapi/catalog.go +++ b/internal/httpapi/catalog.go @@ -307,6 +307,24 @@ func (h *catalogHandlers) repository(c *gin.Context) { c.JSON(http.StatusOK, domain.PublicRepository(repository)) } +func validateCatalogAgentCLI(agent *domain.AgentDefinition) error { + agent.ExecutorID = strings.TrimSpace(agent.ExecutorID) + if agent.ExecutorID == "" { + if strings.TrimSpace(agent.Model) == assistantDefaultModel { + agent.Model = "" + } + if strings.TrimSpace(agent.Model) != "" || strings.TrimSpace(agent.Effort) != "" { + return fmt.Errorf("指定模型或思考强度前请先选择 CLI") + } + return nil + } + executor, ok := repo.BuiltInExecutor(agent.ExecutorID) + if !ok { + return fmt.Errorf("不支持的 CLI:%s", agent.ExecutorID) + } + return domain.ValidateAgentEffort(agent.Effort, executor.Kind) +} + func (h *catalogHandlers) agents(c *gin.Context) { if c.Request.Method == http.MethodGet { agents := h.repo.Agents() @@ -340,15 +358,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 := validateCatalogAgentCLI(&v); err != nil { c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()}) return } @@ -1064,6 +1074,13 @@ func (h *catalogHandlers) workflows(c *gin.Context) { return } + v.DefaultExecutorID = "" + if id := v.Preview.Executor(); 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 @@ -1258,15 +1275,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 := validateCatalogAgentCLI(&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 59110f6b..64e25358 100644 --- a/internal/httpapi/clarify_mcp.go +++ b/internal/httpapi/clarify_mcp.go @@ -3,7 +3,6 @@ package httpapi import ( "context" "encoding/json" - "errors" "fmt" "path/filepath" "regexp" @@ -23,24 +22,6 @@ var ( gongfengIssueURLRe = regexp.MustCompile(`(?i)https?://git\.example\.com/[^\s<>"')】\]]+/issues/\d+`) ) -func clarifyAllowedModel(id string) string { - return assistantAllowedModel(id, assistantKnownCatalog()) -} - -// 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 { diff --git a/internal/httpapi/clarify_mcp_test.go b/internal/httpapi/clarify_mcp_test.go index b307692d..07871385 100644 --- a/internal/httpapi/clarify_mcp_test.go +++ b/internal/httpapi/clarify_mcp_test.go @@ -13,19 +13,6 @@ import ( "agentflow/internal/repo" ) -func TestClarifyAllowedModelFallsBackToCatalog(t *testing.T) { - t.Setenv("AGENTFLOW_ASSISTANT_MODELS", "public-model") - if got := clarifyAllowedModel(""); got != clarifyDefaultModel { - t.Fatalf("empty model = %q", got) - } - if got := clarifyAllowedModel("not-a-model"); got != clarifyDefaultModel { - t.Fatalf("unknown model = %q", got) - } - if got := clarifyAllowedModel("public-model"); got != "public-model" { - t.Fatalf("listed model = %q", got) - } -} - 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/feature_model.go b/internal/httpapi/feature_model.go new file mode 100644 index 00000000..a3d224b6 --- /dev/null +++ b/internal/httpapi/feature_model.go @@ -0,0 +1,66 @@ +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 resolveFeatureModel(user domain.User, requested string) (string, error) { + model, err := normalizeFeatureModel(requested) + if err != nil { + return "", err + } + if model == assistantDefaultModel { + 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 models := assistantSavedModels(user, engine); len(models) > 0 { + return engine + ":" + models[0].ID + } + if engine == assistantEngineCodeBuddy { + return engine + ":" + assistantFixedCatalog().Default + } + 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..78924f6d --- /dev/null +++ b/internal/httpapi/feature_model_test.go @@ -0,0 +1,238 @@ +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"} + 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"}, + {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") + } +} + +// 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/misc_cases_test.go b/internal/httpapi/misc_cases_test.go index 19d1017a..5f148428 100644 --- a/internal/httpapi/misc_cases_test.go +++ b/internal/httpapi/misc_cases_test.go @@ -194,6 +194,17 @@ func TestMiscScheduleRemainingHelpersAndHTTP(t *testing.T) { if !h.ensureBaselineAlignAgent() { t.Fatal("ensure align agent") } + resolver, _ := f.s.Agent(domain.BaselineAlignAgentID) + resolver.ExecutorID, resolver.Model = "codex", "custom-model" + if err := f.s.PutAgent(resolver); err != nil { + t.Fatal(err) + } + if !h.ensureBaselineAlignAgent() { + t.Fatal("ensure existing align agent") + } + if got, _ := f.s.Agent(domain.BaselineAlignAgentID); got.ExecutorID != "codex" || got.Model != "custom-model" { + t.Fatalf("baseline registration overwrote the saved executor: %+v", got) + } _ = f.s.DeleteWorkflow(engine.BaselineAlignWorkflowID) if !h.ensureBaselineAlignWorkflow(domain.ScheduleJob{}) { t.Fatal("ensure align workflow") diff --git a/internal/httpapi/notifications.go b/internal/httpapi/notifications.go index e11d1df8..c69a32b7 100644 --- a/internal/httpapi/notifications.go +++ b/internal/httpapi/notifications.go @@ -153,12 +153,9 @@ func (h *notificationHandlers) save(c *gin.Context, old *domain.NotificationBot) bot.InteractionEnabled = *req.InteractionEnabled } if req.Model != nil { - model := strings.TrimSpace(*req.Model) - if model == "" { - model = domain.DefaultNotificationReportModel - } - if assistantAllowedModel(model, assistantKnownCatalog()) != model { - c.JSON(400, gin.H{"error": "请选择有效的 CodeBuddy 模型"}) + model, err := normalizeFeatureModel(*req.Model) + if err != nil { + c.JSON(400, gin.H{"error": err.Error()}) return } bot.Model = model diff --git a/internal/httpapi/run_eval.go b/internal/httpapi/run_eval.go index 56d6aa3d..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 := loadAssistantModels(c.Request.Context(), user.CodeBuddyInternetEnvironment) - 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 c1227402..baf261c1 100644 --- a/internal/httpapi/schedule.go +++ b/internal/httpapi/schedule.go @@ -320,7 +320,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" } @@ -607,8 +607,8 @@ fi echo "校验通过:HEAD 为合并提交,无未解决冲突与残留标记"` func (h *scheduleHandlers) ensureBaselineAlignAgent() bool { - if err := h.repo.PutAgent(repo.BaselineAlignResolverAgent()); err != nil { - log.Printf("baseline align agent upsert failed: %v", err) + if err := h.repo.CreateBaselineAlignResolver(); err != nil { + log.Printf("baseline align agent creation failed: %v", err) return false } return true diff --git a/internal/httpapi/stream.go b/internal/httpapi/stream.go index fabb8838..e08f596d 100644 --- a/internal/httpapi/stream.go +++ b/internal/httpapi/stream.go @@ -381,7 +381,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 +420,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 +448,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 +467,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 +499,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 +569,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 +583,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 +636,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 +677,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(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.CodeBuddyCredential{APIKey: responsible.CodeBuddyAPIKey, InternetEnvironment: responsible.CodeBuddyInternetEnvironment}, + GitHTTPCredentials: h.repo.GitHTTPCredentialSecrets(ctx, responsible.ID), + } } turnPrompt := userMsg if resume { @@ -674,11 +712,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 +745,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/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..52f65084 100644 --- a/internal/repo/catalog.go +++ b/internal/repo/catalog.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "math" + "os" "path/filepath" "sort" "strings" @@ -13,6 +14,7 @@ import ( "agentflow/internal/domain" "gorm.io/gorm" + "gorm.io/gorm/clause" ) // BaselineAlignResolverAgent is the shared platform role for scheduled @@ -26,10 +28,19 @@ 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", } } +// CreateBaselineAlignResolver stores the built-in role on first use. A +// concurrent scheduler or an operator-edited resolver wins on conflict. +func (r *CatalogRepo) CreateBaselineAlignResolver() error { + agent := BaselineAlignResolverAgent() + agent.UpdatedAt = time.Now().UTC() + return r.DB.Table("agents").Clauses(clause.OnConflict{DoNothing: true}).Create(map[string]any{ + "id": agent.ID, "name": agent.Name, "payload": mustJSON(agent), "updated_at": timePtr(agent.UpdatedAt), + }).Error +} + // ---------- Agents ---------- func (r *CatalogRepo) Agents() []domain.AgentDefinition { @@ -247,6 +258,26 @@ func BuiltInExecutors() []domain.ExecutorDefinition { } } +// DefaultExecutorID is resolved when a run starts. A personal machine can +// supply the CLI's local login only for its owner. The legacy default covers +// deployments that rely on a shared CodeBuddy credential. +func DefaultExecutorID(user domain.User, runner domain.Runner) string { + if id := strings.TrimSpace(os.Getenv("AGENTFLOW_DEFAULT_EXECUTOR")); id != "" { + return id + } + for _, executor := range BuiltInExecutors() { + if runner.ID != "" && !runner.SupportsProvider(executor.Kind) { + continue + } + login := runner.ID != "" && runner.OwnerUserID == user.ID && domain.SupportsRunnerLogin(executor.Kind) && + runner.RuntimeAuthMode(executor.Kind) == domain.RuntimeAuthLocal + if login || user.CLIAPIKey(executor.Kind) != "" { + return executor.ID + } + } + return "codebuddy" +} + func BuiltInExecutor(id string) (domain.ExecutorDefinition, bool) { for _, executor := range BuiltInExecutors() { if executor.ID == strings.TrimSpace(id) { 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/runs.go b/internal/repo/runs.go index 32f45ffe..da747ba3 100644 --- a/internal/repo/runs.go +++ b/internal/repo/runs.go @@ -1679,9 +1679,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/runtime/command_binding.go b/internal/runtime/command_binding.go index c6776888..8c0fe5a2 100644 --- a/internal/runtime/command_binding.go +++ b/internal/runtime/command_binding.go @@ -185,27 +185,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/sandbox_docker.go b/internal/runtime/sandbox_docker.go index c4fb30fa..b479f557 100644 --- a/internal/runtime/sandbox_docker.go +++ b/internal/runtime/sandbox_docker.go @@ -627,7 +627,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) { @@ -905,6 +905,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 @@ -947,15 +948,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/tracker/service.go b/internal/tracker/service.go index 7edf45f7..3018c547 100644 --- a/internal/tracker/service.go +++ b/internal/tracker/service.go @@ -6,6 +6,7 @@ import ( "log" "maps" "net/url" + "os" "sort" "strconv" "strings" @@ -91,7 +92,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. +// to AGENTFLOW_MCP_TOKEN. Legacy host CodeBuddy OAuth is opt-in. func (s *Service) Configure(cfg domain.SyncConfig) { s.ConfigureWithCatalog(cfg, nil) } @@ -99,8 +100,15 @@ 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")) + bind := func(kind string) mcpBinding { + binding := bindTrackerMCP(kind, cfg, servers, s.authToken, "") + if binding.URL != "" && !headerHas(binding.Headers, "Authorization") && + os.Getenv("AGENTFLOW_TRACKER_CODEBUDDY_AUTH") == "1" { + binding = bindTrackerMCP(kind, cfg, servers, "", LoadAuthFromCodeBuddy(kind)) + } + return binding + } + gf, tapd := bind("gongfeng"), bind("tapd") s.gfSource, s.tapdSource = gf.Source, tapd.Source if gf.URL != "" { s.gongfeng = NewMCPClient(gf.URL, gf.Headers) diff --git a/migrations/040_inherit_stock_sop_executors.sql b/migrations/040_inherit_stock_sop_executors.sql new file mode 100644 index 00000000..e6cd6527 --- /dev/null +++ b/migrations/040_inherit_stock_sop_executors.sql @@ -0,0 +1,47 @@ +-- Optional upgrade for existing installations. Run after the prior catalog +-- migrations with template edits paused. New seeds already inherit the CLI. +-- Keep edited roles, explicit models and existing run snapshots. +SET NAMES utf8mb4; +START TRANSACTION; + +UPDATE generic_templates AS target +JOIN ( + SELECT id, inherited_agents + FROM ( + SELECT id, agent_order, + JSON_ARRAYAGG(IF(inherit_cli, JSON_REMOVE(definition, '$.executorId'), definition)) + OVER (PARTITION BY id ORDER BY agent_order ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS inherited_agents, + SUM(inherit_cli) OVER (PARTITION BY id) AS changed + FROM ( + SELECT t.id, a.agent_order, a.definition, + (a.version = 1 AND a.executor_id = 'codebuddy' + AND COALESCE(a.model, '') IN ('', 'default') + AND COALESCE(a.effort, '') = '' + AND a.agent_id REGEXP CONCAT('^', t.id, '-(clarify|design|implement|review|test|deliver|mr)$')) AS inherit_cli + FROM generic_templates AS t + JOIN JSON_TABLE(t.payload, '$.Agents[*]' COLUMNS ( + agent_order FOR ORDINALITY, + definition JSON PATH '$', + agent_id VARCHAR(64) PATH '$.id', + version INT PATH '$.version', + executor_id VARCHAR(64) PATH '$.executorId', + model VARCHAR(128) PATH '$.model', + effort VARCHAR(64) PATH '$.effort' + )) AS a + WHERE t.id IN ('generic-backend-delivery', 'generic-frontend-delivery', 'issue-fix-production', 'generic-product-delivery') + ) AS candidates + ) AS templates_with_order + WHERE agent_order = 1 AND changed > 0 +) AS migrated ON migrated.id = target.id +SET target.payload = JSON_SET(target.payload, '$.Agents', JSON_EXTRACT(migrated.inherited_agents, '$')), + target.updated_at = UTC_TIMESTAMP(); + +UPDATE agents +SET payload = JSON_REMOVE(payload, '$.executorId'), updated_at = UTC_TIMESTAMP() +WHERE id = 'baseline-align-resolver' + AND JSON_EXTRACT(payload, '$.version') = 1 + AND JSON_UNQUOTE(JSON_EXTRACT(payload, '$.executorId')) = 'codebuddy' + AND COALESCE(JSON_UNQUOTE(JSON_EXTRACT(payload, '$.model')), '') IN ('', 'default') + AND COALESCE(JSON_UNQUOTE(JSON_EXTRACT(payload, '$.effort')), '') = ''; + +COMMIT; diff --git a/migrations/seed/001_public_catalog.sql b/migrations/seed/001_public_catalog.sql index 2fcaa548..7bec1363 100644 --- a/migrations/seed/001_public_catalog.sql +++ b/migrations/seed/001_public_catalog.sql @@ -4,12 +4,12 @@ SET NAMES utf8mb4; START TRANSACTION; INSERT IGNORE INTO sandboxes (`id`,`name`,`payload`) VALUES ('local','本地执行(仅可信任务)','{"id":"local","name":"本地执行(仅可信任务)","driver":"local"}'); INSERT IGNORE INTO sandboxes (`id`,`name`,`payload`) VALUES ('generic-docker','Docker 隔离沙箱','{"id":"generic-docker","name":"Docker 隔离沙箱","shared":true,"driver":"docker","dockerfileId":"generic-backend","readOnlyRootFS":false}'); -INSERT IGNORE INTO dockerfiles (`id`,`name`,`payload`) VALUES ('generic-backend','公共开发环境','{"id":"generic-backend","name":"公共开发环境","shared":true,"content":"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"}'); +INSERT IGNORE INTO dockerfiles (`id`,`name`,`payload`) VALUES ('generic-backend','公共开发环境','{"id":"generic-backend","name":"公共开发环境","shared":true,"content":"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\\nARG CODEBUDDY_PACKAGE=@tencent-ai/codebuddy-code\\nRUN if [ -n \\"$CODEBUDDY_PACKAGE\\" ]; then npm install -g \\"$CODEBUDDY_PACKAGE\\"; fi\\nWORKDIR /workspace\\n"}'); INSERT IGNORE INTO rules (`id`,`name`,`payload`) VALUES ('public-engineering','工程与验证约束','{"version":1,"updatedAt":"2026-10-15T00:00:00Z","id":"public-engineering","name":"工程与验证约束","shared":true,"priority":100,"content":"先阅读仓库约束并明确范围;只修改任务所需文件。不得泄露凭据,不得伪造测试或交付证据。使用项目现有构建与测试命令,报告真实结果与限制。发布 PR 前检查 diff;未经任务授权不得合并主分支。"}'); -INSERT IGNORE INTO generic_templates (id,name,payload,updated_at) VALUES ('generic-backend-delivery','通用后端交付 SOP','{"Workflow": {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery", "name": "通用后端交付 SOP", "revision": 1, "status": "published", "description": "后端需求从需求定型到独立评审与交付。", "sandboxProfileId": "generic-docker", "generic": true, "owner": "LoopForge", "tags": ["public"], "nodes": [{"id": "clarify", "name": "需求定型", "type": "agent", "agentId": "generic-backend-delivery-clarify", "maxAttempts": 2, "position": {"x": 100, "y": 150}, "artifactOutputs": [{"name": "clarify", "path": "requirement.md", "mediaType": "text/markdown", "required": true}]}, {"id": "design", "name": "方案设计", "type": "agent", "agentId": "generic-backend-delivery-design", "maxAttempts": 2, "position": {"x": 345, "y": 150}, "artifactOutputs": [{"name": "design", "path": "design.md", "mediaType": "text/markdown", "required": true}]}, {"id": "implement", "name": "开发实现", "type": "agent", "agentId": "generic-backend-delivery-implement", "maxAttempts": 2, "position": {"x": 590, "y": 150}, "artifactOutputs": [{"name": "implement", "path": "implementation.md", "mediaType": "text/markdown", "required": true}]}, {"id": "review", "name": "独立评审", "type": "agent", "agentId": "generic-backend-delivery-review", "maxAttempts": 2, "position": {"x": 835, "y": 150}, "artifactOutputs": [{"name": "review", "path": "review.md", "mediaType": "text/markdown", "required": true}]}, {"id": "test", "name": "测试验证", "type": "agent", "agentId": "generic-backend-delivery-test", "maxAttempts": 2, "position": {"x": 1080, "y": 150}, "artifactOutputs": [{"name": "test", "path": "test-report.md", "mediaType": "text/markdown", "required": true}]}, {"id": "accept", "name": "人工验收", "type": "approval", "maxAttempts": 1, "rejectTo": "implement", "position": {"x": 1325, "y": 150}}, {"id": "deliver", "name": "交付汇总", "type": "agent", "agentId": "generic-backend-delivery-deliver", "maxAttempts": 2, "position": {"x": 1815, "y": 150}, "artifactOutputs": [{"name": "deliver", "path": "delivery.md", "mediaType": "text/markdown", "required": true}]}, {"id": "mr", "name": "发起 MR", "type": "agent", "agentId": "generic-backend-delivery-mr", "maxAttempts": 2, "position": {"x": 1570, "y": 150}, "artifactOutputs": [{"name": "mr-body", "path": "mr-body.md", "mediaType": "text/markdown", "required": true}]}], "edges": [{"id": "e-0", "source": "clarify", "target": "design", "when": "success"}, {"id": "e-1", "source": "design", "target": "implement", "when": "success"}, {"id": "e-2", "source": "implement", "target": "review", "when": "success"}, {"id": "e-3", "source": "review", "target": "test", "when": "success"}, {"id": "e-4", "source": "test", "target": "accept", "when": "success"}, {"id": "e-5", "source": "accept", "target": "mr", "when": "success"}, {"id": "e-6", "source": "mr", "target": "deliver", "when": "success"}]}, "Agents": [{"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-clarify", "name": "需求定型", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。确认目标、范围、用户、边界与可测试验收标准,输出 requirement.md。不要开始编码。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-design", "name": "方案设计", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。阅读已确认需求与可用代码,写出最小实现方案、接口影响、风险与验证计划到 design.md。未绑定仓库的新项目可在任务工作区设计和实现;修改已有系统或修复缺陷时必须取得相关源码,缺少时明确阻塞并请求补充。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-implement", "name": "开发实现", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。依据 requirement.md 和 design.md 实现需求,保持范围最小;执行适用验证,记录实现、改动和验证到 implementation.md。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-review", "name": "独立评审", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。独立审查改动及测试证据;按严重程度列出有位置与影响的缺陷及修复建议到 review.md。发现阻断问题必须明确写出 REJECT。不得伪造通过结论。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-test", "name": "测试验证", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。根据验收标准执行项目真实测试、构建及必要端到端场景。必要时修复问题并复测。将命令、退出码、结果、未验证范围写到 test-report.md。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-deliver", "name": "交付汇总", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。核对各阶段实际产物与验证证据,将完成内容、真实测试结果、已知限制及交付物清单写到 delivery.md。未绑定仓库时交付任务工作区中的源码和报告,无需 Git Token。代码已由「发起 MR」节点提交、推送并创建 MR/PR:按 mr-body.md 把链接、分支和提交 SHA 写进交付物清单;本节点不再修改代码、推送或创建 PR,不得合并。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-11-16T00:00:00Z", "id": "generic-backend-delivery-mr", "name": "发起 MR", "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。人工验收已通过,本节点把本轮代码改动提交到工作分支、推送并发起 MR/PR,不再修改业务逻辑。\\n\\n1. 未绑定代码仓库时不推送、不创建 MR/PR:在 mr-body.md 写明「未绑定代码仓库,源码保留在任务工作区」并列出交付文件,然后提交 pass。\\n2. 已绑定仓库时逐个处理每个仓库检出目录,本轮没有改动的仓库跳过,不创建空 MR/PR:确认当前在本轮工作分支上,不得在主分支提交,也不得切换或新建分支;检查 git status 与 diff,只提交本任务相关的源码改动,不提交 .agentflow、依赖目录、构建产物和 SOP 阶段文档;用概括本次改动的提交信息 commit,再 git push -u origin 当前工作分支。平台已注入 Git 凭据,不得打印、回显或写入任何令牌。\\n3. 以仓库上下文中的目标分支为目标创建 MR/PR:使用托管平台的 CLI(如 gh、glab)或已配置的 MCP,也可查阅该平台官方 API。调用 API 需要令牌时,用 git credential fill 按仓库主机获取,只在进程内存中使用。本轮工作分支已有指向同一目标分支的 MR/PR 时更新它,不重复创建。\\n4. 标题概括本次改动;描述写需求摘要、改动要点、测试结果(依据 test-report.md)和已知限制。不得合并 MR/PR,不得推送主分支或强推。\\n5. 把每个仓库的 MR/PR 链接、源分支、目标分支和提交 SHA 写到 mr-body.md。\\n6. 推送或创建 MR/PR 失败(缺少凭据、无权限、网络错误等)时不得提交 pass:在 mr-body.md 记录失败原因,提交 human,并在 actionRequired 写明需要人工处理什么,例如配置 Git Token 后重试,或到托管平台手动创建 MR。\\n\\nMR 约束:{{existingMR}}\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}", "loop": {"enabled": true, "maxIterations": 2, "exitCondition": "all_gates_pass", "onExhausted": "human"}, "verification": [{"id": "mr-pushed", "name": "改动已提交并推送", "mode": "command", "stage": "after_execution", "commands": ["fail=0\\ntab=\\"$(printf ''\\\\t'')\\"\\nwhile IFS=\\"$tab\\" read -r d work base; do\\n [ -n \\"$d\\" ] || continue\\n dirty=\\"$(git -C \\"$d\\" status --porcelain --untracked-files=all -- . \\":(exclude).agentflow\\" \\":(exclude,glob)**/node_modules/**\\")\\" || { printf \\"%s 不是可用的 Git 检出目录\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ -n \\"$dirty\\" ]; then printf \\"%s 有未提交的改动:\\\\n%s\\\\n\\" \\"$d\\" \\"$dirty\\"; fail=1; continue; fi\\n refs=HEAD\\n if git -C \\"$d\\" rev-parse -q --verify \\"refs/heads/$work\\" >/dev/null; then refs=\\"HEAD refs/heads/$work\\"; fi\\n ahead=\\"$(git -C \\"$d\\" rev-list --count $refs --not \\"refs/remotes/origin/$base\\")\\" || { printf \\"%s 找不到目标分支 origin/%s\\\\n\\" \\"$d\\" \\"$base\\"; fail=1; continue; }\\n [ \\"$ahead\\" != 0 ] || continue\\n branch=\\"$(git -C \\"$d\\" branch --show-current)\\"\\n if [ \\"$branch\\" != \\"$work\\" ]; then printf \\"%s 当前在 %s,不在本轮工作分支 %s\\\\n\\" \\"$d\\" \\"${branch:-分离的 HEAD}\\" \\"$work\\"; fail=1; continue; fi\\n head=\\"$(git -C \\"$d\\" rev-parse HEAD)\\"\\n pushed=\\"$(git -C \\"$d\\" ls-remote origin \\"refs/heads/$work\\")\\" || { printf \\"%s 无法读取远端 origin\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ \\"${pushed%%\\"$tab\\"*}\\" != \\"$head\\" ]; then printf \\"%s 的工作分支 %s 在 origin 上不是 %s,本轮提交还没推送\\\\n\\" \\"$d\\" \\"$work\\" \\"$head\\"; fail=1; fi\\ndone </dev/null; then refs=\\"HEAD refs/heads/$work\\"; fi\\n ahead=\\"$(git -C \\"$d\\" rev-list --count $refs --not \\"refs/remotes/origin/$base\\")\\" || { printf \\"%s 找不到目标分支 origin/%s\\\\n\\" \\"$d\\" \\"$base\\"; fail=1; continue; }\\n [ \\"$ahead\\" != 0 ] || continue\\n branch=\\"$(git -C \\"$d\\" branch --show-current)\\"\\n if [ \\"$branch\\" != \\"$work\\" ]; then printf \\"%s 当前在 %s,不在本轮工作分支 %s\\\\n\\" \\"$d\\" \\"${branch:-分离的 HEAD}\\" \\"$work\\"; fail=1; continue; fi\\n head=\\"$(git -C \\"$d\\" rev-parse HEAD)\\"\\n pushed=\\"$(git -C \\"$d\\" ls-remote origin \\"refs/heads/$work\\")\\" || { printf \\"%s 无法读取远端 origin\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ \\"${pushed%%\\"$tab\\"*}\\" != \\"$head\\" ]; then printf \\"%s 的工作分支 %s 在 origin 上不是 %s,本轮提交还没推送\\\\n\\" \\"$d\\" \\"$work\\" \\"$head\\"; fail=1; fi\\ndone </dev/null; then refs=\\"HEAD refs/heads/$work\\"; fi\\n ahead=\\"$(git -C \\"$d\\" rev-list --count $refs --not \\"refs/remotes/origin/$base\\")\\" || { printf \\"%s 找不到目标分支 origin/%s\\\\n\\" \\"$d\\" \\"$base\\"; fail=1; continue; }\\n [ \\"$ahead\\" != 0 ] || continue\\n branch=\\"$(git -C \\"$d\\" branch --show-current)\\"\\n if [ \\"$branch\\" != \\"$work\\" ]; then printf \\"%s 当前在 %s,不在本轮工作分支 %s\\\\n\\" \\"$d\\" \\"${branch:-分离的 HEAD}\\" \\"$work\\"; fail=1; continue; fi\\n head=\\"$(git -C \\"$d\\" rev-parse HEAD)\\"\\n pushed=\\"$(git -C \\"$d\\" ls-remote origin \\"refs/heads/$work\\")\\" || { printf \\"%s 无法读取远端 origin\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ \\"${pushed%%\\"$tab\\"*}\\" != \\"$head\\" ]; then printf \\"%s 的工作分支 %s 在 origin 上不是 %s,本轮提交还没推送\\\\n\\" \\"$d\\" \\"$work\\" \\"$head\\"; fail=1; fi\\ndone </dev/null; then refs=\\"HEAD refs/heads/$work\\"; fi\\n ahead=\\"$(git -C \\"$d\\" rev-list --count $refs --not \\"refs/remotes/origin/$base\\")\\" || { printf \\"%s 找不到目标分支 origin/%s\\\\n\\" \\"$d\\" \\"$base\\"; fail=1; continue; }\\n [ \\"$ahead\\" != 0 ] || continue\\n branch=\\"$(git -C \\"$d\\" branch --show-current)\\"\\n if [ \\"$branch\\" != \\"$work\\" ]; then printf \\"%s 当前在 %s,不在本轮工作分支 %s\\\\n\\" \\"$d\\" \\"${branch:-分离的 HEAD}\\" \\"$work\\"; fail=1; continue; fi\\n head=\\"$(git -C \\"$d\\" rev-parse HEAD)\\"\\n pushed=\\"$(git -C \\"$d\\" ls-remote origin \\"refs/heads/$work\\")\\" || { printf \\"%s 无法读取远端 origin\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ \\"${pushed%%\\"$tab\\"*}\\" != \\"$head\\" ]; then printf \\"%s 的工作分支 %s 在 origin 上不是 %s,本轮提交还没推送\\\\n\\" \\"$d\\" \\"$work\\" \\"$head\\"; fail=1; fi\\ndone </dev/null; then refs=\\"HEAD refs/heads/$work\\"; fi\\n ahead=\\"$(git -C \\"$d\\" rev-list --count $refs --not \\"refs/remotes/origin/$base\\")\\" || { printf \\"%s 找不到目标分支 origin/%s\\\\n\\" \\"$d\\" \\"$base\\"; fail=1; continue; }\\n [ \\"$ahead\\" != 0 ] || continue\\n branch=\\"$(git -C \\"$d\\" branch --show-current)\\"\\n if [ \\"$branch\\" != \\"$work\\" ]; then printf \\"%s 当前在 %s,不在本轮工作分支 %s\\\\n\\" \\"$d\\" \\"${branch:-分离的 HEAD}\\" \\"$work\\"; fail=1; continue; fi\\n head=\\"$(git -C \\"$d\\" rev-parse HEAD)\\"\\n pushed=\\"$(git -C \\"$d\\" ls-remote origin \\"refs/heads/$work\\")\\" || { printf \\"%s 无法读取远端 origin\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ \\"${pushed%%\\"$tab\\"*}\\" != \\"$head\\" ]; then printf \\"%s 的工作分支 %s 在 origin 上不是 %s,本轮提交还没推送\\\\n\\" \\"$d\\" \\"$work\\" \\"$head\\"; fail=1; fi\\ndone </dev/null; then refs=\\"HEAD refs/heads/$work\\"; fi\\n ahead=\\"$(git -C \\"$d\\" rev-list --count $refs --not \\"refs/remotes/origin/$base\\")\\" || { printf \\"%s 找不到目标分支 origin/%s\\\\n\\" \\"$d\\" \\"$base\\"; fail=1; continue; }\\n [ \\"$ahead\\" != 0 ] || continue\\n branch=\\"$(git -C \\"$d\\" branch --show-current)\\"\\n if [ \\"$branch\\" != \\"$work\\" ]; then printf \\"%s 当前在 %s,不在本轮工作分支 %s\\\\n\\" \\"$d\\" \\"${branch:-分离的 HEAD}\\" \\"$work\\"; fail=1; continue; fi\\n head=\\"$(git -C \\"$d\\" rev-parse HEAD)\\"\\n pushed=\\"$(git -C \\"$d\\" ls-remote origin \\"refs/heads/$work\\")\\" || { printf \\"%s 无法读取远端 origin\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ \\"${pushed%%\\"$tab\\"*}\\" != \\"$head\\" ]; then printf \\"%s 的工作分支 %s 在 origin 上不是 %s,本轮提交还没推送\\\\n\\" \\"$d\\" \\"$work\\" \\"$head\\"; fail=1; fi\\ndone < reports/welcome.md","maxAttempts":1,"position":{"x":100,"y":150},"artifactOutputs":[{"name":"welcome","path":"reports/welcome.md","mediaType":"text/markdown","required":true}]},{"id":"approve","name":"请确认验收报告","type":"approval","maxAttempts":1,"rejectTo":"prepare","position":{"x":370,"y":150}},{"id":"finish","name":"完成验收","type":"script","scriptLanguage":"shell","executionScope":"run","script":"printf ''# 验收完成\\\\n\\\\n审批已通过,执行成功恢复。\\\\n'' > completed.md","artifactOutputs":[{"name":"completed","path":"completed.md","mediaType":"text/markdown","required":true}],"maxAttempts":1,"position":{"x":640,"y":150}}],"edges":[{"id":"e-1","source":"prepare","target":"approve","when":"success"},{"id":"e-2","source":"approve","target":"finish","when":"success"}]}',1,1,'published'); -INSERT IGNORE INTO agents (id,name,payload,updated_at) VALUES ('baseline-align-resolver','基线对齐执行员','{"id": "baseline-align-resolver", "name": "基线对齐执行员", "version": 1, "shared": true, "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "只做基线对齐:fetch 默认分支并 merge 到当前工作分支;解决冲突时保留双方有效实现,拿不准时记录取舍。创建本地合并提交。不要自行 push 或修改默认分支,不要执行与本次基线对齐无关的测试或编写修复报告。"}',UTC_TIMESTAMP()); +INSERT IGNORE INTO agents (id,name,payload,updated_at) VALUES ('baseline-align-resolver','基线对齐执行员','{"id": "baseline-align-resolver", "name": "基线对齐执行员", "version": 1, "shared": true, "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "只做基线对齐:fetch 默认分支并 merge 到当前工作分支;解决冲突时保留双方有效实现,拿不准时记录取舍。创建本地合并提交。不要自行 push 或修改默认分支,不要执行与本次基线对齐无关的测试或编写修复报告。"}',UTC_TIMESTAMP()); COMMIT; diff --git a/scripts/test-runtime-image.sh b/scripts/test-runtime-image.sh index efff5a87..3eb39d27 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 printf 'Runtime image compatibility checks passed.\n' CHECK diff --git a/web/app/agents.js b/web/app/agents.js index aa9b56d4..5fd67c12 100644 --- a/web/app/agents.js +++ b/web/app/agents.js @@ -117,7 +117,7 @@ function syncAgentTabIndicators(){$$('#agentsView .agent-tabs, #agentModal .agen if(typeof document!=='undefined'&&document.fonts?.ready)document.fonts.ready.then(()=>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']),items=(state.data.executors||[]).filter(x=>allowed.has(x.id)),legacy=selected&&!allowed.has(selected)?``:'';return ''+legacy+items.map(x=>``).join('')} const AGENT_CUSTOM_MODEL='__custom__'; let executorModelCatalogUser, executorModelCatalogRequest, agentModelRevision=0; function executorModelCatalogs(){ @@ -130,7 +130,7 @@ function loadExecutorModelCatalogs(){ executorModelCatalogUser=user; const request={user}; request.pending=api('/api/executor-models',{silent:true}).then(data=>{ - if(executorModelCatalogRequest===request&&state.currentUser?.id===user&&data?.codebuddy&&data.codex&&data.claude){ + if(executorModelCatalogRequest===request&&state.currentUser?.id===user&&data){ window.AgentFlowExecutorModels=data; } }).catch(()=>{}).finally(()=>{ @@ -140,9 +140,10 @@ 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'); + items.unshift({id:'',name:executorId?'CLI 默认模型':'随执行器选择',icon:false}); if(current&¤t!=='default'&¤t!==AGENT_CUSTOM_MODEL&&!items.some(m=>m.id===current))items.push({id:current,name:`${current}(历史模型)`,family:'other'}); if(cat.customModel)items.push({id:AGENT_CUSTOM_MODEL,name:'手动输入模型 ID…',icon:false}); return items; @@ -242,7 +243,7 @@ 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'); + if(f.elements.executorId)f.elements.executorId.innerHTML=executorOptions(a.executorId||''); const modelRevision=++agentModelRevision; const modelUser=state.currentUser?.id; const refreshModels=loadExecutorModelCatalogs(); @@ -254,7 +255,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()!==(a.executorId||'')); } if(state.agentModalMode==='create'&&state.agentCreateStep===3)renderAgentCreateReview(); }); @@ -425,9 +426,8 @@ function saveAgent(e){ } async function persistAgent(f){ const creating=state.agentModalMode==='create'; - const changedExecutor=currentAgentExecutorId()!==(agentWizardSubject()?.executorId||'codebuddy'); const model=agentEffectiveModel(f); - if((creating||changedExecutor||f.elements.modelChoice?.value===AGENT_CUSTOM_MODEL)&&(!model||model==='default')){ + if(f.elements.modelChoice?.value===AGENT_CUSTOM_MODEL&&!model){ 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..723641f4 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,11 @@ 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}; + return catalog.models.find(m => m.id === value) || {id: value, family: familyOf(value), name: value === DEFAULT_MODEL ? '按执行身份自动选择' : value}; } function fillModelIcon(el, family, id) { if (!el) return; @@ -149,22 +148,18 @@ 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 renderCodeBuddyList(menu, selectedId, onPick) { - renderOptions(menu, codeBuddyModels(), selectedId, onPick); - } - // codeBuddyModel keeps a CodeBuddy id and turns an empty id, or a saved id - // of another CLI, into the CLI default the server resolves itself. - 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; + // A neutral default is resolved using the credentials of the executing account. + function renderFeatureList(menu, selectedId, onPick) { + const items = [{id: DEFAULT_MODEL, name: '按执行身份自动选择', icon: false}]; + for (const model of catalog.models) { + const engine = catalog.engines?.find(item => item.id === engineOf(model.id)); + if (engine && !(engine.personal ?? engine.configured)) continue; + items.push({...model, name: engine ? model.name + ' · ' + engine.name : model.name}); + } + if (selectedId && !items.some(item => item.id === selectedId)) { + items.push(modelMeta(selectedId)); + } + renderOptions(menu, items, selectedId, onPick); } async function fetchCatalog() { const resp = await fetch('/api/assistant/models', {headers: {Accept: 'application/json'}, credentials: 'same-origin'}); @@ -188,13 +183,11 @@ DEFAULT: DEFAULT_MODEL, catalog: () => catalog, cliIcon: id => Object.hasOwn(CLI_ICON, id) ? '/images/credentials/' + CLI_ICON[id] : '', - codeBuddyModel, - codeBuddyModels, engineOf, load, paint, paintItem, - renderCodeBuddyList, + renderFeatureList, renderList, renderOptions }; diff --git a/web/app/bots.js b/web/app/bots.js index 3dd63320..7b845818 100644 --- a/web/app/bots.js +++ b/web/app/bots.js @@ -1,5 +1,5 @@ function loadBotModels(){return window.AgentFlowAssistantModels?.load?.()||Promise.resolve()} -function botModelPickerHTML(bot){return `
    `} +function botModelPickerHTML(bot){return `
    `} function closeBotModelPicker(){const picker=document.querySelector('#botModelPicker');if(!picker)return;picker.querySelector('.ai-model-menu').hidden=true;picker.querySelector('[data-model-toggle]').setAttribute('aria-expanded','false')} function bindBotModelPicker(host){ const picker=host.querySelector('#botModelPicker'),models=window.AgentFlowAssistantModels; @@ -9,7 +9,7 @@ function bindBotModelPicker(host){ 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()}); + models.renderFeatureList(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; @@ -119,7 +119,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 节点触发通知后,会在这里展示发送状态。

    '; diff --git a/web/app/flows.js b/web/app/flows.js index a52efd57..d672d0b2 100644 --- a/web/app/flows.js +++ b/web/app/flows.js @@ -3,16 +3,6 @@ function workflowPreviewContract(wf){ } const PREVIEW_BUILD_NODE_ID='af-preview-build'; const PREVIEW_BUILD_AGENT_ID='af-preview-builder'; -const PREVIEW_MODEL_FALLBACK=[ - {id:'default',name:'GLM-5.3-Flash'}, - {id:'glm-5.3-ioa',name:'GLM-5.3'}, - {id:'gpt-5.6-terra',name:'GPT-5.6-Terra'}, - {id:'gpt-5.6-luna',name:'GPT-5.6-Luna'}, - {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 workflowPreviewModel(wf){ const api=window.AgentFlowAssistantModels; @@ -20,19 +10,14 @@ function workflowPreviewModel(wf){ 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){ +function fillPreviewModelSelect(sel, selected, executorId){ 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}); + const catalog=executorModelCatalogs()[executorId]; + const items=[{id:'default',name:executorId?'CLI 默认模型':'随执行器选择'},...(catalog?.models||[]).filter(m=>m.id!=='default')]; + const keep=selected||'default'; + if(!items.some(m=>m.id===keep))items.push({id:keep,name:keep}); sel.innerHTML=items.map(m=>``).join(''); + sel.disabled=!executorId||flowReadOnly(); } function ensurePreviewContract(){ const wf=state.workflow;if(!wf)return null; @@ -43,7 +28,7 @@ function ensurePreviewContract(){ ...prev, enabled:true, kind:'static', - executorId:'codebuddy', + executorId:prev.executorId||'', model, sourcePath:prev.sourcePath||'dist', indexFile:prev.indexFile||'index.html', @@ -81,7 +66,7 @@ function syncPreviewBuildGraph(){ name:'构建静态站点', type:'agent', agentId:PREVIEW_BUILD_AGENT_ID, - executorId:'codebuddy', + executorId:wf.preview.executorId||'', executionScope:'run', onFailure:'fail', retryStrategy:'targeted_fix', @@ -196,7 +181,7 @@ function addNode(type,opts={}){ if(existing){state.selectedNode=existing.id;renderCanvas();renderProperties();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:state.workflow.preview.executorId||'',executionScope:'run',onFailure:'fail',retryStrategy:'targeted_fix',maxAttempts:2,maxReworks:1,position:at,artifactOutputs:[{name:'frontend-preview',path:'dist/index.html',required:true}]}); state.selectedNode=PREVIEW_BUILD_NODE_ID; dirty();renderCanvas();renderProperties(); return; @@ -284,7 +269,7 @@ 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))return {kind:'preview',subtitle:'静态站点构建',tags:[{text:workflowPreviewModel(state.workflow)}]}; 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)); @@ -390,7 +375,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?'通用模板角色未加载':'角色不属于当前项目或未共享');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()} @@ -984,20 +969,30 @@ 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=()=>fillPreviewModelSelect(sel,workflowPreviewModel(state.workflow),executor.value); + fill(); + loadExecutorModelCatalogs().then(()=>{if(executor.isConnected)fill()}); + executor.onchange=()=>{ + flowHistory.record(); + updatePreviewContract({executorId:executor.value,model:'default'}); + 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();}; } 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..d1e04e69 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,10 @@ 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 runEvalModel(){ + return state.runEvalModel||localStorage.getItem('agentflow.runEvalModel')||window.AgentFlowAssistantModels?.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||[]; @@ -1328,7 +1329,7 @@ function runEvalPaneHTML(run){ } if(rec?.status==='failed'){ - return `
    ${heroCard}
    评测执行失败
    ${escapeHTML(rec.error||'模型未返回结果')}

    请检查个人配置中的 CodeBuddy API Key 配置或网络状态后重新评测。

    `; + return `
    ${heroCard}
    评测执行失败
    ${escapeHTML(rec.error||'模型未返回结果')}

    请检查所选 CLI 的凭据、安装状态或网络后重新评测。

    `; } if(!rec||!rec.status){ @@ -1378,7 +1379,7 @@ function bindRunEvalModelPicker(host){ 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')}); + if(open)api.renderFeatureList(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')}); } @@ -1398,7 +1399,6 @@ 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} state.runEvalBusy=true;state.runEvalThoughts=['正在提交评测…']; const host=$('#runDetail'),pane=host?.querySelector('[data-run-pane="eval"]'); if(pane){pane.innerHTML=runEvalPaneHTML(run);bindRunEvalPane(run,host)} diff --git a/web/app/sops.js b/web/app/sops.js index 0a125d6d..519808c4 100644 --- a/web/app/sops.js +++ b/web/app/sops.js @@ -95,9 +95,11 @@ function sopRunRequirements(w){ const usesRepo=(catalogGeneric(w)||(w?.tags||[]).some(t=>String(t).startsWith('generic-source:')))&&!!project?.defaultRepositoryId; const rows=[]; const providers=new Set(); + let inherited=false; for(const node of nodes.filter(n=>n.type==='agent')){ const role=(state.data?.agents||[]).find(a=>a.id===node.agentId); - const id=role?.executorId||node.executorId||'codebuddy'; + const id=(isPreviewBuildNode(node.id)?w.preview?.executorId:role?.executorId||node.executorId)||''; + inherited ||= !id; 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,7 +111,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(inherited){ + const ready=!!(user.codeBuddyApiKeyConfigured||user.codexApiKeyConfigured||user.claudeCodeApiKeyConfigured|| + Object.values(user.agentCliCredentials||{}).some(cred=>cred.apiKeyConfigured)|| + window.AgentFlowAssistantModels?.catalog().engines?.some(engine=>engine.configured)); + rows.push({key:'run-cli',fix:'settings',fixLabel:'去个人配置',label:'CLI',ok:ready,hint:'未指定 CLI 的角色使用 SOP 执行身份或部署配置的默认 CLI。'}); } 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 沙箱里运行,首次运行会构建镜像,需要几分钟。'}); diff --git a/web/app/sync-schedule.js b/web/app/sync-schedule.js index 98928edd..3d46c528 100644 --- a/web/app/sync-schedule.js +++ b/web/app/sync-schedule.js @@ -101,8 +101,6 @@ 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){ @@ -140,7 +138,7 @@ function bindClarifyModelPicker(host){ menu.hidden=!open; toggle.setAttribute('aria-expanded',open?'true':'false'); if(open){ - api.renderCodeBuddyList(menu, selectedClarifyModel(), id=>{ + api.renderFeatureList(menu, selectedClarifyModel(), id=>{ setClarifyModel(id); api.paint(toggle, id); menu.hidden=true; diff --git a/web/app/workbench.js b/web/app/workbench.js index 1b210afd..6f06b8b0 100644 --- a/web/app/workbench.js +++ b/web/app/workbench.js @@ -73,7 +73,7 @@ const CREDENTIAL_KINDS=[ placeholder:'请输入个人 ck_ key', extra:{name:'codeBuddyInternetEnvironment',label:'网络环境',options:CODEBUDDY_ENVIRONMENTS}, 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 自带模型,填写后跟随服务发布的模型;也可以自己挑选、排序和命名。', diff --git a/web/assistant_models_test.js b/web/assistant_models_test.js index b45b2f6a..0bb0616e 100644 --- a/web/assistant_models_test.js +++ b/web/assistant_models_test.js @@ -75,7 +75,7 @@ const ctx = { { 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 }], }), }), }; @@ -125,21 +125,14 @@ vm.runInContext(moduleSource, ctx); } // 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'); + assert.equal(api.engineOf('codex:gpt-5.5'), 'codex'); api.paint(toggle, api.DEFAULT); - assert.equal(label.textContent, '默认'); + assert.equal(label.textContent, '按执行身份自动选择'); assert.equal(icon.dataset.family, 'other'); - assert.equal(api.codeBuddyModels().length, 0, 'the placeholder is not selectable before loading'); 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'); // Pull the real picker helpers out of the bundle and bind them to the stub host. for (const name of ['selectedClarifyModel', 'setClarifyModel', 'bindClarifyModelPicker']) { @@ -154,18 +147,14 @@ vm.runInContext(moduleSource, ctx); 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'); + assert.equal(menu.children.length, 4, 'menu lists the neutral default and personal models'); + assert.ok(menu.children[1].className.includes('is-active'), 'stored model is marked active'); - menu.children[1].onclick(); - assert.equal(store.get('agentflow.clarifyModel'), 'model-b'); - assert.equal(input.value, 'model-b'); + menu.children.find(opt => opt.dataset.id === 'codex:gpt-5.5').onclick(); + assert.equal(store.get('agentflow.clarifyModel'), 'codex:gpt-5.5'); + assert.equal(input.value, 'codex:gpt-5.5'); assert.equal(menu.hidden, true); - assert.equal(label.textContent, 'Model B'); - - // A Codex id saved before this fix must not reach chat-clarify. - store.set('agentflow.clarifyModel', 'codex:gpt-5.5'); - assert.equal(ctx.selectedClarifyModel(), 'default'); + assert.equal(label.textContent, 'GPT-5.5'); + assert.equal(ctx.selectedClarifyModel(), 'codex:gpt-5.5'); console.log('assistant models ok'); })().catch(err => { console.error(err); process.exit(1); }); diff --git a/web/orchestrate.js b/web/orchestrate.js index 7d36327e..f50cee77 100644 --- a/web/orchestrate.js +++ b/web/orchestrate.js @@ -4,15 +4,18 @@ let aiAbort = null; const aiHistory = {}; function aiOrchestratorEngine(model) { - const listed = window.AgentFlowAssistantModels?.catalog().models.find(item => item.id === model); - return listed?.engine || (String(model || '').includes(':') ? model.split(':')[0] : 'codebuddy'); + return window.AgentFlowAssistantModels?.engineOf(model) || ''; } function selectedAIOrchestratorModel() { - const api = window.AgentFlowAssistantModels; + const catalog = window.AgentFlowAssistantModels?.catalog(); const remembered = localStorage.getItem('agentflow.orchestratorModel') || localStorage.getItem('agentflow.assistantModel'); - if (remembered && remembered !== api?.DEFAULT) return remembered; - return api?.codeBuddyModels()[0]?.id || api?.catalog().default || remembered || ''; + if (remembered && remembered !== 'default') { + const engine = aiOrchestratorEngine(remembered); + if (!catalog?.engines?.length || catalog.engines.some(item => item.id === engine && item.configured)) return remembered; + } + const model = catalog?.models?.find(item => catalog.engines?.some(engine => engine.id === aiOrchestratorEngine(item.id) && engine.configured)); + return model?.id || ''; } function aiOrchestratorModels(engine = aiOrchestratorEngine(selectedAIOrchestratorModel())) { diff --git a/web/sop_catalog_test.js b/web/sop_catalog_test.js index b0f25828..0898221f 100644 --- a/web/sop_catalog_test.js +++ b/web/sop_catalog_test.js @@ -19,6 +19,7 @@ const ctx = { percent: n => `${Math.round(n || 0)}%`, formatTimestamp: v => (v ? 'T' : ''), catalogGeneric: item => !!item?.generic, + isPreviewBuildNode: id => id === "af-preview-build", catalogOwned: projectId => !!ctx.state.projectFilter && projectId === ctx.state.projectFilter, isPlatformAdmin: () => ctx.admin, lfT: zh => zh, diff --git a/webtest/tests/assets-agents.test.mjs b/webtest/tests/assets-agents.test.mjs index b5fff6e0..1d21e237 100644 --- a/webtest/tests/assets-agents.test.mjs +++ b/webtest/tests/assets-agents.test.mjs @@ -94,6 +94,7 @@ test('agent catalog search, presets, validation, persistence, clone, and delete const form = app.document.querySelector('#agentForm'); form.elements.executorId.append(new app.window.Option('CodeBuddy', 'codebuddy')); form.elements.executorId.value = 'codebuddy'; + form.elements.executorId.dispatchEvent(new app.window.Event('change', { bubbles: true })); assert.equal(form.elements.name.value, '研发工程师'); assert.match(form.elements.id.value, /^role-/); app.evaluate(`setAgentCreateStep(3)`); @@ -138,15 +139,15 @@ test('role model picker reloads the editor catalog and preserves a CLI change wh complete(catalog([{ id: 'private/second', name: 'Second' }, { id: 'private/first', name: 'First' }])); await settle(); const menu = () => [...app.document.querySelectorAll('#agentModelPicker [role=option]')]; - assert.deepEqual(menu().map(row => row.dataset.id), ['private/second', 'private/first', '__custom__']); - assert.equal(menu()[0].querySelector('.ai-model-name').textContent, 'Second'); + assert.deepEqual(menu().map(row => row.dataset.id), ['', 'private/second', 'private/first', '__custom__']); + assert.equal(menu()[1].querySelector('.ai-model-name').textContent, 'Second'); assert.equal(f.elements.executorId.value, 'codex'); assert.equal(app.evaluate(`agentEffectiveModel($('#agentForm'))`), 'private/second'); app.router.get('/api/executor-models', () => catalog([{ id: 'private/second', name: 'Renamed model' }])); app.evaluate(`openAgentWizard({id:'role-review',name:'Review',prompt:'Review changes',executorId:'codex',model:'private/second'})`); await settle(); - assert.deepEqual(menu().map(row => row.dataset.id), ['private/second', '__custom__']); + assert.deepEqual(menu().map(row => row.dataset.id), ['', 'private/second', '__custom__']); assert.equal(app.document.querySelector('#agentModelPicker [data-model-label]').textContent, 'Renamed model'); let refresh; @@ -161,32 +162,23 @@ test('role model picker reloads the editor catalog and preserves a CLI change wh assert.equal(app.evaluate(`agentEffectiveModel($('#agentForm'))`), 'private/second'); }); -test('a new role saves the first model from the refreshed catalog', async (t) => { +test('a new role inherits its executor across model catalog refreshes', async (t) => { const app = await loadApp(); t.after(app.close); const catalog = id => ({ codebuddy: { models: [{ id }] }, codex: { models: [] }, claude: { models: [] } }); app.router.get('/api/executor-models', catalog('retired-model')); app.router.put('/api/agents', call => ({ status: 200, body: call.body })); - app.evaluate(`openAgentWizard()`); - await settle(); - const model = () => app.evaluate(`agentEffectiveModel($('#agentForm'))`); - assert.equal(model(), 'retired-model'); - app.document.querySelector('#agentModal .modal-close').click(); - - let complete; - app.router.get('/api/executor-models', () => new Promise(resolve => { complete = resolve; })); - app.evaluate(`openAgentWizard(); applyAgentPreset('developer')`); + app.evaluate("openAgentWizard(); applyAgentPreset('developer')"); await settle(); - assert.equal(model(), ''); - await app.evaluate(`persistAgent($('#agentForm'))`); - assert.equal(app.router.calls.some(call => call.path === '/api/agents' && call.method === 'PUT'), false); - app.evaluate(`setAgentCreateStep(3)`); - complete(catalog('current-model')); - await settle(); - assert.equal(model(), 'current-model'); - assert.match(app.document.querySelector('#agentCreateReview').textContent, /current-model/); - await app.evaluate(`persistAgent($('#agentForm'))`); - assert.equal(app.router.calls.find(call => call.path === '/api/agents' && call.method === 'PUT').body.model, 'current-model'); + assert.equal(app.evaluate("currentAgentExecutorId()"), ''); + assert.equal(app.evaluate("agentEffectiveModel($('#agentForm'))"), ''); + + app.router.get('/api/executor-models', catalog('current-model')); + await app.evaluate("loadExecutorModelCatalogs()"); + await app.evaluate("persistAgent($('#agentForm'))"); + const created = app.router.calls.find(call => call.path === '/api/agents' && call.method === 'PUT'); + assert.equal(created.body.executorId, ''); + assert.equal(created.body.model, ''); }); test('role effort picker follows each model and resets an unsupported level on model changes', async (t) => { diff --git a/webtest/tests/flows-editor.test.mjs b/webtest/tests/flows-editor.test.mjs index 5b040404..129f2dff 100644 --- a/webtest/tests/flows-editor.test.mjs +++ b/webtest/tests/flows-editor.test.mjs @@ -68,10 +68,15 @@ test('flow editor handles artifact/list editors and saves workflow changes', asy assert.equal(app.evaluate(`state.workflowDirty`), false); }); -test('flow preview properties update model and SPA fallback in observable state', async (t) => { +test('flow preview properties persist the CLI, model and SPA fallback', async (t) => { const app = await loadApp(); t.after(app.close); - app.evaluate(`switchView('flow');addNode('preview',{at:{x:200,y:100}});renderProperties()`); + app.router.get('/api/executor-models', {codex: {models:[{id:'preview-model',name:'Preview model'}]}}); + app.evaluate(`state.data.executors=[{id:'codex',name:'Codex'}];switchView('flow');addNode('preview',{at:{x:200,y:100}});renderProperties()`); + await app.evaluate('loadExecutorModelCatalogs()'); + const executor = app.document.querySelector('#previewNodeExecutor'); + executor.value = 'codex'; + executor.dispatchEvent(new app.window.Event('change')); const model = app.document.querySelector('#previewNodeModel'); model.value = model.options[model.options.length - 1].value; model.dispatchEvent(new app.window.Event('change')); @@ -80,7 +85,9 @@ test('flow preview properties update model and SPA fallback in observable state' spa.dispatchEvent(new app.window.Event('change')); assert.equal(app.evaluate(`state.workflow.preview.model`), model.value); assert.equal(app.evaluate(`state.workflow.preview.spaFallback`), false); - assert.match(app.document.querySelector('#properties').textContent, /CodeBuddy 模型/); + assert.equal(app.evaluate(`state.workflow.preview.executorId`), 'codex'); + assert.equal(app.evaluate(`state.workflow.nodes.find(n=>isPreviewBuildNode(n.id)).executorId`), 'codex'); + assert.equal(model.value, 'preview-model'); }); test('SOP wizard creates a workflow and publish/delete actions send expected requests', async (t) => { From f6396ed4bf7bcbc354b4ce21f9c76009cb510867 Mon Sep 17 00:00:00 2001 From: roberttwang Date: Sat, 21 Nov 2026 01:17:33 +0800 Subject: [PATCH 02/25] Preserve validation for legacy Bot model IDs --- internal/httpapi/notifications.go | 7 +++++++ internal/httpapi/notifications_test.go | 10 +++++++++- web/app/assistant-models.js | 4 +++- web/app/bots.js | 8 +++++++- 4 files changed, 26 insertions(+), 3 deletions(-) diff --git a/internal/httpapi/notifications.go b/internal/httpapi/notifications.go index c69a32b7..b620ab0d 100644 --- a/internal/httpapi/notifications.go +++ b/internal/httpapi/notifications.go @@ -158,6 +158,13 @@ func (h *notificationHandlers) save(c *gin.Context, old *domain.NotificationBot) c.JSON(400, gin.H{"error": err.Error()}) return } + // 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 } if bot.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/web/app/assistant-models.js b/web/app/assistant-models.js index 723641f4..ce744231 100644 --- a/web/app/assistant-models.js +++ b/web/app/assistant-models.js @@ -69,7 +69,9 @@ } 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 fillModelIcon(el, family, id) { if (!el) return; diff --git a/web/app/bots.js b/web/app/bots.js index 7b845818..651be6ae 100644 --- a/web/app/bots.js +++ b/web/app/bots.js @@ -9,7 +9,13 @@ function bindBotModelPicker(host){ toggle.onclick=event=>{ event.stopPropagation();if(toggle.disabled||toggle.closest('fieldset')?.disabled)return; const open=menu.hidden;closeBotModelPicker();if(!open)return; - models.renderFeatureList(menu,value.value,id=>{value.value=id;models.paint(toggle,id);captureBotDraft(host);closeBotModelPicker()}); + models.renderFeatureList(menu,value.value,id=>{ + const qualified=id!==models.DEFAULT&&models.engineOf(id)==='codebuddy'&&!id.startsWith('codebuddy:')?'codebuddy:'+id:id; + value.value=qualified; + models.paint(toggle,qualified); + 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; From 0cde746ea2f1b3d837397f397e0ac278beccfab5 Mon Sep 17 00:00:00 2001 From: roberttwang Date: Sat, 21 Nov 2026 01:49:58 +0800 Subject: [PATCH 03/25] Keep CodeBuddy defaults while allowing alternate CLIs --- README.md | 2 +- README.zh-CN.md | 2 +- chatbot/src/QuickAccessWizard.jsx | 5 ++ chatbot/src/useChat.js | 5 +- chatbot/tests/quick-access-wizard.test.jsx | 2 +- compose.yaml | 3 +- docs/deployment.md | 8 ++-- e2e/README.md | 2 +- e2e/lib/env.mjs | 2 +- e2e/local.sh | 7 +-- internal/domain/preview.go | 15 +++--- internal/domain/preview_build.go | 8 ++-- internal/domain/user.go | 14 ------ internal/domain/workflow.go | 33 ++++++------- internal/engine/align.go | 22 +++++++++ internal/engine/align_test.go | 40 ++++++++++++++++ internal/engine/assets.go | 10 ++++ internal/engine/engine_test.go | 48 ++----------------- internal/engine/node_execute.go | 14 ++---- internal/engine/preview_finalizer_test.go | 2 +- internal/engine/run_ops.go | 6 ++- internal/engine/run_start.go | 16 +++---- internal/engine/runner_dispatch.go | 2 +- internal/engine/workspace_preparation.go | 2 +- internal/httpapi/assistant.go | 2 +- internal/httpapi/assistant_approval_review.go | 4 +- internal/httpapi/assistant_engines.go | 8 ++-- internal/httpapi/assistant_generation.go | 8 ++-- internal/httpapi/catalog.go | 41 ++++++++-------- internal/httpapi/executor_models.go | 4 +- internal/httpapi/feature_model.go | 7 +-- internal/httpapi/feature_model_test.go | 6 +++ internal/httpapi/misc_cases_test.go | 11 ----- internal/httpapi/schedule.go | 4 +- internal/repo/catalog.go | 33 +------------ internal/tracker/service.go | 10 ++-- .../040_inherit_stock_sop_executors.sql | 47 ------------------ migrations/seed/001_public_catalog.sql | 12 ++--- web/app/agents.js | 14 +++--- web/app/assistant-models.js | 22 ++++++--- web/app/bots.js | 2 +- web/app/flows.js | 16 ++++--- web/app/runs.js | 5 +- web/app/sops.js | 17 +++---- web/app/sync-schedule.js | 8 ++-- web/assistant-models.css | 1 + web/assistant_models_test.js | 11 ++++- web/orchestrate.js | 6 +-- web/sop_catalog_test.js | 1 + webtest/tests/assets-agents.test.mjs | 38 +++++++++------ webtest/tests/flows-editor.test.mjs | 10 +++- 51 files changed, 292 insertions(+), 326 deletions(-) delete mode 100644 migrations/040_inherit_stock_sop_executors.sql diff --git a/README.md b/README.md index b5ba9a7c..04b4b472 100644 --- a/README.md +++ b/README.md @@ -111,7 +111,7 @@ New accounts join the **LoopForge demo project**, which includes an SOP made onl
    -- **Executors.** Choose a CLI and model for chat, requirement clarification, Bot replies, notification reports, run evaluation, or static preview. SOP roles can pin an executor or inherit the default selected for the responsible account. Scheduled prompts use the CLI selected on the schedule. The platform can run without a CodeBuddy installation or key. [Deployment and upgrade](docs/deployment.md#choosing-an-executor) +- **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 | | --- | --- | --- | diff --git a/README.zh-CN.md b/README.zh-CN.md index 844082c7..458de657 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -111,7 +111,7 @@ GitLab、Gitea、Gogs 等托管可[配置 Git SSH](docs/deployment.md#git-reposi
    -- **执行器。** 首页对话、需求澄清、Bot 回复、通知汇报、运行评测和静态预览均可选择 CLI 与模型。SOP 角色可以指定执行器,也可以继承责任人或部署配置的默认执行器。定时提示词使用任务所选的 CLI。平台可以在未安装 CodeBuddy、未配置其 Key 的环境中运行。详见[部署与升级说明](docs/deployment.md#choosing-an-executor)。 +- **执行器。** 首页对话、需求澄清、Bot 回复、通知汇报、运行评测和静态预览均可选择 CLI 与模型。每个 SOP 角色可以独立选择 CLI,内置模板仍默认使用 CodeBuddy。定时提示词使用任务所选的 CLI。将使用中的流程配置为其他 CLI 后,平台可在未安装 CodeBuddy、未配置其 Key 的环境中运行。[部署与升级说明](docs/deployment.md#choosing-an-executor) | 执行器 | 凭据 | 安装方式 | | --- | --- | --- | diff --git a/chatbot/src/QuickAccessWizard.jsx b/chatbot/src/QuickAccessWizard.jsx index caa73bee..ab77be5b 100644 --- a/chatbot/src/QuickAccessWizard.jsx +++ b/chatbot/src/QuickAccessWizard.jsx @@ -701,6 +701,7 @@ async function provisionFallbackProjectSOP(projectId, workflowId, owner) { name: role.name, projectId, version: 1, + executorId: "codebuddy", description: role.description, prompt: role.prompt, artifactOutputs: [ @@ -1290,6 +1291,10 @@ export default function QuickAccessWizard({ if (saving) return; setError(""); if (activeStep.id === "auth") { + if (!gitReady && !hasSSHKeys && !cliReady) { + setError("请先配置 GitHub Git Token、Git SSH 密钥或一种模型 CLI 的凭据。"); + return; + } setSaving(true); try { await saveTypedCredentials(); diff --git a/chatbot/src/useChat.js b/chatbot/src/useChat.js index 4d47a66e..06bde4ed 100644 --- a/chatbot/src/useChat.js +++ b/chatbot/src/useChat.js @@ -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 { personalEngineConfigured, EXECUTORS, concreteModel, conversationEngine, engineModels, engineOfModel } from "./engines.js"; +import { EXECUTORS, concreteModel, conversationEngine, engineModels, engineOfModel } from "./engines.js"; import { readComposerPreference, useComposerOptions, writeComposerPreference } from "./composer-preferences.js"; import { enqueue, @@ -635,12 +635,11 @@ export function useChat() { useEffect(() => { if (!user || user.isGuest || activeId || submitting || !catalogEngines.length || readComposerPreference("executor")) return; - const choices = catalogEngines.filter(engine => engine.configured); // Account-authenticated runners advertise their runtime independently of // the personal API catalog. Keep a selected CLI if that machine can run it. const machine = executionMachines.machines.find(item => item.id === executionMachines.defaultRunnerId); if (machine?.runtimes?.some(runtime => runtime.provider === executor && runtime.authMode !== "personal")) return; - const next = choices.find(engine => personalEngineConfigured(user, engine.id)) || choices[0]; + const next = catalogEngines.find(engine => engine.configured); if (next && next.id !== executor) setSelection({ executor: next.id, model: null, effort: null }); }, [user, activeId, submitting, catalogEngines, executor, executionMachines.machines, executionMachines.defaultRunnerId]); function resolveComposerModel( diff --git a/chatbot/tests/quick-access-wizard.test.jsx b/chatbot/tests/quick-access-wizard.test.jsx index 5883ae00..46b59ea8 100644 --- a/chatbot/tests/quick-access-wizard.test.jsx +++ b/chatbot/tests/quick-access-wizard.test.jsx @@ -203,7 +203,7 @@ describe("QuickAccessWizard", () => { ); 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.getByRole("alert")).toHaveTextContent("请先配置 GitHub Git Token、Git SSH 密钥或一种模型 CLI 的凭据"); expect(screen.queryByText(/工蜂/)).toBeNull(); await userAction.click(screen.getByText("使用访问令牌(高级)")); await userAction.type( diff --git a/compose.yaml b/compose.yaml index 214cce21..9fbecd75 100644 --- a/compose.yaml +++ b/compose.yaml @@ -36,9 +36,8 @@ services: AGENTFLOW_ASSISTANT_SESSION_DIR: /data/assistant AGENTFLOW_CONVERSATION_DIR: ${LOOPFORGE_DATA_DIR}/conversations AGENTFLOW_CLARIFY_SESSION_DIR: /data/clarify - AGENTFLOW_DEFAULT_EXECUTOR: ${AGENTFLOW_DEFAULT_EXECUTOR:-} + AGENTFLOW_BASELINE_ALIGN_EXECUTOR: ${AGENTFLOW_BASELINE_ALIGN_EXECUTOR:-} AGENTFLOW_SKIP_CODEBUDDY_INSTALL: ${AGENTFLOW_SKIP_CODEBUDDY_INSTALL:-} - AGENTFLOW_TRACKER_CODEBUDDY_AUTH: ${AGENTFLOW_TRACKER_CODEBUDDY_AUTH:-} AGENTFLOW_ASSISTANT_MODEL: ${AGENTFLOW_ASSISTANT_MODEL:-} AGENTFLOW_ASSISTANT_MODELS: ${AGENTFLOW_ASSISTANT_MODELS:-} AGENTFLOW_PREVIEW_PUBLIC_URL: ${AGENTFLOW_PREVIEW_PUBLIC_URL:-} diff --git a/docs/deployment.md b/docs/deployment.md index 6d573843..53410851 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -33,12 +33,12 @@ Use `AGENTFLOW_MYSQL_DSN` for your own MySQL deployment. A fresh account command ## Choosing an executor -- The model pickers for requirement clarification, Bot replies, SOP notification reports and run evaluation 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` follows a configured personal CLI. A concrete model is passed unchanged to its CLI. +- The model pickers for requirement clarification, Bot replies, SOP notification reports and run evaluation 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 existing CodeBuddy default when the account has a personal CodeBuddy key and uses the first configured alternative otherwise. A concrete model is passed unchanged to its CLI. - 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 preview builds can specify a CLI. An unset executor inherits the run's default. `AGENTFLOW_DEFAULT_EXECUTOR` sets the deployment default using a built-in executor ID such as `codex` or `claude`. When unset, the first compatible CLI with personal credentials or the responsible account's runner login is chosen in catalog order. Installations relying on the shared CodeBuddy credential keep the historical default. The default is recorded in new run snapshots. -- On existing databases, operators can apply `migrations/040_inherit_stock_sop_executors.sql` to move stock version-one templates and the stock baseline resolver to inheritance. Operators can also select inheritance in the role editor for existing project copies. Explicit role executors and models continue to work. New installs use the updated seed. +- 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 takes headers from the catalog or `AGENTFLOW_MCP_TOKEN`. Installations that rely on host CodeBuddy OAuth can opt in with `AGENTFLOW_TRACKER_CODEBUDDY_AUTH=1`. +- Tracker MCP authentication uses the catalog's headers or `AGENTFLOW_MCP_TOKEN` before trying the legacy host CodeBuddy OAuth fallback. ## Container installation diff --git a/e2e/README.md b/e2e/README.md index 126d33a8..56edb5c2 100644 --- a/e2e/README.md +++ b/e2e/README.md @@ -36,7 +36,7 @@ AGENTFLOW_E2E_CODEBUDDY_API_KEY=ck_... ./local.sh api/40-model.test.mjs # 带 | `AGENTFLOW_E2E_MODEL_ID` | 真实 Agent 节点使用的模型 ID,例如 `deepseek-v4.1-flash` | | `AGENTFLOW_E2E_CLI_KEY` | 本地实测时所选 CLI 的个人凭据 | | `AGENTFLOW_E2E_CLI_BASE_URL` | 本地实测可选的自定义模型网关 | -| `AGENTFLOW_E2E_EXECUTOR` | 执行器,默认 `codex` | +| `AGENTFLOW_E2E_EXECUTOR` | 执行器,默认 `codebuddy` | | `AGENTFLOW_E2E_SANDBOX` | 沙箱,默认 `local`,仅对可信的验收任务使用 | | `AGENTFLOW_E2E_MODEL_SANDBOX` | 真实模型用例使用的沙箱,镜像里要有执行器 CLI;默认同 `AGENTFLOW_E2E_SANDBOX` | | `AGENTFLOW_E2E_REPO_CLONE_URL` | 带代码仓库的用例克隆这个仓库(只读,不推送)。不设置就跳过这些用例;`local.sh` 会自动设成本机裸仓库 | diff --git a/e2e/lib/env.mjs b/e2e/lib/env.mjs index 212a0763..c3c20df5 100644 --- a/e2e/lib/env.mjs +++ b/e2e/lib/env.mjs @@ -38,7 +38,7 @@ export const cfg = { projectId: process.env.AGENTFLOW_E2E_PROJECT || 'e2e-auto', // Real-model scenarios are opt-in because they consume model credits. model: flag('AGENTFLOW_E2E_MODEL', false), - executor: process.env.AGENTFLOW_E2E_EXECUTOR || 'codex', + executor: process.env.AGENTFLOW_E2E_EXECUTOR || 'codebuddy', modelID: process.env.AGENTFLOW_E2E_MODEL_ID || '', sandbox: process.env.AGENTFLOW_E2E_SANDBOX || 'local', keep: flag('AGENTFLOW_E2E_KEEP', false), diff --git a/e2e/local.sh b/e2e/local.sh index 7c2c62eb..8244638d 100755 --- a/e2e/local.sh +++ b/e2e/local.sh @@ -11,7 +11,7 @@ # for the repository-bound scenarios, and removes all of it afterwards. # # Optional environment: -# AGENTFLOW_E2E_EXECUTOR CLI executor ID (default codex) +# 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 @@ -112,10 +112,7 @@ 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 [ -z "${AGENTFLOW_E2E_EXECUTOR:-}" ] && [ -n "${AGENTFLOW_E2E_CODEBUDDY_API_KEY:-}" ]; then - export AGENTFLOW_E2E_EXECUTOR=codebuddy -fi -export AGENTFLOW_E2E_EXECUTOR=${AGENTFLOW_E2E_EXECUTOR:-codex} +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. diff --git a/internal/domain/preview.go b/internal/domain/preview.go index ad9c0d32..77271247 100644 --- a/internal/domain/preview.go +++ b/internal/domain/preview.go @@ -35,6 +35,7 @@ const ( PreviewBuildNodeID = "af-preview-build" PreviewBuildAgentID = "af-preview-builder" + PreviewBuildExecutor = "codebuddy" PreviewDefaultModel = "default" PreviewDefaultSource = "dist" PreviewBuildEdgeID = "af-preview-build-edge" @@ -48,7 +49,7 @@ const ( type PreviewContract struct { Enabled bool `json:"enabled"` Kind string `json:"kind"` // static; later service/environment - ExecutorID string `json:"executorId,omitempty"` // optional CLI executor; empty inherits the workflow default + ExecutorID string `json:"executorId,omitempty"` // CLI executor; defaults to CodeBuddy 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 @@ -94,11 +95,13 @@ func (c *PreviewContract) SourceOrDist() string { return PreviewDefaultSource } -func (c *PreviewContract) Executor() string { - if c == nil { - return "" +func (c *PreviewContract) ExecutorOrCodeBuddy() string { + if c != nil { + if id := strings.TrimSpace(c.ExecutorID); id != "" { + return id + } } - return strings.TrimSpace(c.ExecutorID) + return PreviewBuildExecutor } func (c *PreviewContract) ModelOrDefault() string { @@ -131,7 +134,7 @@ func (c *PreviewContract) Normalize() { return } c.Kind = c.KindOrStatic() - c.ExecutorID = c.Executor() + c.ExecutorID = c.ExecutorOrCodeBuddy() c.Model = c.ModelOrDefault() c.SourcePath = c.SourceOrDist() c.IndexFile = c.Index() diff --git a/internal/domain/preview_build.go b/internal/domain/preview_build.go index 102a1f33..ebe02980 100644 --- a/internal/domain/preview_build.go +++ b/internal/domain/preview_build.go @@ -46,9 +46,9 @@ func AttachPreviewBuild(wf WorkflowDefinition) (WorkflowDefinition, error) { 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.Executor() { + if node.ExecutorID != wf.Preview.ExecutorOrCodeBuddy() { wf.Nodes = append([]WorkflowNode(nil), wf.Nodes...) - wf.Nodes[i].ExecutorID = wf.Preview.Executor() + wf.Nodes[i].ExecutorID = wf.Preview.ExecutorOrCodeBuddy() } return wf, nil } @@ -75,7 +75,7 @@ func PreviewBuildNode(wf WorkflowDefinition) WorkflowNode { Name: "构建静态站点", Type: "agent", AgentID: PreviewBuildAgentID, - ExecutorID: contract.Executor(), + ExecutorID: contract.ExecutorOrCodeBuddy(), ExecutionScope: ExecutionScopeRun, ArtifactOutputs: []ArtifactContract{PreviewBuildArtifact(contract)}, OnFailure: "fail", @@ -93,7 +93,7 @@ func PreviewBuildAgent(contract *PreviewContract) AgentDefinition { ID: PreviewBuildAgentID, Name: "构建静态站点", Description: "系统步骤:构建可托管的静态站点并归档为预览。", - ExecutorID: contract.Executor(), + ExecutorID: contract.ExecutorOrCodeBuddy(), Model: contract.ModelOrDefault(), Prompt: PreviewBuildPrompt(contract), ArtifactOutputs: []ArtifactContract{PreviewBuildArtifact(contract)}, diff --git a/internal/domain/user.go b/internal/domain/user.go index bcae25ae..d5502629 100644 --- a/internal/domain/user.go +++ b/internal/domain/user.go @@ -45,20 +45,6 @@ type User struct { UpdatedAt time.Time `json:"updatedAt"` } -// CLIAPIKey returns the personal credential for a CLI provider kind. -func (u User) CLIAPIKey(kind string) string { - switch kind { - case "codebuddy": - return strings.TrimSpace(u.CodeBuddyAPIKey) - case "codex": - return strings.TrimSpace(u.CodexAPIKey) - case "claude-code": - return strings.TrimSpace(u.ClaudeCodeAPIKey) - default: - return strings.TrimSpace(u.AgentCLICredentials[kind].APIKey) - } -} - 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 559b8f69..59175e63 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. @@ -177,9 +177,6 @@ type WorkflowDefinition struct { // the resolved profile plus Dockerfile/environment payload so retries can // reconstruct the original environment after catalog definitions change. SandboxSnapshot *RunnerSandboxSpec `json:"sandboxSnapshot,omitempty"` - // DefaultExecutorID freezes the executor inherited by unconfigured SOP - // roles. It is assigned by the engine when creating a run snapshot. - DefaultExecutorID string `json:"defaultExecutorId,omitempty"` // Preview is the optional frontend delivery contract. It is frozen into // the run snapshot so later SOP edits cannot change an in-flight archive. Preview *PreviewContract `json:"preview,omitempty"` 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..23ede28d 100644 --- a/internal/engine/assets.go +++ b/internal/engine/assets.go @@ -208,6 +208,16 @@ func workflowAgent(st *repo.Store, wf domain.WorkflowDefinition, id string) (dom 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/engine_test.go b/internal/engine/engine_test.go index 35b6df62..57d1b8ac 100644 --- a/internal/engine/engine_test.go +++ b/internal/engine/engine_test.go @@ -2804,46 +2804,6 @@ func TestRecoverMisplacedArtifactsCopiesHostLeakIntoSandbox(t *testing.T) { } } -func TestRunFreezesInheritedExecutorForRolesAndPreview(t *testing.T) { - t.Setenv("AGENTFLOW_DEFAULT_EXECUTOR", "") - store, err := repo.OpenTest() - if err != nil { - t.Fatal(err) - } - defer store.Close() - responsible := domain.User{ID: 701, LoginName: "codex-worker", CodexAPIKey: "test-only"} - if err := store.PutUser(responsible); err != nil { - t.Fatal(err) - } - role := domain.AgentDefinition{ID: "inherited-role", Name: "Inherited role"} - if err := store.PutAgent(role); err != nil { - t.Fatal(err) - } - eng := New(store, runtime.NewManager(t.TempDir())) - eng.ConfigureExecution("", "", 0, false) - wf := domain.WorkflowDefinition{ - ID: "inherit-executor", Name: "Inherited executor", SandboxProfileID: "local", - Nodes: []domain.WorkflowNode{{ID: "work", Name: "Work", Type: "agent", AgentID: role.ID}}, - Preview: &domain.PreviewContract{Enabled: true}, - } - run, err := eng.startWorkflowDefinition(wf, "", nil, domain.TelemetryContext{ProjectID: "platform", ResponsibleUserID: responsible.ID}, false) - if err != nil { - t.Fatal(err) - } - t.Setenv("AGENTFLOW_DEFAULT_EXECUTOR", "claude") - snapshot := run.WorkflowSnapshot - if snapshot.DefaultExecutorID != "codex" { - t.Fatalf("stored default = %q", snapshot.DefaultExecutorID) - } - for _, node := range snapshot.Nodes { - agent, _ := workflowAgent(store, snapshot, node.AgentID) - ex, err := resolveNodeExecutor(store, node, agent, snapshot.DefaultExecutorID) - if err != nil || ex.Kind != "codex" { - t.Fatalf("node %s resolved to %q: %v", node.ID, ex.Kind, err) - } - } -} - func TestResolveNodeExecutorPrefersAgentModel(t *testing.T) { t.Parallel() s, err := repo.OpenTest() @@ -2852,7 +2812,7 @@ func TestResolveNodeExecutorPrefersAgentModel(t *testing.T) { } defer s.Close() agent := domain.AgentDefinition{ID: "analyst", Name: "Analyst", ExecutorID: "codebuddy", Model: "agent-model"} - got, err := resolveNodeExecutor(s, domain.WorkflowNode{AgentID: "analyst", ExecutorID: "mock"}, agent, "") + got, err := resolveNodeExecutor(s, domain.WorkflowNode{AgentID: "analyst", ExecutorID: "mock"}, agent) if err != nil { t.Fatal(err) } @@ -2863,7 +2823,7 @@ func TestResolveNodeExecutorPrefersAgentModel(t *testing.T) { t.Fatalf("model = %s, want agent override", got.Model) } agentEffort := domain.AgentDefinition{ID: "analyst", Name: "Analyst", ExecutorID: "codex", Effort: "xhigh"} - withEffort, err := resolveNodeExecutor(s, domain.WorkflowNode{AgentID: "analyst"}, agentEffort, "") + withEffort, err := resolveNodeExecutor(s, domain.WorkflowNode{AgentID: "analyst"}, agentEffort) if err != nil { t.Fatal(err) } @@ -2873,14 +2833,14 @@ func TestResolveNodeExecutorPrefersAgentModel(t *testing.T) { if err := s.PutExecutor(domain.ExecutorDefinition{ID: "legacy-codex", Name: "Legacy Codex", Kind: "codex", Binary: "custom-codex", Args: []string{"unsafe"}, Model: "legacy-model"}); err != nil { t.Fatal(err) } - legacy, err := resolveNodeExecutor(s, domain.WorkflowNode{ExecutorID: "legacy-codex"}, domain.AgentDefinition{ID: "legacy"}, "") + legacy, err := resolveNodeExecutor(s, domain.WorkflowNode{ExecutorID: "legacy-codex"}, domain.AgentDefinition{ID: "legacy"}) if err != nil { t.Fatal(err) } if legacy.ID != "codex" || legacy.Binary != "codex" || legacy.Model != "legacy-model" { t.Fatalf("legacy executor was not safely mapped to the built-in CLI: %+v", legacy) } - _, err = resolveNodeExecutor(s, domain.WorkflowNode{ExecutorID: "custom"}, domain.AgentDefinition{ID: "legacy"}, "") + _, err = resolveNodeExecutor(s, domain.WorkflowNode{ExecutorID: "custom"}, domain.AgentDefinition{ID: "legacy"}) if err == nil || !strings.Contains(err.Error(), "not found") { t.Fatalf("custom executor must be rejected: %v", err) } diff --git a/internal/engine/node_execute.go b/internal/engine/node_execute.go index 53db3418..5ca17b72 100644 --- a/internal/engine/node_execute.go +++ b/internal/engine/node_execute.go @@ -186,16 +186,12 @@ func (e *Engine) execute(ctx context.Context, runID string) { } } -func resolveNodeExecutor(st *repo.Store, node domain.WorkflowNode, agent domain.AgentDefinition, defaultExecutorID string) (domain.ExecutorDefinition, error) { - executorID := strings.TrimSpace(agent.ExecutorID) +func resolveNodeExecutor(st *repo.Store, node domain.WorkflowNode, agent domain.AgentDefinition) (domain.ExecutorDefinition, error) { + executorID := agent.ExecutorID if executorID == "" { - executorID = strings.TrimSpace(node.ExecutorID) + executorID = node.ExecutorID } if executorID == "" { - executorID = defaultExecutorID - } - if executorID == "" { - // Runs created before the inherited executor was frozen used CodeBuddy. executorID = "codebuddy" } ex, found := repo.BuiltInExecutor(executorID) @@ -237,7 +233,7 @@ 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, wf.DefaultExecutorID) + executor, err := resolveNodeExecutor(st, node, agent) if err != nil { return runtime.SandboxRequirements{}, err } @@ -693,7 +689,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, wf.DefaultExecutorID) + ex, errResolve := resolveNodeExecutor(e.repo, node, agent) if errResolve != nil { err = errResolve break diff --git a/internal/engine/preview_finalizer_test.go b/internal/engine/preview_finalizer_test.go index cdf1f03f..055e7ece 100644 --- a/internal/engine/preview_finalizer_test.go +++ b/internal/engine/preview_finalizer_test.go @@ -208,7 +208,7 @@ func TestStartInjectsPreviewBuildNode(t *testing.T) { t.Fatalf("catalog SOP must stay without the injected node: %+v", stored.Nodes) } agent, ok := workflowAgent(store, run.WorkflowSnapshot, domain.PreviewBuildAgentID) - if !ok || agent.ExecutorID != "" || agent.Model != "gpt-5.6-terra" { + if !ok || agent.ExecutorID != domain.PreviewBuildExecutor || agent.Model != "gpt-5.6-terra" { t.Fatalf("synthetic agent = %+v ok=%v", agent, ok) } } diff --git a/internal/engine/run_ops.go b/internal/engine/run_ops.go index 2e86ce6e..f96c334f 100644 --- a/internal/engine/run_ops.go +++ b/internal/engine/run_ops.go @@ -844,8 +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 - latest.DefaultExecutorID = r.WorkflowSnapshot.DefaultExecutorID - var err error + latest, err := configureBaselineAlignCLI(latest) + if err != nil { + return err + } latest, err = domain.AttachPreviewBuild(latest) if err != nil { return err diff --git a/internal/engine/run_start.go b/internal/engine/run_start.go index 22fd0ffc..70c5aa63 100644 --- a/internal/engine/run_start.go +++ b/internal/engine/run_start.go @@ -2,7 +2,6 @@ package engine import ( "agentflow/internal/domain" - "agentflow/internal/repo" "context" "fmt" "strings" @@ -91,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 } @@ -111,6 +114,9 @@ func (e *Engine) startWorkflowDefinition(wf domain.WorkflowDefinition, input str if err != nil { return domain.Run{}, err } + if _, err := workflowSandboxRequirements(e.repo, wf); err != nil { + return domain.Run{}, err + } now := time.Now().UTC() id := fmt.Sprintf("run-%d", now.UnixNano()) assignWorkBranches(repositories, func() string { @@ -146,12 +152,6 @@ func (e *Engine) startWorkflowDefinition(wf domain.WorkflowDefinition, input str } else { executionContext.ExecutionMode = domain.ExecutionModeCloud } - responsible, _ := e.repo.User(executionContext.ResponsibleUserID) - runner, _ := e.repo.Runner(executionContext.ExecutionRunnerID) - wf.DefaultExecutorID = repo.DefaultExecutorID(responsible, runner) - if _, err := workflowSandboxRequirements(e.repo, wf); err != nil { - return domain.Run{}, err - } if err := e.requireWorkBranchCapabilities(executionContext.ExecutionRunnerID, repositories); err != nil { return domain.Run{}, err } diff --git a/internal/engine/runner_dispatch.go b/internal/engine/runner_dispatch.go index efa732ea..82d1cc3d 100644 --- a/internal/engine/runner_dispatch.go +++ b/internal/engine/runner_dispatch.go @@ -527,7 +527,7 @@ func (e *Engine) validateExecutionReconnect(run domain.Run, nodeID string) error if !found { return fmt.Errorf("无法重连原执行环境:agent %s 不存在", node.AgentID) } - executor, err := resolveNodeExecutor(e.repo, node, agent, run.WorkflowSnapshot.DefaultExecutorID) + executor, err := resolveNodeExecutor(e.repo, node, agent) if err != nil { return fmt.Errorf("无法重连原执行环境:%w", err) } diff --git a/internal/engine/workspace_preparation.go b/internal/engine/workspace_preparation.go index e9fd9db8..a599845a 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, wf.DefaultExecutorID) + executor, err := resolveNodeExecutor(st, node, agent) if err != nil { continue } diff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.go index e50b83b7..70869f51 100644 --- a/internal/httpapi/assistant.go +++ b/internal/httpapi/assistant.go @@ -170,7 +170,7 @@ func (h *assistantHandlers) chat(c *gin.Context) { } req.ExecutionTarget = target } - req.Model = assistantChatRequestModel(req, old, stored) + req.Model = h.assistantChatRequestModel(req, old, stored) cliEngine, _ := assistantModelEngine(req.Model) loginRunner := h.assistantLoginRunner(stored.ID, req.ExecutionTarget, cliEngine) runnerLogin := loginRunner.ID != "" diff --git a/internal/httpapi/assistant_approval_review.go b/internal/httpapi/assistant_approval_review.go index 51e20b43..a2a5d911 100644 --- a/internal/httpapi/assistant_approval_review.go +++ b/internal/httpapi/assistant_approval_review.go @@ -140,9 +140,9 @@ 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) selected := assistantRequestModel(req.Executor, req.Model) - engine, id := assistantModelEngine(selected) + engine, _ := assistantModelEngine(selected) var models []string - if id != "" && !codeBuddyIsDefaultModel(id) || engine != assistantEngineCodeBuddy { + if engine != assistantEngineCodeBuddy || (req.RequireExactModel && selected != "") { models = []string{selected} } else if h.reviewCatalog != nil { models = assistantApprovalReviewModels(h.reviewCatalog(user.CodeBuddyInternetEnvironment)) diff --git a/internal/httpapi/assistant_engines.go b/internal/httpapi/assistant_engines.go index d11fd894..66942146 100644 --- a/internal/httpapi/assistant_engines.go +++ b/internal/httpapi/assistant_engines.go @@ -667,13 +667,15 @@ func writeAssistantEngineState(root string, state assistantEngineState) error { // assistantChatRequestModel keeps an existing conversation's model when // omitted, or chooses a personal CLI for a new conversation with no selection. -func assistantChatRequestModel(req assistantRequest, saved domain.AssistantSession, user domain.User) string { +func (h *assistantHandlers) assistantChatRequestModel(req assistantRequest, saved domain.AssistantSession, user domain.User) string { if strings.TrimSpace(req.Executor) == "" && (strings.TrimSpace(req.Model) == "" || req.Model == assistantDefaultModel) { if saved.Model != "" || saved.Executor != "" { return assistantRequestModel(saved.Executor, saved.Model) } - if model, err := resolveFeatureModel(user, ""); err == nil { - return model + if _, _, codeBuddyAvailable := h.assistantChatUser(user); !codeBuddyAvailable { + if model, err := resolveFeatureModel(user, ""); err == nil { + return model + } } } return assistantRequestModel(req.Executor, req.Model) diff --git a/internal/httpapi/assistant_generation.go b/internal/httpapi/assistant_generation.go index ab97549b..65daa122 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 { @@ -84,7 +84,7 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) { return } } - req.Model = assistantChatRequestModel(req, old, stored) + req.Model = h.assistantChatRequestModel(req, old, stored) cliEngine, _ := assistantModelEngine(req.Model) loginRunner := h.assistantLoginRunner(stored.ID, req.ExecutionTarget, cliEngine) runnerLogin := loginRunner.ID != "" @@ -499,7 +499,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) @@ -562,7 +562,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 := assistantChatCatalog(c.Request.Context(), user.CodeBuddyInternetEnvironment, nil) + var catalog assistantModelCatalog if engine, _ := assistantModelEngine(model); engine == assistantEngineCodeBuddy { catalog = h.turnCatalog(c.Request.Context(), user, model) } diff --git a/internal/httpapi/catalog.go b/internal/httpapi/catalog.go index 27811d69..6237061b 100644 --- a/internal/httpapi/catalog.go +++ b/internal/httpapi/catalog.go @@ -307,24 +307,6 @@ func (h *catalogHandlers) repository(c *gin.Context) { c.JSON(http.StatusOK, domain.PublicRepository(repository)) } -func validateCatalogAgentCLI(agent *domain.AgentDefinition) error { - agent.ExecutorID = strings.TrimSpace(agent.ExecutorID) - if agent.ExecutorID == "" { - if strings.TrimSpace(agent.Model) == assistantDefaultModel { - agent.Model = "" - } - if strings.TrimSpace(agent.Model) != "" || strings.TrimSpace(agent.Effort) != "" { - return fmt.Errorf("指定模型或思考强度前请先选择 CLI") - } - return nil - } - executor, ok := repo.BuiltInExecutor(agent.ExecutorID) - if !ok { - return fmt.Errorf("不支持的 CLI:%s", agent.ExecutorID) - } - return domain.ValidateAgentEffort(agent.Effort, executor.Kind) -} - func (h *catalogHandlers) agents(c *gin.Context) { if c.Request.Method == http.MethodGet { agents := h.repo.Agents() @@ -358,7 +340,15 @@ func (h *catalogHandlers) agents(c *gin.Context) { if !h.requireProjectWriter(c, v.ProjectID) { return } - if err := validateCatalogAgentCLI(&v); err != nil { + 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 { c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()}) return } @@ -1074,8 +1064,7 @@ func (h *catalogHandlers) workflows(c *gin.Context) { return } - v.DefaultExecutorID = "" - if id := v.Preview.Executor(); v.Preview.Static() && id != "" { + if id := v.Preview.ExecutorOrCodeBuddy(); v.Preview.Static() { if _, supported := repo.BuiltInExecutor(id); !supported { c.JSON(http.StatusBadRequest, gin.H{"error": "前端预览使用了不支持的 CLI:" + id}) return @@ -1275,7 +1264,15 @@ func (h *catalogHandlers) workflow(c *gin.Context) { if !decode(c, &agent) { return } - if err := validateCatalogAgentCLI(&agent); err != nil { + 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 { c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()}) return } diff --git a/internal/httpapi/executor_models.go b/internal/httpapi/executor_models.go index c96344a3..39399c65 100644 --- a/internal/httpapi/executor_models.go +++ b/internal/httpapi/executor_models.go @@ -221,7 +221,9 @@ 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) + if key := strings.TrimSpace(user.CodeBuddyAPIKey); key != "" { + refreshCLIModels(c.Request.Context(), user.CodeBuddyInternetEnvironment, key) + } } } _, kimiBaseURL := assistantEngineCredential(user, runtime.AgentCLIKimi) diff --git a/internal/httpapi/feature_model.go b/internal/httpapi/feature_model.go index a3d224b6..5075570b 100644 --- a/internal/httpapi/feature_model.go +++ b/internal/httpapi/feature_model.go @@ -53,12 +53,13 @@ func resolveFeatureModel(user domain.User, requested string) (string, error) { } func featureDefaultModel(user domain.User, engine string) string { - if models := assistantSavedModels(user, engine); len(models) > 0 { - return engine + ":" + models[0].ID - } 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 } diff --git a/internal/httpapi/feature_model_test.go b/internal/httpapi/feature_model_test.go index 78924f6d..0a67f0b5 100644 --- a/internal/httpapi/feature_model_test.go +++ b/internal/httpapi/feature_model_test.go @@ -23,6 +23,9 @@ 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"}} for _, tc := range []struct { user domain.User in string @@ -31,6 +34,9 @@ func TestFeatureModelPreservesExplicitChoice(t *testing.T) { {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"}, {codeBuddyUser, "deepseek-v4.1-flash", "deepseek-v4.1-flash"}, {codeBuddyUser, "codebuddy:deepseek-v4.1-flash", "codebuddy:deepseek-v4.1-flash"}, } { diff --git a/internal/httpapi/misc_cases_test.go b/internal/httpapi/misc_cases_test.go index 5f148428..19d1017a 100644 --- a/internal/httpapi/misc_cases_test.go +++ b/internal/httpapi/misc_cases_test.go @@ -194,17 +194,6 @@ func TestMiscScheduleRemainingHelpersAndHTTP(t *testing.T) { if !h.ensureBaselineAlignAgent() { t.Fatal("ensure align agent") } - resolver, _ := f.s.Agent(domain.BaselineAlignAgentID) - resolver.ExecutorID, resolver.Model = "codex", "custom-model" - if err := f.s.PutAgent(resolver); err != nil { - t.Fatal(err) - } - if !h.ensureBaselineAlignAgent() { - t.Fatal("ensure existing align agent") - } - if got, _ := f.s.Agent(domain.BaselineAlignAgentID); got.ExecutorID != "codex" || got.Model != "custom-model" { - t.Fatalf("baseline registration overwrote the saved executor: %+v", got) - } _ = f.s.DeleteWorkflow(engine.BaselineAlignWorkflowID) if !h.ensureBaselineAlignWorkflow(domain.ScheduleJob{}) { t.Fatal("ensure align workflow") diff --git a/internal/httpapi/schedule.go b/internal/httpapi/schedule.go index baf261c1..7f5c27a2 100644 --- a/internal/httpapi/schedule.go +++ b/internal/httpapi/schedule.go @@ -607,8 +607,8 @@ fi echo "校验通过:HEAD 为合并提交,无未解决冲突与残留标记"` func (h *scheduleHandlers) ensureBaselineAlignAgent() bool { - if err := h.repo.CreateBaselineAlignResolver(); err != nil { - log.Printf("baseline align agent creation failed: %v", err) + if err := h.repo.PutAgent(repo.BaselineAlignResolverAgent()); err != nil { + log.Printf("baseline align agent upsert failed: %v", err) return false } return true diff --git a/internal/repo/catalog.go b/internal/repo/catalog.go index 52f65084..369eb6c8 100644 --- a/internal/repo/catalog.go +++ b/internal/repo/catalog.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "math" - "os" "path/filepath" "sort" "strings" @@ -14,7 +13,6 @@ import ( "agentflow/internal/domain" "gorm.io/gorm" - "gorm.io/gorm/clause" ) // BaselineAlignResolverAgent is the shared platform role for scheduled @@ -28,19 +26,10 @@ 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", } } -// CreateBaselineAlignResolver stores the built-in role on first use. A -// concurrent scheduler or an operator-edited resolver wins on conflict. -func (r *CatalogRepo) CreateBaselineAlignResolver() error { - agent := BaselineAlignResolverAgent() - agent.UpdatedAt = time.Now().UTC() - return r.DB.Table("agents").Clauses(clause.OnConflict{DoNothing: true}).Create(map[string]any{ - "id": agent.ID, "name": agent.Name, "payload": mustJSON(agent), "updated_at": timePtr(agent.UpdatedAt), - }).Error -} - // ---------- Agents ---------- func (r *CatalogRepo) Agents() []domain.AgentDefinition { @@ -258,26 +247,6 @@ func BuiltInExecutors() []domain.ExecutorDefinition { } } -// DefaultExecutorID is resolved when a run starts. A personal machine can -// supply the CLI's local login only for its owner. The legacy default covers -// deployments that rely on a shared CodeBuddy credential. -func DefaultExecutorID(user domain.User, runner domain.Runner) string { - if id := strings.TrimSpace(os.Getenv("AGENTFLOW_DEFAULT_EXECUTOR")); id != "" { - return id - } - for _, executor := range BuiltInExecutors() { - if runner.ID != "" && !runner.SupportsProvider(executor.Kind) { - continue - } - login := runner.ID != "" && runner.OwnerUserID == user.ID && domain.SupportsRunnerLogin(executor.Kind) && - runner.RuntimeAuthMode(executor.Kind) == domain.RuntimeAuthLocal - if login || user.CLIAPIKey(executor.Kind) != "" { - return executor.ID - } - } - return "codebuddy" -} - func BuiltInExecutor(id string) (domain.ExecutorDefinition, bool) { for _, executor := range BuiltInExecutors() { if executor.ID == strings.TrimSpace(id) { diff --git a/internal/tracker/service.go b/internal/tracker/service.go index 3018c547..27e9c9b6 100644 --- a/internal/tracker/service.go +++ b/internal/tracker/service.go @@ -6,7 +6,6 @@ import ( "log" "maps" "net/url" - "os" "sort" "strconv" "strings" @@ -92,7 +91,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. Legacy host CodeBuddy OAuth is opt-in. +// to AGENTFLOW_MCP_TOKEN, then legacy host CodeBuddy OAuth. func (s *Service) Configure(cfg domain.SyncConfig) { s.ConfigureWithCatalog(cfg, nil) } @@ -102,9 +101,10 @@ func (s *Service) ConfigureWithCatalog(cfg domain.SyncConfig, servers []domain.M s.cfg.Set(cfg) bind := func(kind string) mcpBinding { binding := bindTrackerMCP(kind, cfg, servers, s.authToken, "") - if binding.URL != "" && !headerHas(binding.Headers, "Authorization") && - os.Getenv("AGENTFLOW_TRACKER_CODEBUDDY_AUTH") == "1" { - binding = bindTrackerMCP(kind, cfg, servers, "", LoadAuthFromCodeBuddy(kind)) + if binding.URL != "" && !headerHas(binding.Headers, "Authorization") { + if auth := LoadAuthFromCodeBuddy(kind); auth != "" { + binding = bindTrackerMCP(kind, cfg, servers, "", auth) + } } return binding } diff --git a/migrations/040_inherit_stock_sop_executors.sql b/migrations/040_inherit_stock_sop_executors.sql deleted file mode 100644 index e6cd6527..00000000 --- a/migrations/040_inherit_stock_sop_executors.sql +++ /dev/null @@ -1,47 +0,0 @@ --- Optional upgrade for existing installations. Run after the prior catalog --- migrations with template edits paused. New seeds already inherit the CLI. --- Keep edited roles, explicit models and existing run snapshots. -SET NAMES utf8mb4; -START TRANSACTION; - -UPDATE generic_templates AS target -JOIN ( - SELECT id, inherited_agents - FROM ( - SELECT id, agent_order, - JSON_ARRAYAGG(IF(inherit_cli, JSON_REMOVE(definition, '$.executorId'), definition)) - OVER (PARTITION BY id ORDER BY agent_order ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS inherited_agents, - SUM(inherit_cli) OVER (PARTITION BY id) AS changed - FROM ( - SELECT t.id, a.agent_order, a.definition, - (a.version = 1 AND a.executor_id = 'codebuddy' - AND COALESCE(a.model, '') IN ('', 'default') - AND COALESCE(a.effort, '') = '' - AND a.agent_id REGEXP CONCAT('^', t.id, '-(clarify|design|implement|review|test|deliver|mr)$')) AS inherit_cli - FROM generic_templates AS t - JOIN JSON_TABLE(t.payload, '$.Agents[*]' COLUMNS ( - agent_order FOR ORDINALITY, - definition JSON PATH '$', - agent_id VARCHAR(64) PATH '$.id', - version INT PATH '$.version', - executor_id VARCHAR(64) PATH '$.executorId', - model VARCHAR(128) PATH '$.model', - effort VARCHAR(64) PATH '$.effort' - )) AS a - WHERE t.id IN ('generic-backend-delivery', 'generic-frontend-delivery', 'issue-fix-production', 'generic-product-delivery') - ) AS candidates - ) AS templates_with_order - WHERE agent_order = 1 AND changed > 0 -) AS migrated ON migrated.id = target.id -SET target.payload = JSON_SET(target.payload, '$.Agents', JSON_EXTRACT(migrated.inherited_agents, '$')), - target.updated_at = UTC_TIMESTAMP(); - -UPDATE agents -SET payload = JSON_REMOVE(payload, '$.executorId'), updated_at = UTC_TIMESTAMP() -WHERE id = 'baseline-align-resolver' - AND JSON_EXTRACT(payload, '$.version') = 1 - AND JSON_UNQUOTE(JSON_EXTRACT(payload, '$.executorId')) = 'codebuddy' - AND COALESCE(JSON_UNQUOTE(JSON_EXTRACT(payload, '$.model')), '') IN ('', 'default') - AND COALESCE(JSON_UNQUOTE(JSON_EXTRACT(payload, '$.effort')), '') = ''; - -COMMIT; diff --git a/migrations/seed/001_public_catalog.sql b/migrations/seed/001_public_catalog.sql index 7bec1363..2fcaa548 100644 --- a/migrations/seed/001_public_catalog.sql +++ b/migrations/seed/001_public_catalog.sql @@ -4,12 +4,12 @@ SET NAMES utf8mb4; START TRANSACTION; INSERT IGNORE INTO sandboxes (`id`,`name`,`payload`) VALUES ('local','本地执行(仅可信任务)','{"id":"local","name":"本地执行(仅可信任务)","driver":"local"}'); INSERT IGNORE INTO sandboxes (`id`,`name`,`payload`) VALUES ('generic-docker','Docker 隔离沙箱','{"id":"generic-docker","name":"Docker 隔离沙箱","shared":true,"driver":"docker","dockerfileId":"generic-backend","readOnlyRootFS":false}'); -INSERT IGNORE INTO dockerfiles (`id`,`name`,`payload`) VALUES ('generic-backend','公共开发环境','{"id":"generic-backend","name":"公共开发环境","shared":true,"content":"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\\nARG CODEBUDDY_PACKAGE=@tencent-ai/codebuddy-code\\nRUN if [ -n \\"$CODEBUDDY_PACKAGE\\" ]; then npm install -g \\"$CODEBUDDY_PACKAGE\\"; fi\\nWORKDIR /workspace\\n"}'); +INSERT IGNORE INTO dockerfiles (`id`,`name`,`payload`) VALUES ('generic-backend','公共开发环境','{"id":"generic-backend","name":"公共开发环境","shared":true,"content":"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"}'); INSERT IGNORE INTO rules (`id`,`name`,`payload`) VALUES ('public-engineering','工程与验证约束','{"version":1,"updatedAt":"2026-10-15T00:00:00Z","id":"public-engineering","name":"工程与验证约束","shared":true,"priority":100,"content":"先阅读仓库约束并明确范围;只修改任务所需文件。不得泄露凭据,不得伪造测试或交付证据。使用项目现有构建与测试命令,报告真实结果与限制。发布 PR 前检查 diff;未经任务授权不得合并主分支。"}'); -INSERT IGNORE INTO generic_templates (id,name,payload,updated_at) VALUES ('generic-backend-delivery','通用后端交付 SOP','{"Workflow": {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery", "name": "通用后端交付 SOP", "revision": 1, "status": "published", "description": "后端需求从需求定型到独立评审与交付。", "sandboxProfileId": "generic-docker", "generic": true, "owner": "LoopForge", "tags": ["public"], "nodes": [{"id": "clarify", "name": "需求定型", "type": "agent", "agentId": "generic-backend-delivery-clarify", "maxAttempts": 2, "position": {"x": 100, "y": 150}, "artifactOutputs": [{"name": "clarify", "path": "requirement.md", "mediaType": "text/markdown", "required": true}]}, {"id": "design", "name": "方案设计", "type": "agent", "agentId": "generic-backend-delivery-design", "maxAttempts": 2, "position": {"x": 345, "y": 150}, "artifactOutputs": [{"name": "design", "path": "design.md", "mediaType": "text/markdown", "required": true}]}, {"id": "implement", "name": "开发实现", "type": "agent", "agentId": "generic-backend-delivery-implement", "maxAttempts": 2, "position": {"x": 590, "y": 150}, "artifactOutputs": [{"name": "implement", "path": "implementation.md", "mediaType": "text/markdown", "required": true}]}, {"id": "review", "name": "独立评审", "type": "agent", "agentId": "generic-backend-delivery-review", "maxAttempts": 2, "position": {"x": 835, "y": 150}, "artifactOutputs": [{"name": "review", "path": "review.md", "mediaType": "text/markdown", "required": true}]}, {"id": "test", "name": "测试验证", "type": "agent", "agentId": "generic-backend-delivery-test", "maxAttempts": 2, "position": {"x": 1080, "y": 150}, "artifactOutputs": [{"name": "test", "path": "test-report.md", "mediaType": "text/markdown", "required": true}]}, {"id": "accept", "name": "人工验收", "type": "approval", "maxAttempts": 1, "rejectTo": "implement", "position": {"x": 1325, "y": 150}}, {"id": "deliver", "name": "交付汇总", "type": "agent", "agentId": "generic-backend-delivery-deliver", "maxAttempts": 2, "position": {"x": 1815, "y": 150}, "artifactOutputs": [{"name": "deliver", "path": "delivery.md", "mediaType": "text/markdown", "required": true}]}, {"id": "mr", "name": "发起 MR", "type": "agent", "agentId": "generic-backend-delivery-mr", "maxAttempts": 2, "position": {"x": 1570, "y": 150}, "artifactOutputs": [{"name": "mr-body", "path": "mr-body.md", "mediaType": "text/markdown", "required": true}]}], "edges": [{"id": "e-0", "source": "clarify", "target": "design", "when": "success"}, {"id": "e-1", "source": "design", "target": "implement", "when": "success"}, {"id": "e-2", "source": "implement", "target": "review", "when": "success"}, {"id": "e-3", "source": "review", "target": "test", "when": "success"}, {"id": "e-4", "source": "test", "target": "accept", "when": "success"}, {"id": "e-5", "source": "accept", "target": "mr", "when": "success"}, {"id": "e-6", "source": "mr", "target": "deliver", "when": "success"}]}, "Agents": [{"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-clarify", "name": "需求定型", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。确认目标、范围、用户、边界与可测试验收标准,输出 requirement.md。不要开始编码。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-design", "name": "方案设计", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。阅读已确认需求与可用代码,写出最小实现方案、接口影响、风险与验证计划到 design.md。未绑定仓库的新项目可在任务工作区设计和实现;修改已有系统或修复缺陷时必须取得相关源码,缺少时明确阻塞并请求补充。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-implement", "name": "开发实现", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。依据 requirement.md 和 design.md 实现需求,保持范围最小;执行适用验证,记录实现、改动和验证到 implementation.md。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-review", "name": "独立评审", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。独立审查改动及测试证据;按严重程度列出有位置与影响的缺陷及修复建议到 review.md。发现阻断问题必须明确写出 REJECT。不得伪造通过结论。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-test", "name": "测试验证", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。根据验收标准执行项目真实测试、构建及必要端到端场景。必要时修复问题并复测。将命令、退出码、结果、未验证范围写到 test-report.md。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-10-15T00:00:00Z", "id": "generic-backend-delivery-deliver", "name": "交付汇总", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。核对各阶段实际产物与验证证据,将完成内容、真实测试结果、已知限制及交付物清单写到 delivery.md。未绑定仓库时交付任务工作区中的源码和报告,无需 Git Token。代码已由「发起 MR」节点提交、推送并创建 MR/PR:按 mr-body.md 把链接、分支和提交 SHA 写进交付物清单;本节点不再修改代码、推送或创建 PR,不得合并。\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}"}, {"version": 1, "updatedAt": "2026-11-16T00:00:00Z", "id": "generic-backend-delivery-mr", "name": "发起 MR", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "工作领域:后端服务、数据与 API。人工验收已通过,本节点把本轮代码改动提交到工作分支、推送并发起 MR/PR,不再修改业务逻辑。\\n\\n1. 未绑定代码仓库时不推送、不创建 MR/PR:在 mr-body.md 写明「未绑定代码仓库,源码保留在任务工作区」并列出交付文件,然后提交 pass。\\n2. 已绑定仓库时逐个处理每个仓库检出目录,本轮没有改动的仓库跳过,不创建空 MR/PR:确认当前在本轮工作分支上,不得在主分支提交,也不得切换或新建分支;检查 git status 与 diff,只提交本任务相关的源码改动,不提交 .agentflow、依赖目录、构建产物和 SOP 阶段文档;用概括本次改动的提交信息 commit,再 git push -u origin 当前工作分支。平台已注入 Git 凭据,不得打印、回显或写入任何令牌。\\n3. 以仓库上下文中的目标分支为目标创建 MR/PR:使用托管平台的 CLI(如 gh、glab)或已配置的 MCP,也可查阅该平台官方 API。调用 API 需要令牌时,用 git credential fill 按仓库主机获取,只在进程内存中使用。本轮工作分支已有指向同一目标分支的 MR/PR 时更新它,不重复创建。\\n4. 标题概括本次改动;描述写需求摘要、改动要点、测试结果(依据 test-report.md)和已知限制。不得合并 MR/PR,不得推送主分支或强推。\\n5. 把每个仓库的 MR/PR 链接、源分支、目标分支和提交 SHA 写到 mr-body.md。\\n6. 推送或创建 MR/PR 失败(缺少凭据、无权限、网络错误等)时不得提交 pass:在 mr-body.md 记录失败原因,提交 human,并在 actionRequired 写明需要人工处理什么,例如配置 Git Token 后重试,或到托管平台手动创建 MR。\\n\\nMR 约束:{{existingMR}}\\n\\n完成本节点约定的工作并交付产物。\\n\\n### 输入\\n\\n- 任务需求:{{input}}\\n- 仓库上下文:{{repository}}", "loop": {"enabled": true, "maxIterations": 2, "exitCondition": "all_gates_pass", "onExhausted": "human"}, "verification": [{"id": "mr-pushed", "name": "改动已提交并推送", "mode": "command", "stage": "after_execution", "commands": ["fail=0\\ntab=\\"$(printf ''\\\\t'')\\"\\nwhile IFS=\\"$tab\\" read -r d work base; do\\n [ -n \\"$d\\" ] || continue\\n dirty=\\"$(git -C \\"$d\\" status --porcelain --untracked-files=all -- . \\":(exclude).agentflow\\" \\":(exclude,glob)**/node_modules/**\\")\\" || { printf \\"%s 不是可用的 Git 检出目录\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ -n \\"$dirty\\" ]; then printf \\"%s 有未提交的改动:\\\\n%s\\\\n\\" \\"$d\\" \\"$dirty\\"; fail=1; continue; fi\\n refs=HEAD\\n if git -C \\"$d\\" rev-parse -q --verify \\"refs/heads/$work\\" >/dev/null; then refs=\\"HEAD refs/heads/$work\\"; fi\\n ahead=\\"$(git -C \\"$d\\" rev-list --count $refs --not \\"refs/remotes/origin/$base\\")\\" || { printf \\"%s 找不到目标分支 origin/%s\\\\n\\" \\"$d\\" \\"$base\\"; fail=1; continue; }\\n [ \\"$ahead\\" != 0 ] || continue\\n branch=\\"$(git -C \\"$d\\" branch --show-current)\\"\\n if [ \\"$branch\\" != \\"$work\\" ]; then printf \\"%s 当前在 %s,不在本轮工作分支 %s\\\\n\\" \\"$d\\" \\"${branch:-分离的 HEAD}\\" \\"$work\\"; fail=1; continue; fi\\n head=\\"$(git -C \\"$d\\" rev-parse HEAD)\\"\\n pushed=\\"$(git -C \\"$d\\" ls-remote origin \\"refs/heads/$work\\")\\" || { printf \\"%s 无法读取远端 origin\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ \\"${pushed%%\\"$tab\\"*}\\" != \\"$head\\" ]; then printf \\"%s 的工作分支 %s 在 origin 上不是 %s,本轮提交还没推送\\\\n\\" \\"$d\\" \\"$work\\" \\"$head\\"; fail=1; fi\\ndone </dev/null; then refs=\\"HEAD refs/heads/$work\\"; fi\\n ahead=\\"$(git -C \\"$d\\" rev-list --count $refs --not \\"refs/remotes/origin/$base\\")\\" || { printf \\"%s 找不到目标分支 origin/%s\\\\n\\" \\"$d\\" \\"$base\\"; fail=1; continue; }\\n [ \\"$ahead\\" != 0 ] || continue\\n branch=\\"$(git -C \\"$d\\" branch --show-current)\\"\\n if [ \\"$branch\\" != \\"$work\\" ]; then printf \\"%s 当前在 %s,不在本轮工作分支 %s\\\\n\\" \\"$d\\" \\"${branch:-分离的 HEAD}\\" \\"$work\\"; fail=1; continue; fi\\n head=\\"$(git -C \\"$d\\" rev-parse HEAD)\\"\\n pushed=\\"$(git -C \\"$d\\" ls-remote origin \\"refs/heads/$work\\")\\" || { printf \\"%s 无法读取远端 origin\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ \\"${pushed%%\\"$tab\\"*}\\" != \\"$head\\" ]; then printf \\"%s 的工作分支 %s 在 origin 上不是 %s,本轮提交还没推送\\\\n\\" \\"$d\\" \\"$work\\" \\"$head\\"; fail=1; fi\\ndone </dev/null; then refs=\\"HEAD refs/heads/$work\\"; fi\\n ahead=\\"$(git -C \\"$d\\" rev-list --count $refs --not \\"refs/remotes/origin/$base\\")\\" || { printf \\"%s 找不到目标分支 origin/%s\\\\n\\" \\"$d\\" \\"$base\\"; fail=1; continue; }\\n [ \\"$ahead\\" != 0 ] || continue\\n branch=\\"$(git -C \\"$d\\" branch --show-current)\\"\\n if [ \\"$branch\\" != \\"$work\\" ]; then printf \\"%s 当前在 %s,不在本轮工作分支 %s\\\\n\\" \\"$d\\" \\"${branch:-分离的 HEAD}\\" \\"$work\\"; fail=1; continue; fi\\n head=\\"$(git -C \\"$d\\" rev-parse HEAD)\\"\\n pushed=\\"$(git -C \\"$d\\" ls-remote origin \\"refs/heads/$work\\")\\" || { printf \\"%s 无法读取远端 origin\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ \\"${pushed%%\\"$tab\\"*}\\" != \\"$head\\" ]; then printf \\"%s 的工作分支 %s 在 origin 上不是 %s,本轮提交还没推送\\\\n\\" \\"$d\\" \\"$work\\" \\"$head\\"; fail=1; fi\\ndone </dev/null; then refs=\\"HEAD refs/heads/$work\\"; fi\\n ahead=\\"$(git -C \\"$d\\" rev-list --count $refs --not \\"refs/remotes/origin/$base\\")\\" || { printf \\"%s 找不到目标分支 origin/%s\\\\n\\" \\"$d\\" \\"$base\\"; fail=1; continue; }\\n [ \\"$ahead\\" != 0 ] || continue\\n branch=\\"$(git -C \\"$d\\" branch --show-current)\\"\\n if [ \\"$branch\\" != \\"$work\\" ]; then printf \\"%s 当前在 %s,不在本轮工作分支 %s\\\\n\\" \\"$d\\" \\"${branch:-分离的 HEAD}\\" \\"$work\\"; fail=1; continue; fi\\n head=\\"$(git -C \\"$d\\" rev-parse HEAD)\\"\\n pushed=\\"$(git -C \\"$d\\" ls-remote origin \\"refs/heads/$work\\")\\" || { printf \\"%s 无法读取远端 origin\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ \\"${pushed%%\\"$tab\\"*}\\" != \\"$head\\" ]; then printf \\"%s 的工作分支 %s 在 origin 上不是 %s,本轮提交还没推送\\\\n\\" \\"$d\\" \\"$work\\" \\"$head\\"; fail=1; fi\\ndone </dev/null; then refs=\\"HEAD refs/heads/$work\\"; fi\\n ahead=\\"$(git -C \\"$d\\" rev-list --count $refs --not \\"refs/remotes/origin/$base\\")\\" || { printf \\"%s 找不到目标分支 origin/%s\\\\n\\" \\"$d\\" \\"$base\\"; fail=1; continue; }\\n [ \\"$ahead\\" != 0 ] || continue\\n branch=\\"$(git -C \\"$d\\" branch --show-current)\\"\\n if [ \\"$branch\\" != \\"$work\\" ]; then printf \\"%s 当前在 %s,不在本轮工作分支 %s\\\\n\\" \\"$d\\" \\"${branch:-分离的 HEAD}\\" \\"$work\\"; fail=1; continue; fi\\n head=\\"$(git -C \\"$d\\" rev-parse HEAD)\\"\\n pushed=\\"$(git -C \\"$d\\" ls-remote origin \\"refs/heads/$work\\")\\" || { printf \\"%s 无法读取远端 origin\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ \\"${pushed%%\\"$tab\\"*}\\" != \\"$head\\" ]; then printf \\"%s 的工作分支 %s 在 origin 上不是 %s,本轮提交还没推送\\\\n\\" \\"$d\\" \\"$work\\" \\"$head\\"; fail=1; fi\\ndone </dev/null; then refs=\\"HEAD refs/heads/$work\\"; fi\\n ahead=\\"$(git -C \\"$d\\" rev-list --count $refs --not \\"refs/remotes/origin/$base\\")\\" || { printf \\"%s 找不到目标分支 origin/%s\\\\n\\" \\"$d\\" \\"$base\\"; fail=1; continue; }\\n [ \\"$ahead\\" != 0 ] || continue\\n branch=\\"$(git -C \\"$d\\" branch --show-current)\\"\\n if [ \\"$branch\\" != \\"$work\\" ]; then printf \\"%s 当前在 %s,不在本轮工作分支 %s\\\\n\\" \\"$d\\" \\"${branch:-分离的 HEAD}\\" \\"$work\\"; fail=1; continue; fi\\n head=\\"$(git -C \\"$d\\" rev-parse HEAD)\\"\\n pushed=\\"$(git -C \\"$d\\" ls-remote origin \\"refs/heads/$work\\")\\" || { printf \\"%s 无法读取远端 origin\\\\n\\" \\"$d\\"; fail=1; continue; }\\n if [ \\"${pushed%%\\"$tab\\"*}\\" != \\"$head\\" ]; then printf \\"%s 的工作分支 %s 在 origin 上不是 %s,本轮提交还没推送\\\\n\\" \\"$d\\" \\"$work\\" \\"$head\\"; fail=1; fi\\ndone < reports/welcome.md","maxAttempts":1,"position":{"x":100,"y":150},"artifactOutputs":[{"name":"welcome","path":"reports/welcome.md","mediaType":"text/markdown","required":true}]},{"id":"approve","name":"请确认验收报告","type":"approval","maxAttempts":1,"rejectTo":"prepare","position":{"x":370,"y":150}},{"id":"finish","name":"完成验收","type":"script","scriptLanguage":"shell","executionScope":"run","script":"printf ''# 验收完成\\\\n\\\\n审批已通过,执行成功恢复。\\\\n'' > completed.md","artifactOutputs":[{"name":"completed","path":"completed.md","mediaType":"text/markdown","required":true}],"maxAttempts":1,"position":{"x":640,"y":150}}],"edges":[{"id":"e-1","source":"prepare","target":"approve","when":"success"},{"id":"e-2","source":"approve","target":"finish","when":"success"}]}',1,1,'published'); -INSERT IGNORE INTO agents (id,name,payload,updated_at) VALUES ('baseline-align-resolver','基线对齐执行员','{"id": "baseline-align-resolver", "name": "基线对齐执行员", "version": 1, "shared": true, "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "只做基线对齐:fetch 默认分支并 merge 到当前工作分支;解决冲突时保留双方有效实现,拿不准时记录取舍。创建本地合并提交。不要自行 push 或修改默认分支,不要执行与本次基线对齐无关的测试或编写修复报告。"}',UTC_TIMESTAMP()); +INSERT IGNORE INTO agents (id,name,payload,updated_at) VALUES ('baseline-align-resolver','基线对齐执行员','{"id": "baseline-align-resolver", "name": "基线对齐执行员", "version": 1, "shared": true, "executorId": "codebuddy", "rules": ["public-engineering"], "skills": [], "mcpServers": [], "prompt": "只做基线对齐:fetch 默认分支并 merge 到当前工作分支;解决冲突时保留双方有效实现,拿不准时记录取舍。创建本地合并提交。不要自行 push 或修改默认分支,不要执行与本次基线对齐无关的测试或编写修复报告。"}',UTC_TIMESTAMP()); COMMIT; diff --git a/web/app/agents.js b/web/app/agents.js index 5fd67c12..aa9b56d4 100644 --- a/web/app/agents.js +++ b/web/app/agents.js @@ -117,7 +117,7 @@ function syncAgentTabIndicators(){$$('#agentsView .agent-tabs, #agentModal .agen if(typeof document!=='undefined'&&document.fonts?.ready)document.fonts.ready.then(()=>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']),items=(state.data.executors||[]).filter(x=>allowed.has(x.id)),legacy=selected&&!allowed.has(selected)?``:'';return legacy+items.map(x=>``).join('')} const AGENT_CUSTOM_MODEL='__custom__'; let executorModelCatalogUser, executorModelCatalogRequest, agentModelRevision=0; function executorModelCatalogs(){ @@ -130,7 +130,7 @@ function loadExecutorModelCatalogs(){ executorModelCatalogUser=user; const request={user}; request.pending=api('/api/executor-models',{silent:true}).then(data=>{ - if(executorModelCatalogRequest===request&&state.currentUser?.id===user&&data){ + if(executorModelCatalogRequest===request&&state.currentUser?.id===user&&data?.codebuddy&&data.codex&&data.claude){ window.AgentFlowExecutorModels=data; } }).catch(()=>{}).finally(()=>{ @@ -140,10 +140,9 @@ function loadExecutorModelCatalogs(){ return request.pending; } function agentModelAPI(){return window.AgentFlowAssistantModels} -function currentAgentExecutorId(){return $('#agentForm')?.elements?.executorId?.value||''} +function currentAgentExecutorId(){return $('#agentForm')?.elements?.executorId?.value||'codebuddy'} function agentModelItems(executorId,current){ const cat=executorModelCatalogs()[executorId]||{},items=(cat.models||[]).filter(item=>item.id!=='default'); - items.unshift({id:'',name:executorId?'CLI 默认模型':'随执行器选择',icon:false}); if(current&¤t!=='default'&¤t!==AGENT_CUSTOM_MODEL&&!items.some(m=>m.id===current))items.push({id:current,name:`${current}(历史模型)`,family:'other'}); if(cat.customModel)items.push({id:AGENT_CUSTOM_MODEL,name:'手动输入模型 ID…',icon:false}); return items; @@ -243,7 +242,7 @@ 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||''); + if(f.elements.executorId)f.elements.executorId.innerHTML=executorOptions(a.executorId||'codebuddy'); const modelRevision=++agentModelRevision; const modelUser=state.currentUser?.id; const refreshModels=loadExecutorModelCatalogs(); @@ -255,7 +254,7 @@ function selectAgent(a,rerender=true){ renderAgentModelPicker(); renderAgentEffortPicker(); }else{ - applyAgentModelUI(currentAgentExecutorId(),model,f.elements.effort?.value,!a.id||currentAgentExecutorId()!==(a.executorId||'')); + applyAgentModelUI(currentAgentExecutorId(),model,f.elements.effort?.value,!a.id||currentAgentExecutorId()!==(a.executorId||'codebuddy')); } if(state.agentModalMode==='create'&&state.agentCreateStep===3)renderAgentCreateReview(); }); @@ -426,8 +425,9 @@ function saveAgent(e){ } async function persistAgent(f){ const creating=state.agentModalMode==='create'; + const changedExecutor=currentAgentExecutorId()!==(agentWizardSubject()?.executorId||'codebuddy'); const model=agentEffectiveModel(f); - if(f.elements.modelChoice?.value===AGENT_CUSTOM_MODEL&&!model){ + if((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 ce744231..b387e6f0 100644 --- a/web/app/assistant-models.js +++ b/web/app/assistant-models.js @@ -71,7 +71,7 @@ const value = id || DEFAULT_MODEL; 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}; + return {id: value, family: familyOf(value), name: value === DEFAULT_MODEL ? '默认模型' : value}; } function fillModelIcon(el, family, id) { if (!el) return; @@ -90,7 +90,7 @@ return credits.endsWith('credits') ? credits : credits + ' credits'; } // paint draws a catalog entry into a `} +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; diff --git a/web/app/flows.js b/web/app/flows.js index d672d0b2..e2029e9b 100644 --- a/web/app/flows.js +++ b/web/app/flows.js @@ -3,7 +3,9 @@ function workflowPreviewContract(wf){ } const PREVIEW_BUILD_NODE_ID='af-preview-build'; const PREVIEW_BUILD_AGENT_ID='af-preview-builder'; +const PREVIEW_DEFAULT_EXECUTOR='codebuddy'; function isPreviewBuildNode(id){return id===PREVIEW_BUILD_NODE_ID} +function workflowPreviewExecutor(wf){return workflowPreviewContract(wf)?.executorId?.trim()||PREVIEW_DEFAULT_EXECUTOR} function workflowPreviewModel(wf){ const api=window.AgentFlowAssistantModels; const fallback=(api&&api.DEFAULT)||'default'; @@ -13,11 +15,11 @@ function workflowPreviewModel(wf){ function fillPreviewModelSelect(sel, selected, executorId){ if(!sel)return; const catalog=executorModelCatalogs()[executorId]; - const items=[{id:'default',name:executorId?'CLI 默认模型':'随执行器选择'},...(catalog?.models||[]).filter(m=>m.id!=='default')]; + const items=[{id:'default',name:'默认模型'},...(catalog?.models||[]).filter(m=>m.id!=='default')]; const keep=selected||'default'; if(!items.some(m=>m.id===keep))items.push({id:keep,name:keep}); sel.innerHTML=items.map(m=>``).join(''); - sel.disabled=!executorId||flowReadOnly(); + sel.disabled=flowReadOnly(); } function ensurePreviewContract(){ const wf=state.workflow;if(!wf)return null; @@ -28,7 +30,7 @@ function ensurePreviewContract(){ ...prev, enabled:true, kind:'static', - executorId:prev.executorId||'', + executorId:workflowPreviewExecutor(wf), model, sourcePath:prev.sourcePath||'dist', indexFile:prev.indexFile||'index.html', @@ -66,7 +68,7 @@ function syncPreviewBuildGraph(){ name:'构建静态站点', type:'agent', agentId:PREVIEW_BUILD_AGENT_ID, - executorId:wf.preview.executorId||'', + executorId:workflowPreviewExecutor(wf), executionScope:'run', onFailure:'fail', retryStrategy:'targeted_fix', @@ -181,7 +183,7 @@ function addNode(type,opts={}){ if(existing){state.selectedNode=existing.id;renderCanvas();renderProperties();return toast('预览节点已存在,可拖拽连线调整它的位置')} flowHistory.record(); ensurePreviewContract(); - state.workflow.nodes.push({id:PREVIEW_BUILD_NODE_ID,name:'构建静态站点',type:'agent',agentId:PREVIEW_BUILD_AGENT_ID,executorId:state.workflow.preview.executorId||'',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}]}); state.selectedNode=PREVIEW_BUILD_NODE_ID; dirty();renderCanvas();renderProperties(); return; @@ -375,7 +377,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?`插在流程中间:${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?'通用模板角色未加载':'角色不属于当前项目或未共享');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()} @@ -974,7 +976,7 @@ function renderPreviewBuildProperties(host,n){
    主配置

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

    -
    +
    diff --git a/web/app/runs.js b/web/app/runs.js index d1e04e69..fcfdb6c0 100644 --- a/web/app/runs.js +++ b/web/app/runs.js @@ -1369,7 +1369,8 @@ 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)}; + const defaultDescription='优先使用你配置的 CodeBuddy。未配置时使用你在个人配置中添加的其他 CLI。'; + const paint=()=>{const keep=runEvalModel();const inp=host.querySelector('[name=runEvalModel]');if(inp)inp.value=keep;api.paint(toggle,keep,defaultDescription)}; paint(); api.load?.().then(paint).catch(paint); if(host.dataset.bound)return; @@ -1379,7 +1380,7 @@ function bindRunEvalModelPicker(host){ const open=menu.hidden; menu.hidden=!open; toggle.setAttribute('aria-expanded',open?'true':'false'); - if(open)api.renderFeatureList(menu,runEvalModel(),id=>{setRunEvalModel(id);paint();menu.hidden=true;toggle.setAttribute('aria-expanded','false')}); + if(open)api.renderFeatureList(menu,runEvalModel(),id=>{setRunEvalModel(id);paint();menu.hidden=true;toggle.setAttribute('aria-expanded','false')},defaultDescription); }; document.addEventListener('click',e=>{if(host.contains(e.target))return;menu.hidden=true;toggle.setAttribute('aria-expanded','false')}); } diff --git a/web/app/sops.js b/web/app/sops.js index 519808c4..196da567 100644 --- a/web/app/sops.js +++ b/web/app/sops.js @@ -94,12 +94,13 @@ function sopRunRequirements(w){ 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(); - let inherited=false; - for(const node of nodes.filter(n=>n.type==='agent')){ + 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=(isPreviewBuildNode(node.id)?w.preview?.executorId:role?.executorId||node.executorId)||''; - inherited ||= !id; + 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); } @@ -113,12 +114,6 @@ function sopRunRequirements(w){ } 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(inherited){ - const ready=!!(user.codeBuddyApiKeyConfigured||user.codexApiKeyConfigured||user.claudeCodeApiKeyConfigured|| - Object.values(user.agentCliCredentials||{}).some(cred=>cred.apiKeyConfigured)|| - window.AgentFlowAssistantModels?.catalog().engines?.some(engine=>engine.configured)); - rows.push({key:'run-cli',fix:'settings',fixLabel:'去个人配置',label:'CLI',ok:ready,hint:'未指定 CLI 的角色使用 SOP 执行身份或部署配置的默认 CLI。'}); - } 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; diff --git a/web/app/sync-schedule.js b/web/app/sync-schedule.js index 3d46c528..f905c070 100644 --- a/web/app/sync-schedule.js +++ b/web/app/sync-schedule.js @@ -116,7 +116,9 @@ 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)}; + const defaultDescription='优先使用需求负责人的 CodeBuddy。未配置时使用负责人配置的其他 CLI,未指派需求使用项目负责人的配置。'; + const paint=()=>{const keep=selectedClarifyModel();const hidden=host.querySelector('[data-clarify-model-value]');if(hidden)hidden.value=keep;api.paint(toggle,keep,defaultDescription)}; + paint(); api.load?.().then(paint).catch(paint); if(!bindClarifyModelPicker.docBound){ bindClarifyModelPicker.docBound=true; @@ -140,10 +142,10 @@ function bindClarifyModelPicker(host){ if(open){ api.renderFeatureList(menu, selectedClarifyModel(), id=>{ setClarifyModel(id); - api.paint(toggle, id); + api.paint(toggle, id, defaultDescription); menu.hidden=true; toggle.setAttribute('aria-expanded','false'); - }); + }, defaultDescription); } }; } diff --git a/web/assistant-models.css b/web/assistant-models.css index e6e29062..2971c42e 100644 --- a/web/assistant-models.css +++ b/web/assistant-models.css @@ -41,6 +41,7 @@ } .ai-model-option{padding:8px 10px;gap:8px} .ai-model-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.ai-model-description{display:block;margin-top:3px;color:var(--muted-2);font-size:11px;font-weight:400;line-height:1.45;white-space:normal} .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 0bb0616e..520d0dea 100644 --- a/web/assistant_models_test.js +++ b/web/assistant_models_test.js @@ -127,7 +127,7 @@ vm.runInContext(moduleSource, ctx); // must already render a usable label. assert.equal(api.engineOf('codex:gpt-5.5'), 'codex'); api.paint(toggle, api.DEFAULT); - assert.equal(label.textContent, '按执行身份自动选择'); + assert.equal(label.textContent, '默认模型'); assert.equal(icon.dataset.family, 'other'); await api.load(); @@ -147,7 +147,9 @@ vm.runInContext(moduleSource, ctx); toggle.onclick({ stopPropagation() {} }); assert.equal(menu.hidden, false, 'clicking 选择模型 must open the menu'); - assert.equal(menu.children.length, 4, 'menu lists the neutral default and personal models'); + assert.equal(menu.children.length, 4, 'menu lists the default and personal models'); + assert.equal(menu.children[0].querySelector('.ai-model-name').textContent, '默认模型'); + assert.match(menu.children[0].querySelector('.ai-model-description').textContent, /需求负责人.*CodeBuddy/); assert.ok(menu.children[1].className.includes('is-active'), 'stored model is marked active'); menu.children.find(opt => opt.dataset.id === 'codex:gpt-5.5').onclick(); @@ -156,5 +158,10 @@ vm.runInContext(moduleSource, ctx); assert.equal(menu.hidden, true); assert.equal(label.textContent, 'GPT-5.5'); assert.equal(ctx.selectedClarifyModel(), 'codex:gpt-5.5'); + toggle.onclick({ stopPropagation() {} }); + menu.children[0].onclick(); + assert.equal(input.value, 'default'); + assert.equal(label.textContent, '默认模型'); + assert.match(toggle.title, /未指派需求使用项目负责人/); console.log('assistant models ok'); })().catch(err => { console.error(err); process.exit(1); }); diff --git a/web/orchestrate.js b/web/orchestrate.js index f50cee77..cbfcb1df 100644 --- a/web/orchestrate.js +++ b/web/orchestrate.js @@ -10,9 +10,9 @@ function aiOrchestratorEngine(model) { function selectedAIOrchestratorModel() { const catalog = window.AgentFlowAssistantModels?.catalog(); const remembered = localStorage.getItem('agentflow.orchestratorModel') || localStorage.getItem('agentflow.assistantModel'); - if (remembered && remembered !== 'default') { - const engine = aiOrchestratorEngine(remembered); - if (!catalog?.engines?.length || catalog.engines.some(item => item.id === engine && item.configured)) return remembered; + if (remembered && remembered !== 'default') return remembered; + if (!catalog?.engines?.length || catalog.engines.some(engine => engine.id === 'codebuddy' && engine.configured)) { + return aiOrchestratorModels('codebuddy')[0]?.id || catalog?.default || 'default'; } const model = catalog?.models?.find(item => catalog.engines?.some(engine => engine.id === aiOrchestratorEngine(item.id) && engine.configured)); return model?.id || ''; diff --git a/web/sop_catalog_test.js b/web/sop_catalog_test.js index 0898221f..ee23e0cb 100644 --- a/web/sop_catalog_test.js +++ b/web/sop_catalog_test.js @@ -20,6 +20,7 @@ const ctx = { formatTimestamp: v => (v ? 'T' : ''), catalogGeneric: item => !!item?.generic, isPreviewBuildNode: id => id === "af-preview-build", + workflowPreviewExecutor: wf => wf?.preview?.executorId || 'codebuddy', catalogOwned: projectId => !!ctx.state.projectFilter && projectId === ctx.state.projectFilter, isPlatformAdmin: () => ctx.admin, lfT: zh => zh, diff --git a/webtest/tests/assets-agents.test.mjs b/webtest/tests/assets-agents.test.mjs index 1d21e237..b5fff6e0 100644 --- a/webtest/tests/assets-agents.test.mjs +++ b/webtest/tests/assets-agents.test.mjs @@ -94,7 +94,6 @@ test('agent catalog search, presets, validation, persistence, clone, and delete const form = app.document.querySelector('#agentForm'); form.elements.executorId.append(new app.window.Option('CodeBuddy', 'codebuddy')); form.elements.executorId.value = 'codebuddy'; - form.elements.executorId.dispatchEvent(new app.window.Event('change', { bubbles: true })); assert.equal(form.elements.name.value, '研发工程师'); assert.match(form.elements.id.value, /^role-/); app.evaluate(`setAgentCreateStep(3)`); @@ -139,15 +138,15 @@ test('role model picker reloads the editor catalog and preserves a CLI change wh complete(catalog([{ id: 'private/second', name: 'Second' }, { id: 'private/first', name: 'First' }])); await settle(); const menu = () => [...app.document.querySelectorAll('#agentModelPicker [role=option]')]; - assert.deepEqual(menu().map(row => row.dataset.id), ['', 'private/second', 'private/first', '__custom__']); - assert.equal(menu()[1].querySelector('.ai-model-name').textContent, 'Second'); + assert.deepEqual(menu().map(row => row.dataset.id), ['private/second', 'private/first', '__custom__']); + assert.equal(menu()[0].querySelector('.ai-model-name').textContent, 'Second'); assert.equal(f.elements.executorId.value, 'codex'); assert.equal(app.evaluate(`agentEffectiveModel($('#agentForm'))`), 'private/second'); app.router.get('/api/executor-models', () => catalog([{ id: 'private/second', name: 'Renamed model' }])); app.evaluate(`openAgentWizard({id:'role-review',name:'Review',prompt:'Review changes',executorId:'codex',model:'private/second'})`); await settle(); - assert.deepEqual(menu().map(row => row.dataset.id), ['', 'private/second', '__custom__']); + assert.deepEqual(menu().map(row => row.dataset.id), ['private/second', '__custom__']); assert.equal(app.document.querySelector('#agentModelPicker [data-model-label]').textContent, 'Renamed model'); let refresh; @@ -162,23 +161,32 @@ test('role model picker reloads the editor catalog and preserves a CLI change wh assert.equal(app.evaluate(`agentEffectiveModel($('#agentForm'))`), 'private/second'); }); -test('a new role inherits its executor across model catalog refreshes', async (t) => { +test('a new role saves the first model from the refreshed catalog', async (t) => { const app = await loadApp(); t.after(app.close); const catalog = id => ({ codebuddy: { models: [{ id }] }, codex: { models: [] }, claude: { models: [] } }); app.router.get('/api/executor-models', catalog('retired-model')); app.router.put('/api/agents', call => ({ status: 200, body: call.body })); - app.evaluate("openAgentWizard(); applyAgentPreset('developer')"); + app.evaluate(`openAgentWizard()`); + await settle(); + const model = () => app.evaluate(`agentEffectiveModel($('#agentForm'))`); + assert.equal(model(), 'retired-model'); + app.document.querySelector('#agentModal .modal-close').click(); + + let complete; + app.router.get('/api/executor-models', () => new Promise(resolve => { complete = resolve; })); + app.evaluate(`openAgentWizard(); applyAgentPreset('developer')`); await settle(); - assert.equal(app.evaluate("currentAgentExecutorId()"), ''); - assert.equal(app.evaluate("agentEffectiveModel($('#agentForm'))"), ''); - - app.router.get('/api/executor-models', catalog('current-model')); - await app.evaluate("loadExecutorModelCatalogs()"); - await app.evaluate("persistAgent($('#agentForm'))"); - const created = app.router.calls.find(call => call.path === '/api/agents' && call.method === 'PUT'); - assert.equal(created.body.executorId, ''); - assert.equal(created.body.model, ''); + assert.equal(model(), ''); + await app.evaluate(`persistAgent($('#agentForm'))`); + assert.equal(app.router.calls.some(call => call.path === '/api/agents' && call.method === 'PUT'), false); + app.evaluate(`setAgentCreateStep(3)`); + complete(catalog('current-model')); + await settle(); + assert.equal(model(), 'current-model'); + assert.match(app.document.querySelector('#agentCreateReview').textContent, /current-model/); + await app.evaluate(`persistAgent($('#agentForm'))`); + assert.equal(app.router.calls.find(call => call.path === '/api/agents' && call.method === 'PUT').body.model, 'current-model'); }); test('role effort picker follows each model and resets an unsupported level on model changes', async (t) => { diff --git a/webtest/tests/flows-editor.test.mjs b/webtest/tests/flows-editor.test.mjs index 129f2dff..119b1413 100644 --- a/webtest/tests/flows-editor.test.mjs +++ b/webtest/tests/flows-editor.test.mjs @@ -71,10 +71,16 @@ test('flow editor handles artifact/list editors and saves workflow changes', asy test('flow preview properties persist the CLI, model and SPA fallback', async (t) => { const app = await loadApp(); t.after(app.close); - app.router.get('/api/executor-models', {codex: {models:[{id:'preview-model',name:'Preview model'}]}}); - app.evaluate(`state.data.executors=[{id:'codex',name:'Codex'}];switchView('flow');addNode('preview',{at:{x:200,y:100}});renderProperties()`); + app.router.get('/api/executor-models', { + codebuddy: {models:[{id:'deepseek-v4.1-flash',name:'DeepSeek Flash'}]}, + codex: {models:[{id:'preview-model',name:'Preview model'}]}, + claude: {models:[]}, + }); + app.evaluate(`state.data.executors=[{id:'codebuddy',name:'CodeBuddy'},{id:'codex',name:'Codex'}];switchView('flow');addNode('preview',{at:{x:200,y:100}});renderProperties()`); await app.evaluate('loadExecutorModelCatalogs()'); const executor = app.document.querySelector('#previewNodeExecutor'); + assert.equal(executor.value, 'codebuddy'); + assert.equal(app.evaluate('state.workflow.preview.executorId'), 'codebuddy'); executor.value = 'codex'; executor.dispatchEvent(new app.window.Event('change')); const model = app.document.querySelector('#previewNodeModel'); From 584947af37e1581c4934bc393128770b01f65ebb Mon Sep 17 00:00:00 2001 From: roberttwang Date: Sat, 21 Nov 2026 02:11:57 +0800 Subject: [PATCH 04/25] Show concrete models in platform pickers --- web/app/assistant-models.js | 53 ++++++++++++++++++----------- web/app/bots.js | 19 +++++++---- web/app/flows.js | 29 +++++++++------- web/app/issue-drawer.js | 5 +-- web/app/runs.js | 13 +++---- web/app/sync-schedule.js | 11 +++--- web/assistant-models.css | 2 +- web/assistant_models_test.js | 23 +++++++------ web/bots_test.go | 2 +- web/syntax_test.go | 3 +- webtest/tests/flows-editor.test.mjs | 4 +++ 11 files changed, 97 insertions(+), 67 deletions(-) diff --git a/web/app/assistant-models.js b/web/app/assistant-models.js index b387e6f0..c5cb67aa 100644 --- a/web/app/assistant-models.js +++ b/web/app/assistant-models.js @@ -71,7 +71,16 @@ const value = id || DEFAULT_MODEL; 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}; + 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; @@ -90,7 +99,7 @@ return credits.endsWith('credits') ? credits : credits + ' credits'; } // paint draws a catalog entry into a
    `} +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); + models.paintFeature(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.renderFeatureList(menu,value.value,id=>{ - const qualified=id!==models.DEFAULT&&models.engineOf(id)==='codebuddy'&&!id.startsWith('codebuddy:')?'codebuddy:'+id:id; + const qualified=models.engineOf(id)==='codebuddy'&&!id.startsWith('codebuddy:')?'codebuddy:'+id:id; value.value=qualified; - models.paint(toggle,qualified); + models.paintFeature(toggle,qualified); captureBotDraft(host); closeBotModelPicker(); }); @@ -27,7 +27,7 @@ function bindBotModelPicker(host){ } // Project-scoped enterprise chat notifications. const botUI={projectId:'',items:[],deliveries:[],selected:null,sessions:[],query:'',loading:false,error:'',busy:false,busyAction:'',revision:0,tab:'list',step:1,recordsTab:'deliveries',interactionBotId:'',interaction:null,interactionLoading:false,interactionError:'',testResult:'',flashId:'',motion:null,animations:[],shownCount:null,shownError:'',watchTimer:0,watchCount:0,deletingId:''}; -const BOT_TABS=['list','edit','records'],BOT_STEPS=[[1,'填写凭据'],[2,'选择接收会话'],[3,'发送测试']],BOT_DEFAULT_MODEL='glm-5.3-flash-ioa'; +const BOT_TABS=['list','edit','records'],BOT_STEPS=[[1,'填写凭据'],[2,'选择接收会话'],[3,'发送测试']]; // In-progress states breathe; terminal states stay still. const BOT_LIVE_STATES=['pending','sending','connecting','reconnecting','queued','running','ready']; const BOT_CONNECTION={connected:['已连接','success'],connecting:['连接中','info'],reconnecting:['重连中','info'],error:['连接异常','error'],offline:['未连接','neutral']}; @@ -45,7 +45,7 @@ function canManageBot(bot){ function botStepAllowed(bot,step){return step===1||(step===2&&!!bot?.id)||(step===3&&!!bot?.id&&!!bot?.target&&!bot._targetChanged)} function botStepDone(bot,step){return step===1?!!bot?.id:step===2?botStepAllowed(bot,3):false} function botStoredBot(bot){return bot?.id?botUI.items.find(b=>b.id===bot.id):null} -function botCredentialsDirty(bot){const stored=botStoredBot(bot);if(!stored)return !!bot;return !!bot._secret||(bot.name||'')!==(stored.name||'')||(bot.botId||'')!==(stored.botId||'')||(bot.model||BOT_DEFAULT_MODEL)!==(stored.model||BOT_DEFAULT_MODEL)||!!bot.enabled!==!!stored.enabled||!!bot.interactionEnabled!==!!stored.interactionEnabled} +function botCredentialsDirty(bot){const stored=botStoredBot(bot);if(!stored)return !!bot;return !!bot._secret||(bot.name||'')!==(stored.name||'')||(bot.botId||'')!==(stored.botId||'')||(bot.model||'')!==(stored.model||'')||!!bot.enabled!==!!stored.enabled||!!bot.interactionEnabled!==!!stored.interactionEnabled} function botIcon(name){return ``} // Harness StatusBadge: in-progress states breathe, settled states carry a glyph so colour is never the only cue. @@ -81,7 +81,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){ @@ -334,6 +335,10 @@ function bindBotEditor(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-model-toggle]')?.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 e2029e9b..d6bfaf5c 100644 --- a/web/app/flows.js +++ b/web/app/flows.js @@ -7,31 +7,26 @@ const PREVIEW_DEFAULT_EXECUTOR='codebuddy'; function isPreviewBuildNode(id){return id===PREVIEW_BUILD_NODE_ID} function workflowPreviewExecutor(wf){return workflowPreviewContract(wf)?.executorId?.trim()||PREVIEW_DEFAULT_EXECUTOR} function workflowPreviewModel(wf){ - const api=window.AgentFlowAssistantModels; - const fallback=(api&&api.DEFAULT)||'default'; - const model=(workflowPreviewContract(wf)||{}).model; - return (model&&String(model).trim())||fallback; + const model=String(workflowPreviewContract(wf)?.model||'').trim(); + return model==='default'||(model==='default-model'&&workflowPreviewExecutor(wf)===PREVIEW_DEFAULT_EXECUTOR)?'':model; } function fillPreviewModelSelect(sel, selected, executorId){ if(!sel)return; const catalog=executorModelCatalogs()[executorId]; - const items=[{id:'default',name:'默认模型'},...(catalog?.models||[]).filter(m=>m.id!=='default')]; - const keep=selected||'default'; - if(!items.some(m=>m.id===keep))items.push({id:keep,name:keep}); - sel.innerHTML=items.map(m=>``).join(''); + const items=(catalog?.models||[]).filter(m=>m.id!=='default'&&(executorId!==PREVIEW_DEFAULT_EXECUTOR||m.id!=='default-model')); + if(selected&&!items.some(m=>m.id===selected))items.push({id:selected,name:selected}); + sel.innerHTML=``+items.map(m=>``).join(''); sel.disabled=flowReadOnly(); } 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:workflowPreviewExecutor(wf), - model, + model:prev.model??(prev.enabled?'default':''), sourcePath:prev.sourcePath||'dist', indexFile:prev.indexFile||'index.html', spaFallback:prev.spaFallback!==false, @@ -271,7 +266,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:'静态站点构建',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)); @@ -988,7 +986,7 @@ function renderPreviewBuildProperties(host,n){ loadExecutorModelCatalogs().then(()=>{if(executor.isConnected)fill()}); executor.onchange=()=>{ flowHistory.record(); - updatePreviewContract({executorId:executor.value,model:'default'}); + updatePreviewContract({executorId:executor.value,model:''}); n.executorId=executor.value; fill(); dirty(); @@ -1098,6 +1096,11 @@ 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&&state.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/issue-drawer.js b/web/app/issue-drawer.js index c51400f5..13f94746 100644 --- a/web/app/issue-drawer.js +++ b/web/app/issue-drawer.js @@ -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,8 @@ async function sendIssueClarification(initialMessage=''){ attachIssueClarifyStream(issueId); return; } + const model=selectedClarifyModel(); + if(!model)return toast('请先选择模型'); const msg=initialMessage||collectIssueClarifyReply(); if(!msg)return toast('请先选择或填写答案'); const c=issue.clarification||(issue.clarification={}); @@ -425,7 +426,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/runs.js b/web/app/runs.js index fcfdb6c0..c0b74634 100644 --- a/web/app/runs.js +++ b/web/app/runs.js @@ -1279,7 +1279,8 @@ function defaultRunEval(){return{enabled:true,version:1,threshold:70,dimensions: {id:'delivery',name:'交付完整',question:'终态、产物和验证信号是否齐全?',weight:10} ]}} function runEvalModel(){ - return state.runEvalModel||localStorage.getItem('agentflow.runEvalModel')||window.AgentFlowAssistantModels?.DEFAULT||'default'; + const selected=state.runEvalModel||localStorage.getItem('agentflow.runEvalModel'); + return window.AgentFlowAssistantModels?.concreteModelId(selected)||''; } function setRunEvalModel(id){state.runEvalModel=id;localStorage.setItem('agentflow.runEvalModel',id)} 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)} @@ -1369,8 +1370,7 @@ 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 defaultDescription='优先使用你配置的 CodeBuddy。未配置时使用你在个人配置中添加的其他 CLI。'; - const paint=()=>{const keep=runEvalModel();const inp=host.querySelector('[name=runEvalModel]');if(inp)inp.value=keep;api.paint(toggle,keep,defaultDescription)}; + const paint=()=>{const keep=runEvalModel();const inp=host.querySelector('[name=runEvalModel]');if(inp)inp.value=keep;api.paintFeature(toggle,keep)}; paint(); api.load?.().then(paint).catch(paint); if(host.dataset.bound)return; @@ -1380,7 +1380,7 @@ function bindRunEvalModelPicker(host){ const open=menu.hidden; menu.hidden=!open; toggle.setAttribute('aria-expanded',open?'true':'false'); - if(open)api.renderFeatureList(menu,runEvalModel(),id=>{setRunEvalModel(id);paint();menu.hidden=true;toggle.setAttribute('aria-expanded','false')},defaultDescription); + if(open)api.renderFeatureList(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')}); } @@ -1389,7 +1389,6 @@ async function loadRunEval(runId,background){ 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'); @@ -1400,11 +1399,13 @@ async function loadRunEval(runId,background){ } async function startRunEval(run){ if(!['succeeded','failed','cancelled'].includes(run.status))return toast('请等 SOP 跑完后再评测'); + const model=runEvalModel(); + 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/sync-schedule.js b/web/app/sync-schedule.js index f905c070..d950cd16 100644 --- a/web/app/sync-schedule.js +++ b/web/app/sync-schedule.js @@ -99,9 +99,7 @@ function scheduleIssueStatusValues(job){ } function scheduleModelAPI(){return window.AgentFlowAssistantModels} function selectedClarifyModel(){ - const api=window.AgentFlowAssistantModels; - const stored=localStorage.getItem('agentflow.clarifyModel')||''; - return stored||(api&&api.DEFAULT)||'default'; + return window.AgentFlowAssistantModels?.concreteModelId(localStorage.getItem('agentflow.clarifyModel'))||''; } function setClarifyModel(id){ if(!id)return; @@ -116,8 +114,7 @@ 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 defaultDescription='优先使用需求负责人的 CodeBuddy。未配置时使用负责人配置的其他 CLI,未指派需求使用项目负责人的配置。'; - const paint=()=>{const keep=selectedClarifyModel();const hidden=host.querySelector('[data-clarify-model-value]');if(hidden)hidden.value=keep;api.paint(toggle,keep,defaultDescription)}; + const paint=()=>{const keep=selectedClarifyModel();const hidden=host.querySelector('[data-clarify-model-value]');if(hidden)hidden.value=keep;api.paintFeature(toggle,keep)}; paint(); api.load?.().then(paint).catch(paint); if(!bindClarifyModelPicker.docBound){ @@ -142,10 +139,10 @@ function bindClarifyModelPicker(host){ if(open){ api.renderFeatureList(menu, selectedClarifyModel(), id=>{ setClarifyModel(id); - api.paint(toggle, id, defaultDescription); + paint(); menu.hidden=true; toggle.setAttribute('aria-expanded','false'); - }, defaultDescription); + }); } }; } diff --git a/web/assistant-models.css b/web/assistant-models.css index 2971c42e..88fd6398 100644 --- a/web/assistant-models.css +++ b/web/assistant-models.css @@ -41,7 +41,7 @@ } .ai-model-option{padding:8px 10px;gap:8px} .ai-model-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} -.ai-model-description{display:block;margin-top:3px;color:var(--muted-2);font-size:11px;font-weight:400;line-height:1.45;white-space:normal} +.ai-model-empty{padding:8px 10px;color:var(--muted-2);font-size:12px} .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 520d0dea..349644dc 100644 --- a/web/assistant_models_test.js +++ b/web/assistant_models_test.js @@ -71,6 +71,8 @@ const ctx = { 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' }, @@ -126,8 +128,9 @@ vm.runInContext(moduleSource, ctx); // Pickers keep painting before the catalog lands, so the built-in fallback // must already render a usable label. assert.equal(api.engineOf('codex:gpt-5.5'), 'codex'); - api.paint(toggle, api.DEFAULT); - assert.equal(label.textContent, '默认模型'); + api.paintFeature(toggle, api.DEFAULT); + assert.equal(label.textContent, '选择模型'); + assert.equal(toggle.title, ''); assert.equal(icon.dataset.family, 'other'); await api.load(); @@ -147,10 +150,8 @@ vm.runInContext(moduleSource, ctx); toggle.onclick({ stopPropagation() {} }); assert.equal(menu.hidden, false, 'clicking 选择模型 must open the menu'); - assert.equal(menu.children.length, 4, 'menu lists the default and personal models'); - assert.equal(menu.children[0].querySelector('.ai-model-name').textContent, '默认模型'); - assert.match(menu.children[0].querySelector('.ai-model-description').textContent, /需求负责人.*CodeBuddy/); - assert.ok(menu.children[1].className.includes('is-active'), 'stored model is marked active'); + assert.equal(menu.children.length, 3, 'menu only lists concrete personal models'); + assert.ok(menu.children[0].className.includes('is-active'), 'stored model is marked active'); menu.children.find(opt => opt.dataset.id === 'codex:gpt-5.5').onclick(); assert.equal(store.get('agentflow.clarifyModel'), 'codex:gpt-5.5'); @@ -158,10 +159,12 @@ vm.runInContext(moduleSource, ctx); assert.equal(menu.hidden, true); assert.equal(label.textContent, 'GPT-5.5'); assert.equal(ctx.selectedClarifyModel(), 'codex:gpt-5.5'); + store.set('agentflow.clarifyModel', 'codebuddy:default-model'); + ctx.bindClarifyModelPicker(host); + assert.equal(input.value, ''); + assert.equal(label.textContent, '选择模型'); toggle.onclick({ stopPropagation() {} }); - menu.children[0].onclick(); - assert.equal(input.value, 'default'); - assert.equal(label.textContent, '默认模型'); - assert.match(toggle.title, /未指派需求使用项目负责人/); + assert.equal(menu.children.length, 3); + assert.equal(menu.children.some(item => item.getAttribute('aria-selected') === 'true'), false); console.log('assistant models ok'); })().catch(err => { console.error(err); process.exit(1); }); diff --git a/web/bots_test.go b/web/bots_test.go index 5c0d5216..b9780e29 100644 --- a/web/bots_test.go +++ b/web/bots_test.go @@ -44,7 +44,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/syntax_test.go b/web/syntax_test.go index 8713f3c4..42d58dc0 100644 --- a/web/syntax_test.go +++ b/web/syntax_test.go @@ -41,7 +41,8 @@ func TestClarifyModelPickerAndMCPPrompt(t *testing.T) { "agentflow.clarifyModel", "selectedClarifyModel", "data-clarify-model", - "model:selectedClarifyModel()", + "const model=selectedClarifyModel()", + "JSON.stringify({message:msg,history,model})", } { if !strings.Contains(string(app), want) { t.Fatalf("clarify model picker is missing %q", want) diff --git a/webtest/tests/flows-editor.test.mjs b/webtest/tests/flows-editor.test.mjs index 119b1413..cbeff5dd 100644 --- a/webtest/tests/flows-editor.test.mjs +++ b/webtest/tests/flows-editor.test.mjs @@ -84,6 +84,10 @@ test('flow preview properties persist the CLI, model and SPA fallback', async (t executor.value = 'codex'; executor.dispatchEvent(new app.window.Event('change')); const model = app.document.querySelector('#previewNodeModel'); + assert.equal(model.value, ''); + assert.deepEqual([...model.options].map(option => option.value), ['', 'preview-model']); + assert.equal(model.options[0].disabled, true); + await assert.rejects(app.evaluate('saveWorkflow()'), /请选择构建静态站点的模型/); model.value = model.options[model.options.length - 1].value; model.dispatchEvent(new app.window.Event('change')); const spa = app.document.querySelector('#previewNodeSpa'); From 96f95baf75cad400097502be2b32f92825be52ac Mon Sep 17 00:00:00 2001 From: roberttwang Date: Sat, 21 Nov 2026 02:48:54 +0800 Subject: [PATCH 05/25] Separate executor and model choices for platform features --- docs/api/openapi.yaml | 33 +++++ internal/httpapi/assistant_models.go | 24 ++-- internal/httpapi/issues.go | 21 ++++ internal/httpapi/project_write_access_test.go | 35 +++++- internal/httpapi/server.go | 1 + web/app/assistant-models.js | 100 +++++++++++---- web/app/bots.js | 49 +++----- web/app/flows.js | 41 ++++-- web/app/issue-drawer.js | 7 +- web/app/runs.js | 42 ++----- web/app/sync-schedule.js | 90 ++++++------- web/assistant-models.css | 4 +- web/assistant_models_test.js | 118 +++++++++--------- web/bots.css | 4 +- web/bots_test.go | 15 ++- web/index.html | 5 +- web/product-v4.css | 109 ++-------------- web/syntax_test.go | 4 +- webtest/tests/flows-editor.test.mjs | 11 +- webtest/tests/sync-schedule.test.mjs | 14 ++- 20 files changed, 383 insertions(+), 344 deletions(-) diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml index f0b5bd12..de7b0f56 100644 --- a/docs/api/openapi.yaml +++ b/docs/api/openapi.yaml @@ -182,6 +182,16 @@ paths: required: [default, models] properties: default: {type: string} + 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: @@ -191,6 +201,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" @@ -1428,6 +1439,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" diff --git a/internal/httpapi/assistant_models.go b/internal/httpapi/assistant_models.go index f7d0ec5a..c4ddfed8 100644 --- a/internal/httpapi/assistant_models.go +++ b/internal/httpapi/assistant_models.go @@ -238,14 +238,7 @@ func (h *assistantHandlers) models(c *gin.Context) { 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 = assistantChatCatalog(c.Request.Context(), user.CodeBuddyInternetEnvironment, nil) - 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 @@ -285,6 +278,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} + } + refreshCLIModels(ctx, user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey) + catalog := assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, nil) + if saved := codeBuddyPersonalModels(user); len(saved) > 0 { + catalog.Default = saved[0].ID + if listed := selectableCodeBuddyModels(saved); 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 { diff --git a/internal/httpapi/issues.go b/internal/httpapi/issues.go index 4778cba2..8f627b4f 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,26 @@ 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) + 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/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/server.go b/internal/httpapi/server.go index 1f4ef7a0..81738dd5 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -386,6 +386,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) diff --git a/web/app/assistant-models.js b/web/app/assistant-models.js index c5cb67aa..06b8b2f8 100644 --- a/web/app/assistant-models.js +++ b/web/app/assistant-models.js @@ -121,10 +121,6 @@ const credits = creditLabel(item); toggle.title = credits ? `${item?.name || id} ${credits}` : (item?.name || id || ''); } - function paintFeature(toggle, selectedId) { - const selected = concreteModelId(selectedId); - paintItem(toggle, selected ? modelMeta(selected) : null); - } // renderOptions renders any {id,name,family,credits,icon} list; icon:false // skips the icon slot (effort levels, custom model entry). function renderOptions(menu, items, selectedId, onPick) { @@ -164,28 +160,79 @@ function renderList(menu, selectedId, onPick) { renderOptions(menu, catalog.models || [], selectedId, onPick); } - function renderFeatureList(menu, selectedId, onPick) { - const selected = concreteModelId(selectedId); - const items = []; - for (const model of catalog.models) { - const engine = catalog.engines?.find(item => item.id === engineOf(model.id)); - if (engine && !(engine.personal ?? engine.configured)) continue; - const id = !model.engine && selected === 'codebuddy:' + model.id ? selected : model.id; - items.push({...model, id, name: engine ? model.name + ' · ' + engine.name : model.name}); - } - if (selected && !items.some(item => item.id === selected)) { - items.push(modelMeta(selected)); - } - renderOptions(menu, items, selected, onPick); - if (!items.length) { - const empty = document.createElement('div'); - empty.className = 'ai-model-empty'; - empty.textContent = '暂无可选模型'; - menu.append(empty); + function featurePickerHTML(modelName = '') { + return ` + `; + } + function qualifiedModel(engine, id) { + return id.startsWith(engine + ':') ? id : engine + ':' + id; + } + function featureExecutors(source) { + const engines = (source.engines || []).map(engine => ({ + ...engine, available: engine.personal ?? engine.configured, 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?.available) engine.models.push({...model, id: qualifiedModel(engine.id, model.id)}); } + return engines; + } + function bindFeaturePicker(host, {model = '', 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); + let engine = selected ? engines.find(engine => engine.id === engineOf(selected, source)) : undefined; + 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.models.length) || engines.find(item => item.available); + } + 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 configured = current?.id === 'codebuddy' && concreteModelId(source.default); + const preferred = configured && qualifiedModel(current.id, configured); + const next = value || items.find(item => item.id === preferred)?.id || items[0]?.id || ''; + 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(); } @@ -206,13 +253,14 @@ DEFAULT: DEFAULT_MODEL, catalog: () => catalog, cliIcon: id => Object.hasOwn(CLI_ICON, id) ? '/images/credentials/' + CLI_ICON[id] : '', + bindFeaturePicker, concreteModelId, engineOf, + featurePickerHTML, + fetchCatalog, load, paint, - paintFeature, paintItem, - renderFeatureList, renderList, renderOptions }; diff --git a/web/app/bots.js b/web/app/bots.js index ed64321c..eab8ba1c 100644 --- a/web/app/bots.js +++ b/web/app/bots.js @@ -1,30 +1,5 @@ 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.paintFeature(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.renderFeatureList(menu,value.value,id=>{ - const qualified=models.engineOf(id)==='codebuddy'&&!id.startsWith('codebuddy:')?'codebuddy:'+id:id; - value.value=qualified; - models.paintFeature(toggle,qualified); - 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,'发送测试']]; @@ -45,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||'')!==(stored.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. @@ -104,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; @@ -322,21 +302,26 @@ 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-model-toggle]')?.focus(); + 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}; diff --git a/web/app/flows.js b/web/app/flows.js index d6bfaf5c..9fbfb8ab 100644 --- a/web/app/flows.js +++ b/web/app/flows.js @@ -10,13 +10,20 @@ function workflowPreviewModel(wf){ const model=String(workflowPreviewContract(wf)?.model||'').trim(); return model==='default'||(model==='default-model'&&workflowPreviewExecutor(wf)===PREVIEW_DEFAULT_EXECUTOR)?'':model; } +function previewModelOptions(executorId){ + return (executorModelCatalogs()[executorId]?.models||[]).filter(m=>m.id!=='default'&&(executorId!==PREVIEW_DEFAULT_EXECUTOR||m.id!=='default-model')); +} +function defaultPreviewModel(executorId, items=previewModelOptions(executorId)){ + const preferred=executorModelCatalogs()[executorId]?.default; + return items.find(item=>item.id===preferred)?.id||items[0]?.id||''; +} function fillPreviewModelSelect(sel, selected, executorId){ - if(!sel)return; - const catalog=executorModelCatalogs()[executorId]; - const items=(catalog?.models||[]).filter(m=>m.id!=='default'&&(executorId!==PREVIEW_DEFAULT_EXECUTOR||m.id!=='default-model')); - if(selected&&!items.some(m=>m.id===selected))items.push({id:selected,name:selected}); - sel.innerHTML=``+items.map(m=>``).join(''); - sel.disabled=flowReadOnly(); + 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; @@ -974,14 +981,20 @@ function renderPreviewBuildProperties(host,n){
    主配置

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

    -
    +
    从左侧「成功」出口连到下一步;预览节点没有失败出口
    `; const executor=$('#previewNodeExecutor'),sel=$('#previewNodeModel'); - const fill=()=>fillPreviewModelSelect(sel,workflowPreviewModel(state.workflow),executor.value); + 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=()=>{ @@ -1097,9 +1110,15 @@ 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&&state.workflow.preview.model===''){ - const message='请选择构建静态站点的模型'; - toast(message); - throw new Error(message); + 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(){ diff --git a/web/app/issue-drawer.js b/web/app/issue-drawer.js index 13f94746..baeafc87 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); @@ -408,7 +408,10 @@ async function sendIssueClarification(initialMessage=''){ attachIssueClarifyStream(issueId); return; } - const model=selectedClarifyModel(); + const picker=$('#issueDetailBody [data-clarify-model]'); + await picker?.modelPickerReady; + if(!picker?.isConnected||state.issueDetailData?.issue?.id!==issueId||issueClarifyJobs.get(issueId)?.attached)return; + const model=picker.querySelector('[data-feature-model]')?.value; if(!model)return toast('请先选择模型'); const msg=initialMessage||collectIssueClarifyReply(); if(!msg)return toast('请先选择或填写答案'); diff --git a/web/app/runs.js b/web/app/runs.js index c0b74634..19ef14a6 100644 --- a/web/app/runs.js +++ b/web/app/runs.js @@ -1278,11 +1278,6 @@ function defaultRunEval(){return{enabled:true,version:1,threshold:70,dimensions: {id:'recovery',name:'错误恢复',question:'相同错误是否反复出现?',weight:10}, {id:'delivery',name:'交付完整',question:'终态、产物和验证信号是否齐全?',weight:10} ]}} -function runEvalModel(){ - const selected=state.runEvalModel||localStorage.getItem('agentflow.runEvalModel'); - return window.AgentFlowAssistantModels?.concreteModelId(selected)||''; -} -function setRunEvalModel(id){state.runEvalModel=id;localStorage.setItem('agentflow.runEvalModel',id)} 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||[]; @@ -1301,16 +1296,10 @@ function runEvalPaneHTML(run){
    -
    评测大模型
    +
    评测执行器与模型
    -
    - - - +
    + ${window.AgentFlowAssistantModels?.featurePickerHTML()||''}
    `; -} -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.paintFeature(toggle,keep)}; - paint(); - 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.renderFeatureList(menu, selectedClarifyModel(), id=>{ - setClarifyModel(id); - paint(); - menu.hidden=true; - toggle.setAttribute('aria-expanded','false'); - }); - } - }; + return `
    ${scheduleModelAPI()?.featurePickerHTML()||''}
    `; +} +function bindClarifyModelPicker(host, issue){ + const models=scheduleModelAPI(); + return models?.bindFeaturePicker(host,{ + model:localStorage.getItem('agentflow.clarifyModel'), + readOnly:host.hasAttribute('data-picker-readonly'), + onChange:id=>localStorage.setItem('agentflow.clarifyModel',id), + 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 @@ -156,6 +120,11 @@ function scheduleModelCatalog(){ function scheduleEngineModels(engine){ return (scheduleModelCatalog().models||[]).filter(m=>(m.engine||'codebuddy')===engine); } +function scheduleDefaultModel(engine){ + const models=scheduleEngineModels(engine); + const preferred=engine==='codebuddy'&&models.find(item=>item.id===scheduleModelCatalog().default); + return preferred?.id||models[0]?.id||''; +} function scheduleModelEngine(id){ return scheduleModelAPI()?.engineOf?.(id,scheduleModelCatalog())||'codebuddy'; } @@ -224,8 +193,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()}); @@ -237,12 +205,21 @@ 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 fallback=!form.elements.id.value&&!picker.concreteModelId(selected) + ?(catalog?.engines||[]).filter(engine=>engine.configured).map(engine=>scheduleDefaultModel(engine.id)).find(Boolean) + :''; + paintScheduleModel(fallback||selected||picker.DEFAULT); } function paintScheduleModel(selected){ const api=scheduleModelAPI(); @@ -367,6 +344,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||{}); @@ -374,7 +352,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; @@ -592,6 +571,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?'':'触发配置'), @@ -618,7 +602,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/assistant-models.css b/web/assistant-models.css index 88fd6398..350e8fb3 100644 --- a/web/assistant-models.css +++ b/web/assistant-models.css @@ -41,7 +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} -.ai-model-empty{padding:8px 10px;color:var(--muted-2);font-size:12px} +.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 349644dc..c9bd65b8 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,29 +37,30 @@ 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 () => ({ @@ -82,8 +78,6 @@ const ctx = { }), }; 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); @@ -125,46 +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.engineOf('codex:gpt-5.5'), 'codex'); - api.paintFeature(toggle, api.DEFAULT); - assert.equal(label.textContent, '选择模型'); - assert.equal(toggle.title, ''); - assert.equal(icon.dataset.family, 'other'); - + 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'); + 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'); + 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']); - toggle.onclick({ stopPropagation() {} }); - assert.equal(menu.hidden, false, 'clicking 选择模型 must open the menu'); - assert.equal(menu.children.length, 3, 'menu only lists concrete personal models'); - assert.ok(menu.children[0].className.includes('is-active'), 'stored model is marked active'); + 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.equal(codexOnly.executor.options[0].disabled, true); + assert.equal(codexOnly.model.value, 'codex:gpt-5.5'); - menu.children.find(opt => opt.dataset.id === 'codex:gpt-5.5').onclick(); - assert.equal(store.get('agentflow.clarifyModel'), 'codex:gpt-5.5'); - assert.equal(input.value, 'codex:gpt-5.5'); - assert.equal(menu.hidden, true); - assert.equal(label.textContent, 'GPT-5.5'); - assert.equal(ctx.selectedClarifyModel(), 'codex:gpt-5.5'); - store.set('agentflow.clarifyModel', 'codebuddy:default-model'); - ctx.bindClarifyModelPicker(host); - assert.equal(input.value, ''); - assert.equal(label.textContent, '选择模型'); - toggle.onclick({ stopPropagation() {} }); - assert.equal(menu.children.length, 3); - assert.equal(menu.children.some(item => item.getAttribute('aria-selected') === 'true'), false); + 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 b9780e29..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) diff --git a/web/index.html b/web/index.html index 48d4376d..c3be8ba9 100644 --- a/web/index.html +++ b/web/index.html @@ -1139,7 +1139,7 @@

    触发配置

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

    diff --git a/chatbot/src/credentials.js b/chatbot/src/credentials.js index eef30323..f6931ff9 100644 --- a/chatbot/src/credentials.js +++ b/chatbot/src/credentials.js @@ -179,11 +179,11 @@ export function credentialHint(text) { } export function openCredentialSettings(field, sshRemote) { - const credential = CREDENTIALS[field] ? field : ""; + const credential = field === "executors" || Object.hasOwn(CREDENTIALS, field) ? field : ""; if (window.parent !== window) window.parent.postMessage( { type: "agentflow-chat-open-view", view: "settings", credential, ...(credential === "gitSshKey" && sshRemote ? { sshRemote } : {}) }, location.origin, ); - else location.href = "/#/settings"; + else location.href = credential === "executors" ? "/#/settings/executors" : "/#/settings"; } diff --git a/chatbot/src/styles.css b/chatbot/src/styles.css index 9125c9f0..bc84f188 100644 --- a/chatbot/src/styles.css +++ b/chatbot/src/styles.css @@ -1577,33 +1577,37 @@ small { .credential-notice { display: flex; align-items: center; - gap: 8px; + gap: 10px; margin-bottom: 10px; - padding: 9px 11px; - border: 1px solid #f3e2b8; + padding: 8px 10px 8px 12px; + border: 1px solid var(--line); border-radius: 10px; - background: #fffbf0; - color: #7a5a12; - font-size: 12px; + background: var(--subtle); + color: var(--text); + font-size: 13px; line-height: 1.5; } +.credential-notice > svg { + flex: none; + color: var(--muted); +} .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 06bde4ed..cb74174b 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, @@ -87,7 +87,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(""), @@ -101,6 +104,7 @@ export function useChat() { ), [models, setModels] = useState([]), [catalogEngines, setCatalogEngines] = useState([]), + [accountDefaults, setAccountDefaults] = useState(null), [modelCatalogRefresh, requestModelCatalogRefresh] = useState(0), [sessions, setSessions] = useState([]), [session, setSession] = useState(null), @@ -134,7 +138,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) => { @@ -210,7 +216,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); @@ -251,6 +258,8 @@ export function useChat() { setSession(stored); } const applyModelCatalog = useCallback((catalog) => { + accountDefaultsRef.current = catalog.preferences || null; + setAccountDefaults(accountDefaultsRef.current); setModels(catalog.models || []); setCatalogEngines(catalog.engines || []); setCodeBuddyDefault({ id: catalog.default || "default", name: "默认", efforts: catalog.defaultEfforts }); @@ -301,7 +310,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 || []); @@ -632,23 +641,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] || ""; - useEffect(() => { - if (!user || user.isGuest || activeId || submitting || !catalogEngines.length || - readComposerPreference("executor")) return; - // Account-authenticated runners advertise their runtime independently of - // the personal API catalog. Keep a selected CLI if that machine can run it. - const machine = executionMachines.machines.find(item => item.id === executionMachines.defaultRunnerId); - if (machine?.runtimes?.some(runtime => runtime.provider === executor && runtime.authMode !== "personal")) return; - const next = catalogEngines.find(engine => engine.configured); - if (next && next.id !== executor) setSelection({ executor: next.id, model: null, effort: null }); - }, [user, activeId, submitting, catalogEngines, executor, executionMachines.machines, executionMachines.defaultRunnerId]); + 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, ); @@ -658,7 +679,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)) @@ -667,9 +688,11 @@ export function useChat() { const listedModel = findExecutorModel(executorModels, executor, model); const hasSelectedModel = model !== null && !listedModel?.disabled && !listedModel?.unavailable && (conversation || !executorModels.length || listedModel); + const saved = draft && accountDefaults?.executor === executor ? accountDefaults : null; + const savedModel = saved ? findExecutorModel(executorModels, executor, saved.model) : null; const selectedModel = hasSelectedModel ? model : preferredModel( executorModels, executor, codeBuddyDefault.id, - draft ? readComposerPreference(`model.${executor}`) : null, + savedModel?.id ?? (draft && !saved ? readComposerPreference(`model.${executor}`) : null), ); const availableModel = sponsored && !sponsoredModels.includes(selectedModel) ? sponsoredModel : selectedModel; const catalogEntry = findExecutorModel(executorModels, executor, availableModel) ?? @@ -684,7 +707,8 @@ export function useChat() { : undefined; // null follows the browser preference, while "" is the CLI's default level. const preferredEffort = ((model === null || hasSelectedModel) ? effort : null) ?? - (draft ? readComposerPreference(effortPreference(executor, availableModel)) : 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; @@ -693,13 +717,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) => { @@ -787,12 +811,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 }); } @@ -835,31 +860,20 @@ 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]); useEffect(() => { const onMessage = (e) => { if ( @@ -872,13 +886,14 @@ export function useChat() { requestModelCatalogRefresh((revision) => revision + 1); } }; + 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]); useEffect(() => { if (!ready || !modelCatalogRefresh) return; void refreshUser(); @@ -1036,6 +1051,7 @@ export function useChat() { setError("会话仍在加载,请稍候再发送。"); return false; } + if (!executor) return false; const modelError = composerModelError(composerModel); if (modelError) { setError(modelError); @@ -1099,8 +1115,9 @@ export function useChat() { user && !user.isGuest ) { + 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); if (fresh && !fresh.codeBuddyApiKeyConfigured) { if (viewingTarget()) setError("请先在个人配置中配置自己的 CodeBuddy API Key"); @@ -1573,6 +1590,7 @@ export function useChat() { }, []); return { user, + defaultApproval: accountDefaults?.approval, refreshUser, users, issueId: session?.issueId || (!activeId ? draftIssueId : ""), @@ -1589,11 +1607,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 adce39be..35325728 100644 --- a/chatbot/tests/app-render.test.jsx +++ b/chatbot/tests/app-render.test.jsx @@ -893,10 +893,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: [], @@ -909,11 +912,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 d16bb7d9..f6fa9a6b 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")); @@ -755,7 +834,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); }); @@ -844,7 +923,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 46b59ea8..a6af5bfc 100644 --- a/chatbot/tests/quick-access-wizard.test.jsx +++ b/chatbot/tests/quick-access-wizard.test.jsx @@ -13,7 +13,6 @@ 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: "测试", @@ -36,7 +35,7 @@ const { project, user, apiMock, writeMock, mockState } = vi.hoisted(() => { if (path.includes("/verify")) return { valid: true }; return []; }); - const mockState = { failClone: false, unconfigured: false, users: null, sshKeys: null }; + const mockState = { failClone: false, unconfigured: false, sshKeys: null }; const writeMock = vi.fn(async (path, body) => { if (path.includes("/git-token/verify")) return { valid: true }; if (path === "/api/projects") return { ...project, ...body }; @@ -203,7 +202,7 @@ describe("QuickAccessWizard", () => { ); await screen.findByRole("dialog"); await userAction.click(screen.getByRole("button", { name: "下一步" })); - expect(screen.getByRole("alert")).toHaveTextContent("请先配置 GitHub Git Token、Git SSH 密钥或一种模型 CLI 的凭据"); + expect(screen.getByRole("alert")).toHaveTextContent("请先添加一个 Git 凭据或执行器。"); expect(screen.queryByText(/工蜂/)).toBeNull(); await userAction.click(screen.getByText("使用访问令牌(高级)")); await userAction.type( @@ -219,143 +218,32 @@ describe("QuickAccessWizard", () => { mockState.unconfigured = false; }); - test("saves a typed CodeBuddy key when moving past the credential step", async () => { + test("opens the executor picker from 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 () => { - 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 parent = { postMessage: vi.fn() }; + 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", - ); - } finally { - mockState.users = null; - } - }); - - test("a refresh after switching to 国际站 elsewhere drops the omitted environment", async () => { - let environment = "internal"; - mockState.users = () => [ - { ...user, ...(environment ? { codeBuddyInternetEnvironment: environment } : {}) }, - ]; - writeMock.mockClear(); - const userAction = userEvent.setup(); - try { - render( - , - ); - await screen.findByRole("dialog"); - const keyLink = screen.getByRole("link", { name: /获取 API Key/ }); - await waitFor(() => - expect(keyLink).toHaveAttribute("href", "https://copilot.tencent.com/profile/"), - ); - // 个人配置 switched the environment to 国际站; the users API omits it now. - environment = ""; - window.dispatchEvent(new Event("focus")); - await waitFor(() => - expect(keyLink).toHaveAttribute("href", "https://www.codebuddy.ai/profile/keys"), - ); - await userAction.type(screen.getByLabelText("CodeBuddy API Key"), "ck_new"); - await userAction.click(screen.getByRole("button", { name: "下一步" })); - await screen.findByText("项目与仓库", { selector: "h3" }); - expect(writeMock).toHaveBeenCalledWith( - "/api/users/1/credentials", - { codeBuddyApiKey: "ck_new", codeBuddyInternetEnvironment: "" }, - "PUT", + expect(screen.queryByLabelText("CodeBuddy API Key")).not.toBeInTheDocument(); + await userEvent.click(screen.getByRole("button", { name: "执行器配置" })); + expect(parent.postMessage).toHaveBeenCalledWith( + { type: "agentflow-chat-open-view", view: "settings", credential: "executors" }, + location.origin, ); + expect(onClose).toHaveBeenCalledTimes(1); } finally { - mockState.users = null; + parentWindow.mockRestore(); + mockState.unconfigured = false; } }); diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml index de7b0f56..8321d720 100644 --- a/docs/api/openapi.yaml +++ b/docs/api/openapi.yaml @@ -182,6 +182,8 @@ paths: required: [default, models] properties: default: {type: string} + preferences: + $ref: "#/components/schemas/AssistantDefaults" engines: type: array items: @@ -686,8 +688,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} @@ -4143,6 +4148,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 @@ -4539,6 +4551,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 53410851..046eee19 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -33,7 +33,8 @@ Use `AGENTFLOW_MYSQL_DSN` for your own MySQL deployment. A fresh account command ## Choosing an executor -- The model pickers for requirement clarification, Bot replies, SOP notification reports and run evaluation 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 existing CodeBuddy default when the account has a personal CodeBuddy key and uses the first configured alternative otherwise. A concrete model is passed unchanged to its CLI. +- 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. diff --git a/internal/application/operations.go b/internal/application/operations.go index a7c4839a..cc2571ea 100644 --- a/internal/application/operations.go +++ b/internal/application/operations.go @@ -123,7 +123,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 CodeBuddy prompt only. 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. 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/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/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..40d96e8a 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,6 +40,7 @@ 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"` 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/runner_dispatch.go b/internal/engine/runner_dispatch.go index 82d1cc3d..fdc7e5ee 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] diff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.go index 70869f51..dd03b074 100644 --- a/internal/httpapi/assistant.go +++ b/internal/httpapi/assistant.go @@ -1567,7 +1567,7 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U break } 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}) - inv.credentials = runtime.RunCredentials{CodeBuddy: runtime.CodeBuddyCredential{APIKey: user.CodeBuddyAPIKey, InternetEnvironment: user.CodeBuddyInternetEnvironment}} + inv.credentials = runtime.RunCredentials{CodeBuddy: runtime.CodeBuddyUserCredential(user)} inv.sessionRef = sessionID } if err != nil { @@ -1719,6 +1719,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 a2a5d911..65057300 100644 --- a/internal/httpapi/assistant_approval_review.go +++ b/internal/httpapi/assistant_approval_review.go @@ -142,7 +142,7 @@ func (h *assistantHandlers) approvalReviewer(req assistantRequest, user domain.U selected := assistantRequestModel(req.Executor, req.Model) engine, _ := assistantModelEngine(selected) var models []string - if engine != assistantEngineCodeBuddy || (req.RequireExactModel && selected != "") { + if engine != assistantEngineCodeBuddy || user.CodeBuddyBaseURL != "" || (req.RequireExactModel && selected != "") { models = []string{selected} } else if h.reviewCatalog != nil { models = assistantApprovalReviewModels(h.reviewCatalog(user.CodeBuddyInternetEnvironment)) 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_engines.go b/internal/httpapi/assistant_engines.go index 66942146..3bee9e2f 100644 --- a/internal/httpapi/assistant_engines.go +++ b/internal/httpapi/assistant_engines.go @@ -111,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 { @@ -311,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) @@ -668,10 +666,13 @@ func writeAssistantEngineState(root string, state assistantEngineState) error { // 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) == "" && (strings.TrimSpace(req.Model) == "" || req.Model == assistantDefaultModel) { + 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 diff --git a/internal/httpapi/assistant_models.go b/internal/httpapi/assistant_models.go index c4ddfed8..f173f81c 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() {} @@ -139,6 +140,12 @@ func refreshCLIModels(ctx context.Context, environment, apiKey string) { 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 { @@ -258,6 +265,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" { @@ -282,11 +292,11 @@ func personalCodeBuddyCatalog(ctx context.Context, user domain.User) assistantMo if strings.TrimSpace(user.CodeBuddyAPIKey) == "" { return assistantModelCatalog{Default: assistantDefaultModel} } - refreshCLIModels(ctx, user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey) + refreshOfficialCodeBuddyModels(ctx, user) catalog := assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, nil) - if saved := codeBuddyPersonalModels(user); len(saved) > 0 { - catalog.Default = saved[0].ID - if listed := selectableCodeBuddyModels(saved); len(listed) > 0 { + if personal := codeBuddyPersonalModels(ctx, user); len(personal) > 0 { + catalog.Default = personal[0].ID + if listed := selectableCodeBuddyModels(personal); len(listed) > 0 { catalog.Models = listed } } @@ -309,25 +319,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 diff --git a/internal/httpapi/assistant_process.go b/internal/httpapi/assistant_process.go index 4f764882..52cd1ad1 100644 --- a/internal/httpapi/assistant_process.go +++ b/internal/httpapi/assistant_process.go @@ -158,6 +158,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) @@ -498,6 +502,9 @@ func (h *assistantHandlers) testRunnerCLI(ctx context.Context, runnerID, provide model := provider + ":default" if provider == assistantEngineCodeBuddy { model = loadAssistantModels(ctx, user.CodeBuddyInternetEnvironment).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 801bde44..1939d8cd 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 acde23c7..6202e90b 100644 --- a/internal/httpapi/assistant_schedule.go +++ b/internal/httpapi/assistant_schedule.go @@ -84,7 +84,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. @@ -130,9 +130,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) { @@ -151,21 +150,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 { @@ -174,8 +178,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)) } @@ -210,6 +218,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) { @@ -224,6 +255,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 7bf67711..95221d88 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 @@ -72,7 +73,7 @@ func (h *assistantHandlers) usesSharedKey(user domain.User) bool { func (h *assistantHandlers) chatCatalog(ctx context.Context, user domain.User) assistantModelCatalog { key, shared := h.assistantSharedKey() if !shared || !h.usesSharedKey(user) { - return withCodeBuddyPersonalModels(assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, nil), user) + return withCodeBuddyPersonalModels(ctx, assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, nil), user) } return restrictAssistantCatalog(assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, key.Models), key.Models) } @@ -87,7 +88,7 @@ func (h *assistantHandlers) turnCatalog(ctx context.Context, user domain.User, m if model == "" || assistantCatalogLists(catalog, model) { return catalog } - refreshCLIModels(ctx, user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey) + 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) diff --git a/internal/httpapi/assistant_sponsor_test.go b/internal/httpapi/assistant_sponsor_test.go index a460801c..602937bc 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 diff --git a/internal/httpapi/assistant_task_engines_test.go b/internal/httpapi/assistant_task_engines_test.go index 353be25b..7e09d9b9 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", @@ -88,6 +89,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) } @@ -100,8 +105,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 2cb840a4..a06898bf 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 @@ -222,7 +223,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 { @@ -234,7 +236,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} @@ -243,10 +244,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 { @@ -479,17 +480,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(ctx, env), 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(ctx, env), user); model == requested { + engine, id := assistantModelEngine(requested) + if engine == assistantEngineCodeBuddy { + env := user.CodeBuddyInternetEnvironment + catalog := withCodeBuddyPersonalModels(ctx, loadAssistantModels(ctx, env), 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(ctx, env)); 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 3c114da9..bf28514b 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/cli_models_probe.go b/internal/httpapi/cli_models_probe.go index 195426d6..a834ff73 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 diff --git a/internal/httpapi/executor_models.go b/internal/httpapi/executor_models.go index 39399c65..d19fd230 100644 --- a/internal/httpapi/executor_models.go +++ b/internal/httpapi/executor_models.go @@ -221,9 +221,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 - if key := strings.TrimSpace(user.CodeBuddyAPIKey); key != "" { - refreshCLIModels(c.Request.Context(), user.CodeBuddyInternetEnvironment, key) - } + refreshOfficialCodeBuddyModels(c.Request.Context(), user) } } _, kimiBaseURL := assistantEngineCredential(user, runtime.AgentCLIKimi) diff --git a/internal/httpapi/feature_model.go b/internal/httpapi/feature_model.go index 5075570b..a7bb710a 100644 --- a/internal/httpapi/feature_model.go +++ b/internal/httpapi/feature_model.go @@ -29,12 +29,30 @@ var ( 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 @@ -53,6 +71,9 @@ func resolveFeatureModel(user domain.User, requested string) (string, error) { } 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 diff --git a/internal/httpapi/feature_model_test.go b/internal/httpapi/feature_model_test.go index 0a67f0b5..56ab80dc 100644 --- a/internal/httpapi/feature_model_test.go +++ b/internal/httpapi/feature_model_test.go @@ -26,6 +26,8 @@ func TestFeatureModelPreservesExplicitChoice(t *testing.T) { 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 @@ -37,6 +39,10 @@ func TestFeatureModelPreservesExplicitChoice(t *testing.T) { {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"}, } { @@ -47,6 +53,13 @@ func TestFeatureModelPreservesExplicitChoice(t *testing.T) { 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 diff --git a/internal/httpapi/issues.go b/internal/httpapi/issues.go index 8f627b4f..81907eb7 100644 --- a/internal/httpapi/issues.go +++ b/internal/httpapi/issues.go @@ -492,6 +492,9 @@ func (h issuesHandlers) clarifyModels(c *gin.Context, issue domain.Issue) { 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") diff --git a/internal/httpapi/schedule.go b/internal/httpapi/schedule.go index 7f5c27a2..0386b223 100644 --- a/internal/httpapi/schedule.go +++ b/internal/httpapi/schedule.go @@ -243,6 +243,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) { @@ -267,6 +271,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 } @@ -309,10 +317,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 { diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 81738dd5..acb2d4e6 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -775,6 +775,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 := "" @@ -792,8 +799,9 @@ 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, }) } diff --git a/internal/httpapi/stream.go b/internal/httpapi/stream.go index e08f596d..beb9d5d9 100644 --- a/internal/httpapi/stream.go +++ b/internal/httpapi/stream.go @@ -688,7 +688,7 @@ func (h *streamHandlers) executeClarify(ctx context.Context, issue domain.Issue, var credentials runtime.RunCredentials if useCodeBuddy { credentials = runtime.RunCredentials{ - CodeBuddy: runtime.CodeBuddyCredential{APIKey: responsible.CodeBuddyAPIKey, InternetEnvironment: responsible.CodeBuddyInternetEnvironment}, + CodeBuddy: runtime.CodeBuddyUserCredential(responsible), GitHTTPCredentials: h.repo.GitHTTPCredentialSecrets(ctx, responsible.ID), } } 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/repo/models.go b/internal/repo/models.go index 524e2577..40745ec4 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/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/user_assistant_defaults.go b/internal/repo/user_assistant_defaults.go new file mode 100644 index 00000000..c9d866af --- /dev/null +++ b/internal/repo/user_assistant_defaults.go @@ -0,0 +1,36 @@ +package repo + +import ( + "errors" + "strings" + + "agentflow/internal/domain" +) + +var ErrAssistantDefaultExecutorUnavailable = errors.New("请选择已配置的执行器") + +func hasAssistantExecutor(user domain.User, executor string) bool { + var key string + switch executor { + case "codebuddy": + key = user.CodeBuddyAPIKey + case "codex": + key = user.CodexAPIKey + case "claude-code": + key = user.ClaudeCodeAPIKey + default: + if domain.IsAgentCLIKind(executor) { + key = user.AgentCLICredentials[executor].APIKey + } + } + return strings.TrimSpace(key) != "" +} + +func firstAssistantExecutor(user domain.User) string { + for _, executor := range append([]string{"codebuddy", "codex", "claude-code"}, domain.AgentCLIExecutorKinds...) { + if hasAssistantExecutor(user, executor) { + return executor + } + } + return "" +} diff --git a/internal/repo/users.go b/internal/repo/users.go index f1fdba34..917388d8 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 !hasAssistantExecutor(user, update.AssistantDefaults.Executor) { + return domain.User{}, ErrAssistantDefaultExecutorUnavailable + } + user.AssistantDefaults = *update.AssistantDefaults + } else if !hasAssistantExecutor(user, 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/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 8c0fe5a2..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 diff --git a/internal/runtime/conversation_process.go b/internal/runtime/conversation_process.go index 0ceca393..9b381a0a 100644 --- a/internal/runtime/conversation_process.go +++ b/internal/runtime/conversation_process.go @@ -285,6 +285,10 @@ func (p *ConversationProcessPool) Handle(ctx context.Context, root, workspace st defer stopWrite() if req.EOF { err = input.Close() + // 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 { _, err = io.WriteString(input, conversationRemap(req.Data, req.SourceRoot, root)) } 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_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/web/app.js b/web/app.js index 36c167d9..fcfd9abc 100644 --- a/web/app.js +++ b/web/app.js @@ -928,6 +928,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(); @@ -951,7 +952,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(); @@ -1556,7 +1558,7 @@ 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)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); diff --git a/web/app/access.js b/web/app/access.js index 0a8530fe..49efb84e 100644 --- a/web/app/access.js +++ b/web/app/access.js @@ -39,7 +39,7 @@ function accessViewActive(){return !!$('#guideView')?.classList.contains('active let credentialFocusRequest=0; 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'); @@ -57,9 +57,17 @@ function gotoCredential(name,sshRemote){ } if(performance.now() ({ - ...engine, available: engine.personal ?? engine.configured, models: [] - })); + 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?.available) engine.models.push({...model, id: qualifiedModel(engine.id, model.id)}); + if (engine) engine.models.push({...model, id: qualifiedModel(engine.id, model.id)}); } return engines; } - function bindFeaturePicker(host, {model = '', readOnly = false, keepSaved = false, onChange, loadCatalog = load} = {}) { + 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]'); @@ -186,15 +194,24 @@ host.modelPickerReady = loadCatalog().then(source => { if (!host.isConnected) return; const engines = featureExecutors(source); - let selected = concreteModelId(model); - let engine = selected ? engines.find(engine => engine.id === engineOf(selected, source)) : undefined; + 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.models.length) || engines.find(item => item.available); + 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); @@ -208,9 +225,7 @@ const remembered = new Map(); const paintModels = (current, value) => { const items = current?.models || []; - const configured = current?.id === 'codebuddy' && concreteModelId(source.default); - const preferred = configured && qualifiedModel(current.id, configured); - const next = value || items.find(item => item.id === preferred)?.id || items[0]?.id || ''; + 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; @@ -242,7 +257,7 @@ loading = fetchCatalog().then(data => { if (Array.isArray(data?.models)) { const models = data.models.filter(m => concreteModelId(m.id)); - catalog = {default: data.default || DEFAULT_MODEL, models, engines: data.engines || []}; + catalog = {default: data.default || DEFAULT_MODEL, models, engines: data.engines || [], preferences: data.preferences}; } return catalog; }).catch(() => catalog).finally(() => { loading = null; }); @@ -256,11 +271,13 @@ bindFeaturePicker, concreteModelId, engineOf, + featureExecutors, featurePickerHTML, fetchCatalog, load, paint, paintItem, + preferredFeatureModel, renderList, renderOptions }; diff --git a/web/app/flows.js b/web/app/flows.js index 9fbfb8ab..e7fae8e2 100644 --- a/web/app/flows.js +++ b/web/app/flows.js @@ -14,6 +14,9 @@ function previewModelOptions(executorId){ return (executorModelCatalogs()[executorId]?.models||[]).filter(m=>m.id!=='default'&&(executorId!==PREVIEW_DEFAULT_EXECUTOR||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||''; } @@ -28,11 +31,12 @@ function fillPreviewModelSelect(sel, selected, executorId){ function ensurePreviewContract(){ const wf=state.workflow;if(!wf)return null; const prev=workflowPreviewContract(wf)||{}; + const preferred=state.data.assistantDefaults?.executor; wf.preview={ ...prev, enabled:true, kind:'static', - executorId:workflowPreviewExecutor(wf), + executorId:prev.executorId||(preferred==='claude-code'?'claude':preferred)||PREVIEW_DEFAULT_EXECUTOR, model:prev.model??(prev.enabled?'default':''), sourcePath:prev.sourcePath||'dist', indexFile:prev.indexFile||'index.html', 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/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..d6ab3771 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); diff --git a/web/app/issue-drawer.js b/web/app/issue-drawer.js index baeafc87..e0a151af 100644 --- a/web/app/issue-drawer.js +++ b/web/app/issue-drawer.js @@ -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=[]; @@ -410,9 +410,9 @@ async function sendIssueClarification(initialMessage=''){ } const picker=$('#issueDetailBody [data-clarify-model]'); await picker?.modelPickerReady; - if(!picker?.isConnected||state.issueDetailData?.issue?.id!==issueId||issueClarifyJobs.get(issueId)?.attached)return; - const model=picker.querySelector('[data-feature-model]')?.value; - if(!model)return toast('请先选择模型'); + if((picker&&!picker.isConnected)||state.issueDetailData?.issue?.id!==issueId||issueClarifyJobs.get(issueId)?.attached)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={}); diff --git a/web/app/runs.js b/web/app/runs.js index 19ef14a6..5f4d0dc5 100644 --- a/web/app/runs.js +++ b/web/app/runs.js @@ -1344,7 +1344,7 @@ function runEvalRecHTML(item){ return `
    ${escapeHTML(item.title||item.action||'建议')}

    ${escapeHTML(item.rationale||'')}

    ${escapeHTML(item.target||'')} ${escapeHTML(item.action||'')} ${item.nodeId?('· '+escapeHTML(item.nodeId)):''}${patch?`
    预览补丁
    ${escapeHTML(JSON.stringify(patch,null,2))}
    `:''}${item.applyError?`${escapeHTML(item.applyError)}`:''}
    ${applied?``:(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')); @@ -1355,10 +1355,12 @@ 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){ +let runEvalModelChoice; +function bindRunEvalModelPicker(host,runId){ window.AgentFlowAssistantModels?.bindFeaturePicker(host,{ - model:localStorage.getItem('agentflow.runEvalModel'), - onChange:id=>localStorage.setItem('agentflow.runEvalModel',id) + model:runEvalModelChoice?.runId===runId?runEvalModelChoice.model:'', + legacyModel:localStorage.getItem('agentflow.runEvalModel'), + onChange:model=>{runEvalModelChoice={runId,model}} }); } async function loadRunEval(runId,background){ diff --git a/web/app/sync-schedule.js b/web/app/sync-schedule.js index 290447dc..58147c0c 100644 --- a/web/app/sync-schedule.js +++ b/web/app/sync-schedule.js @@ -101,12 +101,14 @@ function scheduleModelAPI(){return window.AgentFlowAssistantModels} function clarifyModelPickerHTML(disabled){ return `
    ${scheduleModelAPI()?.featurePickerHTML()||''}
    `; } +let clarifyModelChoice; function bindClarifyModelPicker(host, issue){ const models=scheduleModelAPI(); return models?.bindFeaturePicker(host,{ - model:localStorage.getItem('agentflow.clarifyModel'), + model:clarifyModelChoice?.issueId===issue.id?clarifyModelChoice.model:'', + legacyModel:localStorage.getItem('agentflow.clarifyModel'), readOnly:host.hasAttribute('data-picker-readonly'), - onChange:id=>localStorage.setItem('agentflow.clarifyModel',id), + onChange:model=>{clarifyModelChoice={issueId:issue.id,model}}, loadCatalog:()=>models.fetchCatalog(`/api/issues/${encodeURIComponent(issue.id)}/clarify-models`) }); } @@ -122,8 +124,10 @@ function scheduleEngineModels(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 preferred?.id||models[0]?.id||''; + return saved?.id||preferred?.id||models[0]?.id||''; } function scheduleModelEngine(id){ return scheduleModelAPI()?.engineOf?.(id,scheduleModelCatalog())||'codebuddy'; @@ -133,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=>{ @@ -143,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'); @@ -216,8 +224,10 @@ async function loadScheduleModels(){ 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) - ?(catalog?.engines||[]).filter(engine=>engine.configured).map(engine=>scheduleDefaultModel(engine.id)).find(Boolean) + ?(preferred&&scheduleDefaultModel(preferred.id))||configured.map(engine=>scheduleDefaultModel(engine.id)).find(Boolean) :''; paintScheduleModel(fallback||selected||picker.DEFAULT); } @@ -441,7 +451,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; diff --git a/web/app/workbench.js b/web/app/workbench.js index 6f06b8b0..e5ac3d9c 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 配置',icon:'git'}, + {id:'model',name:'执行器配置',icon:'sparkles'}, ]; // A CodeBuddy key only works on the edition that issued it; the CLI treats unknown values as 国际站. // Keep in sync with chatbot/src/credentials.js and domain.NormalizeCodeBuddyInternetEnvironment. @@ -69,9 +69,10 @@ 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:'CodeBuddy 会使用可用的共享配置。其他 CLI 继续使用各自的凭据。'}, {key:'codexApiKey',group:'model',name:'Codex',short:'Codex API Key',logo:'codex',monochrome:true, @@ -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,278 @@ 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 `
    +
    +

    ${credentialGlyph(group.icon,16)}${group.name}

    + ${credentialAddMenu(group,user)} + ${git?`

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

    `:''} +
    +
    ${kinds.map(kind=>credentialRowHTML(kind,user)).join('')}${git?'
    ':''}
    + ${git?'':` + ${credentialGlyph('monitor',16)} + 使用已有订阅Claude Code、Codex 和 Antigravity 可用「账号登录」运行对话和 SOP。 + 配置执行机器${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 `
    +

    ${credentialGlyph('settings',16)}AI 默认设置

    + +
    `; +} +function credentialDefaultField(label,name,options=''){ + 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',executorOptions)} + ${credentialDefaultField('默认模型','model')} + ${credentialDefaultField('思考强度','effort')} + ${credentialDefaultField('操作确认方式','approval',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(); + 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)); + host.querySelector('[name="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 +969,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 +979,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 +995,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 +1011,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 +1022,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 +1095,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 +1126,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 +1159,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 +1167,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 +1178,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 +1212,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 +1228,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 +1243,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 +1253,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 +1286,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 +1331,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 +1378,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 +1391,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 +1428,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 +1456,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 +1488,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 +1502,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,19 +1533,12 @@ 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(!!row!==!!fresh.gitHubCredentialConfigured)renderCredentialGitGroup(panel,fresh); + else void loadCredentialGitRows(panel,fresh); if(!fresh.gitHubCredentialConfigured){repaintCredentialRow('gitToken');return} state.gitTokenAnnounceVerify=true; toast('工蜂授权已保存,正在校验授权有效性…'); @@ -1286,7 +1547,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 +1566,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 +2244,7 @@ function renderUserProfilePopover() { ⚠️ 认证换票未通过
    此前统一认证票据已失效,请点击下方按钮重新登录。 ` : ` -

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

    +

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

    `}
    diff --git a/web/assistant_models_test.js b/web/assistant_models_test.js index c9bd65b8..86d04c1c 100644 --- a/web/assistant_models_test.js +++ b/web/assistant_models_test.js @@ -155,7 +155,7 @@ vm.runInContext(moduleSource, ctx); }), }); assert.equal(codexOnly.executor.value, 'codex'); - assert.equal(codexOnly.executor.options[0].disabled, true); + assert.deepEqual(codexOnly.executor.options.map(item => item.value), ['codex']); assert.equal(codexOnly.model.value, 'codex:gpt-5.5'); const saved = pickerFixture(); 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..eea1fd3a 100644 --- a/web/gongfeng_oauth_notify_test.go +++ b/web/gongfeng_oauth_notify_test.go @@ -55,11 +55,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 +80,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 c206952f..b4b08450 100644 --- a/web/i18n-en.js +++ b/web/i18n-en.js @@ -229,6 +229,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 c3be8ba9..6d1edc3a 100644 --- a/web/index.html +++ b/web/index.html @@ -12,7 +12,7 @@ - + @@ -188,10 +188,13 @@

    设置

    -
    -

    个人中心

    个人配置

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

    +
    +
    +

    个人配置

    + +
    +
    -
    @@ -1142,7 +1145,7 @@

    触发配置

    @@ -861,6 +874,14 @@ function paintCredentialDefaults(host,catalog){ 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=''; @@ -917,7 +938,8 @@ async function saveCredentialDefaults(form,host){ if(host.isConnected){ paintCredentialDefaults(host,ui.catalog); CREDENTIAL_KINDS.filter(kind=>kind.group==='model').forEach(kind=>repaintCredentialRow(kind.key)); - host.querySelector('[name="executor"]')?.focus({preventScroll:true}); + 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(); diff --git a/web/index.html b/web/index.html index 6d1edc3a..bd272fcd 100644 --- a/web/index.html +++ b/web/index.html @@ -12,7 +12,7 @@ - + @@ -1336,7 +1336,7 @@

    确认操作

    - + diff --git a/web/platform.css b/web/platform.css index ce2220b2..ab585d44 100644 --- a/web/platform.css +++ b/web/platform.css @@ -2291,67 +2291,81 @@ html[data-theme="light"] body{color-scheme:light}html[data-theme="light"] .platf .credential-tip:hover::after,.credential-tip:focus-within::after{opacity:1;transform:translate(0,-50%)} /* account row */ -#settingsView .personal-settings{display:grid;grid-template-columns:minmax(0,50rem);justify-content:center} -#settingsView .personal-settings-heading{align-items:center;gap:12px 20px;margin-bottom:20px} +#settingsView .personal-settings{display:grid;grid-template-columns:minmax(0,42rem);justify-content:center} +#settingsView .personal-settings-heading{align-items:center;gap:12px 20px;margin-bottom:28px} body:has(#settingsView.active) #toastContainer{top:auto;bottom:84px} -.credential-account{display:flex;align-items:center;gap:8px;min-width:0;max-width:45%;padding:4px 10px 4px 4px;border-radius:999px;background:var(--hui-soft);color:var(--hui-text)} +.credential-account{display:flex;align-items:center;gap:8px;min-width:0;max-width:45%;color:var(--hui-secondary)} .credential-account[hidden]{display:none} .credential-account>div{min-width:0} -.credential-avatar{position:relative;display:grid;place-items:center;flex:none;width:30px;height:30px;overflow:hidden;border-radius:50%;background:var(--hui-soft);color:var(--hui-secondary);font-size:13px;font-weight:550} +.credential-avatar{position:relative;display:grid;place-items:center;flex:none;width:24px;height:24px;overflow:hidden;border-radius:50%;background:var(--hui-soft);color:var(--hui-secondary);font-size:12px;font-weight:550} .credential-avatar img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover} .credential-account :is(b,small){display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} -.credential-account b{font-size:13px;font-weight:550} +.credential-account b{font-size:12.5px;font-weight:500} .credential-account small{color:var(--hui-secondary);font-size:11.5px} /* Personal configuration */ #personalSettingsContent{container:personal-settings / inline-size} -.credential-list{--credential-section-padding:20px;border:1px solid var(--hui-border);border-radius:14px;background:var(--hui-surface);box-shadow:var(--hui-panel-shadow)} +.credential-list{display:grid;grid-template-columns:minmax(0,1fr);gap:26px} .credential-panel.is-entering .credential-list{animation:credentialPop .44s var(--cr-spring) both} .credential-group{min-width:0} -.credential-group+.credential-group{border-top:1px solid var(--hui-border)} -.credential-group-title{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;gap:4px 10px;min-height:58px;padding:12px var(--credential-section-padding)} -.credential-group-heading{display:flex;align-items:center;gap:9px;min-width:0;margin:0;color:var(--hui-text);font-size:15px;font-weight:600;line-height:1.35} -.credential-group-heading>svg{flex:none;color:var(--hui-muted)} -.credential-group-note{grid-column:1/-1;margin:0 0 0 25px;color:var(--hui-secondary);font-size:12px;line-height:1.45} -.credential-add-menu,.credential-add-trigger{justify-self:end} -.credential-add-trigger.hui-select-trigger{height:34px;border-color:var(--hui-border-strong);background:var(--hui-surface);color:var(--hui-text);font-weight:500} -.credential-add-trigger.hui-select-trigger:is(:hover,[aria-expanded="true"]){border-color:color-mix(in srgb,var(--hui-accent) 30%,var(--hui-border));background:var(--hui-accent-soft);color:var(--hui-accent-hover)} -.credential-add-trigger .hui-select-lead{color:inherit} -.hui-select-panel.credential-add-panel{min-width:0;padding:5px} +.credential-group-title{display:flex;flex-wrap:wrap;align-items:baseline;gap:4px 10px;margin-bottom:9px} +.credential-group-heading{min-width:0;margin:0;color:var(--hui-text);font-size:15px;font-weight:600;line-height:1.4} +.credential-group-note{margin:0;color:var(--hui-muted);font-size:12px;line-height:1.45} +.credential-group-body{min-width:0;padding:0 14px;border:1px solid var(--hui-border);border-radius:11px;background:color-mix(in srgb,var(--hui-surface) 98%,var(--hui-text))} +.credential-add-row,.credential-default-field{position:relative;min-width:0} +.credential-add-row{display:flex;align-items:center;min-height:44px} +.credential-add-row .hui-select-trigger,.credential-default-field .hui-select-trigger{height:auto;min-height:34px;padding:0;border:0;background:transparent} +.credential-add-row .hui-select-trigger{padding-right:22px;color:var(--hui-accent-hover);font-weight:500} +.credential-add-trigger .hui-select-lead{width:16px;height:16px;margin-inline:9px 11px;color:inherit} +.credential-add-trigger .hui-select-chevron{position:absolute;right:0} +.credential-add-row .hui-select-trigger::after,.credential-default-field .hui-select-trigger::after{position:absolute;inset:2px -11px;border-radius:7px;content:""} +.credential-add-row .hui-select-trigger:enabled:is(:hover,[aria-expanded="true"])::after, +.credential-default-field .hui-select-trigger:enabled:is(:hover,[aria-expanded="true"])::after{background:color-mix(in srgb,var(--hui-text) 4%,transparent)} +.credential-add-row .hui-select-trigger:focus-visible,.credential-default-field .hui-select-trigger:focus-visible{outline:0} +.credential-add-row .hui-select-trigger:focus-visible::after,.credential-default-field .hui-select-trigger:focus-visible::after{outline:2px solid var(--hui-focus-ring)} +.hui-select-panel:is(.credential-add-panel,.credential-default-panel){min-width:0;padding:5px} +.credential-default-panel .hui-select-options{max-height:286px} .credential-add-panel .hui-select-option{height:38px;padding-inline:8px} .credential-add-panel .hui-select-option-brand{box-sizing:border-box;width:24px;height:24px;margin-right:9px;padding:4px;border-radius:6px;background:var(--hui-soft);vertical-align:middle} .credential-add-panel .hui-select-option-brand.is-glyph{color:var(--hui-secondary)} .credential-add-panel .hui-select-option-meta:empty{display:none} html[data-theme="dark"] .credential-add-panel img.hui-select-option-brand.is-monochrome{background:transparent} -.credential-group .credential-rows{margin:0 calc(var(--credential-section-padding) - 10px) 7px} .credential-rows:not(:has(.credential-row)){display:none} +.credential-rows .credential-row{margin:0;border:0} +.credential-rows .credential-row+.credential-row, +.credential-rows .credential-row+[data-credential-git-rows]>.credential-row:first-child, +.credential-rows:has(.credential-row)+:is(.credential-add-row,.credential-subscription), +.credential-add-row+.credential-subscription, +.credential-default-field+.credential-default-field{border-top:1px solid var(--hui-border)} .credential-row .credential-row-who b .credential-default-badge{display:inline-flex;margin-left:7px;padding:1px 6px;border-radius:5px;background:var(--hui-accent-soft);color:var(--hui-accent);font-size:11px;font-weight:550} -.credential-subscription{display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:10px;margin:0 var(--credential-section-padding) 14px;padding:10px 12px;border-radius:8px;background:var(--hui-soft);color:var(--hui-text);text-decoration:none;transition:background-color .16s} -.credential-subscription>svg{align-self:start;margin-top:3px;color:var(--hui-muted)} -.credential-subscription strong{display:block;font-size:13px;font-weight:600} -.credential-subscription small{display:block;margin-top:2px;color:var(--hui-secondary);font-size:12px;line-height:1.5} -.credential-subscription-action{display:inline-flex;align-items:center;gap:6px;color:var(--hui-secondary);font-size:12px;white-space:nowrap} -.credential-subscription:hover{background:color-mix(in srgb,var(--hui-soft) 80%,var(--hui-accent-soft))} -.credential-subscription:is(:hover,:focus-visible) .credential-subscription-action{color:var(--hui-accent-hover)} -.credential-subscription:focus-visible{outline:2px solid var(--hui-accent);outline-offset:2px} -.credential-default-feedback{color:var(--hui-success);font-size:12px;font-weight:500} -.credential-default-status{margin:0;padding:0 var(--credential-section-padding) 15px;color:var(--hui-secondary);font-size:13px} -.credential-default-form{padding:0 var(--credential-section-padding) 14px} +.credential-group-body .credential-subscription{margin:0;padding-inline:0;border-radius:0;text-decoration:none} +.credential-subscription:is(:hover,:focus-visible){background:color-mix(in srgb,var(--hui-text) 4%,transparent)} +.credential-subscription:hover .credential-row-action{color:var(--hui-accent-hover)} +.credential-subscription .credential-logo{color:var(--hui-muted)} +.credential-subscription .credential-row-who small{display:block;line-height:1.45;white-space:normal} +.credential-default-feedback{margin-left:auto;color:var(--hui-success);font-size:12px;font-weight:500} +.credential-default-status{margin:0;color:var(--hui-secondary);font-size:13px} .credential-default-form fieldset{min-width:0;margin:0;padding:0;border:0} -.credential-default-field{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,min(62%,420px));align-items:center;gap:10px;margin:0;padding:5px 0} -.credential-default-field>span{min-width:0;color:var(--hui-text);font-size:13px;font-weight:500} -.credential-default-field .select{width:100%;height:36px;min-width:0;padding-left:11px;font-size:13px} -.credential-default-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:6px;padding-top:12px;border-top:1px solid var(--hui-border)} +.credential-default-field{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,60%);align-items:center;gap:12px;min-height:46px} +.credential-default-label{display:flex;align-items:center;gap:10px;min-width:0;color:var(--hui-text);font-size:13.5px;font-weight:500;line-height:1.4} +.credential-default-label svg{flex:none;margin-inline:9px;color:var(--hui-muted)} +.credential-default-field .hui-select-trigger,.credential-default-select{justify-self:end;min-width:0;max-width:100%;color:var(--hui-secondary);font-size:13px} +.credential-default-field .hui-select-trigger:is(:hover,[aria-expanded="true"]){color:var(--hui-text)} +.credential-default-field .hui-select-trigger:disabled::after{content:none} +.credential-default-field .hui-select-chevron{flex:none} +.credential-default-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:10px} .credential-default-actions[hidden]{display:none} .credential-default-error{margin:8px 0 0;color:var(--hui-error);font-size:12px} -@container personal-settings (max-width:460px){ - .credential-list{--credential-section-padding:12px} - .credential-subscription{grid-template-columns:auto minmax(0,1fr);gap:6px 8px} - .credential-subscription-action{grid-column:2;justify-self:start} -} -@container personal-settings (max-width:340px){ - .credential-default-field{grid-template-columns:minmax(0,1fr);gap:6px} +@container personal-settings (max-width:380px){ + .credential-list{gap:22px} + .credential-group-title:has(.credential-group-note:not([hidden])){display:grid} + .credential-group-body{padding-inline:11px} + .credential-subscription #credentialSubscriptionAction{display:none} + .credential-default-field{grid-template-columns:minmax(88px,auto) minmax(0,1fr);gap:8px} + .credential-default-label{gap:6px;font-size:13px} + .credential-default-label svg{margin:0} + .credential-default-field .hui-select-trigger{gap:5px} } /* rows */ @@ -2376,8 +2390,11 @@ html[data-theme="dark"] .credential-logo.monochrome img{filter:invert(1)} .credential-mono{font-family:var(--cr-mono);font-size:11.5px} .credential-row-who .is-ok{color:var(--cr-ok)}.credential-row-who .is-err{color:var(--cr-err)}.credential-row-who .is-info{color:var(--cr-info)} .credential-row-end{display:flex;flex:none;align-items:center;gap:6px} -.credential-row-action,.credential-row-end .credential-row-link{display:inline-flex;align-items:center;gap:5px;min-height:30px;padding:0 8px;border:1px solid var(--hui-border);border-radius:7px;background:var(--hui-surface);color:var(--hui-secondary);font-size:12px;white-space:nowrap;transition:border-color .16s,color .16s} -.credential-row-main:is(:hover,:focus-visible) .credential-row-action,.credential-row.is-open .credential-row-action,.credential-row-end .credential-row-link:is(:hover,:focus-visible){border-color:var(--hui-border-strong);color:var(--hui-text)} +.credential-row-action,.credential-row-end .credential-row-link{display:inline-flex;align-items:center;gap:5px;min-height:32px;padding:0;color:var(--hui-secondary);font-size:12.5px;white-space:nowrap;transition:color .16s} +.credential-row-main:is(:hover,:focus-visible) .credential-row-action,.credential-row.is-open .credential-row-action,.credential-row-end .credential-row-link:is(:hover,:focus-visible){color:var(--hui-text)} +.credential-row-end .credential-row-link{position:static;isolation:auto;overflow:visible} +.credential-row-link::after{position:absolute;inset:0;content:""} +.credential-row-main:has(.credential-row-link:hover){background:var(--cr-hover)} .credential-chevron{display:inline-flex;color:var(--cr-tertiary);transition:transform .3s var(--cr-fold),color .16s} .credential-row.is-open .credential-chevron{color:var(--cr-text);transform:rotate(180deg)} From 66878c08ae400affdadde8d34df0d52c4132aed2 Mon Sep 17 00:00:00 2001 From: roberttwang Date: Sat, 21 Nov 2026 17:35:37 +0800 Subject: [PATCH 12/25] fix(chatbot): restore amber styling for the executor setup notice --- chatbot/src/styles.css | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/chatbot/src/styles.css b/chatbot/src/styles.css index fb65f70c..b9848de7 100644 --- a/chatbot/src/styles.css +++ b/chatbot/src/styles.css @@ -1595,16 +1595,20 @@ small { gap: 10px; margin-bottom: 10px; padding: 8px 10px 8px 12px; - border: 1px solid var(--line); + border: 1px solid #f3e2b8; border-radius: 10px; - background: var(--subtle); - color: var(--text); + background: #fffbf0; + color: #7a5a12; font-size: 13px; line-height: 1.5; } +[data-theme="dark"] .credential-notice { + border-color: #5a4a22; + background: #2b2513; + color: #e8cf8c; +} .credential-notice > svg { flex: none; - color: var(--muted); } .credential-notice > span { flex: 1; From 17d2fc128c3390f6f74a5ecdb246c34655f47ee7 Mon Sep 17 00:00:00 2001 From: roberttwang Date: Sat, 21 Nov 2026 18:16:21 +0800 Subject: [PATCH 13/25] fix(onboarding): configure Git and executors in quick access --- chatbot/public/personal-credentials.html | 38 +++ chatbot/src/App.jsx | 2 +- chatbot/src/QuickAccessWizard.jsx | 371 +++++---------------- chatbot/src/quick-access-wizard.css | 49 +-- chatbot/src/useChat.js | 13 +- chatbot/tests/quick-access-wizard.test.jsx | 74 ++-- chatbot/vite.config.js | 2 + web/app.js | 16 + web/app/access.js | 1 + web/app/credentials-surface.js | 40 +++ web/app/git-ssh-keys.js | 2 +- web/app/workbench.js | 15 +- web/platform.css | 3 +- 13 files changed, 260 insertions(+), 366 deletions(-) create mode 100644 chatbot/public/personal-credentials.html create mode 100644 web/app/credentials-surface.js diff --git a/chatbot/public/personal-credentials.html b/chatbot/public/personal-credentials.html new file mode 100644 index 00000000..4d7d9c22 --- /dev/null +++ b/chatbot/public/personal-credentials.html @@ -0,0 +1,38 @@ + + + + + + Git 与执行器配置 · LoopForge + + + + + + + + + + + + + + +
    +

    正在读取个人配置…

    +
    +
    + + + + + + + + + + + + + + diff --git a/chatbot/src/App.jsx b/chatbot/src/App.jsx index 9411544c..123a3705 100644 --- a/chatbot/src/App.jsx +++ b/chatbot/src/App.jsx @@ -2582,7 +2582,7 @@ export default function App() { sponsoredModels={chat.sponsoredModels} onClose={() => setQuickAccessOpen(false)} 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 0715825a..982eb576 100644 --- a/chatbot/src/QuickAccessWizard.jsx +++ b/chatbot/src/QuickAccessWizard.jsx @@ -13,11 +13,11 @@ import HarnessIcon from "./HarnessIcon"; import SlidingTabs from "./SlidingTabs"; import { api, canChatInProject, canManageProjectRepos, write } from "./api"; import { usePanelPresence } from "./usePanelPresence"; -import { openCredentialSettings } from "./credentials"; import { EXECUTORS, personalEngineConfigured } from "./engines.js"; 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 = "") { @@ -468,45 +468,6 @@ export function HarnessSwitch({ checked, onChange, disabled = false, label }) { ); } -/** Pill whose dot pops once each time `ok` flips; alternating keyframe names restart it. */ -function StatusPill({ ok, okLabel = "已就绪", needLabel = "待配置" }) { - const previous = useRef(ok); - const [pops, setPops] = useState(0); - useEffect(() => { - if (previous.current === ok) return; - previous.current = ok; - setPops((n) => n + 1); - }, [ok]); - return ( - - {ok ? okLabel : needLabel} - - ); -} - -function VerifyMessage({ result, okText }) { - const text = result.valid - ? okText - : result.error || `缺少权限:${(result.missing || []).join("、")}`; - return ( -

    - - {text} -

    - ); -} - -/** Both labels share one grid cell so the button keeps its widest width while busy. */ function BusyLabel({ busy, busyLabel, children }) { return ( @@ -765,7 +726,11 @@ 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 [sshCredentials, setSSHCredentials] = useState({ userId: null, keys: null, error: false }); const [catalogProjects, setCatalogProjects] = useState(projects); const [repositories, setRepositories] = useState([]); @@ -775,9 +740,6 @@ export default function QuickAccessWizard({ const [loading, setLoading] = useState(false); const [saving, setSaving] = useState(false); const [error, setError] = useState(""); - const [gitToken, setGitToken] = useState(""); - const [verifyingGit, setVerifyingGit] = useState(false); - const [gitVerify, setGitVerify] = useState(null); const [projectMode, setProjectMode] = useState("existing"); const [selectedProjectId, setSelectedProjectId] = useState(projectId); const [newProjectName, setNewProjectName] = useState(""); @@ -797,6 +759,11 @@ export default function QuickAccessWizard({ const [stepAnimated, setStepAnimated] = useState(false); const headingRef = useRef(null); const bodyRef = useRef(null); + const credentialsFrame = useRef(null); + const fromCredentialsFrame = useCallback((event) => { + const source = credentialsFrame.current?.contentWindow; + return Boolean(source && event.source === source && event.origin === location.origin); + }, []); const presence = usePanelPresence(open, 300); const reopenedWhileClosing = presence.phase === "closing"; @@ -926,8 +893,9 @@ export default function QuickAccessWizard({ setStepAnimated(false); setPhase("wizard"); setError(""); - setGitToken(""); - setGitVerify(null); + setCredentialUser(null); + setCredentialsPending(false); + setGitHttpHosts([]); setCompletedSummary(null); setBindRepoNow(true); setPreviewTab("stages"); @@ -935,50 +903,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(freshUser); - if (freshUser?.gitHubCredentialConfigured && freshUser?.id) { - void verifyStoredGitToken(freshUser.id); - } const nextProjects = Array.isArray(projectsRes) ? projectsRes : projects; @@ -987,9 +925,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) { @@ -1006,8 +943,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)); @@ -1020,24 +957,48 @@ 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.origin !== location.origin || event.data?.type !== "agentflow-credentials-changed") return; + if (fromCredentialsFrame(event)) { + setCredentialsPending(true); + setError(previous => previous === CREDENTIALS_REQUIRED ? "" : previous); + onCredentialsSaved?.(); + if (window.parent !== window) { + window.parent.postMessage({ type: "agentflow-credentials-changed" }, location.origin); + } + } else if (event.source !== window.parent) { + return; + } + refresh(); }; refresh(); window.addEventListener("focus", refresh); @@ -1047,7 +1008,7 @@ export default function QuickAccessWizard({ window.removeEventListener("focus", refresh); window.removeEventListener("message", credentialsChanged); }; - }, [open, user?.id, user?.isGuest]); + }, [open, userId, isGuest, fromCredentialsFrame, onCredentialsSaved]); useEffect(() => { if (!open || !selectedWorkflowId) return undefined; @@ -1077,42 +1038,21 @@ 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(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?.(); }; + const closeFromFrame = (event) => { + if (!saving && fromCredentialsFrame(event) && event.data?.type === "agentflow-credentials-close") onClose?.(); + }; window.addEventListener("keydown", onKeyDown); - return () => window.removeEventListener("keydown", onKeyDown); - }, [open, saving, onClose]); + window.addEventListener("message", closeFromFrame); + return () => { + window.removeEventListener("keydown", onKeyDown); + window.removeEventListener("message", closeFromFrame); + }; + }, [open, saving, onClose, fromCredentialsFrame]); useEffect(() => { if (projectMode !== "create" || !parsedRepo) return; @@ -1163,15 +1103,22 @@ 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 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); + const repoAccess = gitAccess(selectedRepo); const readyCLIs = EXECUTORS.filter(cli => personalEngineConfigured(storedUser, cli.id)); const cliReady = readyCLIs.length > 0 || Boolean(sponsoredModel); const nodes = @@ -1184,66 +1131,15 @@ export default function QuickAccessWizard({ setStep(next); } - async function saveTypedGitToken() { - const token = gitToken.trim(); - if (!user?.id || !token) return storedUser; - 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 }, "PUT"); - const merged = { ...storedUser, gitHubCredentialConfigured: true, gitHttpCredentialsConfigured: true }; - setStoredUser(merged); - setGitToken(""); - void onCredentialsSaved?.(); - window.parent !== window && - window.parent.postMessage( - { type: "agentflow-credentials-changed" }, - location.origin, - ); - return merged; - } - - async function verifyGit() { - if (!user?.id || verifyingGit) return; - 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`, - ); - setGitVerify(result); - if (result?.valid && typed) await saveTypedGitToken(); - } catch (err) { - setGitVerify({ valid: false, error: err.message }); - } finally { - setVerifyingGit(false); - } - } - async function nextStep() { if (saving) return; setError(""); if (activeStep.id === "auth") { - if (!gitReady && !hasSSHKeys && !storedUser?.gitHttpCredentialsConfigured && !cliReady) { - setError("请先添加一个 Git 凭据或执行器。"); + if (!hasGit && !cliReady) { + setError(CREDENTIALS_REQUIRED); return; } - setSaving(true); - try { - await saveTypedGitToken(); - goToStep(1); - } catch (err) { - setError(err.message); - } finally { - setSaving(false); - } + goToStep(1); return; } if (activeStep.id === "project") { @@ -1289,7 +1185,6 @@ export default function QuickAccessWizard({ setSaving(true); setError(""); try { - const latestUser = await saveTypedGitToken(); let targetProject = currentProject; // Save the SOP the page shows; a stale id hidden by the current // filter must never be bound to the project. @@ -1462,8 +1357,8 @@ export default function QuickAccessWizard({ repository: boundRepo, workflow: provisionedWorkflow || activeWorkflow, rolesCount: roles.length, - gitReady: Boolean(boundRepo?.provider === "ssh" ? hasSSHKey(parseGongfengRepo(boundRepo.cloneUrl)) : latestUser?.gitHubCredentialConfigured), - cliNames: EXECUTORS.filter(cli => personalEngineConfigured(latestUser || storedUser, cli.id)).map(cli => cli.label), + gitAccess: gitAccess(parseGongfengRepo(boundRepo?.cloneUrl)), + cliNames: EXECUTORS.filter(cli => personalEngineConfigured(storedUser, cli.id)).map(cli => cli.label), }); setPhase("success"); await onCompleted?.(targetProject?.id || ""); @@ -1626,16 +1521,16 @@ export default function QuickAccessWizard({
    • - {completedSummary?.repository?.provider === "ssh" ? "Git SSH 访问:" : "GitHub 访问:"} - {completedSummary?.gitReady + {completedSummary?.gitAccess.label || "Git"} 访问: + {completedSummary?.gitAccess.ready ? "已就绪" : "未配置,克隆/推送私有仓库前可在个人配置补齐"} @@ -1730,7 +1625,7 @@ export default function QuickAccessWizard({
      @@ -1748,94 +1643,12 @@ export default function QuickAccessWizard({ ) : null} {activeStep.id === "auth" ? ( -
      -
      -
      -
      - GitHub 代码仓库授权 - - 用于克隆私有仓库、创建分支、推送代码与发起 PR - -
      - -
      -
      - -

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

      -

      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} -
      -
      -
      - -
      -
      -
      - 执行器 - {readyCLIs.length ? readyCLIs.map(cli => cli.label).join("、") : sponsoredModel ? "可使用平台共享模型" : "尚未配置执行器"} -
      - -
      -
      - -
      -
      -
      +