Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.
JavaScript agent-orchestrationagentic-workflowai-agentsai-codingclaude-codecode-reviewcodebuddycodexcoding-agentscursordeveloper-toolshuman-on-the-loopllmmcpmulti-agentsdlcself-hostedsopworkflow-automationworkflow-engine
feat(runner): add CLI authentication and maintenance controls (#972)
crispinhu27236f1c50bc81
diff --git a/chatbot/src/useChat.js b/chatbot/src/useChat.jsindex 1ca76ec1..9689d9e6 100644--- a/chatbot/src/useChat.js+++ b/chatbot/src/useChat.js@@ -551,6 +551,12 @@ export function useChat() {);return () => window.removeEventListener("message", listener);}, [ready]);+ const personalMachineId = executionLocked(session)+ ? (session.executionTarget?.pool === "runner" ? session.executionTarget.runnerId : "")+ : executionMachines.defaultRunnerId;+ const personalMachine = executionMachines.machines.find(+ (machine) => machine.id === personalMachineId && machine.ownerUserId === user?.id,+ );const codeBuddy = executor === "codebuddy";const listedForEngine = engineModels(models, executor);const executorModels = listedForEngine.length || codeBuddy@@ -1282,7 +1288,11 @@ export function useChat() {selectSandbox,models: executorModels,executor,- executors: EXECUTORS,+ executors: EXECUTORS.map((item) => {+ if (!personalMachine || (item.id !== "codex" && item.id !== "claude-code")) return item;+ const runtime = personalMachine.runtimes?.find((runtime) => runtime.provider === item.id);+ return runtime?.authMode === "personal" ? item : { ...item, detail: "使用执行机器上的本机登录态。" };+ }),setExecutor: chooseExecutor,sessions,session,diff --git a/docs/ai-scheduled-task-capabilities.md b/docs/ai-scheduled-task-capabilities.mdindex 6e74c9b4..473ffba2 100644--- a/docs/ai-scheduled-task-capabilities.md+++ b/docs/ai-scheduled-task-capabilities.md@@ -13,7 +13,9 @@| Skill | 与主页现有能力一致,不额外禁用内置 Skill 工具。启动 SOP 后,节点会按原有逻辑装载角色绑定的 Skill。主页与定时对话均未独立提供平台 Skill 绑定和自动装载功能,本次不新增这套机制。 || 结果与产物 | 支持自然语言结果,以及主页相同的草稿提交回退;终止 CLI 后仍按完全权限落库并保留已提交结果。工作区附件和浏览器截图写入定时会话。 |-执行身份是保存任务的人:新建时是创建人,其他成员编辑保存后改为他(不会借用别人的 Key);在这之前保存、没有绑定的任务仍是项目 Owner,否则是非共享任务的任务 Owner。用的是所选 CLI 的 Key,不是只能用 CodeBuddy。没有个人 CodeBuddy Key 时使用平台共享 Key,只能用管理员允许的模型;Codex / Claude Code 仍要该账号自己的凭据。两者都没有时保存会被拒绝并提示原因。工具访问范围沿用执行账号和当前项目的现有规则。关闭页面不会中断执行。定时任务没有单独的超时:它就是一轮普通对话,CLI 结束或有人从会话页停止时结束,MCP 网关跟这一轮一起结束。+执行身份由最后保存任务的人决定。未绑定身份的旧任务按项目 Owner、独立任务记录的 Owner 的顺序查找个人凭据。Codex 和 Claude Code 优先使用执行账号的默认个人执行机器上的「账号登录」,需要 Runner 0.10.2 或以上版本,并启用对应 CLI。默认机器离线或未启用账号登录时,任务改用执行账号在个人配置中填写的 API Key,以所选 CLI 和模型在云端执行。Key 缺失或执行失败时记录具体原因。CodeBuddy 缺少个人 Key 时可以使用平台共享 Key,模型限于管理员允许的列表。保存时会校验可用的凭据。++工具访问范围由执行账号和项目决定。关闭页面后任务继续执行,直到 CLI 结束或在会话页停止。MCP 网关在本轮结束时关闭。由于任务以保存人(或项目 Owner)身份、完全权限执行,`/api/schedule-jobs` 的新建、修改、立即运行和删除都要求项目写权限(Owner、平台管理员或非 viewer 成员),列表只返回调用者所在项目的任务;按 id 保存时既校验原项目也校验目标项目。执行身份只由服务端决定,请求里的 `ownerUserId`、`runAsUserId` 不生效。项目记录已不存在的任务只允许平台管理员或该任务原 Owner 管理。diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex d88869a9..4d993a59 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -166,10 +166,12 @@ paths:get:tags: [Assistant]operationId: listAssistantModels- summary: List CodeBuddy models available to the Studio assistant- description: |- Hardcoded iOA assistant catalog with display names and credit- multipliers. Defaults to default.+ summary: List models available to the Studio assistant+ parameters:+ - name: schedule+ in: query+ schema: {type: integer, enum: [1]}+ description: Include built-in models for CLIs configured to use account login on the signed-in user's default execution machine.responses:"200":description: Model catalog@@ -184,7 +186,7 @@ paths:type: arrayitems:type: object- required: [id, name, family, credits]+ required: [id, name, family]properties:id: {type: string}name: {type: string}@@ -5344,19 +5346,19 @@ components:description: Optional 5-field cron (minute hour day month weekday) in Asia/Shanghai. When set, intervalSec is ignored.assistantPrompt:type: string- description: User-written CodeBuddy prompt executed at schedule time. Required for independent AI jobs; subscriptions resolve their pinned shared version instead. Cleared on trigger jobs.+ description: User-written prompt executed at schedule time. Required for independent AI jobs. Subscriptions resolve their pinned shared version. Cleared on trigger jobs.assistantModel:type: string- description: CodeBuddy model id from GET /api/assistant/models.+ description: Model id from GET /api/assistant/models?schedule=1.ownerUserId:type: integerformat: int64- description: Project owner, whose keys run assistantPrompt for a job without runAsUserId (saved before the binding, or without a signed-in user)+ description: Project owner recorded for jobs saved without a run-as identity.runAsUserId:type: integerformat: int64readOnly: true- description: User whose keys run the AI job, set by the server to whoever last saved it (never taken from the request). Their own key for the model's CLI is used, else the platform's shared CodeBuddy key limited to the models it allows; a save with neither is rejected with 400. 0 means the project owner. A bound job fails rather than fall back to another account when that user is gone or can no longer write to the project.+ description: User bound by the server to the last saver. Codex and Claude Code use configured account login on their online default personal Runner. Other configurations and offline Runners use the saver's personal API Key. CodeBuddy can use the shared key for allowed models if the personal key is missing. A bound user must retain write access to the project. Zero uses legacy owner selection.runAsName:type: stringreadOnly: truediff --git a/docs/api/orchestration.md b/docs/api/orchestration.mdindex eccee11f..21afc3f5 100644--- a/docs/api/orchestration.md+++ b/docs/api/orchestration.md@@ -336,7 +336,7 @@ curl -u "$AGENTFLOW_USER:$AGENTFLOW_PASS" \触发任务可选 `maxDispatch`,配置每次最多成功触发的需求数,取值为 1–10;不配置(或为 0)时默认为 10,旧任务同样适用。自动执行和「立即运行」共用此上限;已有任务、基线阻塞或派发时被跳过的需求不占用名额,其余需求留待后续执行。`lastPulled` 仍记录所有匹配候选数,`lastDispatched` 记录本次实际成功触发数。AI 定时任务不使用此配置。-AI 定时任务(`skipDispatch=true`)字段包括 `id`、`name`、`enabled`、`projectId`、`assistantPrompt` / `assistantModel` / `ownerUserId`、`intervalSec` 或 `cron`。到点用项目 Owner(否则任务 Owner)在所选 CLI 上的 Key,按提示词原文走与主页相同的对话轮次并自动写入,不扫描需求、不派发 SOP。非 CodeBuddy CLI 仍要该账号自己的凭据,不借用平台共享的 CodeBuddy Key。+AI 定时任务(`skipDispatch=true`)字段包括 `id`、`name`、`enabled`、`projectId`、`assistantPrompt`、`assistantModel`、`ownerUserId` 以及 `intervalSec` 或 `cron`。触发后以保存人的身份开启一轮完全权限对话,使用任务的提示词。模型目录通过 `GET /api/assistant/models?schedule=1` 读取。AI 定时任务固定使用自动执行模式,不受 Studio 对话审批模式影响,平台写入无需逐次人工确认。@@ -348,7 +348,13 @@ AI 定时任务没有单独的时长上限:这一轮和普通对话一样,### `POST|PUT /api/schedule-jobs`-新建或按 `id` 更新,两种方法语义相同。`name` 必填。调度为 `intervalSec`(常用间隔)或 5 段 `cron`(东八区)。`skipDispatch` 为 true 时是 AI 定时任务,必须有 `assistantPrompt`,保存时清空 SOP 字段;否则是触发任务,必须有 `workflowId`,保存时清空提示词。可选 `useIssueWorkflow`。`assistantModel` 保存时保留已支持 CLI 的模型(`codex:…`、`claude-code:…`);CodeBuddy 模型仍限制在助手目录内。运行前检查执行账号在该 CLI 上的 Key。保存时把项目 Owner 记为 `ownerUserId`。AI 定时任务用保存人的 Key 执行:服务端把 `runAsUserId` 设为本次保存的登录用户(请求里传的值不生效),其他成员编辑保存后改用他的 Key。保存人没有个人 CodeBuddy Key 时用平台共享 Key,`assistantModel` 必须是共享 Key 允许的模型(为空或 `default` 时取共享 Key 的默认模型);没有可用 Key(没配个人 Key 且平台也没有共享 Key,或 Codex / Claude Code 模型缺对应 Key)时返回 `400` 并说明原因;只有停用任务、提示词和模型等执行配置都不变时例外,此时只把库中当前任务的 `enabled` 改为 false,其余字段(包括名称、通知、调度以及期间其他人已保存的修改)保持库中的值,原执行身份也保留,方便没有 Key 的成员停用任务;写入前在行锁内重新核对当前任务仍在原项目、执行配置仍与请求一致,否则返回 `409`,需刷新后重试。没有执行身份的旧任务先按项目 Owner、任务 Owner 的顺序找个人 Key,都没有时才用平台共享 Key。AI 定时任务的 `sessionMode` 为空时每次执行新开一个会话,`fixed` 时始终在同一个会话里继续;每次新开时用 `sessionKeep` 设置保留最近多少个会话(`10` / `50` / `100`,`-1` 不限,不传默认 `50`,其他值 `400`),每次执行结束后删除更早的会话,执行记录不受影响。更新时若请求未带 `blockers`,保留触发任务已有的基线暂停状态。+新建或按 `id` 更新,两种方法语义相同。`name` 必填。调度为 `intervalSec`(常用间隔)或 5 段 `cron`(东八区)。AI 定时任务需要 `assistantPrompt` 或共享任务版本。触发任务需要 `workflowId`,可选 `useIssueWorkflow`。更新时若请求未带 `blockers`,沿用触发任务的基线暂停状态。++服务端把 `runAsUserId` 绑定到本次保存的登录用户。Codex 和 Claude Code 优先使用该用户默认个人执行机器上的「账号登录」,需要 Runner 0.10.2 或以上及已启用的 CLI。默认机器离线或未启用账号登录时,以该用户的个人 API Key 在云端执行任务指定的 CLI 和模型。Key 缺失或执行失败时,任务记录具体原因。CodeBuddy 缺少个人 Key 时使用平台共享 Key,只能选择管理员允许的模型。模型为空或 `default` 时取共享 Key 的默认模型。没有执行身份的旧任务依次尝试项目 Owner、独立任务记录的 Owner 的个人凭据,最后尝试平台共享 Key。++缺少凭据的保存返回 `400`。没有凭据的项目成员也可以停用执行配置未变的任务,服务端在行锁内重新核对项目和执行配置,然后仅将 `enabled` 改为 false。若并发修改使核对失败,返回 `409`。++AI 定时任务的 `sessionMode` 为空时每次执行新开一个会话,`fixed` 时始终在同一个会话里继续;每次新开时用 `sessionKeep` 设置保留最近多少个会话(`10` / `50` / `100`,`-1` 不限,不传默认 `50`,其他值 `400`),每次执行结束后删除更早的会话,执行记录不受影响。`id` 为空时生成;`projectId` 默认 `platform`;`intervalSec<30` 时重置为 `300`。更新若不提供 `lastRunAt` 会保留已有最近运行字段。成功 `200` 返回 job;校验/存储错误 `400`。diff --git a/docs/conversation-native-cli.md b/docs/conversation-native-cli.mdindex 00924f4e..3c99cb80 100644--- a/docs/conversation-native-cli.md+++ b/docs/conversation-native-cli.md@@ -22,6 +22,18 @@ ZCode 恢复时通过官方会话协议应用当前选择的模型,再启动Runner 需要 0.10.1 或以上版本,该版本支持取消后台导出并释放工作区锁。Docker 镜像优先使用已安装的 CLI;支持官方安装器的 CLI 缺失时自动安装。ZCode 没有独立 npm 包,须在执行机器及工作区镜像内预装官方 CLI 并加入 PATH,缺失时明确报错。原生工具调用围栏与进程生命周期管理依赖 Python3。每个 Docker 会话阶段使用独立的 Linux 子进程收养进程,结束或取消时回收其全部后代,包含另建进程组的原生命令;不影响容器里的其他命令。平台会在启动前检查依赖,固定安装步骤以容器 root 用户在 `/` 中运行,实际 CLI 保留工作区的容器用户;无法准备时中止,不降级绕过调用围栏。建议在受控工作区镜像中预安装 CLI 和依赖。+个人执行机器可为 Codex 和 Claude Code 选择「账号登录」。Runner 0.10.2 起,对话按所绑定机器的认证设置启动 CLI。在运行 Runner 的系统账户下登录后,Codex 读取 `CODEX_HOME` 下的 `auth.json`,Claude Code 读取 `CLAUDE_CONFIG_DIR` 下的 `.credentials.json` 或 Runner 环境中的 `CLAUDE_CODE_OAUTH_TOKEN`。登录状态仅在该执行机器上使用。每次运行把登录文件复制进隔离的 CLI home,结束后删除;CLI 在运行中刷新了 token(Codex、Claude Code 的 refresh token 会轮换)时,删除前按内容做比较并交换写回 Runner 账户的原文件:原文件在此期间未被改动、且刷新后的文件仍是同一账号(顶层字段一致,Codex 的 `tokens.account_id` 相同)才写回,否则保留宿主机上的版本。仍需直接通过 CLI 管理登录和续期。仅存于系统钥匙串的登录需要改用 CLI 支持的文件式登录或 API Key。设置页在 CLI 行的「更多」菜单提供「测试」,按当前认证方式在该机器上发送一次短模型请求。++SOP 的 native 和 Docker 沙箱也使用所选 Runner 的认证设置。每次 CLI 调用都在节点的独立 HOME 中使用临时登录文件,结束后清理该文件,会话可在同一节点续接。++Runner 0.10.2 起,机器卡片可检查并手动安装平台提供的 Runner 构建。更新在机器空闲时应用。自行安装的 CLI 如提供非交互更新命令,可以在 CLI 菜单中直接执行更新。托管安装使用托管更新。如果 CLI 无法自更新,界面会提示按原安装方式更新。++CLI 菜单中的「模型列表」与个人配置共用当前用户的模型目录。可以获取、筛选、添加、重命名和排序模型。保存后,AI 对话和角色编辑器使用该目录。API Key 模式通过个人配置里的 Key 与服务地址获取模型,留空地址时使用 CLI 的官方服务。Codex 和 Claude Code 的账号登录模式从所选机器查询,需要 Runner 0.10.2 或以上版本。++其他 CLI 使用个人配置中保存的 API Key。Antigravity 将本机登录保存在系统凭据库中,LoopForge 沙箱目前无法复用。请在个人配置中填写 Gemini API Key,用量按 Gemini API 单独计费。详见 [Antigravity CLI 认证](https://antigravity.google/docs/install?tab=cli)和 [Gemini API 计费](https://ai.google.dev/gemini-api/docs/billing)。++ZCode 可通过 GLM Coding Plan 的 API Key 和套餐专用端点使用订阅额度。Start Plan 的额度需要登录 ZCode 账号,无法通过 API Key 使用。详见 [ZCode 模型配置](https://zcode.z.ai/cn/docs/configuration)。+原生会话的工具回调在执行机器上中继。宿主进程使用 Docker host gateway;通过 docker.sock 管理工作区的容器进程自动识别自身容器网络,工作区加入相同网络并访问该地址。自定义路由可通过 `AGENTFLOW_CONVERSATION_RELAY_HOST` 和 `AGENTFLOW_CONVERSATION_DOCKER_NETWORK` 显式指定工作区能访问的执行进程地址与 Docker 网络。会话目录会以相同路径挂进工作区,而 docker.sock 背后的 Docker 守护进程按自己所在主机解析挂载源,因此容器内的平台进程须把 `AGENTFLOW_CONVERSATION_DIR` 设在与宿主机同路径挂载的目录中;`compose.yaml` 将其设为 `${LOOPFORGE_DATA_DIR}/conversations`。Runner 不读该变量,原生会话目录固定在其工作区根目录的 `.conversations` 下,容器内运行 Runner 时须同路径挂载该工作区目录。未设置时会话目录位于 `AGENTFLOW_ASSISTANT_SESSION_DIR` 下,该目录在命名卷里时打开工作区会报 `mkdirat ... read-only file system`。附件等按用户保存的助手数据仍在 `AGENTFLOW_ASSISTANT_SESSION_DIR`,不挂进工作区。Docker 工作区直接在主容器中运行 SOP 脚本和 CLI。历史容器存在指令遮蔽挂载时,工作区下次取得执行权后会重建容器并保留工作区文件。标记为重建时运行的准备脚本随后在新容器补跑。模式交接时,交接工具要求模型只回复一句「好的。」再结束旧阶段,交接之后的展示由平台隐藏;不要求“不输出任何内容”,否则模型可能只产出推理、没有正文的回合,该回合写入原生日志后,续接时会被模型服务拒绝(如 `the conversation must end with a user message`)。交接工具成功后,旧阶段即使未输出 `type=result` 或异常退出,也继续完成交接。续接原生会话时,如果原生日志缺失,或模型服务在本阶段产生任何输出或工具调用之前就拒绝了续接(400/422、会话结构无效、无结果退出),平台用完整对话上下文新建一次原生会话重试;已有输出或工具调用的中断,以及鉴权、限流、额度、网络、执行机器不可用等原因,仍续接原会话或直接报错,不重复执行副作用。diff --git a/internal/domain/runner.go b/internal/domain/runner.goindex 02718a08..938cb3da 100644--- a/internal/domain/runner.go+++ b/internal/domain/runner.go@@ -81,6 +81,14 @@ const RunnerVersionConversationWorkspace = "0.8.0"// queued CLI or block a following turn behind a previous background save.const RunnerVersionConversationCLI = "0.10.1"+// RunnerVersionCLISettings adds chat account login, CLI tests, model discovery+// and updates from the machine card.+const RunnerVersionCLISettings = "0.10.2"++func (r Runner) SupportsCLISettings() bool {+ return versionAtLeast(r.RunnerVersion, RunnerVersionCLISettings)+}+func (r Runner) SupportsConversationCLI() bool {return versionAtLeast(r.RunnerVersion, RunnerVersionConversationCLI)}@@ -295,13 +303,24 @@ func (r Runner) RuntimeAuthMode(provider string) string {}const (- RuntimeStatusOnline = "online"- RuntimeStatusOffline = "offline"- RuntimeStatusDisabled = "disabled"- RuntimeAuthLocal = "local"- RuntimeAuthPersonal = "personal"+ RuntimeStatusOnline = "online"+ RuntimeStatusOffline = "offline"+ RuntimeStatusDisabled = "disabled"+ RuntimeAuthLocal = "local"+ RuntimeAuthPersonal = "personal"+ RuntimeCapabilityManagedUpdate = "managed_update"+ RuntimeCapabilityNativeUpdate = "native_update")+func (rt RunnerRuntime) SupportsCLIUpdate() bool {+ for _, capability := range rt.Capabilities {+ if capability == RuntimeCapabilityManagedUpdate || capability == RuntimeCapabilityNativeUpdate {+ return true+ }+ }+ return false+}+// RunnerRuntime is one discovered Agent CLI on the runner machine. Credentials// for the CLI stay on that machine; the control plane only learns the binary// path, version, and capabilities.diff --git a/internal/domain/runner_workspace.go b/internal/domain/runner_workspace.goindex 6d5f999b..8fddae42 100644--- a/internal/domain/runner_workspace.go+++ b/internal/domain/runner_workspace.go@@ -31,14 +31,18 @@ const (RunnerWorkspaceOperationCommit = "commit"RunnerWorkspaceOperationBrowser = "browser"RunnerWorkspaceOperationCheckouts = "checkouts"+ RunnerWorkspaceOperationMaintenance = "maintenance"+ RunnerWorkspaceOperationLoginModels = "login_models")// RunnerWorkspaceRequest is a bounded workspace request sent over the// runner's outbound control socket. Responses are transient and are never// persisted in runner_tasks or the run record.type RunnerWorkspaceRequest struct {- Conversation json.RawMessage `json:"conversation,omitempty"`- RunKind string `json:"runKind,omitempty"`+ Maintenance *RunnerMaintenanceRequest `json:"maintenance,omitempty"`+ ModelProvider string `json:"modelProvider,omitempty"`+ Conversation json.RawMessage `json:"conversation,omitempty"`+ RunKind string `json:"runKind,omitempty"`// ConcurrentEdit marks a person editing from the IDE: the runner writes and// opens terminals beside running tasks instead of waiting for their fence.ConcurrentEdit bool `json:"concurrentEdit,omitempty"`@@ -75,6 +79,20 @@ type RunnerWorkspaceRequest struct {Repositories []RepositoryContext `json:"repositories,omitempty"`}+type RunnerMaintenanceRequest struct {+ Provider string `json:"provider,omitempty"` // Empty selects the Runner binary.+ Apply bool `json:"apply,omitempty"`+ StatusOnly bool `json:"statusOnly,omitempty"`+}++type RunnerMaintenanceResult struct {+ Status string `json:"status"`+ Current string `json:"current,omitempty"`+ Version string `json:"version,omitempty"`+ Message string `json:"message,omitempty"`+ CanUpdate bool `json:"canUpdate,omitempty"`+}+// RunnerToolRequest is forwarded over the same instance-owned control socket// as the conversation process, avoiding loopback and load-balancer affinity.type RunnerToolRequest struct {diff --git a/internal/domain/sync.go b/internal/domain/sync.goindex 0f282a2b..c8823556 100644--- a/internal/domain/sync.go+++ b/internal/domain/sync.go@@ -98,10 +98,9 @@ type ScheduleJob struct {// first fixed-mode execution and cleared when the mode leaves "fixed".FixedSessionID string `json:"fixedSessionId,omitempty"`OwnerUserID int64 `json:"ownerUserId,omitempty"`- // RunAsUserID is server-managed: the user whose keys run an AI job, set to- // whoever last saved it. Zero (jobs saved before the binding, or without a- // signed-in user) runs it with the project owner's keys. RunAsName is for- // display.+ // RunAsUserID is server-managed: the user whose credentials run an AI job,+ // set to whoever last saved it. Zero keeps the legacy project-owner+ // selection. RunAsName is for display.RunAsUserID int64 `json:"runAsUserId,omitempty"`RunAsName string `json:"runAsName,omitempty"`LastRunAt time.Time `json:"lastRunAt,omitempty"`diff --git a/internal/domain/user.go b/internal/domain/user.goindex b2535895..afdd52f0 100644--- a/internal/domain/user.go+++ b/internal/domain/user.go@@ -29,18 +29,19 @@ type User struct {DeptName string `json:"deptName"`// PlatformRole is a platform-wide role, independent of project membership.// "admin" may edit generic SOP templates; empty is a regular user.- PlatformRole string `json:"platformRole,omitempty"`- GitToken string `json:"gitToken,omitempty"`- GitTokenConfigured bool `json:"gitTokenConfigured,omitempty"`- GitTokenOAuth bool `json:"gitTokenOAuth,omitempty"`- GitSSHKeyConfigured bool `json:"gitSshKeyConfigured,omitempty"`- GongfengRefreshToken string `json:"-"`- GongfengTokenExpiresAt time.Time `json:"-"`- CodeBuddyAPIKey string `json:"codeBuddyApiKey,omitempty"`- CodeBuddyAPIKeyConfigured bool `json:"codeBuddyApiKeyConfigured,omitempty"`- CodeBuddyInternetEnvironment string `json:"codeBuddyInternetEnvironment,omitempty"`- CreatedAt time.Time `json:"createdAt"`- UpdatedAt time.Time `json:"updatedAt"`+ PlatformRole string `json:"platformRole,omitempty"`+ GitToken string `json:"gitToken,omitempty"`+ GitTokenConfigured bool `json:"gitTokenConfigured,omitempty"`+ GitTokenOAuth bool `json:"gitTokenOAuth,omitempty"`+ GitSSHKeyConfigured bool `json:"gitSshKeyConfigured,omitempty"`+ GongfengRefreshToken string `json:"-"`+ GongfengTokenExpiresAt time.Time `json:"-"`+ CodeBuddyAPIKey string `json:"codeBuddyApiKey,omitempty"`+ CodeBuddyAPIKeyConfigured bool `json:"codeBuddyApiKeyConfigured,omitempty"`+ CodeBuddyInternetEnvironment string `json:"codeBuddyInternetEnvironment,omitempty"`+ CodeBuddyModels []CLIModel `json:"codeBuddyModels,omitempty"`+ CreatedAt time.Time `json:"createdAt"`+ UpdatedAt time.Time `json:"updatedAt"`}const PlatformRoleAdmin = "admin"@@ -123,6 +124,7 @@ type AgentCLICredential struct {BaseURL string `json:"baseUrl,omitempty"`Protocol string `json:"protocol,omitempty"`Models []CLIModel `json:"models,omitempty"`+ ModelsCustomized bool `json:"modelsCustomized,omitempty"` // Cursor: preserve explicit edits across discovery.}// Wire protocols an agent CLI can speak to a user Base URL.diff --git a/internal/httpapi/agent_tool_session.go b/internal/httpapi/agent_tool_session.goindex 005936b0..6e490b53 100644--- a/internal/httpapi/agent_tool_session.go+++ b/internal/httpapi/agent_tool_session.go@@ -56,6 +56,8 @@ type AgentToolSession struct {modeAction func(context.Context) errorSelectedMCPIDs map[string]boolExecutionRunnerID string+ runnerLogin bool+ transient boolRuntimeMode stringNotify func(string, any)Token stringdiff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.goindex 887ee753..71691e8b 100644--- a/internal/httpapi/assistant.go+++ b/internal/httpapi/assistant.go@@ -113,14 +113,6 @@ func (h *assistantHandlers) chat(c *gin.Context) {}req.Executor = assistantExecutor(req.Executor)req.Model = assistantRequestModel(req.Executor, req.Model)- user, model, refusal := h.assistantTurnUser(stored, req.Model)- if refusal != "" {- c.JSON(400, gin.H{"error": refusal})- return- }- req.Model = model- cliEngine, _ := assistantModelEngine(req.Model)- req.Executor = cliEngineif len(req.Messages) == 0 {c.JSON(400, gin.H{"error": "请提供对话消息"})return@@ -141,17 +133,50 @@ func (h *assistantHandlers) chat(c *gin.Context) {return}}- ownerID, shared, scopeErr := h.conversationScope(c, req.SessionID, req.RunID, req.ProjectID, user.ID)+ ownerID, shared, scopeErr := h.conversationScope(c, req.SessionID, req.RunID, req.ProjectID, stored.ID)if scopeErr != nil {c.JSON(403, gin.H{"error": scopeErr.Error()})return}+ req.SessionID = strings.TrimSpace(req.SessionID)+ if req.SessionID == "" {+ req.SessionID = newAssistantSessionID()+ }+ if _, loaded := h.active.LoadOrStore(fmt.Sprintf("%d/%s", ownerID, req.SessionID), true); loaded {+ c.JSON(429, gin.H{"error": "已有对话正在生成,请稍后重试"})+ return+ }+ defer h.active.Delete(fmt.Sprintf("%d/%s", ownerID, req.SessionID))+ old, exists := h.repo.AssistantSession(ownerID, req.SessionID)+ if exists {+ target := old.Execution()+ if req.ExecutionTarget != nil && *req.ExecutionTarget != target {+ c.JSON(409, gin.H{"error": "会话执行机器已固定,不能更换;请新建对话"})+ return+ }+ req.ExecutionTarget = &target+ } else {+ target, err := h.newExecutionTarget(stored.ID, req.ProjectID, req.ExecutionTarget)+ if err != nil {+ c.JSON(400, gin.H{"error": err.Error()})+ return+ }+ req.ExecutionTarget = target+ }+ cliEngine, _ := assistantModelEngine(req.Model)+ runnerLogin := h.assistantUsesRunnerLogin(stored.ID, req.ExecutionTarget, cliEngine)+ user, model, refusal := h.assistantTurnUser(stored, req.Model, runnerLogin)+ if refusal != "" {+ c.JSON(400, gin.H{"error": refusal})+ return+ }+ req.Model = modelif err := h.validateAssistantTriggerHistory(ownerID, req); err != nil {c.JSON(400, gin.H{"error": err.Error()})return}if shared {- if old, ok := h.repo.AssistantSession(ownerID, req.SessionID); ok {+ if exists {if !sharedTranscriptPrefix(old.Messages, req.Messages) {c.JSON(409, gin.H{"error": "共享会话已更新,请重新打开后发送"})return@@ -173,7 +198,6 @@ func (h *assistantHandlers) chat(c *gin.Context) {} else {// Generations stamp their question before this point; a direct chat// call stamps it here so personal messages also carry a send time.- old, _ := h.repo.AssistantSession(ownerID, req.SessionID)for i := len(old.Messages); i < len(req.Messages); i++ {if req.Messages[i].Role == "user" && req.Messages[i].CreatedAt.IsZero() {req.Messages[i].CreatedAt = time.Now().UTC()@@ -189,25 +213,19 @@ func (h *assistantHandlers) chat(c *gin.Context) {if catalogEngine == assistantEngineCodeBuddy {catalog = h.turnCatalog(c.Request.Context(), user, req.Model)}- req.Model = assistantAllowedUserModel(req.Model, catalog, user)+ if !runnerLogin {+ req.Model = assistantAllowedUserModel(req.Model, catalog, user)+ }cliEngine, _ = assistantModelEngine(req.Model)req.Executor = cliEngineif err := validateAssistantEffort(user, req.Model, req.Effort); err != nil {c.JSON(400, gin.H{"error": err.Error()})return}- legacyExecutor := ""- if old, ok := h.repo.AssistantSession(ownerID, req.SessionID); ok {- legacyExecutor = old.Executor- }- if refusal := assistantEngineSwitchRefusal(assistantConversationEngine(req.Messages, legacyExecutor), req.Model); refusal != "" {+ if refusal := assistantEngineSwitchRefusal(assistantConversationEngine(req.Messages, old.Executor), req.Model); refusal != "" {c.JSON(409, gin.H{"error": refusal})return}- req.SessionID = strings.TrimSpace(req.SessionID)- if req.SessionID == "" {- req.SessionID = newAssistantSessionID()- }sink, _ := c.Request.Context().Value(assistantGenerationSinkKey{}).(func(string, any))if sink == nil {if job, ok := h.readGeneration(ownerID, req.SessionID); ok && job.Status == "running" {@@ -219,31 +237,13 @@ func (h *assistantHandlers) chat(c *gin.Context) {approvalMode := assistantRequestApprovalMode(req)req.ApprovalMode = approvalModelogAgentToolEvent("assistant-chat", "mode="+approvalMode, "raw="+strings.TrimSpace(req.ApprovalMode), "sid="+req.SessionID)- if _, loaded := h.active.LoadOrStore(fmt.Sprintf("%d/%s", ownerID, req.SessionID), true); loaded {- c.JSON(429, gin.H{"error": "已有对话正在生成,请稍后重试"})- return- }- defer h.active.Delete(fmt.Sprintf("%d/%s", ownerID, req.SessionID))- savedConversation, exists := h.repo.AssistantSession(ownerID, req.SessionID)- if exists {- target := savedConversation.Execution()- if req.ExecutionTarget != nil && *req.ExecutionTarget != target {- c.JSON(409, gin.H{"error": "会话执行机器已固定,不能更换;请新建对话"})- return- }- req.ExecutionTarget = &target- } else {- target, err := h.newExecutionTarget(user.ID, req.ProjectID, req.ExecutionTarget)- if err != nil {- c.JSON(400, gin.H{"error": err.Error()})- return- }- savedConversation = assistantConversation{ID: req.SessionID, ProjectID: req.ProjectID, RunID: req.RunID, Model: req.Model, Effort: req.Effort, ExecutionTarget: target, Messages: req.Messages}- if err = h.repo.PutAssistantSession(ownerID, savedConversation); err != nil {+ savedConversation := old+ if !exists {+ savedConversation = assistantConversation{ID: req.SessionID, ProjectID: req.ProjectID, RunID: req.RunID, Model: req.Model, Effort: req.Effort, ExecutionTarget: req.ExecutionTarget, Messages: req.Messages}+ if err := h.repo.PutAssistantSession(ownerID, savedConversation); err != nil {c.JSON(409, gin.H{"error": err.Error()})return}- req.ExecutionTarget = target}req.workspaceMode = savedConversation.Mode() == domain.AssistantModeWorkspacesourceRoot := h.resolvedSourceRoot()@@ -295,6 +295,7 @@ func (h *assistantHandlers) chat(c *gin.Context) {sess.ChatOwnerID = ownerIDsess.turnMessages = append([]assistantMessage(nil), req.Messages...)sess.ExecutionRunnerID = savedConversation.Execution().RunnerID+ sess.runnerLogin = runnerLoginsess.RuntimeMode = savedConversation.Mode()sess.SelectedMCPIDs = map[string]bool{}for _, id := range req.MCPServerIDs {@@ -501,7 +502,7 @@ func (h *assistantHandlers) chat(c *gin.Context) {prompt = assistantPlatformExecutionReminder + "\n" + prompt}prompt += conversationAttachmentNote(cliRoot, req)- cliReq := assistantCLIRequest{Executor: req.Executor, Prompt: prompt, Model: req.Model, Effort: req.Effort, SessionID: cliSessionID, Resume: resume, UserID: u.ID, Native: true, MCPConfig: mcp, Settings: settings, SystemPrompt: system, SessionRoot: cliRoot, OnUsage: turnUsage.add, Workspace: req.workspaceMode, RemoteBinary: req.workspaceMode || toolSession.ExecutionRunnerID != "", Execute: h.conversationExecutor(toolSession, cliRoot)}+ cliReq := assistantCLIRequest{Executor: req.Executor, Prompt: prompt, Model: req.Model, Effort: req.Effort, SessionID: cliSessionID, Resume: resume, UserID: u.ID, Native: true, MCPConfig: mcp, Settings: settings, SystemPrompt: system, SessionRoot: cliRoot, RunnerLogin: runnerLogin, OnUsage: turnUsage.add, Workspace: req.workspaceMode, RemoteBinary: req.workspaceMode || toolSession.ExecutionRunnerID != "", Execute: h.conversationExecutor(toolSession, cliRoot)}persistAttempt := func(unstarted bool) error {if nativeSession != nil {nativeSession.checkpoint.Unstarted = unstarted@@ -1389,7 +1390,7 @@ func stripAssistantSecretValue(value any) {type assistantCLIRequest struct {Workspace boolExecute func(context.Context, string, runtime.CommandSpec, runtime.RunCredentials, runtime.EventSink) (string, error)- RemoteBinary bool+ RemoteBinary, RunnerLogin boolPrompt, Model, Effort, SessionID, SystemPrompt stringExecutor stringSessionRoot string@@ -1406,13 +1407,17 @@ 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.Execute == nil {- if execute := helperCLIExecution(ctx, req.SessionRoot); execute != nil {+ if execute, runnerLogin := helperCLIExecution(ctx, req.SessionRoot, user.ID, engine); execute != nil {req.Execute = executereq.RemoteBinary = true+ req.RunnerLogin = runnerLogin}}- engine, engineModel := assistantModelEngine(req.Model)+ if engineModel == "default" && (engine == assistantEngineCodex || engine == assistantEngineClaude) {+ engineModel = ""+ }attempt := assistantDiagnosticsFrom(ctx).begin(engine, engineModel, req.Resume, user)defer func() { attempt.finish(returnedErr) }()if engine != assistantEngineCodeBuddy && (req.ReportOnly || (!req.Native && !req.ReviewOnly)) {@@ -1471,10 +1476,14 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.UengineOpts := 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}switch engine {case assistantEngineClaude:- engineOpts.User = runtime.ProviderCredential{APIKey: user.ClaudeCodeAPIKey, BaseURL: user.ClaudeCodeBaseURL}+ if !req.RunnerLogin {+ engineOpts.User = runtime.ProviderCredential{APIKey: user.ClaudeCodeAPIKey, BaseURL: user.ClaudeCodeBaseURL}+ }inv, err = prepareAssistantClaudeInvocation(engineOpts)case assistantEngineCodex:- engineOpts.User = runtime.ProviderCredential{APIKey: user.CodexAPIKey, BaseURL: user.CodexBaseURL}+ if !req.RunnerLogin {+ engineOpts.User = runtime.ProviderCredential{APIKey: user.CodexAPIKey, BaseURL: user.CodexBaseURL}+ }inv, err = prepareAssistantCodexInvocation(engineOpts)default:if runtime.IsAgentCLI(engine) {@@ -1595,6 +1604,9 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U}if engine != assistantEngineCodeBuddy && ctx.Err() == nil && strings.TrimSpace(final) == "" &&(credentialRejected || (streamError != nil && assistantAuthFailureText(streamError.Error()))) {+ if req.RunnerLogin {+ return "", sessionID, assistantRunnerLoginError(engine)+ }return "", sessionID, assistantCredentialError{engine: engine}}if credentialRejected && strings.TrimSpace(final) == "" && err == nil && ctx.Err() == nil {@@ -1606,6 +1618,12 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.Uerr = streamError}out, err := decodeAssistantCLIResult(final, resultError, err, stderrTail)+ if err != nil && req.RunnerLogin && ctx.Err() == nil && !errors.Is(err, runtime.ErrConversationNotStarted) {+ text := strings.ToLower(err.Error())+ if assistantAuthFailureText(text) || strings.Contains(text, "not logged in") || strings.Contains(text, "login expired") || strings.Contains(text, "please run /login") {+ return "", sessionID, assistantRunnerLoginError(engine)+ }+ }if err != nil {diagnosticID := ""if attempt != nil {diff --git a/internal/httpapi/assistant_codebuddy_default_test.go b/internal/httpapi/assistant_codebuddy_default_test.gonew file mode 100644index 00000000..655b8d00--- /dev/null+++ b/internal/httpapi/assistant_codebuddy_default_test.go@@ -0,0 +1,43 @@+package httpapi++import (+ "context"+ "testing"++ "agentflow/internal/domain"+)++// 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)+ if catalog.Default != "personal-a" {+ t.Fatalf("default = %q, want the first saved model", catalog.Default)+ }+ for _, id := range []string{"env-default", "env-other", "personal-a", "personal-b"} {+ if got := assistantAllowedUserModel(id, catalog, user); got != id {+ t.Fatalf("model %s not accepted: %q", id, got)+ }+ }+ if got := assistantAllowedUserModel("", catalog, user); got != "personal-a" {+ t.Fatalf("empty request runs on %q, want personal-a", got)+ }++ // 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 {+ t.Fatalf("catalog without saved models changed: %+v", got)+ }+ if got := withCodeBuddyPersonalModels(base, domain.User{CodeBuddyModels: user.CodeBuddyModels}); got.Default != "env-default" {+ t.Fatalf("saved models without a key changed the default: %+v", got)+ }++ if model, err := scheduledRunModel(context.Background(), "", user); err != nil || model != "personal-a" {+ t.Fatalf("scheduled run without a model = %q, %v; want personal-a", model, err)+ }+ if model, err := scheduledRunModel(context.Background(), "personal-b", user); err != nil || model != "personal-b" {+ t.Fatalf("scheduled run with a saved model = %q, %v", model, err)+ }+}diff --git a/internal/httpapi/assistant_engine_cli.go b/internal/httpapi/assistant_engine_cli.goindex 8397951b..d06bb522 100644--- a/internal/httpapi/assistant_engine_cli.go+++ b/internal/httpapi/assistant_engine_cli.go@@ -131,6 +131,10 @@ func (e assistantCredentialError) Is(target error) bool {return target == errAssistantCredentialRejected}+func assistantRunnerLoginError(engine string) error {+ return fmt.Errorf("执行机器上的 %s 本机登录态无效或已过期,请检查 Runner 账户的 CLI 登录", assistantEngineLabel(engine))+}+var assistantAuthFailureRe = regexp.MustCompile(`(?i)\b(401|403)\b|unauthorized|invalid api key|invalid x-api-key|authentication_error|incorrect api key`)func assistantAuthFailureText(text string) bool {@@ -194,8 +198,10 @@ func prepareAssistantClaudeInvocation(o assistantEngineInvocationOpts) (assistanargv := []string{o.Bin, "-p", "--verbose", "--output-format", "stream-json", "--include-partial-messages","--max-turns", nativeAssistantUnlimitedTurns, "--system-prompt", o.SystemPrompt,"--mcp-config", mcpPath, "--strict-mcp-config", "--settings", settingsPath, "--setting-sources", "user",- "--permission-mode", "bypassPermissions",- "--model", o.Model}+ "--permission-mode", "bypassPermissions"}+ if o.Model != "" {+ argv = append(argv, "--model", o.Model)+ }if !o.Workspace {argv = append(argv, "--disallowedTools", claudeAssistantDisallowedTools)}diff --git a/internal/httpapi/assistant_engine_codex.go b/internal/httpapi/assistant_engine_codex.goindex 50afdfb7..21c2ebb2 100644--- a/internal/httpapi/assistant_engine_codex.go+++ b/internal/httpapi/assistant_engine_codex.go@@ -189,7 +189,10 @@ func (s *codexAppServer) response(message codexRPCMessage) []string {// App-server builds each thread's hook trust from its own config.// Both the platform guard and workspace approval hook are generated// and reviewed by the platform.- params := map[string]any{"model": s.opts.Model, "developerInstructions": s.opts.SystemPrompt, "sandbox": "read-only", "approvalPolicy": "never", "cwd": filepath.Join(s.opts.Root, "ws"), "config": map[string]any{"bypass_hook_trust": true}}+ params := map[string]any{"developerInstructions": s.opts.SystemPrompt, "sandbox": "read-only", "approvalPolicy": "never", "cwd": filepath.Join(s.opts.Root, "ws"), "config": map[string]any{"bypass_hook_trust": true}}+ if s.opts.Model != "" {+ params["model"] = s.opts.Model+ }if s.opts.Workspace {params["sandbox"] = "danger-full-access"}diff --git a/internal/httpapi/assistant_engine_models_test.go b/internal/httpapi/assistant_engine_models_test.goindex 56c90122..c882f11a 100644--- a/internal/httpapi/assistant_engine_models_test.go+++ b/internal/httpapi/assistant_engine_models_test.go@@ -19,7 +19,7 @@ func TestAssistantEngineModelsKeepPersonalCatalogOnOfficialKey(t *testing.T) {}ids := func(user domain.User) []string {var out []string- for _, model := range assistantEngineModels(context.Background(), user) {+ for _, model := range assistantEngineModels(context.Background(), user, nil) {out = append(out, model.ID)}return outdiff --git a/internal/httpapi/assistant_engines.go b/internal/httpapi/assistant_engines.goindex d5c589ed..b0d00d90 100644--- a/internal/httpapi/assistant_engines.go+++ b/internal/httpapi/assistant_engines.go@@ -134,6 +134,8 @@ func assistantEngineAnthropicModels(engine, protocol string) bool {func assistantEngineCustomModels(user domain.User, engine string) []domain.CLIModel {switch engine {+ case assistantEngineCodeBuddy:+ return user.CodeBuddyModelscase assistantEngineCodex:return user.CodexModelscase assistantEngineClaude:@@ -243,15 +245,20 @@ func assistantEngineMissingKey(engine string) string {return fmt.Sprintf("请先在个人配置中配置 %s API Key 后再使用 %s 模型", assistantEngineLabel(engine), assistantEngineLabel(engine))}-// assistantTurnUser resolves the identity and model of one chat turn. Codex-// and Claude Code models need the caller's own key for that CLI and are never-// sponsored; CodeBuddy models keep the sponsor fallback. The returned user-// still carries a lent CodeBuddy key when there is one, so approval reviews-// keep working on Codex / Claude Code turns.-func (h *assistantHandlers) assistantTurnUser(stored domain.User, model string) (domain.User, string, string) {- engine, _ := assistantModelEngine(model)+// 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 key, _ := assistantEngineCredential(stored, engine); key == "" {+ if runnerLogin {+ if id == "" {+ id = "default"+ }+ if !assistantValidEngineModel(id) {+ return stored, "", "模型 ID 无效"+ }+ model = engine + ":" + id+ } else if key, _ := assistantEngineCredential(stored, engine); key == "" {return stored, "", assistantEngineMissingKey(engine)}user, _, _ := h.assistantChatUser(stored)@@ -301,37 +308,43 @@ func assistantScheduledModel(id string, catalog assistantModelCatalog) string {return assistantAllowedModel(id, catalog)}-// assistantEngineModels lists the models a configured CLI offers in chat.-// A personal catalog wins on the official endpoint and behind a Base URL.-// An empty catalog asks the Base URL for its published models, then falls-// back to the built-in executor catalog. Gemini publishes no OpenAI-style-// list, so an empty catalog there uses the built-in models directly.-func assistantEngineModels(ctx context.Context, user domain.User) []assistantModel {+// assistantDiscoveredModelsFor resolves the model list shared by the chat+// composer and role editor. A saved catalog takes precedence over discovery.+func assistantDiscoveredModelsFor(ctx context.Context, user domain.User, engine string) []assistantDiscoveredModel {+ key, baseURL := assistantEngineCredential(user, engine)+ protocol := assistantEngineProtocol(user, engine)+ listed := assistantSavedModels(user, engine)+ if len(listed) == 0 && key != "" && baseURL != "" && protocol != runtime.AgentCLIProtocolGemini {+ listed = cachedAssistantEngineDiscovery(ctx, assistantEngineAnthropicModels(engine, protocol), key, baseURL)+ }+ if engine == runtime.AgentCLICursor && key != "" && !user.AgentCLICredentials[engine].ModelsCustomized {+ if fresh := cachedCursorModels(key); len(fresh) > 0 {+ listed = fresh+ }+ }+ return listed+}++func assistantSavedModels(user domain.User, engine string) []assistantDiscoveredModel {+ var listed []assistantDiscoveredModel+ for _, model := range assistantEngineCustomModels(user, engine) {+ if assistantValidEngineModel(model.ID) {+ listed = append(listed, assistantDiscoveredModel{ID: model.ID, Name: model.Name, Efforts: model.Efforts, DefaultEffort: model.DefaultEffort})+ }+ }+ return listed+}++func assistantEngineModels(ctx context.Context, user domain.User, runnerLogin map[string]bool) []assistantModel {var out []assistantModelfor _, engine := range assistantCLIEngines() {- key, baseURL := assistantEngineCredential(user, engine)- if key == "" {+ key, _ := assistantEngineCredential(user, engine)+ listed := assistantSavedModels(user, engine)+ if key == "" && !runnerLogin[engine] && len(listed) == 0 {continue}- protocol := assistantEngineProtocol(user, engine)- if protocol == runtime.AgentCLIProtocolGemini {- baseURL = ""- }- var listed []assistantDiscoveredModel- for _, model := range assistantEngineCustomModels(user, engine) {- if assistantValidEngineModel(model.ID) {- listed = append(listed, assistantDiscoveredModel{ID: model.ID, Name: model.Name, Efforts: model.Efforts, DefaultEffort: model.DefaultEffort})- }- }- if len(listed) == 0 && baseURL != "" {- listed = cachedAssistantEngineDiscovery(ctx, assistantEngineAnthropicModels(engine, protocol), key, baseURL)- }- // Cursor's list comes from the CLI; the saved one (the last list- // saveCursorCatalog kept) answers until a fresh one is cached.- if engine == runtime.AgentCLICursor {- if fresh := cachedCursorModels(key); len(fresh) > 0 {- listed = fresh- }+ if !runnerLogin[engine] {+ listed = assistantDiscoveredModelsFor(ctx, user, engine)}if len(listed) == 0 {listed = assistantEngineBuiltinModels(engine)@@ -451,7 +464,7 @@ func cachedCursorModels(apiKey string) []assistantDiscoveredModel {// resolve from that saved list, so a family keeps working on every instance// and after a restart, and each user resolves against their own CLI's list.func (h *assistantHandlers) saveCursorCatalog(user domain.User) {- if h == nil || h.repo == nil || user.ID <= 0 {+ if h == nil || h.repo == nil || user.ID <= 0 || user.AgentCLICredentials[runtime.AgentCLICursor].ModelsCustomized {return}key, _ := assistantEngineCredential(user, runtime.AgentCLICursor)@@ -467,7 +480,7 @@ func (h *assistantHandlers) saveCursorCatalog(user domain.User) {return}if _, err := h.repo.UpdateUserCredentials(user.ID, repo.UserCredentialUpdate{- AgentCLICredentials: map[string]repo.AgentCLICredentialUpdate{runtime.AgentCLICursor: {Models: &models}},+ AgentCLICredentials: map[string]repo.AgentCLICredentialUpdate{runtime.AgentCLICursor: {Models: &models, DiscoveredForKey: key}},}); err != nil {log.Printf("cursor model catalog save skipped user=%d: %v", user.ID, err)}@@ -496,7 +509,11 @@ func discoverAssistantEngineModels(ctx context.Context, anthropic bool, apiKey,}schemes := []string{"bearer"}if anthropic {- schemes = append(schemes, "x-api-key")+ if strings.TrimRight(baseURL, "/") == assistantAnthropicAPIBase {+ schemes = []string{"x-api-key"}+ } else {+ schemes = append(schemes, "x-api-key")+ }}var lastErr errorfor _, scheme := range schemes {@@ -504,11 +521,13 @@ func discoverAssistantEngineModels(ctx context.Context, anthropic bool, apiKey,if err != nil {return nil, err}+ if anthropic {+ req.Header.Set("anthropic-version", "2023-06-01")+ }if scheme == "bearer" {req.Header.Set("Authorization", "Bearer "+apiKey)} else {req.Header.Set("x-api-key", apiKey)- req.Header.Set("anthropic-version", "2023-06-01")}resp, err := http.DefaultClient.Do(req)if err != nil {diff --git a/internal/httpapi/assistant_execution.go b/internal/httpapi/assistant_execution.goindex b8cecb83..5625706d 100644--- a/internal/httpapi/assistant_execution.go+++ b/internal/httpapi/assistant_execution.go@@ -1,8 +1,10 @@package httpapiimport (- "agentflow/internal/domain""fmt"++ "agentflow/internal/domain"+"github.com/gin-gonic/gin")@@ -49,6 +51,24 @@ func (h *assistantHandlers) newExecutionTarget(userID int64, projectID string, rreturn &target, nil}+// Use a machine's login only for its owner on a personal execution target.+func (h *assistantHandlers) assistantUsesRunnerLogin(userID int64, target *domain.AssistantExecutionTarget, engine string) bool {+ if target == nil || target.Pool != domain.ExecutionModeRunner {+ return false+ }+ runner, ok := h.repo.Runner(target.RunnerID)+ return ok && runner.OwnerUserID == userID && runnerUsesLocalLogin(runner, engine)+}++func runnerUsesLocalLogin(runner domain.Runner, engine string) bool {+ return assistantSupportsRunnerLogin(engine) &&+ runner.RuntimeAuthMode(engine) == domain.RuntimeAuthLocal+}++func assistantSupportsRunnerLogin(engine string) bool {+ return engine == assistantEngineCodex || engine == assistantEngineClaude+}+func (h *assistantHandlers) sessionMode(c *gin.Context) {user, ok := h.requestUser(c.Request, true)if !ok {diff --git a/internal/httpapi/assistant_failure.go b/internal/httpapi/assistant_failure.goindex 951df74e..5c53ee6f 100644--- a/internal/httpapi/assistant_failure.go+++ b/internal/httpapi/assistant_failure.go@@ -142,6 +142,10 @@ func classifyAssistantFailureText(f domain.AssistantFailure, err error, text strreturn false}switch {+ case has("本机登录态"):+ f.Code, f.Phase, f.Message, f.Suggestion = "RUNNER_LOGIN_REQUIRED", "setup", "执行机器上的 CLI 本机登录态不可用,请检查执行机器上的 CLI 登录", "请在运行 Runner 的系统账户下检查 CLI 登录,或切换到个人凭证。"+ case has("执行机器需升级至"):+ f.Code, f.Phase, f.Message, f.Suggestion = "EXECUTION_MACHINE_UPDATE_REQUIRED", "setup", "执行机器版本过低,请升级 Runner 后重试", "请升级执行机器上的 Runner 后重试。"case has("insufficient_quota", "quota exceeded", "credit balance", "billing", "额度不足", "余额不足"):f.Code, f.Phase, f.Message, f.Suggestion = "QUOTA_EXCEEDED", "provider", "模型服务额度不足,无法继续生成", "请检查模型服务的余额或额度。"case has("rate limit", "rate_limit", "too many requests", "http 429", "status 429", "status code 429", "status=429"):diff --git a/internal/httpapi/assistant_generation.go b/internal/httpapi/assistant_generation.goindex 6533aa23..03de8956 100644--- a/internal/httpapi/assistant_generation.go+++ b/internal/httpapi/assistant_generation.go@@ -34,14 +34,6 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) {return}req.Model = assistantRequestModel(req.Executor, req.Model)- user, model, refusal := h.assistantTurnUser(stored, req.Model)- if refusal != "" {- c.JSON(400, gin.H{"error": refusal})- return- }- req.Model = model- cliEngine, _ := assistantModelEngine(req.Model)- req.Executor = cliEngineif len(req.Messages) == 0 || req.Messages[len(req.Messages)-1].Role != "user" {c.JSON(400, gin.H{"error": "请提供用户消息"})return@@ -59,17 +51,41 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) {c.JSON(400, gin.H{"error": "会话 ID 无效"})return}- ownerID, shared, err := h.conversationScope(c, req.SessionID, req.RunID, req.ProjectID, user.ID)+ ownerID, shared, err := h.conversationScope(c, req.SessionID, req.RunID, req.ProjectID, stored.ID)if err != nil {c.JSON(403, gin.H{"error": err.Error()})return}+ old, _ := h.repo.AssistantSession(ownerID, req.SessionID)+ if old.ID != "" && old.ExecutionLocked() {+ if req.ExecutionTarget != nil && *req.ExecutionTarget != old.Execution() {+ c.JSON(409, gin.H{"error": "会话执行机器已固定,不能更换"})+ return+ }+ target := old.Execution()+ req.ExecutionTarget = &target+ } else {+ var targetErr error+ req.ExecutionTarget, targetErr = h.newExecutionTarget(stored.ID, req.ProjectID, draftExecutionTarget(old, req.ExecutionTarget))+ if targetErr != nil {+ c.JSON(400, gin.H{"error": targetErr.Error()})+ return+ }+ }+ cliEngine, _ := assistantModelEngine(req.Model)+ runnerLogin := h.assistantUsesRunnerLogin(stored.ID, req.ExecutionTarget, cliEngine)+ user, model, refusal := h.assistantTurnUser(stored, req.Model, runnerLogin)+ if refusal != "" {+ c.JSON(400, gin.H{"error": refusal})+ return+ }+ req.Model = modelif err := h.validateAssistantTriggerHistory(ownerID, req); err != nil {c.JSON(400, gin.H{"error": err.Error()})return}if shared {- if old, ok := h.repo.AssistantSession(ownerID, req.SessionID); ok {+ if old.ID != "" {if !sharedTranscriptPrefix(old.Messages, req.Messages) {c.JSON(409, gin.H{"error": "共享会话已更新,请重新打开后发送"})return@@ -97,26 +113,21 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) {if catalogEngine == assistantEngineCodeBuddy {catalog = h.turnCatalog(c.Request.Context(), user, req.Model)}- req.Model = assistantAllowedUserModel(req.Model, catalog, user)+ if !runnerLogin {+ req.Model = assistantAllowedUserModel(req.Model, catalog, user)+ }cliEngine, _ = assistantModelEngine(req.Model)req.Executor = cliEngineif err := validateAssistantEffort(user, req.Model, req.Effort); err != nil {c.JSON(400, gin.H{"error": err.Error()})return}- legacyExecutor := ""- if old, ok := h.repo.AssistantSession(ownerID, req.SessionID); ok {- legacyExecutor = old.Executor- }- if refusal := assistantEngineSwitchRefusal(assistantConversationEngine(req.Messages, legacyExecutor), req.Model); refusal != "" {+ if refusal := assistantEngineSwitchRefusal(assistantConversationEngine(req.Messages, old.Executor), req.Model); refusal != "" {c.JSON(409, gin.H{"error": refusal})return}- freshCLI := false- if old, ok := h.repo.AssistantSession(ownerID, req.SessionID); ok {- freshCLI = assistantConversationEngine(old.Messages, old.Executor) != cliEngine- }- if old, ok := h.repo.AssistantSession(ownerID, req.SessionID); ok {+ freshCLI := old.ID != "" && assistantConversationEngine(old.Messages, old.Executor) != cliEngine+ if old.ID != "" {if len(req.Messages) < len(old.Messages) {c.JSON(409, gin.H{"error": "会话已更新,请重新打开后发送"})return@@ -130,21 +141,6 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) {}}}- old, _ := h.repo.AssistantSession(ownerID, req.SessionID)- if old.ID != "" && old.ExecutionLocked() {- if req.ExecutionTarget != nil && *req.ExecutionTarget != old.Execution() {- c.JSON(409, gin.H{"error": "会话执行机器已固定,不能更换"})- return- }- req.ExecutionTarget = old.ExecutionTarget- } else {- var targetErr error- req.ExecutionTarget, targetErr = h.newExecutionTarget(user.ID, req.ProjectID, draftExecutionTarget(old, req.ExecutionTarget))- if targetErr != nil {- c.JSON(400, gin.H{"error": targetErr.Error()})- return- }- }// Every message shows when it was sent. The server clock stamps the new// question, so a skewed or missing browser clock cannot misdate it.sentAt := time.Now().UTC()diff --git a/internal/httpapi/assistant_models.go b/internal/httpapi/assistant_models.goindex 4a4fd6e9..1dbc7bf7 100644--- a/internal/httpapi/assistant_models.go+++ b/internal/httpapi/assistant_models.go@@ -212,6 +212,10 @@ func (h *assistantHandlers) models(c *gin.Context) {// 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.Models = saved+ catalog.Default = saved[0].ID+ }default:catalog = assistantChatCatalog(c.Request.Context(), "", nil)}@@ -219,13 +223,54 @@ func (h *assistantHandlers) models(c *gin.Context) {catalog.SponsoredModel, catalog.SponsoredModels = key.Models[0], key.Models}if signedIn {- catalog.Models = append(catalog.Models, assistantEngineModels(c.Request.Context(), user)...)- h.saveCursorCatalog(user)catalog.Engines = assistantEngineOptions(user, shared && strings.TrimSpace(user.CodeBuddyAPIKey) == "")+ var runnerLogin map[string]bool+ if c.Query("schedule") == "1" {+ c.Header("Cache-Control", "private, no-store")+ runnerLogin = make(map[string]bool)+ for i := range catalog.Engines {+ engine := catalog.Engines[i].ID+ if scheduleLoginRunner(h.repo, user.ID, engine).ID != "" {+ runnerLogin[engine] = true+ catalog.Engines[i].Configured = true+ }+ }+ }+ catalog.Models = append(catalog.Models, assistantEngineModels(c.Request.Context(), user, runnerLogin)...)+ h.saveCursorCatalog(user)}c.JSON(200, catalog)}+// withCodeBuddyPersonalModels also accepts the user's saved CodeBuddy models+// and, like the picker (/api/assistant/models), defaults to the first of them,+// so a request without a model (API, bots, scheduled runs) runs on the model+// the UI shows as default. The environment's models stay accepted.+func withCodeBuddyPersonalModels(catalog assistantModelCatalog, user domain.User) assistantModelCatalog {+ saved := codeBuddyPersonalModels(user)+ if len(saved) == 0 {+ return catalog+ }+ catalog.Models = append(catalog.Models, saved...)+ catalog.Default = saved[0].ID+ return catalog+}++func codeBuddyPersonalModels(user domain.User) []assistantModel {+ if strings.TrimSpace(user.CodeBuddyAPIKey) == "" {+ return nil+ }+ var models []assistantModel+ for _, item := range assistantSavedModels(user, assistantEngineCodeBuddy) {+ name := item.Name+ if name == "" {+ name = item.ID+ }+ models = append(models, assistantListedModel(item.ID, name, ""))+ }+ return models+}+// assistantChatCatalog is the catalog used by chat conversations: the same// models, with the shared key's models listed and its default preselected.// Pass shared only for turns that run on the shared key (see chatCatalog).diff --git a/internal/httpapi/assistant_process.go b/internal/httpapi/assistant_process.goindex 4d4dfb40..a62077a4 100644--- a/internal/httpapi/assistant_process.go+++ b/internal/httpapi/assistant_process.go@@ -25,23 +25,24 @@ type assistantHelperExecutionKey struct{}type assistantHelperExecution struct {h *assistantHandlersowner int64- runner string+ target domain.AssistantExecutionTarget}func (h *assistantHandlers) helperExecutionContext(ctx context.Context, owner int64, target *domain.AssistantExecutionTarget) context.Context {if target == nil || target.RunnerID == "" {return ctx}- return context.WithValue(ctx, assistantHelperExecutionKey{}, assistantHelperExecution{h: h, owner: owner, runner: target.RunnerID})+ return context.WithValue(ctx, assistantHelperExecutionKey{}, assistantHelperExecution{h: h, owner: owner, target: *target})}-func helperCLIExecution(ctx context.Context, root string) func(context.Context, string, runtime.CommandSpec, runtime.RunCredentials, runtime.EventSink) (string, error) {+func helperCLIExecution(ctx context.Context, root string, actorID int64, engine string) (func(context.Context, string, runtime.CommandSpec, runtime.RunCredentials, runtime.EventSink) (string, error), bool) {bound, ok := ctx.Value(assistantHelperExecutionKey{}).(assistantHelperExecution)if !ok {- return nil+ return nil, false}- s := &AgentToolSession{ChatOwnerID: bound.owner, ChatSessionID: "helper-" + newAssistantSessionID(), ExecutionRunnerID: bound.runner, RuntimeMode: domain.AssistantModePlatform}- return bound.h.conversationExecutor(s, root)+ s := &AgentToolSession{ChatOwnerID: bound.owner, ChatSessionID: "helper-" + newAssistantSessionID(), ExecutionRunnerID: bound.target.RunnerID, RuntimeMode: domain.AssistantModePlatform}+ s.runnerLogin = bound.h.assistantUsesRunnerLogin(actorID, &bound.target, engine)+ return bound.h.conversationExecutor(s, root), s.runnerLogin}// Protocol translation stays on the API process; the bound machine owns the@@ -112,6 +113,7 @@ func (h *assistantHandlers) conversationExecutor(s *AgentToolSession, root strinreturn runtime.ConversationProcessResult{}, err}req.SessionKey = key+ req.Transient = s.transientreq.SourceRoot = rootif s.ExecutionRunnerID == "" {forward := func(toolCtx context.Context, token string, body json.RawMessage) (json.RawMessage, error) {@@ -151,6 +153,9 @@ func (h *assistantHandlers) conversationExecutor(s *AgentToolSession, root strinif !runner.SupportsConversationCLI() {return preDispatchError(fmt.Errorf("执行机器需升级至 %s", domain.RunnerVersionConversationCLI))}+ if (s.runnerLogin || s.transient) && !runner.SupportsCLISettings() {+ return preDispatchError(fmt.Errorf("执行机器需升级至 %s 才能使用对话本机登录和 CLI 测试", domain.RunnerVersionCLISettings))+ }raw, err := json.Marshal(req)if err != nil {return preDispatchError(err)@@ -184,6 +189,13 @@ func (h *assistantHandlers) conversationExecutor(s *AgentToolSession, root strinerr = json.Unmarshal(response.Payload, &result)return result, err}+ if s.transient {+ defer func() {+ cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second)+ defer cancel()+ _, _ = call(cleanup, runtime.ConversationProcessRequest{Operation: "discard"})+ }()+ }if _, err := call(ctx, runtime.ConversationProcessRequest{Operation: "prepare"}); err != nil {return "", err}@@ -212,6 +224,7 @@ func (h *assistantHandlers) conversationExecutor(s *AgentToolSession, root strincommand, credentials = h.bindWorkspaceGit(ctx, s, command, credentials)}wire := runtime.ConversationCommandFor(command, credentials)+ wire.RunnerLogin = s.runnerLoginif s.ExecutionRunnerID != "" {wire.Argv[0] = assistantEngineBinary(command.Provider)}@@ -456,3 +469,34 @@ func (h *assistantHandlers) bindWorkspaceGit(ctx context.Context, s *AgentToolSe}return command, credentials}++func (h *assistantHandlers) testRunnerCLI(ctx context.Context, runnerID, provider string, runnerLogin bool, user domain.User) error {+ root, err := os.MkdirTemp("", "loopforge-cli-test-")+ if err != nil {+ return err+ }+ defer os.RemoveAll(root)+ model := provider + ":default"+ if provider == assistantEngineCodeBuddy {+ model = loadAssistantModels(ctx, user.CodeBuddyInternetEnvironment).Default+ } else if !runnerLogin {+ models := assistantDiscoveredModelsFor(ctx, user, provider)+ if len(models) == 0 {+ models = assistantEngineBuiltinModels(provider)+ }+ if len(models) > 0 {+ model = provider + ":" + models[0].ID+ }+ }+ session := &AgentToolSession{+ ChatOwnerID: user.ID, ChatSessionID: newAssistantSessionID(), ExecutionRunnerID: runnerID,+ RuntimeMode: domain.AssistantModePlatform, runnerLogin: runnerLogin, transient: true,+ }+ _, _, err = runAssistantCLI(ctx, assistantCLIRequest{+ Executor: provider, Model: model, Prompt: "Respond with OK.",+ SystemPrompt: "You are a connectivity check. Reply in plain text. Do not use tools.",+ SessionRoot: root, ReviewOnly: true, RemoteBinary: true, RunnerLogin: runnerLogin,+ Execute: h.conversationExecutor(session, root),+ }, user, nil)+ return err+}diff --git a/internal/httpapi/assistant_provider_test.go b/internal/httpapi/assistant_provider_test.goindex 587ebd8b..8e04e742 100644--- a/internal/httpapi/assistant_provider_test.go+++ b/internal/httpapi/assistant_provider_test.go@@ -340,3 +340,83 @@ func TestAssistantCodexAppServerDisablesNativeTools(t *testing.T) {t.Fatalf("guard script = %q err=%v", guard, err)}}++func TestAssistantUsesBoundRunnerLoginWithoutPersonalKey(t *testing.T) {+ // Keep reply-asset discovery inside the test's temporary directory.+ t.Setenv("TMPDIR", t.TempDir())+ h, user := workbenchFixture(t)+ runner := domain.Runner{+ ID: "local-login", OwnerUserID: user.ID, Status: domain.RunnerStatusOnline,+ RunnerVersion: domain.RunnerVersionCLISettings,+ Runtimes: []domain.RunnerRuntime{+ {Provider: "codex", AuthMode: domain.RuntimeAuthLocal},+ {Provider: "claude-code", AuthMode: domain.RuntimeAuthLocal},+ },+ }+ if err := h.repo.PutRunner(runner); err != nil {+ t.Fatal(err)+ }+ h.generate = func(_ context.Context, _ string, actor domain.User) (string, error) {+ if actor.CodexAPIKey != "" || actor.ClaudeCodeAPIKey != "" {+ return "", fmt.Errorf("fixture unexpectedly has personal provider credentials")+ }+ return "runner reply", nil+ }+ target := domain.AssistantExecutionTarget{Pool: domain.ExecutionModeRunner, RunnerID: runner.ID}+ messages := []assistantMessage{{Role: "user", Content: "Hello"}}++ // A saved session owns the choice of machine on both generation entry points.+ if err := h.repo.PutAssistantSession(user.ID, domain.AssistantSession{+ ID: "bound-runner", ExecutionTarget: &target, ExecutionTargetLocked: true,+ }); err != nil {+ t.Fatal(err)+ }+ start := assistantRequest{SessionID: "bound-runner", Executor: "codex", Model: "gpt-local", Messages: messages}+ data, _ := json.Marshal(start)+ c, rec := workbenchContext(user, "POST", "/api/assistant/generations", bytes.NewBuffer(data))+ h.startGeneration(c)+ if rec.Code != http.StatusAccepted {+ t.Fatalf("generate on bound runner: %d %s", rec.Code, rec.Body)+ }+ for deadline := time.Now().Add(5 * time.Second); ; {+ generation, _ := h.repo.AssistantGeneration(user.ID, start.SessionID)+ if generation.Status == "completed" {+ break+ }+ if generation.Status == "failed" || time.Now().After(deadline) {+ t.Fatalf("generation = %s: %s", generation.Status, generation.Error)+ }+ time.Sleep(10 * time.Millisecond)+ }+ saved, _ := h.repo.AssistantSession(user.ID, start.SessionID)+ if saved.Model != "codex:gpt-local" || saved.Execution() != target {+ t.Fatalf("saved model or runner changed: %q, %+v", saved.Model, saved.Execution())+ }++ for _, tc := range []struct {+ name string+ target *domain.AssistantExecutionTarget+ want int+ }{+ {"runner", &target, http.StatusOK},+ {"cloud", nil, http.StatusBadRequest},+ {"foreign", &domain.AssistantExecutionTarget{Pool: domain.ExecutionModeRunner, RunnerID: "someone-else"}, http.StatusBadRequest},+ {"personal-key", &target, http.StatusBadRequest},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if tc.name == "personal-key" {+ runner.Runtimes[1].AuthMode = domain.RuntimeAuthPersonal+ if err := h.repo.PutRunner(runner); err != nil {+ t.Fatal(err)+ }+ }+ req := assistantRequest{SessionID: tc.name + "-claude", Executor: "claude-code", Model: "sonnet", Messages: messages, ExecutionTarget: tc.target}+ body, _ := json.Marshal(req)+ c, rec := workbenchContext(user, "POST", "/api/assistant/chat", bytes.NewBuffer(body))+ h.chat(c)+ if rec.Code != tc.want {+ t.Fatalf("chat status %d, want %d: %s", rec.Code, tc.want, rec.Body)+ }+ })+ }+}diff --git a/internal/httpapi/assistant_schedule.go b/internal/httpapi/assistant_schedule.goindex 44a6929a..287a013a 100644--- a/internal/httpapi/assistant_schedule.go+++ b/internal/httpapi/assistant_schedule.go@@ -108,12 +108,9 @@ func (h *assistantHandlers) runScheduleJobPromptReporting(job domain.ScheduleJobreturn firstNonEmpty(task.NotificationResult, task.LastMessage), task.SessionID, nil}-// scheduleJobAssistantUser picks who runs the job: the member the job is bound-// to (whoever last saved it), else the project owner, else (for a non-shared-// job) its owner. A bound job never falls back to someone else's account. The-// model's CLI decides which key they need: their own, else for CodeBuddy the-// platform's shared key, whose allowed models are returned as shared (nil on-// the user's own key).+// scheduleJobAssistantUser picks the saved run-as member, or the project or+// 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 {@@ -134,20 +131,18 @@ func (h *assistantHandlers) scheduleJobAssistantUser(job domain.ScheduleJob, modif job.SharedTaskID == "" {add(job.OwnerUserID)}- // Personal keys go first in the original order, so a job whose recorded- // owner still has a key keeps running on it after the project changes- // owner; the shared key is only the fallback.+ // Try each candidate's own credentials before considering the shared key.for _, user := range candidates {- if key, _ := assistantEngineCredential(user, engine); key != "" {+ if scheduleHasPersonalCredential(h.repo, user, engine) {return user, nil, nil}}for _, user := range candidates {- if user, shared, ok := scheduleKeyUser(h.repo, user, engine); ok {+ if user, shared, ok := scheduleCredentialUser(h.repo, user, engine); ok {return user, shared, nil}}- return domain.User{}, nil, fmt.Errorf("执行提示词需要项目 Owner 的 %s API Key:请在该账号的个人配置中配置,或在自己的个人配置里填好 Key 后编辑并保存一次任务,改用你的 Key", assistantEngineLabel(engine))+ return domain.User{}, nil, fmt.Errorf("项目 Owner 缺少 %s 凭据。请编辑并保存一次任务,以你的凭据执行", assistantEngineLabel(engine))}// scheduleJobRunAsUser runs a bound job as that member while they can still@@ -156,13 +151,16 @@ func (h *assistantHandlers) scheduleJobRunAsUser(job domain.ScheduleJob, enginename := firstNonEmpty(job.RunAsName, fmt.Sprintf("用户 %d", job.RunAsUserID))user, ok := h.repo.User(job.RunAsUserID)if !ok {- return domain.User{}, nil, fmt.Errorf("任务保存人 %s 的账号已不存在:请编辑并保存一次任务,改用你的 Key", name)+ return domain.User{}, nil, fmt.Errorf("任务保存人 %s 的账号已不存在,请编辑并保存一次任务,以你的凭据执行", name)}if !scheduleProjectWriter(h.repo, job.ProjectID, user) {- return domain.User{}, nil, fmt.Errorf("%s 已不是该项目的可写成员,不能再用其 Key 执行:请编辑并保存一次任务,改用你的 Key", name)+ return domain.User{}, nil, fmt.Errorf("%s 已不是该项目的可写成员,请编辑并保存一次任务,以你的凭据执行", name)}- runUser, shared, ok := scheduleKeyUser(h.repo, user, engine)+ runUser, shared, ok := scheduleCredentialUser(h.repo, user, engine)if !ok {+ if assistantSupportsRunnerLogin(engine) {+ return domain.User{}, nil, fmt.Errorf("任务保存人 %s 缺少 %s 凭据,请在其默认执行机器启用账号登录,或在个人配置填写 API Key", name, assistantEngineLabel(engine))+ }if engine != assistantEngineCodeBuddy {return domain.User{}, nil, fmt.Errorf("执行提示词需要 %s 的 %s API Key:请在该账号的个人配置中配置", name, assistantEngineLabel(engine))}@@ -171,14 +169,33 @@ func (h *assistantHandlers) scheduleJobRunAsUser(job domain.ScheduleJob, enginereturn runUser, shared, nil}-// scheduleKeyUser is user with the key a scheduled run for engine uses: their-// own, else for CodeBuddy the platform's shared key (whose allowed models are-// returned as shared). Everything but the key stays the user's own. ok is-// false when neither exists.-func scheduleKeyUser(r interface {- SharedCodeBuddyKey() (repo.SharedCodeBuddyKey, bool)-}, user domain.User, engine string) (domain.User, []string, bool) {- if key, _ := assistantEngineCredential(user, engine); key != "" {+// scheduleLoginRunner resolves the actor's configured personal machine at+// save and run time. At run time an offline machine uses the API Key path.+func scheduleLoginRunner(r *repo.Store, userID int64, engine string) domain.Runner {+ if r == nil || userID <= 0 || !assistantSupportsRunnerLogin(engine) {+ return domain.Runner{}+ }+ id := r.DefaultRunner(userID)+ if id == "" {+ return domain.Runner{}+ }+ machine, ok := r.Runner(id)+ if !ok || machine.OwnerUserID != userID || !machine.SupportsCLISettings() ||+ !machine.SupportsProvider(engine) || !runnerUsesLocalLogin(machine, engine) {+ return domain.Runner{}+ }+ return machine+}++func scheduleHasPersonalCredential(r *repo.Store, user domain.User, engine string) bool {+ key, _ := assistantEngineCredential(user, engine)+ return key != "" || scheduleLoginRunner(r, user.ID, engine).ID != ""+}++// 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) {+ if scheduleHasPersonalCredential(r, user, engine) {return user, nil, true}if engine != assistantEngineCodeBuddy || r == nil {diff --git a/internal/httpapi/assistant_sponsor.go b/internal/httpapi/assistant_sponsor.goindex a4c7c7da..4f7f3865 100644--- a/internal/httpapi/assistant_sponsor.go+++ b/internal/httpapi/assistant_sponsor.go@@ -12,7 +12,7 @@ import (// Users who have not configured their own CodeBuddy API Key can still chat// with the platform's shared key (see repo.SharedCodeBuddyKey), limited to// the models a platform administrator allowed. SOP runs use it the same way-// through the engine, and AI scheduled tasks through scheduleKeyUser;+// through the engine, and AI scheduled tasks through scheduleCredentialUser;// clarification, reports and bots keep requiring the user's own key.const (assistantSponsorLoginEnv = repo.CodeBuddySponsorLoginEnv@@ -72,7 +72,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 assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, nil)+ return withCodeBuddyPersonalModels(assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, nil), user)}return restrictAssistantCatalog(assistantChatCatalog(ctx, user.CodeBuddyInternetEnvironment, key.Models), key.Models)}diff --git a/internal/httpapi/assistant_tasks.go b/internal/httpapi/assistant_tasks.goindex ad40b1fc..a90eb6f5 100644--- a/internal/httpapi/assistant_tasks.go+++ b/internal/httpapi/assistant_tasks.go@@ -133,7 +133,7 @@ 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)- if key, _ := assistantEngineCredential(user, engine); !ok || key == "" {+ if !ok || !scheduleHasPersonalCredential(h.repo, user, engine) {msg := "请先在个人配置中配置自己的 CodeBuddy API Key"if engine != assistantEngineCodeBuddy {msg = assistantEngineMissingKey(engine)@@ -222,24 +222,36 @@ func (h *assistantHandlers) executeAssistantTask(ctx context.Context, user domaiif strings.TrimSpace(task.ID) != "" {_ = saveAssistantTask(h.repo, user.ID, *task)}+ engine, _ := assistantModelEngine(task.Model)+ machine := scheduleLoginRunner(h.repo, user.ID, engine)+ machineOffline := machine.ID != "" && machine.Status != domain.RunnerStatusOnlinefail := func(msg string) error {+ if machineOffline {+ msg = fmt.Sprintf("默认执行机器 %s 已离线。%s", firstNonEmpty(machine.Name, machine.ID), msg)+ }task.LastStatus, task.LastError = "error", msgreturn errors.New(msg)}- // The task's model picks the CLI; a scheduled run needs a key for it (the- // runner's own, or the shared CodeBuddy key already substituted by- // scheduleKeyUser), checked before a conversation is opened.- engine, _ := assistantModelEngine(task.Model)- if key, _ := assistantEngineCredential(user, engine); key == "" {- if engine != assistantEngineCodeBuddy {- return fail(assistantEngineMissingKey(engine))+ // 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}+ } else {+ if key, _ := assistantEngineCredential(user, engine); key == "" {+ if machineOffline {+ return fail(fmt.Sprintf("未配置 %s API Key。请启动 Runner,或在个人配置中填写 Key 后重试", assistantEngineLabel(engine)))+ }+ if engine != assistantEngineCodeBuddy {+ return fail(assistantEngineMissingKey(engine))+ }+ return fail("未配置 CodeBuddy API Key")+ }+ var err error+ if model, err = scheduledRunModel(ctx, model, user); err != nil {+ return fail(err.Error())}- return fail("未配置 CodeBuddy API Key")- }- model, err := scheduledRunModel(ctx, task.Model, user)- if err != nil {- return fail(err.Error())}cliEngine, _ := assistantModelEngine(model)policy := scheduledSessionPolicyFrom(ctx)@@ -247,25 +259,26 @@ func (h *assistantHandlers) executeAssistantTask(ctx context.Context, user domaisessionID := newAssistantSessionID()now := time.Now().UTC()prompt := assistantMessage{Role: "user", Content: scheduledAssistantPrompt(*task, mode), AuthorID: user.ID, AuthorName: user.LoginName, CreatedAt: now}- pending := assistantConversation{ID: sessionID, Title: "定时 · " + task.Name, ProjectID: task.ProjectID, Model: model, Executor: cliEngine, Source: origin.Source, TaskID: origin.TaskID, Messages: []assistantMessage{prompt}}+ pending := assistantConversation{ID: sessionID, Title: "定时 · " + task.Name, ProjectID: task.ProjectID, Model: model, Executor: cliEngine, ExecutionTarget: target, Source: origin.Source, TaskID: origin.TaskID, Messages: []assistantMessage{prompt}}// A pinned conversation continues as long as it is still this job's// conversation in this project; otherwise the run opens a new one, which// becomes the pinned conversation.if id := policy.Continue; id != "" {if prev, ok := h.repo.AssistantSession(user.ID, id); ok && prev.Source == origin.Source && prev.TaskID == origin.TaskID && prev.ProjectID == task.ProjectID {pending = prev- pending.Model, pending.Executor = model, cliEngine+ pending.Model, pending.Executor, pending.ExecutionTarget = model, cliEngine, targetpending.Messages = append(append([]assistantMessage{}, prev.Messages...), prompt)sessionID = prev.ID}}req := assistantRequest{- ApprovalMode: AssistantApprovalAuto,- ProjectID: task.ProjectID,- SessionID: sessionID,- Model: model,- Executor: cliEngine,- Messages: pending.Messages,+ ApprovalMode: AssistantApprovalAuto,+ ProjectID: task.ProjectID,+ SessionID: sessionID,+ Model: model,+ Executor: cliEngine,+ ExecutionTarget: target,+ Messages: pending.Messages,}g := domain.AssistantGeneration{StartedAt: now, ActorID: user.ID, ActorName: user.LoginName, ID: newAssistantSessionID(), SessionID: sessionID, UserID: user.ID, ProjectID: task.ProjectID, Status: "running", Events: []domain.AssistantGenerationEvent{}, MessageCount: len(req.Messages)}if err := h.repo.BeginAssistantGeneration(g, pending); err != nil {@@ -289,7 +302,11 @@ func (h *assistantHandlers) executeAssistantTask(ctx context.Context, user domai// records; the session janitor trims old ones.prevSession, origin.TaskID = "", ""}- return h.readScheduledTurn(user, task, g, len(req.Messages), prevSession, origin.TaskID)+ err := h.readScheduledTurn(user, task, g, len(req.Messages), prevSession, origin.TaskID)+ if err != nil && machineOffline {+ return fail("使用个人 API Key 执行失败。" + err.Error())+ }+ return err}// readScheduledTurn reports the finished turn back onto the task. The reply@@ -460,7 +477,8 @@ func firstNonEmpty(values ...string) string {func scheduledRunModel(ctx context.Context, requested string, user domain.User) (string, error) {requested = strings.TrimSpace(requested)env := user.CodeBuddyInternetEnvironment- model := assistantAllowedUserModel(requested, loadAssistantModels(ctx, env), user)+ catalog := withCodeBuddyPersonalModels(loadAssistantModels(ctx, env), user)+ model := assistantAllowedUserModel(requested, catalog, user)if requested == "" || model == requested {return model, nil}diff --git a/internal/httpapi/catalog_test.go b/internal/httpapi/catalog_test.goindex 539ecebd..501a5a2b 100644--- a/internal/httpapi/catalog_test.go+++ b/internal/httpapi/catalog_test.go@@ -1,6 +1,8 @@package httpapiimport (+ "bytes"+ "encoding/json""net/http""net/http/httptest""path/filepath"@@ -787,3 +789,48 @@ func TestGlobalRuleWorkflowBinding(t *testing.T) {t.Fatalf("turning the switch off must drop SOP bindings: %#v", cleared)}}++func TestExecutorModelsCatalogUsesOnlyTheEditorsSavedModels(t *testing.T) {+ assistant, user := workbenchFixture(t)+ user = domain.User{+ LoginName: "personal-catalog",+ CodexAPIKey: "fixture-secret",+ CodexModels: []domain.CLIModel{{ID: "gateway/second", Name: "Second"}, {ID: "gateway/first"}},+ ClaudeCodeModels: []domain.CLIModel{{ID: "custom-sonnet", Name: "Personal Sonnet"}},+ AgentCLICredentials: map[string]domain.AgentCLICredential{+ "opencode": {Models: []domain.CLIModel{{ID: "open/model", Name: "Open Model"}}},+ },+ }+ if err := assistant.repo.PutUser(user); err != nil {+ t.Fatal(err)+ }+ user, _ = assistant.repo.UserByLoginName(user.LoginName)+ handler := &catalogHandlers{deps: assistant.deps}+ c, rec := workbenchContext(user, "GET", "/api/executor-models", bytes.NewBuffer(nil))+ handler.executorModels(c)+ var catalogs map[string]executorModelCatalog+ if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &catalogs) != nil {+ t.Fatalf("catalog request: %d %s", rec.Code, rec.Body)+ }+ if rec.Header().Get("Cache-Control") != "private, no-store" || strings.Contains(rec.Body.String(), "fixture-secret") {+ t.Fatal("personal model catalog or credentials were cacheable or leaked")+ }+ if models := catalogs["codex"].Models; len(models) != 2 || models[0].Name != "Second" || models[1].ID != "gateway/first" || models[1].Name != "gateway/first" {+ t.Fatalf("Codex models = %+v", models)+ }+ if models := catalogs["claude"].Models; len(models) != 1 || models[0].Name != "Personal Sonnet" {+ t.Fatalf("Claude models = %+v", models)+ }+ if models := catalogs["opencode"].Models; len(models) != 1 || models[0].Name != "Open Model" {+ t.Fatalf("OpenCode models = %+v", models)+ }+ if !catalogs["codex"].CustomModel || len(catalogs["codex"].Efforts) == 0 {+ t.Fatalf("built-in Codex options disappeared: %+v", catalogs["codex"])+ }+ other, _ := assistant.repo.UserByLoginName("workbench-owner")+ c, rec = workbenchContext(other, "GET", "/api/executor-models", bytes.NewBuffer(nil))+ handler.executorModels(c)+ if rec.Code != http.StatusOK || strings.Contains(rec.Body.String(), "gateway/second") || !strings.Contains(rec.Body.String(), "gpt-6.1-sol") {+ t.Fatalf("other user did not receive built-in models: %d %s", rec.Code, rec.Body)+ }+}diff --git a/internal/httpapi/cli_models_probe.go b/internal/httpapi/cli_models_probe.goindex a1a97c16..398bb685 100644--- a/internal/httpapi/cli_models_probe.go+++ b/internal/httpapi/cli_models_probe.go@@ -2,8 +2,10 @@ package httpapiimport ("context"+ "encoding/json""errors""fmt"+ "io""net/http""os""os/exec"@@ -21,14 +23,15 @@ import (type cliModelProbeResult struct {Models []domain.CLIModel `json:"models"`- // Source is "remote" for the Base URL's model list and "builtin" for the- // executor catalog used when no Base URL is set.+ // Source identifies the configured gateway, official provider, Runner or built-in catalog.Source string `json:"source,omitempty"`Error string `json:"error,omitempty"`}-// probeCLIModels backs 「获取可用模型」 for the model catalog of a CLI other-// than CodeBuddy. The form's unsaved API Key, Base URL and protocol win over the stored ones+const assistantAnthropicAPIBase = "https://api.anthropic.com"++// probeCLIModels backs 「获取可用模型」 for a personal model catalog.+// The form's unsaved API Key, Base URL and protocol win over the stored ones// so a user can probe before saving; nothing is stored. Like// verifyGitToken it answers 200 with a structured result.func (h *usersHandlers) probeCLIModels(c *gin.Context) {@@ -49,13 +52,14 @@ func (h *usersHandlers) probeCLIModels(c *gin.Context) {// while "" means the official endpoint.BaseURL *string `json:"baseUrl"`// Protocol is the agent CLI's form value; null keeps the stored one.- Protocol *string `json:"protocol"`+ Protocol *string `json:"protocol"`+ Environment *string `json:"environment"`}if !decode(c, &req) {return}engine := strings.TrimSpace(req.Engine)- if engine == assistantEngineCodeBuddy || !slices.Contains(assistantCLIEngines(), engine) {+ if engine != assistantEngineCodeBuddy && !slices.Contains(assistantCLIEngines(), engine) {c.JSON(http.StatusBadRequest, cliModelProbeResult{Error: "不支持的 CLI:" + engine})return}@@ -63,7 +67,7 @@ func (h *usersHandlers) probeCLIModels(c *gin.Context) {c.JSON(http.StatusOK, cliModelProbeResult{Error: errInvalidCLIBaseURL})return}- apiKey, baseURL, protocol := strings.TrimSpace(req.APIKey), "", ""+ apiKey, baseURL, protocol, environment := strings.TrimSpace(req.APIKey), "", "", ""if h.repo != nil {if stored, found := h.repo.User(id); found {storedKey, storedURL := assistantEngineCredential(stored, engine)@@ -71,6 +75,7 @@ func (h *usersHandlers) probeCLIModels(c *gin.Context) {apiKey = storedKey}baseURL, protocol = storedURL, assistantEngineProtocol(stored, engine)+ environment = stored.CodeBuddyInternetEnvironment}}if req.BaseURL != nil {@@ -79,14 +84,40 @@ func (h *usersHandlers) probeCLIModels(c *gin.Context) {if req.Protocol != nil && runtime.IsAgentCLI(engine) {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+ }+ }+ ctx, cancel := context.WithTimeout(c.Request.Context(), 15*time.Second)+ defer cancel()+ var models []domain.CLIModel+ for _, id := range discoverCLIModels(ctx, environment, apiKey) {+ if assistantValidEngineModel(id) {+ models = append(models, domain.CLIModel{ID: id})+ }+ }+ if len(models) == 0 {+ c.JSON(http.StatusOK, cliModelProbeResult{Error: "CodeBuddy CLI 没有返回模型,请检查 CLI 和个人凭据"})+ return+ }+ source := "official"+ if apiKey == "" {+ source = "builtin"+ }+ c.JSON(http.StatusOK, cliModelProbeResult{Models: models, Source: source})+ return+ }if engine == runtime.AgentCLICursor {h.probeCursorModels(c, apiKey)return}- if protocol == runtime.AgentCLIProtocolGemini {- baseURL = ""- }- if baseURL == "" {+ if baseURL == "" && apiKey == "" {c.JSON(http.StatusOK, cliModelProbeResult{Models: cliModelsOf(assistantEngineBuiltinModels(engine)), Source: "builtin"})return}@@ -96,7 +127,35 @@ func (h *usersHandlers) probeCLIModels(c *gin.Context) {}ctx, cancel := context.WithTimeout(c.Request.Context(), 10*time.Second)defer cancel()- models, err := assistantEngineDiscover(ctx, assistantEngineAnthropicModels(engine, protocol), apiKey, baseURL)+ source := "remote"+ anthropic := assistantEngineAnthropicModels(engine, protocol)+ if baseURL == "" {+ source = "official"+ switch engine {+ case assistantEngineCodex:+ baseURL = "https://api.openai.com/v1"+ case assistantEngineClaude:+ baseURL = assistantAnthropicAPIBase+ case runtime.AgentCLIKimi:+ baseURL, anthropic = "https://api.kimi.com/coding/v1", false+ case runtime.AgentCLIDeepSeek:+ baseURL, anthropic = "https://api.deepseek.com", false+ case runtime.AgentCLIZCode:+ baseURL, anthropic = "https://open.bigmodel.cn/api/coding/paas/v4", false+ }+ }+ var models []assistantDiscoveredModel+ if engine == runtime.AgentCLIAntigravity && protocol == runtime.AgentCLIProtocolGemini {+ if baseURL == "" {+ baseURL = "https://generativelanguage.googleapis.com"+ }+ models, err = discoverGeminiModels(ctx, apiKey, baseURL)+ } else if baseURL != "" {+ models, err = assistantEngineDiscover(ctx, anthropic, apiKey, baseURL)+ } else {+ c.JSON(http.StatusOK, cliModelProbeResult{Error: "请先在个人配置中填写模型服务的 Base URL"})+ return+ }if err != nil {c.JSON(http.StatusOK, cliModelProbeResult{Error: "获取模型列表失败:" + err.Error()})return@@ -105,7 +164,47 @@ func (h *usersHandlers) probeCLIModels(c *gin.Context) {c.JSON(http.StatusOK, cliModelProbeResult{Error: "服务没有返回可用模型,可以手动添加模型"})return}- c.JSON(http.StatusOK, cliModelProbeResult{Models: cliModelsOf(models), Source: "remote"})+ c.JSON(http.StatusOK, cliModelProbeResult{Models: cliModelsOf(models), Source: source})+}++func discoverGeminiModels(ctx context.Context, key, baseURL string) ([]assistantDiscoveredModel, error) {+ baseURL = strings.TrimSuffix(strings.TrimRight(baseURL, "/"), "/v1beta")+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/v1beta/models?pageSize=1000", nil)+ if err != nil {+ return nil, err+ }+ req.Header.Set("x-goog-api-key", key)+ client := *http.DefaultClient+ client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }+ resp, err := client.Do(req)+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ return nil, fmt.Errorf("Gemini 模型接口返回 HTTP %d", resp.StatusCode)+ }+ var payload struct {+ Models []struct {+ Name string `json:"name"`+ DisplayName string `json:"displayName"`+ Methods []string `json:"supportedGenerationMethods"`+ } `json:"models"`+ }+ if err = json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&payload); err != nil {+ return nil, err+ }+ var models []assistantDiscoveredModel+ for _, item := range payload.Models {+ id := strings.TrimPrefix(item.Name, "models/")+ if assistantValidEngineModel(id) && slices.Contains(item.Methods, "generateContent") {+ models = append(models, assistantDiscoveredModel{ID: id, Name: item.DisplayName})+ if len(models) == assistantDiscoveryMaxModels {+ break+ }+ }+ }+ return models, nil}// probeCursorModels asks cursor-agent itself: Cursor has no Base URL, and@@ -130,7 +229,7 @@ func (h *usersHandlers) probeCursorModels(c *gin.Context, apiKey string) {c.JSON(http.StatusOK, cliModelProbeResult{Error: "Cursor CLI 没有返回可用模型,可以手动添加模型"})return}- c.JSON(http.StatusOK, cliModelProbeResult{Models: models, Source: "remote"})+ c.JSON(http.StatusOK, cliModelProbeResult{Models: models, Source: "official"})}var cursorModelLine = regexp.MustCompile(`^([A-Za-z0-9][A-Za-z0-9._-]*) - (.+)$`)diff --git a/internal/httpapi/cli_models_probe_test.go b/internal/httpapi/cli_models_probe_test.goindex 83103f31..447e1770 100644--- a/internal/httpapi/cli_models_probe_test.go+++ b/internal/httpapi/cli_models_probe_test.go@@ -1,12 +1,75 @@package httpapiimport (+ "bytes"+ "context"+ "io"+ "net/http"+ "net/http/httptest""reflect"+ "strconv"+ "strings""testing""agentflow/internal/domain"++ "github.com/gin-gonic/gin")+func TestProbeCLIModelsUsesOfficialEndpointWithoutBaseURL(t *testing.T) {+ h, owner := workbenchFixture(t)+ original := assistantEngineDiscover+ t.Cleanup(func() { assistantEngineDiscover = original })+ handlers := &usersHandlers{deps: h.deps}+ for _, check := range []struct {+ engine, url string+ anthropic bool+ }{+ {"codex", "https://api.openai.com/v1", false},+ {"claude-code", "https://api.anthropic.com", true},+ {"kimi", "https://api.kimi.com/coding/v1", false},+ {"dsh", "https://api.deepseek.com", false},+ {"zcode", "https://open.bigmodel.cn/api/coding/paas/v4", false},+ } {+ t.Run(check.engine, func(t *testing.T) {+ called := false+ assistantEngineDiscover = func(_ context.Context, anthropic bool, key, endpoint string) ([]assistantDiscoveredModel, error) {+ called = true+ if anthropic != check.anthropic || endpoint != check.url || key != "fixture-key" {+ t.Fatalf("unexpected probe: Anthropic=%v endpoint=%s", anthropic, endpoint)+ }+ return []assistantDiscoveredModel{{ID: "official-model"}}, nil+ }+ input := bytes.NewBufferString(`{"engine":"` + check.engine + `","apiKey":"fixture-key","baseUrl":""}`)+ c, w := workbenchContext(owner, http.MethodPost, "/", input)+ c.Params = gin.Params{{Key: "id", Value: strconv.FormatInt(owner.ID, 10)}}+ handlers.probeCLIModels(c)+ if !called || w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"source":"official"`) ||+ !strings.Contains(w.Body.String(), `"id":"official-model"`) {+ t.Fatalf("result %d %s", w.Code, w.Body.String())+ }+ })+ }+}++func TestDiscoverGeminiModelsKeepsGenerativeIDs(t *testing.T) {+ service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet || r.URL.Path != "/v1beta/models" || r.Header.Get("x-goog-api-key") != "fixture-key" {+ http.Error(w, "unexpected model-list request", http.StatusBadRequest)+ return+ }+ _, _ = io.WriteString(w, `{"models":[+ {"name":"models/embedding","supportedGenerationMethods":["embedContent"]},+ {"name":"models/gemini-fixture","displayName":"Gemini Fixture","supportedGenerationMethods":["generateContent"]}+ ]}`)+ }))+ t.Cleanup(service.Close)+ models, err := discoverGeminiModels(context.Background(), "fixture-key", service.URL+"/v1beta")+ if err != nil || !reflect.DeepEqual(models, []assistantDiscoveredModel{{ID: "gemini-fixture", Name: "Gemini Fixture"}}) {+ t.Fatalf("models=%+v error=%v", models, err)+ }+}+func TestCursorModelFamiliesFoldGemini4(t *testing.T) {output := `gemini-4-carbon-low - Gemini 4 Carbon Lowdiff --git a/internal/httpapi/cursor_catalog_test.go b/internal/httpapi/cursor_catalog_test.goindex adb075eb..ea275427 100644--- a/internal/httpapi/cursor_catalog_test.go+++ b/internal/httpapi/cursor_catalog_test.go@@ -86,7 +86,7 @@ func TestCursorFamiliesSurviveRestart(t *testing.T) {t.Fatal("unknown model accepted an effort")}var listed []assistantModel- for _, model := range assistantEngineModels(context.Background(), a) {+ for _, model := range assistantEngineModels(context.Background(), a, nil) {if model.Engine == runtime.AgentCLICursor {listed = append(listed, model)}@@ -122,6 +122,25 @@ func TestCursorFamiliesSurviveRestart(t *testing.T) {t.Errorf("%s %s/%s: argv %q, want --model %s", c.user.LoginName, c.model, c.effort, argv, c.want)}}++ // A refresh already in flight must not replace a catalog just saved in+ // personal settings or on a machine card.+ custom := []domain.CLIModel{{ID: "nova", Name: "My Nova"}}+ save := func(change repo.AgentCLICredentialUpdate) domain.User {+ stored, err := st.UpdateUserCredentials(a.ID, repo.UserCredentialUpdate{+ AgentCLICredentials: map[string]repo.AgentCLICredentialUpdate{runtime.AgentCLICursor: change},+ })+ if err != nil {+ t.Fatal(err)+ }+ return stored+ }+ save(repo.AgentCLICredentialUpdate{Models: &custom})+ refresh := cursorModelFamilies(parseCursorModels(cursorCatalogTestOutput))+ stored := save(repo.AgentCLICredentialUpdate{Models: &refresh, DiscoveredForKey: "crsr_cursor-a"})+ if got := assistantCursorCatalog(stored); len(got) != 1 || got[0].ID != "nova" || got[0].Name != "My Nova" {+ t.Fatalf("discovery replaced a user catalog: %+v", got)+ }}func clearCursorModelsCache() {diff --git a/internal/httpapi/executor_models.go b/internal/httpapi/executor_models.goindex 373dde1c..f59dba1f 100644--- a/internal/httpapi/executor_models.go+++ b/internal/httpapi/executor_models.go@@ -2,6 +2,7 @@ package httpapiimport ("net/http"+ "strings""agentflow/internal/domain""agentflow/internal/runtime"@@ -26,6 +27,7 @@ type executorEffortOption struct {// agent wizard. CustomModel marks CLIs that accept free-form model IDs// (custom base URLs); Credits is only surfaced for CodeBuddy.type executorModelCatalog struct {+ Source string `json:"source,omitempty"`Default string `json:"default,omitempty"`CustomModel bool `json:"customModel,omitempty"`Models []executorModelInfo `json:"models"`@@ -157,14 +159,42 @@ func cursorCatalogModels() []executorModelInfo {return out}-// executorModels serves the built-in model/effort catalog. It is a static,-// non-sensitive list (model IDs, credit multipliers, effort levels), so it is-// readable without login; role editing and runs still enforce auth elsewhere.+// executorModels returns built-in defaults and effort levels, with the+// signed-in editor's model lists substituted where available.func (h *catalogHandlers) executorModels(c *gin.Context) {+ c.Header("Cache-Control", "private, no-store")+ if c.Query("builtin") == "1" {+ c.JSON(http.StatusOK, executorModelCatalogs())+ return+ }+ var user domain.Userif current, ok := h.requestUser(c.Request, true); ok {- if user, ok := h.repo.User(current.ID); ok {+ if stored, found := h.repo.User(current.ID); found {+ user = storedrefreshCLIModels(c.Request.Context(), user.CodeBuddyInternetEnvironment, user.CodeBuddyAPIKey)}}- c.JSON(http.StatusOK, executorModelCatalogs())+ catalogs := executorModelCatalogs()+ for _, engine := range append([]string{assistantEngineCodeBuddy}, assistantCLIEngines()...) {+ models := assistantDiscoveredModelsFor(c.Request.Context(), user, engine)+ if len(models) == 0 {+ continue+ }+ id := engine+ if engine == assistantEngineClaude {+ id = "claude"+ }+ catalog := catalogs[id]+ catalog.Source = "personal"+ catalog.Models = make([]executorModelInfo, 0, len(models))+ for _, model := range models {+ name := strings.TrimSpace(model.Name)+ if name == "" {+ name = model.ID+ }+ catalog.Models = append(catalog.Models, executorModelInfo{ID: model.ID, Name: name})+ }+ catalogs[id] = catalog+ }+ c.JSON(http.StatusOK, catalogs)}diff --git a/internal/httpapi/runner_maintenance.go b/internal/httpapi/runner_maintenance.gonew file mode 100644index 00000000..153d2822--- /dev/null+++ b/internal/httpapi/runner_maintenance.go@@ -0,0 +1,75 @@+package httpapi++import (+ "context"+ "fmt"+ "net/http"+ "slices"+ "strings"+ "time"++ "agentflow/internal/domain"++ "github.com/gin-gonic/gin"+)++func (h *runnersHandlers) runnerMaintenance(c *gin.Context) {+ user, authenticated := h.requestUser(c.Request, true)+ if !authenticated {+ c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录后管理执行机器"})+ return+ }+ runner, found := h.repo.Runner(strings.TrimSpace(c.Param("id")))+ if !found {+ c.JSON(http.StatusNotFound, gin.H{"error": "执行机器不存在"})+ return+ }+ if runner.OwnerUserID != user.ID {+ c.JSON(http.StatusForbidden, gin.H{"error": "只能更新自己绑定的执行机器"})+ return+ }+ if runner.Status != domain.RunnerStatusOnline || h.runnerControls == nil {+ c.JSON(http.StatusServiceUnavailable, gin.H{"error": "执行机器暂未连接,请稍后重试"})+ return+ }+ if !runner.SupportsCLISettings() {+ c.JSON(http.StatusConflict, gin.H{"error": fmt.Sprintf("网页更新需要 Runner %s 或以上版本,请先在执行机器上升级", domain.RunnerVersionCLISettings)})+ return+ }+ input := domain.RunnerMaintenanceRequest{+ Provider: strings.TrimSpace(c.Query("provider")), Apply: c.Request.Method == http.MethodPost,+ StatusOnly: c.Query("status") == "1",+ }+ if input.Provider != "" {+ canUpdate := slices.ContainsFunc(runner.Runtimes, func(rt domain.RunnerRuntime) bool {+ return rt.Provider == input.Provider && (rt.SupportsCLIUpdate() || input.StatusOnly)+ })+ if !canUpdate {+ c.JSON(http.StatusConflict, gin.H{"error": "请在执行机器上使用该 CLI 原来的安装方式更新"})+ return+ }+ }+ ctx, cancel := context.WithTimeout(c.Request.Context(), 20*time.Second)+ defer cancel()+ response, err := h.runnerControls.requestWorkspace(ctx, runner.ID, domain.RunnerWorkspaceRequest{+ Operation: domain.RunnerWorkspaceOperationMaintenance, Maintenance: &input,+ })+ if err != nil {+ c.JSON(http.StatusServiceUnavailable, gin.H{"error": "暂时无法连接 Runner,请稍后重试"})+ return+ }+ if response.Error != "" {+ status := response.Status+ if status < http.StatusBadRequest || status > 599 {+ status = http.StatusBadGateway+ }+ c.JSON(status, gin.H{"error": response.Error})+ return+ }+ status := http.StatusOK+ if input.Apply {+ status = http.StatusAccepted+ }+ c.Header("Cache-Control", "no-store")+ c.Data(status, "application/json", response.Payload)+}diff --git a/internal/httpapi/runner_maintenance_test.go b/internal/httpapi/runner_maintenance_test.gonew file mode 100644index 00000000..bcec21bb--- /dev/null+++ b/internal/httpapi/runner_maintenance_test.go@@ -0,0 +1,68 @@+package httpapi++import (+ "bytes"+ "net/http"+ "strings"+ "testing"++ "agentflow/internal/domain"++ "github.com/gin-gonic/gin"+)++func TestRunnerMaintenanceRequiresOwnerAndDispatchesToBoundRunner(t *testing.T) {+ h, owner := workbenchFixture(t)+ row := domain.Runner{ID: "maintenance-runner", OwnerUserID: owner.ID, RunnerVersion: domain.RunnerVersionCLISettings,+ Status: domain.RunnerStatusOnline, Runtimes: []domain.RunnerRuntime{+ {Provider: "codex", Capabilities: []string{domain.RuntimeCapabilityManagedUpdate}},+ {Provider: "claude-code"},+ {Provider: "cursor", Capabilities: []string{domain.RuntimeCapabilityNativeUpdate}},+ }}+ if err := h.repo.PutRunner(row); err != nil {+ t.Fatal(err)+ }+ hub := quietRunnerHub()+ conn := testRunnerConn(row.ID)+ registerTestConn(hub, conn)+ t.Cleanup(conn.close)+ handlers := &runnersHandlers{deps: h.deps, runnerControls: hub}++ peer := domain.User{ID: owner.ID + 100, LoginName: "maintenance-peer"}+ c, w := workbenchContext(peer, http.MethodPost, "/", bytes.NewBuffer(nil))+ c.Params = gin.Params{{Key: "id", Value: row.ID}}+ handlers.runnerMaintenance(c)+ if w.Code != http.StatusForbidden {+ t.Fatalf("non-owner update returned %d", w.Code)+ }+ c, w = workbenchContext(owner, http.MethodPost, "/?provider=claude-code", bytes.NewBuffer(nil))+ c.Params = gin.Params{{Key: "id", Value: row.ID}}+ handlers.runnerMaintenance(c)+ if w.Code != http.StatusConflict {+ t.Fatalf("unmanaged CLI update returned %d", w.Code)+ }++ for _, tc := range []struct {+ method, query, provider string+ statusOnly bool+ want int+ }{+ {http.MethodGet, "", "", false, 200},+ {http.MethodPost, "", "", false, 202},+ {http.MethodPost, "?provider=codex", "codex", false, 202},+ {http.MethodPost, "?provider=cursor", "cursor", false, 202},+ {http.MethodGet, "?provider=codex&status=1", "codex", true, 200},+ } {+ c, w := workbenchContext(owner, tc.method, "/"+tc.query, bytes.NewBuffer(nil))+ c.Params = gin.Params{{Key: "id", Value: row.ID}}+ done := make(chan struct{})+ go func() { handlers.runnerMaintenance(c); close(done) }()+ request := answerOnce(t, hub, conn, domain.RunnerWorkspaceResponse{Status: 200, Payload: []byte(`{"status":"updating"}`)})+ <-done+ want := domain.RunnerMaintenanceRequest{Provider: tc.provider, Apply: tc.method == http.MethodPost, StatusOnly: tc.statusOnly}+ if request.Operation != domain.RunnerWorkspaceOperationMaintenance || request.Maintenance == nil || *request.Maintenance != want ||+ w.Code != tc.want || !strings.Contains(w.Body.String(), "updating") {+ t.Fatalf("%s %s: request=%+v status=%d %s", tc.method, tc.query, request.Maintenance, w.Code, w.Body)+ }+ }+}diff --git a/internal/httpapi/runner_models.go b/internal/httpapi/runner_models.gonew file mode 100644index 00000000..6b2d729e--- /dev/null+++ b/internal/httpapi/runner_models.go@@ -0,0 +1,74 @@+package httpapi++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "strings"+ "time"++ "agentflow/internal/domain"++ "github.com/gin-gonic/gin"+)++func (h *runnersHandlers) probeRunnerModels(c *gin.Context) {+ c.Header("Cache-Control", "private, no-store")+ user, ok := h.requestUser(c.Request, true)+ if !ok {+ c.JSON(http.StatusUnauthorized, cliModelProbeResult{Error: "请先登录后获取模型"})+ return+ }+ runner, found := h.repo.Runner(strings.TrimSpace(c.Param("id")))+ if !found {+ c.JSON(http.StatusNotFound, cliModelProbeResult{Error: "执行机器不存在"})+ return+ }+ if runner.OwnerUserID != user.ID {+ c.JSON(http.StatusForbidden, cliModelProbeResult{Error: "只能从自己绑定的执行机器获取账号模型"})+ return+ }+ var req struct {+ Provider string `json:"provider"`+ }+ if !decode(c, &req) {+ return+ }+ provider := strings.TrimSpace(req.Provider)+ if !runnerUsesLocalLogin(runner, provider) {+ c.JSON(http.StatusConflict, cliModelProbeResult{Error: "请先为该 CLI 启用账号登录"})+ return+ }+ if runner.Status != domain.RunnerStatusOnline || !runner.SupportsProvider(provider) || h.runnerControls == nil {+ c.JSON(http.StatusServiceUnavailable, cliModelProbeResult{Error: "执行机器或所选 CLI 当前不可用"})+ return+ }+ if !runner.SupportsCLISettings() {+ c.JSON(http.StatusConflict, cliModelProbeResult{Error: fmt.Sprintf("获取账号模型需要 Runner %s 或以上版本", domain.RunnerVersionCLISettings)})+ return+ }+ ctx, cancel := context.WithTimeout(c.Request.Context(), 20*time.Second)+ defer cancel()+ response, err := h.runnerControls.requestWorkspace(ctx, runner.ID, domain.RunnerWorkspaceRequest{+ Operation: domain.RunnerWorkspaceOperationLoginModels, ModelProvider: provider,+ })+ if err != nil {+ c.JSON(http.StatusServiceUnavailable, cliModelProbeResult{Error: "无法连接执行机器,请稍后重试"})+ return+ }+ if response.Error != "" {+ c.JSON(http.StatusBadGateway, cliModelProbeResult{Error: response.Error})+ return+ }+ var models []domain.CLIModel+ if err := json.Unmarshal(response.Payload, &models); err != nil {+ c.JSON(http.StatusBadGateway, cliModelProbeResult{Error: "执行机器返回了无效的模型列表"})+ return+ }+ if len(models) == 0 {+ c.JSON(http.StatusOK, cliModelProbeResult{Error: "账号没有返回可用模型,可以手动添加模型"})+ return+ }+ c.JSON(http.StatusOK, cliModelProbeResult{Models: models, Source: "runner"})+}diff --git a/internal/httpapi/runner_models_test.go b/internal/httpapi/runner_models_test.gonew file mode 100644index 00000000..65071e6e--- /dev/null+++ b/internal/httpapi/runner_models_test.go@@ -0,0 +1,58 @@+package httpapi++import (+ "bytes"+ "net/http"+ "net/http/httptest"+ "testing"++ "agentflow/internal/domain"++ "github.com/gin-gonic/gin"+)++func TestRunnerModelProbeUsesOwnersSelectedMachine(t *testing.T) {+ h, owner := workbenchFixture(t)+ row := domain.Runner{+ ID: "models-runner", OwnerUserID: owner.ID, Status: domain.RunnerStatusOnline, RunnerVersion: domain.RunnerVersionCLISettings,+ Runtimes: []domain.RunnerRuntime{{Provider: "codex"}, {Provider: "claude-code", AuthMode: domain.RuntimeAuthPersonal}},+ }+ if err := h.repo.PutRunner(row); err != nil {+ t.Fatal(err)+ }+ hub := quietRunnerHub()+ conn := testRunnerConn(row.ID)+ registerTestConn(hub, conn)+ t.Cleanup(conn.close)+ handlers := &runnersHandlers{deps: h.deps, runnerControls: hub}+ probe := func(user domain.User, provider string) (*gin.Context, *httptest.ResponseRecorder) {+ c, w := workbenchContext(user, http.MethodPost, "/", bytes.NewBufferString(`{"provider":"`+provider+`"}`))+ c.Params = gin.Params{{Key: "id", Value: row.ID}}+ return c, w+ }+ for _, check := range []struct {+ user domain.User+ provider string+ status int+ }{+ {domain.User{ID: owner.ID + 100, LoginName: "other"}, "codex", http.StatusForbidden},+ {owner, "claude-code", http.StatusConflict},+ {owner, "cursor", http.StatusConflict},+ } {+ c, w := probe(check.user, check.provider)+ handlers.probeRunnerModels(c)+ if w.Code != check.status {+ t.Fatalf("%s returned %d, want %d", check.provider, w.Code, check.status)+ }+ }+ c, w := probe(owner, "codex")+ done := make(chan struct{})+ go func() { handlers.probeRunnerModels(c); close(done) }()+ request := answerOnce(t, hub, conn, domain.RunnerWorkspaceResponse{Status: 200, Payload: []byte(`[{"id":"runner-model"}]`)})+ <-done+ response := w.Result()+ if request.Operation != domain.RunnerWorkspaceOperationLoginModels || request.ModelProvider != "codex" ||+ response.StatusCode != http.StatusOK || response.Header.Get("Cache-Control") != "private, no-store" {+ t.Fatalf("request=%+v response=%+v", request, response)+ }+}diff --git a/internal/httpapi/runner_runtime_check.go b/internal/httpapi/runner_runtime_check.gonew file mode 100644index 00000000..07b3f0f8--- /dev/null+++ b/internal/httpapi/runner_runtime_check.go@@ -0,0 +1,83 @@+package httpapi++import (+ "context"+ "fmt"+ "net/http"+ "slices"+ "strings"+ "time"++ "agentflow/internal/domain"++ "github.com/gin-gonic/gin"+)++const runnerRuntimeTestTimeout = 30 * time.Second++func (h *runnersHandlers) runnerRuntimeTest(c *gin.Context) {+ current, authenticated := h.requestUser(c.Request, true)+ if !authenticated {+ c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录后测试执行机器"})+ return+ }+ var input struct {+ RunnerID string `json:"runnerId"`+ Provider string `json:"provider"`+ }+ if !decode(c, &input) {+ return+ }+ provider := strings.TrimSpace(input.Provider)+ if provider != assistantEngineCodeBuddy && !slices.Contains(assistantCLIEngines(), provider) {+ c.JSON(http.StatusBadRequest, gin.H{"error": "不支持的 CLI"})+ return+ }+ runner, found := h.repo.Runner(strings.TrimSpace(input.RunnerID))+ if !found {+ c.JSON(http.StatusNotFound, gin.H{"error": "执行机器不存在"})+ return+ }+ if runner.OwnerUserID != current.ID {+ c.JSON(http.StatusForbidden, gin.H{"error": "只能测试自己绑定的执行机器"})+ return+ }+ if runner.Status != domain.RunnerStatusOnline {+ c.JSON(http.StatusConflict, gin.H{"error": "执行机器离线,请启动 Runner 后重试"})+ return+ }+ if !runner.SupportsCLISettings() {+ c.JSON(http.StatusConflict, gin.H{"error": fmt.Sprintf("执行机器需升级至 %s 才能测试 CLI", domain.RunnerVersionCLISettings)})+ return+ }+ if !runner.SupportsProvider(provider) {+ c.JSON(http.StatusConflict, gin.H{"error": "该 CLI 未安装或已停用"})+ return+ }+ user, found := h.repo.User(current.ID)+ if !found {+ c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录后测试执行机器"})+ return+ }+ runnerLogin := runnerUsesLocalLogin(runner, provider)+ if key, _ := assistantEngineCredential(user, provider); key == "" && !runnerLogin {+ c.JSON(http.StatusBadRequest, gin.H{"error": assistantEngineMissingKey(provider)})+ return+ }++ ctx, cancel := context.WithTimeout(c.Request.Context(), runnerRuntimeTestTimeout)+ defer cancel()+ if err := h.assistant.testRunnerCLI(ctx, runner.ID, provider, runnerLogin, user); err != nil {+ status, message := assistantGenerationFailure(ctx, err)+ if status == http.StatusGatewayTimeout {+ message = "CLI 测试超时,请检查执行机器和模型服务的连接"+ } else if strings.Contains(err.Error(), "执行机器未安装 CLI") {+ message = "执行机器未安装该 CLI"+ } else if assistantFailureGeneric(classifyAssistantFailure(ctx, err).Code) {+ message = "CLI 测试失败,请检查执行机器上的 CLI、认证和模型服务配置"+ }+ c.JSON(status, gin.H{"error": message})+ return+ }+ c.JSON(http.StatusOK, gin.H{"ok": true})+}diff --git a/internal/httpapi/runner_runtime_check_test.go b/internal/httpapi/runner_runtime_check_test.gonew file mode 100644index 00000000..725ec0f9--- /dev/null+++ b/internal/httpapi/runner_runtime_check_test.go@@ -0,0 +1,84 @@+package httpapi++import (+ "bytes"+ "encoding/json"+ "net/http"+ "strings"+ "testing"+ "time"++ "agentflow/internal/domain"+ "agentflow/internal/runtime"+)++func TestRunnerCLITestUsesOwnerLoginAndCleansUp(t *testing.T) {+ h, owner := workbenchFixture(t)+ runner := domain.Runner{ID: "test-laptop", OwnerUserID: owner.ID, Status: domain.RunnerStatusOnline,+ RunnerVersion: domain.RunnerVersionCLISettings, Runtimes: []domain.RunnerRuntime{{Provider: "claude-code", AuthMode: "local"}}}+ if err := h.repo.PutRunner(runner); err != nil {+ t.Fatal(err)+ }+ h.runnerControls = quietRunnerHub()+ conn := testRunnerConn(runner.ID)+ registerTestConn(h.runnerControls, conn)+ t.Cleanup(conn.close)+ runners := &runnersHandlers{deps: h.deps, assistant: h}+ body := `{"runnerId":"test-laptop","provider":"claude-code"}`++ foreign := domain.User{ID: owner.ID + 1, LoginName: "other"}+ c, rec := workbenchContext(foreign, http.MethodPost, "/api/runners/runtimes/test", bytes.NewBufferString(body))+ runners.runnerRuntimeTest(c)+ if rec.Code != http.StatusForbidden {+ t.Fatalf("other user could test the runner: %d %s", rec.Code, rec.Body)+ }+ c, rec = workbenchContext(owner, http.MethodPost, "/api/runners/runtimes/test", bytes.NewBufferString(body))+ done := make(chan struct{})+ go func() {+ defer close(done)+ runners.runnerRuntimeTest(c)+ }()+ var started bool+ var discarded bool+ for !discarded {+ select {+ case msg := <-conn.send:+ var req runtime.ConversationProcessRequest+ if msg.WorkspaceRequest == nil || json.Unmarshal(msg.WorkspaceRequest.Conversation, &req) != nil ||+ !req.Transient || msg.WorkspaceRequest.RunID != "" {+ t.Fatalf("probe requested an ordinary workspace: %+v", msg)+ }+ result := runtime.ConversationProcessResult{ID: req.ID}+ switch req.Operation {+ case "start":+ if req.Command == nil || !req.Command.RunnerLogin || req.Command.Credentials.ClaudeCode.APIKey != "" {+ t.Fatal("probe failed to select runner login without a personal key")+ }+ if !strings.Contains(strings.Join(req.Command.Argv, " "), "Respond with OK.") {+ t.Fatal("probe did not launch a model request")+ }+ started = true+ case "poll":+ result.Events = []domain.TelemetryEvent{{Name: "process.stdout", Message: `{"type":"result","result":"OK"}`}}+ result.Sequence, result.Done = 1, true+ case "stop":+ result.Done = true+ case "discard":+ discarded = true+ case "prepare", "resetAssets", "sync":+ default:+ t.Fatalf("unexpected runner operation %q", req.Operation)+ }+ raw, _ := json.Marshal(result)+ h.runnerControls.resolveWorkspace(msg.RequestID, domain.RunnerWorkspaceResponse{Status: 200, Payload: raw})+ case <-done:+ t.Fatalf("test ended before runner cleanup: %d %s", rec.Code, rec.Body)+ case <-time.After(5 * time.Second):+ t.Fatal("probe stopped making progress")+ }+ }+ <-done+ if !started || rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"ok":true`) {+ t.Fatalf("probe failed: %d %s", rec.Code, rec.Body)+ }+}diff --git a/internal/httpapi/runners.go b/internal/httpapi/runners.goindex 10e7e0d6..af12bc72 100644--- a/internal/httpapi/runners.go+++ b/internal/httpapi/runners.go@@ -88,6 +88,7 @@ type runnersHandlers struct {*depsrunnerWaiters *runnerWaiterRegistryrunnerControls *runnerControlHub+ assistant *assistantHandlersrunnerBindMu stdsync.MutexrunnerBindCodes map[string]runnerBindCode}diff --git a/internal/httpapi/schedule.go b/internal/httpapi/schedule.goindex 3635a2f3..c1227402 100644--- a/internal/httpapi/schedule.go+++ b/internal/httpapi/schedule.go@@ -219,8 +219,8 @@ func (h *scheduleHandlers) scheduleJobs(c *gin.Context) {// bindScheduleRunAs binds an AI job to the user who saves it: the creator, and// later whoever edits it, so nobody can make a prompt run with another-// member's keys. The binding is never taken from the request. The saver's own-// key for the job's CLI is used, else the platform's shared CodeBuddy key+// member's credentials. The binding is never taken from the request. The saver's+// default machine login or own key is used, else the platform's shared CodeBuddy key// (limited to the models it allows, its default when requestedModel is empty);// with neither the save is refused, since the job could not run. Without a// signed-in user the job stays on the project owner's keys. A saver without@@ -262,7 +262,7 @@ func (h *scheduleHandlers) bindScheduleRunAs(c *gin.Context, job *domain.Schedulc.JSON(200, stored)return true}- _, shared, ok := scheduleKeyUser(h.repo, self, engine)+ _, shared, ok := scheduleCredentialUser(h.repo, self, engine)if !ok {if stopOnly() {return false@@ -316,6 +316,9 @@ func scheduleSharedRequestedModel(model string) string {}func scheduleMissingKeyError(engine string) string {+ if assistantSupportsRunnerLogin(engine) {+ 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))}diff --git a/internal/httpapi/schedule_runner_login_test.go b/internal/httpapi/schedule_runner_login_test.gonew file mode 100644index 00000000..f0bb59ca--- /dev/null+++ b/internal/httpapi/schedule_runner_login_test.go@@ -0,0 +1,186 @@+package httpapi++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "path/filepath"+ "slices"+ "strings"+ "testing"+ "time"++ "agentflow/internal/domain"+ "agentflow/internal/engine"+ "agentflow/internal/repo"+ "agentflow/internal/runtime"+ "agentflow/internal/tracker"+)++func TestScheduleJobUsesSaversDefaultRunnerLogin(t *testing.T) {+ t.Setenv("TMPDIR", t.TempDir())+ t.Setenv("AGENTFLOW_AUTH_REQUIRED", "true")+ t.Setenv("AGENTFLOW_SESSION_SECRET", "schedule-runner-login-test")+ h, owner := workbenchFixture(t)+ st := h.repo+ if err := st.PutUser(domain.User{LoginName: "schedule-runner-saver"}); err != nil {+ t.Fatal(err)+ }+ saver, _ := st.UserByLoginName("schedule-runner-saver")+ joinScheduledProject(t, st, "workbench", saver.ID)+ machine := domain.Runner{ID: "saver-machine", OwnerUserID: saver.ID, Status: domain.RunnerStatusOnline,+ RunnerVersion: domain.RunnerVersionCLISettings, Runtimes: []domain.RunnerRuntime{+ {Provider: assistantEngineClaude, Status: domain.RuntimeStatusOnline, AuthMode: domain.RuntimeAuthLocal},+ },+ }+ foreign := machine+ foreign.ID, foreign.OwnerUserID = "owner-machine", owner.ID+ for _, runner := range []domain.Runner{machine, foreign} {+ if err := st.PutRunner(runner); err != nil {+ t.Fatal(err)+ }+ }+ setDefault := func(id string) {+ t.Helper()+ if err := st.SetDefaultRunner(saver.ID, id, time.Now()); err != nil {+ t.Fatal(err)+ }+ }+ server := New(st, engine.New(st, runtime.NewManager(filepath.Join(t.TempDir(), "workspaces"))), tracker.NewService(), "", "")+ body := domain.ScheduleJob{+ ID: "runner-login-job", ProjectID: "workbench", Name: "巡检", SkipDispatch: true, AssistantPrompt: "检查",+ AssistantModel: "claude-code:opus", RunAsUserID: owner.ID, IntervalSec: 3600, Enabled: true,+ }+ setDefault(foreign.ID)+ if code := scheduleAuthzStatus(t, server, saver, http.MethodPut, "/api/schedule-jobs", body); code != http.StatusBadRequest {+ t.Fatalf("a default runner owned by someone else enabled a keyless save: %d", code)+ }+ setDefault(machine.ID)+ saved := requestJSONAuthed[domain.ScheduleJob](t, server, saver, http.MethodPut, "/api/schedule-jobs", body, http.StatusOK)+ if saved.RunAsUserID != saver.ID || saved.AssistantModel != body.AssistantModel {+ t.Fatalf("saved run-as identity = %d, model = %q", saved.RunAsUserID, saved.AssistantModel)+ }++ for _, test := range []struct {+ query string+ want bool+ }{{"", false}, {"?schedule=1", true}} {+ c, rec := workbenchContext(saver, http.MethodGet, "/api/assistant/models"+test.query, &bytes.Buffer{})+ h.models(c)+ var catalog assistantModelCatalog+ if err := json.Unmarshal(rec.Body.Bytes(), &catalog); err != nil {+ t.Fatal(err)+ }+ hasClaude := slices.ContainsFunc(catalog.Models, func(m assistantModel) bool {+ return m.Engine == assistantEngineClaude+ })+ if rec.Code != http.StatusOK || hasClaude != test.want {+ t.Fatalf("catalog %q lists keyless Claude models = %v, status = %d", test.query, hasClaude, rec.Code)+ }+ }++ h.runnerControls = quietRunnerHub()+ conn := testRunnerConn(machine.ID)+ registerTestConn(h.runnerControls, conn)+ t.Cleanup(conn.close)+ type outcome struct {+ message string+ err error+ }+ done := make(chan outcome, 1)+ go func() {+ message, err := h.prepareScheduleJob(saved)+ done <- outcome{message, err}+ }()++ timeout := time.NewTimer(10 * time.Second)+ defer timeout.Stop()+ var launched, completed bool+ for !completed {+ select {+ case msg := <-conn.send:+ var req runtime.ConversationProcessRequest+ if msg.WorkspaceRequest == nil || json.Unmarshal(msg.WorkspaceRequest.Conversation, &req) != nil {+ t.Fatal("expected runner conversation request")+ }+ result := runtime.ConversationProcessResult{ID: req.ID}+ switch req.Operation {+ case "start":+ if req.Command == nil || !req.Command.RunnerLogin || req.Command.Credentials.ClaudeCode.APIKey != "" {+ t.Fatal("scheduled turn did not request CLI account login")+ }+ launched = true+ case "poll":+ result.Events = []domain.TelemetryEvent{{Name: "process.stdout", Message: `{"type":"result","result":"巡检完成"}`}}+ result.Sequence, result.Done = 1, true+ case "stop":+ result.Done = true+ }+ raw, _ := json.Marshal(result)+ h.runnerControls.resolveWorkspace(msg.RequestID, domain.RunnerWorkspaceResponse{Status: http.StatusOK, Payload: raw})+ case result := <-done:+ if result.err != nil || result.message != "巡检完成" || !launched {+ t.Fatalf("scheduled run = %q, %v, launched = %v", result.message, result.err, launched)+ }+ completed = true+ case <-timeout.C:+ t.Fatal("scheduled run did not finish")+ }+ }++ sessions := st.ListAssistantSessionsByTask(domain.AssistantSourceScheduled, saved.ID)+ if len(sessions) != 1 || sessions[0].UserID != saver.ID || sessions[0].Execution().RunnerID != machine.ID || !sessions[0].ExecutionLocked() {+ t.Fatal("scheduled session did not retain the saver and their machine")+ }+ machine.Status = domain.RunnerStatusOffline+ if err := st.PutRunner(machine); err != nil {+ t.Fatal(err)+ }+ const saverKey = "saver-test-key"+ keyAttempts := 0+ var keyError error+ h.generate = func(_ context.Context, _ string, actor domain.User) (string, error) {+ keyAttempts+++ if actor.ID != saver.ID || actor.ClaudeCodeAPIKey != saverKey {+ return "", errors.New("fallback used the wrong credentials")+ }+ return "云端巡检完成", keyError+ }+ if _, err := h.prepareScheduleJob(saved); err == nil || !strings.Contains(err.Error(), "已离线。未配置 Claude Code API Key") || keyAttempts != 0 {+ t.Fatalf("offline runner without a key = %v, attempts = %d", err, keyAttempts)+ }++ if _, err := st.UpdateUserCredentials(saver.ID, repo.UserCredentialUpdate{ClaudeCodeAPIKey: saverKey}); err != nil {+ t.Fatal(err)+ }+ if message, err := h.prepareScheduleJob(saved); err != nil || message != "云端巡检完成" || keyAttempts != 1 {+ t.Fatalf("offline fallback = %q, %v, attempts = %d", message, err, keyAttempts)+ }+ // Schedule jobs keep every execution's conversation, so the fallback run+ // opens a second one next to the earlier runner conversation.+ runnerSession := sessions[0].ID+ sessions = st.ListAssistantSessionsByTask(domain.AssistantSourceScheduled, saved.ID)+ cloud := slices.IndexFunc(sessions, func(s domain.AssistantSession) bool { return s.ID != runnerSession })+ if len(sessions) != 2 || cloud < 0 || sessions[cloud].UserID != saver.ID ||+ sessions[cloud].Execution().Pool != domain.ExecutionModeCloud || sessions[cloud].Model != saved.AssistantModel {+ t.Fatal("offline fallback did not run the same model and user in the cloud")+ }++ keyError = assistantCredentialError{engine: assistantEngineClaude}+ if _, err := h.prepareScheduleJob(saved); err == nil || !strings.Contains(err.Error(), "已离线") ||+ !strings.Contains(err.Error(), "Claude Code 拒绝了你的 API Key") || keyAttempts != 2 {+ t.Fatalf("offline fallback with rejected key = %v, attempts = %d", err, keyAttempts)+ }++ machine.Status = domain.RunnerStatusOnline+ machine.RunnerVersion = domain.RunnerVersionConversationCLI+ if err := st.PutRunner(machine); err != nil {+ t.Fatal(err)+ }+ keyError = nil+ if message, err := h.prepareScheduleJob(saved); err != nil || message != "云端巡检完成" || keyAttempts != 3 {+ t.Fatalf("fallback with a Runner from main = %q, %v, attempts = %d", message, err, keyAttempts)+ }+}diff --git a/internal/httpapi/server.go b/internal/httpapi/server.goindex 6a31fb30..99b7bb3b 100644--- a/internal/httpapi/server.go+++ b/internal/httpapi/server.go@@ -290,6 +290,7 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Servapi.botIdentities = &botIdentityHandlers{deps: d, publicURL: api.notifications.service.PublicURL}asst := &assistantHandlers{deps: d, runnerControls: runnerControls, sourceRoot: assistantSourceRoot(), notifications: api.notifications, identities: api.botIdentities, attachmentSweepWake: make(chan struct{}, 1)}api.runs.assistant = asst+ api.runners.assistant = asstapi.schedule.assistant = asstapi.notifications.service.GenerateReport = asst.generateSOPReportif api.notifications.service.Interactions != nil {@@ -593,6 +594,9 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Servg.PUT("/api/runners/default", api.runners.runnerDefaultSet)g.DELETE("/api/runners/:id", api.runners.runnerRemove)g.PUT("/api/runners/:id/run-limit", api.runners.runnerRunLimitSet)+ g.GET("/api/runners/:id/maintenance", api.runners.runnerMaintenance)+ g.POST("/api/runners/:id/maintenance", api.runners.runnerMaintenance)+ g.POST("/api/runners/:id/models/probe", api.runners.probeRunnerModels)g.POST("/api/runners/heartbeat", api.runners.runnerHeartbeat)g.GET("/api/runners/tasks", api.runners.runnerTasksCollection)g.POST("/api/runners/tasks", api.runners.runnerTasksCollection)@@ -607,6 +611,7 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Servg.GET("/api/runners/tasks/:id/control", api.runners.runnerTaskControl)g.PUT("/api/runners/runtimes", api.runners.runnerRuntimeStatus)g.POST("/api/runners/runtimes", api.runners.runnerRuntimeStatus)+ g.POST("/api/runners/runtimes/test", api.runners.runnerRuntimeTest)// Machine plane: this prefix is safe to exempt from gateway interactive// login. Public install assets are read-only; daemon APIs authenticate withdiff --git a/internal/managedcli/updater.go b/internal/managedcli/updater.goindex 1bee0876..11e236c5 100644--- a/internal/managedcli/updater.go+++ b/internal/managedcli/updater.go@@ -62,6 +62,14 @@ func (m *Manager) Update(ctx context.Context) (Report, error) {return m.run(ctx, "update", "")}+// UpdateProvider updates a single CLI already selected by the runner.+func (m *Manager) UpdateProvider(ctx context.Context, provider string) (Report, error) {+ if _, ok := providerSpecs[provider]; !ok {+ return Report{}, fmt.Errorf("unsupported managed CLI %q", provider)+ }+ return m.run(ctx, "update", provider)+}+// Rollback is explicit, never triggered by task/model errors. Existing run pins// stay immutable and automatic updates never retry the rejected version.func (m *Manager) Rollback(ctx context.Context, provider string) (Report, error) {@@ -101,16 +109,20 @@ func (m *Manager) run(ctx context.Context, action, provider string) (report Repoif action == "rollback" {return m.rollbackLocked(ctx, provider, &state, &report)}- return m.updateLocked(ctx, &state, &report)+ providers := providerNames()+ if provider != "" {+ providers = []string{provider}+ }+ return m.updateProvidersLocked(ctx, &state, &report, providers)})return report, err}-func (m *Manager) updateLocked(ctx context.Context, state *State, report *Report) error {+func (m *Manager) updateProvidersLocked(ctx context.Context, state *State, report *Report, providers []string) error {candidates := Inventory{}var failures []errortoolsReady := false- for _, provider := range providerNames() {+ for _, provider := range providers {result := ProviderResult{Provider: provider, From: state.Current[provider].Version}candidate, err := m.candidate(ctx, provider)if err == nil {diff --git a/internal/managedcli/updater_test.go b/internal/managedcli/updater_test.goindex 067e2a1e..3089e39e 100644--- a/internal/managedcli/updater_test.go+++ b/internal/managedcli/updater_test.go@@ -381,3 +381,19 @@ func fixtureClient(t *testing.T, server *httptest.Server) *http.Client {type roundTripFunc func(*http.Request) (*http.Response, error)func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }++func TestUpdateProviderOnlyChangesTheRequestedCLI(t *testing.T) {+ f := newUpdaterFixture(t)+ f.update(t, false)+ f.setVersion("2.0.0")+ report, err := f.manager.UpdateProvider(context.Background(), "codex")+ must(t, err)+ if len(report.Results) != 1 || report.Results[0].Provider != "codex" || report.Results[0].Status != "updated" {+ t.Fatalf("update results = %+v", report.Results)+ }+ state := f.state(t)+ if state.Current["codex"].Version != "2.0.0" || state.Current["claude-code"].Version != "1.0.0" ||+ state.Current["codebuddy"].Version != "1.0.0" {+ t.Fatal("single CLI update changed unrelated active versions")+ }+}diff --git a/internal/repo/models.go b/internal/repo/models.goindex 444a6969..538418d6 100644--- a/internal/repo/models.go+++ b/internal/repo/models.go@@ -39,6 +39,7 @@ type userConfigRow struct {GongfengTokenExpiresAt *time.Time `gorm:"column:gongfeng_token_expires_at"`CodeBuddyAPIKey *string `gorm:"column:codebuddy_api_key;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"`CodexBaseURL *string `gorm:"column:codex_base_url;type:text"`CodexModels *string `gorm:"column:codex_models;type:text"`diff --git a/internal/repo/users.go b/internal/repo/users.goindex 6fb2a8f4..0043079c 100644--- a/internal/repo/users.go+++ b/internal/repo/users.go@@ -11,6 +11,8 @@ import ("unicode/utf8""agentflow/internal/domain"++ "gorm.io/gorm")// ---------- Users ----------@@ -29,6 +31,7 @@ type userWithConfig struct {GongfengTokenExpiresAt *time.Time `gorm:"column:gongfeng_token_expires_at"`CodeBuddyAPIKey *string `gorm:"column:codebuddy_api_key"`CodeBuddyInternetEnvironment string `gorm:"column:codebuddy_internet_environment"`+ CodeBuddyModels *string `gorm:"column:codebuddy_models"`CodexAPIKey *string `gorm:"column:codex_api_key"`CodexBaseURL *string `gorm:"column:codex_base_url"`CodexModels *string `gorm:"column:codex_models"`@@ -43,7 +46,7 @@ type userWithConfig struct {const userSelectColumns = `u.id, u.staff_id, u.login_name, u.chinese_name, u.dept_id, u.dept_name,COALESCE(u.platform_role, '') AS platform_role,c.git_token, EXISTS (SELECT 1 FROM user_git_ssh_keys k WHERE k.user_id = u.id) AS git_ssh_key_configured,- c.gongfeng_refresh_token, c.gongfeng_token_expires_at, c.codebuddy_api_key, COALESCE(c.codebuddy_internet_environment, '') AS codebuddy_internet_environment,+ 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.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,u.created_at, u.updated_at`@@ -53,6 +56,7 @@ func (r userWithConfig) toDomain() domain.User {ID: r.ID, StaffID: r.StaffID, LoginName: r.LoginName, ChineseName: r.ChineseName,DeptID: r.DeptID, DeptName: r.DeptName, PlatformRole: r.PlatformRole,CodeBuddyInternetEnvironment: r.CodeBuddyInternetEnvironment,+ CodeBuddyModels: decodeCLIModels(r.CodeBuddyModels),GitSSHKeyConfigured: r.GitSSHKeyConfigured,}if r.GitToken != nil {@@ -160,6 +164,7 @@ func (r *UsersRepo) PutUser(v domain.User) error {v.ClaudeCodeAPIKey, v.ClaudeCodeBaseURL, v.ClaudeCodeModels = old.ClaudeCodeAPIKey, old.ClaudeCodeBaseURL, old.ClaudeCodeModelsv.CodeBuddyAPIKey = old.CodeBuddyAPIKeyv.CodeBuddyInternetEnvironment = old.CodeBuddyInternetEnvironment+ v.CodeBuddyModels = old.CodeBuddyModelsv.AgentCLICredentials = old.AgentCLICredentialsif strings.TrimSpace(v.PlatformRole) == "" {v.PlatformRole = old.PlatformRole@@ -228,6 +233,7 @@ func userHasConfig(user domain.User) bool {user.GongfengRefreshToken != "" ||user.CodeBuddyAPIKey != "" ||user.CodeBuddyInternetEnvironment != "" ||+ len(user.CodeBuddyModels) > 0 ||user.CodexAPIKey != "" ||user.CodexBaseURL != "" ||len(user.CodexModels) > 0 ||@@ -243,6 +249,7 @@ 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"`@@ -262,9 +269,35 @@ type AgentCLICredentialUpdate struct {BaseURL *string `json:"baseUrl"`Protocol *string `json:"protocol"`Models *[]domain.CLIModel `json:"models"`+ // DiscoveredForKey prevents a refresh for an old key from replacing the+ // new key's models.+ DiscoveredForKey string `json:"-"`}func (r *UsersRepo) UpdateUserCredentials(id int64, update UserCredentialUpdate) (domain.User, error) {+ var user domain.User+ err := r.DB.Transaction(func(tx *gorm.DB) error {+ // Serialize edits and CLI discovery for this user even when they+ // arrive at different server instances or before a config row exists.+ var owner userRow+ if err := r.locking(tx.Select("id")).Where("id = ?", id).Take(&owner).Error; err != nil {+ if errors.Is(err, gorm.ErrRecordNotFound) {+ return errors.New("user not found")+ }+ return err+ }+ credentials := &UsersRepo{deps: &deps{DB: tx}}+ var err error+ user, err = credentials.updateUserCredentials(id, update)+ return err+ })+ if err != nil {+ return domain.User{}, err+ }+ return user, nil+}++func (r *UsersRepo) updateUserCredentials(id int64, update UserCredentialUpdate) (domain.User, error) {user, ok := r.User(id)if !ok {return domain.User{}, errors.New("user not found")@@ -288,6 +321,13 @@ func (r *UsersRepo) UpdateUserCredentials(id int64, update UserCredentialUpdate)if update.CodeBuddyInternetEnvironment != nil {user.CodeBuddyInternetEnvironment = strings.TrimSpace(*update.CodeBuddyInternetEnvironment)}+ if update.CodeBuddyModels != nil {+ models, err := normalizeCLIModels(*update.CodeBuddyModels)+ if err != nil {+ return domain.User{}, err+ }+ user.CodeBuddyModels = models+ }if update.CodexAPIKeyClear {user.CodexAPIKey = ""} else if value := strings.TrimSpace(update.CodexAPIKey); value != "" {@@ -352,6 +392,7 @@ func (r *UsersRepo) writeUserConfig(v domain.User) error {"gongfeng_refresh_token": nullableString(v.GongfengRefreshToken), "gongfeng_token_expires_at": timePtr(v.GongfengTokenExpiresAt),"codebuddy_api_key": nullableString(v.CodeBuddyAPIKey),"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),"claude_code_api_key": nullableString(v.ClaudeCodeAPIKey), "claude_code_base_url": nullableString(v.ClaudeCodeBaseURL), "claude_code_models": encodeCLIModels(v.ClaudeCodeModels),"agent_cli_credentials": encodeAgentCLICredentials(v.AgentCLICredentials),@@ -387,10 +428,12 @@ func applyAgentCLICredentialUpdates(user *domain.User, updates map[string]AgentC} else if value := strings.TrimSpace(update.APIKey); value != "" {cred.APIKey = value}- // Cursor's catalog is the list the key's plan offered (saved by the- // chat model list); another key starts from that key's own list.+ // Cursor's catalog and effort variants belong to the key's plan.+ // A replacement key starts with its own list unless the edit also+ // supplies a catalog.if kind == "cursor" && cred.APIKey != previousKey && update.Models == nil {cred.Models = nil+ cred.ModelsCustomized = false}if update.BaseURL != nil {cred.BaseURL = strings.TrimSpace(*update.BaseURL)@@ -402,12 +445,16 @@ func applyAgentCLICredentialUpdates(user *domain.User, updates map[string]AgentC}cred.Protocol = protocol}- if update.Models != nil {+ discovered := update.DiscoveredForKey != ""+ if update.Models != nil && (!discovered || (!cred.ModelsCustomized && cred.APIKey == update.DiscoveredForKey)) {models, err := normalizeCLIModels(*update.Models)if err != nil {return err}cred.Models = models+ if kind == "cursor" {+ cred.ModelsCustomized = !discovered && len(models) != 0+ }}if cred.APIKey == "" && cred.BaseURL == "" && cred.Protocol == "" && len(cred.Models) == 0 {delete(merged, kind)diff --git a/internal/runner/cli_auth_sandbox_test.go b/internal/runner/cli_auth_sandbox_test.gonew file mode 100644index 00000000..370fa9ba--- /dev/null+++ b/internal/runner/cli_auth_sandbox_test.go@@ -0,0 +1,298 @@+package runner++import (+ "context"+ "encoding/json"+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ goruntime "runtime"+ "strings"+ "testing"+ "time"++ "agentflow/internal/domain"+ "agentflow/internal/repo"+ "agentflow/internal/runtime"+)++const runnerAuthFixture = `#!/bin/sh+set -eu+if [ "${1:-}" = --version ]; then+ printf '1.0.0\n'+ exit+fi+if [ "${1:-}" = workspace ]; then+ test "$(cat runner-workspace-marker)" = attached+fi+case "${0##*/}" in+ codex)+ test -z "${CODEX_API_KEY:-}${OPENAI_API_KEY:-}"+ grep -q '"fixture":"codex-login"' "$CODEX_HOME/auth.json"+ printf '%s\n' '{"type":"item.completed","item":{"type":"agent_message","text":"fixture-authenticated"}}'+ ;;+ claude)+ test -z "${ANTHROPIC_API_KEY:-}"+ grep -q '"fixture":"claude-login"' "$CLAUDE_CONFIG_DIR/.credentials.json"+ printf '%s\n' '{"type":"result","subtype":"success","result":"fixture-authenticated"}'+ ;;+ cursor-agent)+ test "$CURSOR_API_KEY" = fixture-cursor-key+ printf '%s\n' '{"type":"result","subtype":"success","result":"fixture-authenticated"}'+ ;;+ agy)+ test "$GEMINI_API_KEY" = fixture-gemini-key+ grep -q '"modelProvider":"gemini"' "$HOME/.gemini/antigravity-cli/settings.json"+ printf '%s\n' '{"type":"result","subtype":"success","result":"fixture-authenticated"}'+ ;;+ *) exit 125 ;;+esac+if [ -d .agentflow/config ]; then+ gate="$(grep -oE '\.agentflow/gate-results/[^"]+\.json' .agentflow/config/*/mcp.json | head -1)"+ test -n "$gate"+ mkdir -p "$(dirname "$gate")"+ printf '%s\n' '{"decision":"pass","reason":"fixture-authenticated"}' > "$gate"+fi+`++func runnerSandboxAuthFixtures(t *testing.T, driver string) (string, domain.DockerfileDefinition) {+ t.Helper()+ if driver == domain.SandboxDriverDocker {+ if os.Getenv("AGENTFLOW_TEST_DOCKER") != "1" {+ t.Skip("set AGENTFLOW_TEST_DOCKER=1 for local Docker sandbox tests")+ }+ // Local Docker VMs such as Colima share the checkout but may not share+ // the OS temporary directory. Create bind sources in the shared root.+ useTempDirOutsideTmp(t, os.Getenv("AGENTFLOW_DOCKER_TEST_ROOT"))+ } else {+ switch goruntime.GOOS {+ case "darwin":+ if _, err := exec.LookPath("sandbox-exec"); err != nil {+ t.Skip(err)+ }+ case "linux":+ if out, err := exec.Command("bwrap", "--ro-bind", "/", "/", "--", "/bin/true").CombinedOutput(); err != nil {+ t.Skipf("bwrap is unavailable: %v %s", err, out)+ }+ // bwrap mounts a private tmpfs over /tmp after binding the+ // workspace, so fixture CLIs and run workspaces under the default+ // t.TempDir() would vanish inside the sandbox. A runner keeps its+ // workspaces under ~/.agentflow-runner; keep the fixtures out of+ // /tmp the same way.+ useTempDirOutsideTmp(t, "")+ default:+ t.Skip("the native sandbox requires macOS or Linux")+ }+ }+ root := t.TempDir()+ for _, login := range []struct{ config, file, data string }{+ {"CODEX_HOME", "auth.json", `{"fixture":"codex-login"}`},+ {"CLAUDE_CONFIG_DIR", ".credentials.json", `{"fixture":"claude-login"}`},+ } {+ dir := filepath.Join(root, login.config)+ if err := os.Mkdir(dir, 0o700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(dir, login.file), []byte(login.data), 0o600); err != nil {+ t.Fatal(err)+ }+ t.Setenv(login.config, dir)+ }+ t.Setenv("CLAUDE_CODE_OAUTH_TOKEN", "")+ t.Setenv("AGENTFLOW_CONVERSATION_RELAY_HOST", "host.docker.internal")+ t.Setenv("AGENTFLOW_CONVERSATION_DOCKER_NETWORK", "none")+ t.Setenv("AGENTFLOW_DOCKER_NETWORK", "none")+ for _, name := range []string{"codex", "claude", "cursor-agent", "agy"} {+ if err := os.WriteFile(filepath.Join(root, name), []byte(runnerAuthFixture), 0o700); err != nil {+ t.Fatal(err)+ }+ }+ t.Setenv("PATH", root+string(os.PathListSeparator)+os.Getenv("PATH"))+ image := domain.DockerfileDefinition{+ ID: "runner-cli-auth-fixture", Name: "Runner CLI auth fixture",+ Content: "FROM python:3.13-alpine\nCOPY --chmod=755 cli-fixture /usr/local/bin/codex\nCOPY --chmod=755 cli-fixture /usr/local/bin/claude\nCOPY --chmod=755 cli-fixture /usr/local/bin/cursor-agent\nCOPY --chmod=755 cli-fixture /usr/local/bin/agy\n",+ Files: map[string]string{"cli-fixture": runnerAuthFixture},+ }+ return root, image+}++func TestRunnerConversationWorkspaceCLIAuthentication(t *testing.T) {+ for _, driver := range []string{domain.SandboxDriverNative, domain.SandboxDriverDocker} {+ t.Run(driver, func(t *testing.T) {+ bin, image := runnerSandboxAuthFixtures(t, driver)+ d, target, workspace := runnerPreparationFixture(t)+ defer d.closeAllRunSandboxes(context.Background())+ target.Sandbox.Profile.Driver = driver+ target.Sandbox.Dockerfile = &image+ target.Workflow = &domain.WorkflowDefinition{}+ d.conversationForward = func(context.Context, string, json.RawMessage) (json.RawMessage, error) {+ return nil, nil+ }+ if err := os.WriteFile(filepath.Join(workspace, "runner-workspace-marker"), []byte("attached"), 0o600); err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)+ defer cancel()+ for i, cli := range []struct {+ provider, binary string+ binding runtime.CredentialBinding+ }{+ {"codex", "codex", runtime.BindCodex},+ {"claude-code", "claude", runtime.BindClaudeCode},+ {"cursor", "cursor-agent", runtime.BindAgentCLI},+ {"agy", "agy", runtime.BindAgentCLI},+ } {+ t.Run(cli.provider, func(t *testing.T) {+ path := filepath.Join(bin, cli.binary)+ if driver == domain.SandboxDriverDocker {+ path = "/usr/local/bin/" + cli.binary+ }+ key := strings.Repeat(fmt.Sprint(i+1), 64)+ invoke := func(req runtime.ConversationProcessRequest) runtime.ConversationProcessResult {+ t.Helper()+ req.SessionKey = key+ target.Conversation = conversationRequest(t, req)+ response := d.conversationProcess(ctx, target)+ var result runtime.ConversationProcessResult+ if response.Status != 200 || json.Unmarshal(response.Payload, &result) != nil {+ t.Fatalf("conversation %s: %d %s", req.Operation, response.Status, response.Error)+ }+ return result+ }+ invoke(runtime.ConversationProcessRequest{Operation: "prepare"})+ result := invoke(runtime.ConversationProcessRequest{Operation: "start", Command: &runtime.ConversationCommand{+ Provider: cli.provider, Argv: []string{path, "workspace"},+ RunnerLogin: cli.binding != runtime.BindAgentCLI, Bindings: []runtime.CredentialBinding{cli.binding},+ Credentials: runtime.RunCredentials{AgentCLI: map[string]runtime.ProviderCredential{+ "cursor": {APIKey: "fixture-cursor-key"}, "agy": {APIKey: "fixture-gemini-key"},+ }},+ AgentCLI: runtime.AgentCLIOptions{Model: "fixture-model"},+ }})+ var output strings.Builder+ for !result.Done && ctx.Err() == nil {+ result = invoke(runtime.ConversationProcessRequest{Operation: "poll", ID: result.ID, After: result.Sequence})+ for _, event := range result.Events {+ output.WriteString(event.Message + "\n")+ }+ time.Sleep(10 * time.Millisecond)+ }+ if result.Error != "" || !strings.Contains(output.String(), "fixture-authenticated") {+ t.Fatalf("conversation CLI did not authenticate: %+v %s", result, output.String())+ }+ })+ }+ })+ }+}++func TestRunnerSOPCLIAuthentication(t *testing.T) {+ for _, driver := range []string{domain.SandboxDriverNative, domain.SandboxDriverDocker} {+ t.Run(driver, func(t *testing.T) {+ bin, image := runnerSandboxAuthFixtures(t, driver)+ server, st, en := newDaemonTestServer(t)+ workspaceRoot := t.TempDir()+ row, _ := startPoolRunnerWithConfig(t, st, Config{+ ServerURL: server.URL, BootstrapToken: "boot-secret", StatePath: filepath.Join(workspaceRoot, "identity.json"),+ Name: "cli-auth-runner", DefaultWorkspaceRoot: workspaceRoot, HeartbeatInterval: time.Second, LongPollTimeout: time.Second,+ })+ if err := st.PutUser(domain.User{LoginName: "cli-auth-test"}); err != nil {+ t.Fatal(err)+ }+ user, _ := st.UserByLoginName("cli-auth-test")+ row.OwnerUserID = user.ID+ if err := st.PutRunner(row); err != nil {+ t.Fatal(err)+ }+ if err := st.SetDefaultRunner(user.ID, row.ID, time.Now()); err != nil {+ t.Fatal(err)+ }+ if _, err := st.UpdateUserCredentials(user.ID, repo.UserCredentialUpdate{AgentCLICredentials: map[string]repo.AgentCLICredentialUpdate{+ "cursor": {APIKey: "fixture-cursor-key"}, "agy": {APIKey: "fixture-gemini-key"},+ }}); err != nil {+ t.Fatal(err)+ }+ if err := st.PutDockerfile(image); err != nil {+ t.Fatal(err)+ }+ profile := domain.SandboxProfile{ID: "runner-cli-auth-sandbox", Name: "CLI auth sandbox", Driver: driver}+ if driver == domain.SandboxDriverDocker {+ profile.DockerfileID = image.ID+ }+ if err := st.PutSandbox(profile); err != nil {+ t.Fatal(err)+ }+ for _, cli := range []struct{ kind, binary string }{+ {"codex", "codex"}, {"claude-code", "claude"}, {"cursor", "cursor-agent"}, {"agy", "agy"},+ } {+ t.Run(cli.kind, func(t *testing.T) {+ binary := filepath.Join(bin, cli.binary)+ if driver == domain.SandboxDriverDocker {+ binary = "/usr/local/bin/" + cli.binary+ }+ id := "runner-cli-auth-" + cli.kind+ if err := st.PutExecutor(domain.ExecutorDefinition{ID: id, Name: id, Kind: cli.kind, Binary: binary, Model: "fixture-model"}); err != nil {+ t.Fatal(err)+ }+ if err := st.PutAgent(domain.AgentDefinition{ID: id, Name: id, ExecutorID: id, Prompt: "{{input}}"}); err != nil {+ t.Fatal(err)+ }+ wf := domain.WorkflowDefinition{ID: id, Name: id, SandboxProfileID: profile.ID,+ Nodes: []domain.WorkflowNode{{ID: "agent", Name: "Authenticate", Type: "agent", AgentID: id}},+ }+ if err := st.PutWorkflow(wf); err != nil {+ t.Fatal(err)+ }+ run, err := en.StartWithExecutionContext(wf.ID, "test", domain.RepositoryContext{}, domain.TelemetryContext{ResponsibleUserID: user.ID})+ if err != nil {+ t.Fatal(err)+ }+ var result domain.Run+ waitFor(t, 20*time.Second, "SOP completion", func() bool {+ result, _ = st.RunState(run.ID)+ return domain.TerminalRunStatus(result.Status) || result.Status == "waiting"+ })+ node := result.Nodes["agent"]+ if result.Status != "succeeded" || result.ExecutionContext.ExecutionRunnerID != row.ID || !strings.Contains(node.Output, "fixture-authenticated") {+ for _, task := range st.RunnerTasks() {+ if task.RunID == run.ID && task.Provider == cli.kind {+ for _, event := range st.RunnerTaskEvents(task.ID) {+ if event.Type == "stderr" {+ t.Log(event.Data)+ }+ }+ }+ }+ t.Fatalf("SOP %s, node %s, error = %q, output = %q", result.Status, node.Status, node.Error, node.Output)+ }+ home := filepath.Join(workspaceRoot, "runs", run.ID, "workspace", ".agentflow", "private-home")+ for _, pattern := range []string{"codex-login-*/.codex/auth.json", "claude-code-login-*/.claude/.credentials.json"} {+ files, err := filepath.Glob(filepath.Join(home, filepath.FromSlash(pattern)))+ if err != nil || len(files) != 0 {+ t.Fatalf("SOP retained a temporary login file: %v, %v", files, err)+ }+ }+ })+ }+ })+ }+}++// useTempDirOutsideTmp points t.TempDir() at a fresh directory under root (the+// package directory when empty) for the rest of the test.+func useTempDirOutsideTmp(t *testing.T, root string) {+ t.Helper()+ if root == "" {+ root = "."+ }+ root, err := filepath.Abs(root)+ if err != nil {+ t.Fatal(err)+ }+ temp, err := os.MkdirTemp(root, ".runner-cli-auth-")+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = os.RemoveAll(temp) })+ t.Setenv("TMPDIR", temp)+}diff --git a/internal/runner/cli_update.go b/internal/runner/cli_update.gonew file mode 100644index 00000000..85aaf64a--- /dev/null+++ b/internal/runner/cli_update.go@@ -0,0 +1,135 @@+package runner++import (+ "context"+ "log"+ "os"+ "os/exec"+ "path/filepath"+ "slices"+ "strings"+ "time"++ "agentflow/internal/domain"+)++func cliListsUpdate(ctx context.Context, binary, subcommand string) bool {+ ctx, cancel := context.WithTimeout(ctx, 4*time.Second)+ defer cancel()+ cmd := exec.CommandContext(ctx, binary, "--help")+ cmd.Env, cmd.Dir, cmd.WaitDelay = cliUpdateEnvironment(binary), os.TempDir(), time.Second+ out, err := cmd.CombinedOutput()+ if err != nil {+ return false+ }+ inCommands := false+ for _, line := range strings.Split(string(out), "\n") {+ trimmed := strings.TrimSpace(line)+ switch strings.ToLower(trimmed) {+ case "commands:", "available commands:", "available subcommands:":+ inCommands = true+ continue+ case "":+ continue+ }+ if line == trimmed {+ inCommands = false+ }+ if !inCommands {+ continue+ }+ fields := strings.Fields(trimmed)+ name := fields[0]+ if name == filepath.Base(binary) && len(fields) > 1 {+ name = fields[1]+ }+ if slices.Contains(strings.Split(name, "|"), subcommand) {+ return true+ }+ }+ return false+}++func cliUpdateEnvironment(binary string) []string {+ paths := append([]string{filepath.Dir(binary)}, extraSearchPaths()...)+ paths = append(paths, os.Getenv("PATH"))+ env := []string{"PATH=" + strings.Join(paths, string(os.PathListSeparator)), "CI=1", "NO_COLOR=1"}+ for _, key := range []string{+ "HOME", "USERPROFILE", "USER", "LOGNAME", "LANG", "SHELL", "TMPDIR", "LOCALAPPDATA", "APPDATA",+ "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME",+ "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "no_proxy",+ "SSL_CERT_FILE", "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS",+ } {+ if value, ok := os.LookupEnv(key); ok {+ env = append(env, key+"="+value)+ }+ }+ return env+}++func cliUpdateManualResult() domain.RunnerMaintenanceResult {+ return domain.RunnerMaintenanceResult{Status: "manual", Message: "请在执行机器上使用该 CLI 原来的安装方式更新"}+}++func (d *Daemon) applyNativeCLIUpdate(ctx context.Context, rt domain.RunnerRuntime) domain.RunnerMaintenanceResult {+ index := slices.IndexFunc(defaultProviders, func(spec providerSpec) bool { return spec.Kind == rt.Provider })+ if index < 0 || defaultProviders[index].Update == "" || rt.BinaryPath == "" {+ return cliUpdateManualResult()+ }+ spec := defaultProviders[index]+ if !cliListsUpdate(ctx, rt.BinaryPath, spec.Update) {+ return cliUpdateManualResult()+ }+ if !d.updateMu.TryLock() {+ return domain.RunnerMaintenanceResult{Status: "failed", Message: "机器上有运行中的工作,请空闲后重试"}+ }+ defer d.updateMu.Unlock()+ if d.updateReady.Load() || d.runnerExecutionActive() {+ return domain.RunnerMaintenanceResult{Status: "failed", Message: "机器上有运行中的工作,请空闲后重试"}+ }+ dir, err := os.MkdirTemp("", "loopforge-cli-update-")+ if err != nil {+ return domain.RunnerMaintenanceResult{Status: "failed", Message: "无法创建 CLI 更新目录"}+ }+ defer os.RemoveAll(dir)+ cmd := exec.CommandContext(ctx, rt.BinaryPath, spec.Update)+ cmd.Env, cmd.Dir, cmd.WaitDelay = cliUpdateEnvironment(rt.BinaryPath), dir, time.Second+ out, err := cmd.CombinedOutput()+ if ctx.Err() == nil && cliUpdateRequiresManual(string(out)) {+ return cliUpdateManualResult()+ }+ if err != nil {+ log.Printf("native CLI update (%s): %v", rt.Provider, err)+ return domain.RunnerMaintenanceResult{Status: "failed", Message: "CLI 自更新失败,请检查执行机器的网络和安装状态"}+ }+ d.refreshRuntimes(ctx)+ select {+ case d.heartbeatWake <- struct{}{}:+ default:+ }+ for _, updated := range d.currentRuntimes() {+ if updated.Provider != rt.Provider || updated.Version == "" {+ continue+ }+ status := "updated"+ if updated.Version == rt.Version {+ status = "current"+ }+ return domain.RunnerMaintenanceResult{Status: status, Version: updated.Version}+ }+ return domain.RunnerMaintenanceResult{Status: "failed", Message: "CLI 更新后无法读取版本,请在执行机器上检查安装"}+}++func cliUpdateRequiresManual(output string) bool {+ output = strings.ToLower(output)+ for _, message := range []string{+ "update manually", "upgrade manually", "manual update", "manual upgrade",+ "update through the package manager", "use your package manager",+ "not supported for this installation", "not installed via", "cannot self-update",+ } {+ if strings.Contains(output, message) {+ return true+ }+ }+ return false+}diff --git a/internal/runner/cli_update_test.go b/internal/runner/cli_update_test.gonew file mode 100644index 00000000..5d68f89b--- /dev/null+++ b/internal/runner/cli_update_test.go@@ -0,0 +1,56 @@+package runner++import (+ "context"+ "fmt"+ "os"+ "path/filepath"+ "slices"+ "testing"++ "agentflow/internal/domain"+)++func TestNativeCLIUpdateRunsDiscoveredCommandAndRefreshesVersion(t *testing.T) {+ dir := t.TempDir()+ t.Setenv("HOME", dir)+ t.Setenv("PATH", dir)+ t.Setenv("CURSOR_API_KEY", "not-for-the-updater")+ mode := filepath.Join(dir, "install-mode")+ version := filepath.Join(dir, "version")+ binary := filepath.Join(dir, "cursor-agent")+ script := fmt.Sprintf(`#!/bin/sh+case "$1" in+ --version) IFS= read -r v < %q; printf '%%s\n' "$v" ;;+ --help) printf 'Usage: agent\n\nCommands:\n update [options] Update Cursor\n' ;;+ update)+ test -z "${CURSOR_API_KEY:-}" || exit 2+ if test -f %q; then printf 'Use your package manager\n'; exit 1; fi+ printf '2.0.0\n' > %q ;;+ *) exit 3 ;;+esac+`, version, mode, version)+ if err := os.WriteFile(binary, []byte(script), 0700); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(version, []byte("1.0.0\n"), 0600); err != nil {+ t.Fatal(err)+ }+ ctx := context.Background()+ d := &Daemon{cfg: Config{ExtraBinaries: map[string]string{"cursor": binary}}, heartbeatWake: make(chan struct{}, 1)}+ d.refreshRuntimes(ctx)+ rt, ok := d.cliUpdateRuntime("cursor")+ if !ok || !slices.Contains(rt.Capabilities, domain.RuntimeCapabilityNativeUpdate) || rt.Version != "1.0.0" {+ t.Fatalf("discovery: %+v", rt)+ }+ result := d.applyCLIUpdate(ctx, "cursor")+ if result.Status != "updated" || result.Version != "2.0.0" {+ t.Fatalf("native update: %+v", result)+ }+ if err := os.WriteFile(mode, nil, 0600); err != nil {+ t.Fatal(err)+ }+ if result = d.applyCLIUpdate(ctx, "cursor"); result.Status != "manual" {+ t.Fatalf("unsupported installation: %+v", result)+ }+}diff --git a/internal/runner/control.go b/internal/runner/control.goindex 102eb577..c308aed0 100644--- a/internal/runner/control.go+++ b/internal/runner/control.go@@ -81,8 +81,8 @@ func (d *Daemon) controlLoop(ctx context.Context) {}}-func (d *Daemon) readControls(ctx context.Context, conn *websocket.Conn) error {- ctx, cancel := context.WithCancel(ctx)+func (d *Daemon) readControls(daemonCtx context.Context, conn *websocket.Conn) error {+ ctx, cancel := context.WithCancel(daemonCtx)var requests sync.WaitGroupvar checkpointMu sync.MutexcheckpointCancels := map[string]context.CancelFunc{}@@ -176,8 +176,17 @@ func (d *Daemon) readControls(ctx context.Context, conn *websocket.Conn) error {delete(checkpointCancels, message.RequestID)checkpointMu.Unlock()}()- response := d.readRunnerWorkspace(requestCtx, *message.WorkspaceRequest)+ var response domain.RunnerWorkspaceResponse+ var startUpdate func()+ if message.WorkspaceRequest.Operation == domain.RunnerWorkspaceOperationMaintenance {+ response, startUpdate = d.maintenanceResponse(requestCtx, daemonCtx, message.WorkspaceRequest.Maintenance)+ } else {+ response = d.readRunnerWorkspace(requestCtx, *message.WorkspaceRequest)+ }err := writeMessage(controlMessage{Type: "workspace.response", RequestID: message.RequestID, WorkspaceResponse: &response})+ if startUpdate != nil {+ startUpdate()+ }if err != nil {_ = conn.Close()}diff --git a/internal/runner/conversation.go b/internal/runner/conversation.goindex 2f1acc8a..9433b9d0 100644--- a/internal/runner/conversation.go+++ b/internal/runner/conversation.go@@ -22,6 +22,12 @@ func (d *Daemon) conversationProcess(ctx context.Context, request domain.RunnerWreturn domain.RunnerWorkspaceResponse{Status: 400, Error: "invalid conversation process request"}}root := filepath.Join(d.cfg.DefaultWorkspaceRoot, ".conversations", req.SessionKey)+ if req.Transient {+ if request.RunID != "" {+ return domain.RunnerWorkspaceResponse{Status: 400, Error: "transient processes cannot use a run workspace"}+ }+ root = filepath.Join(d.cfg.DefaultWorkspaceRoot, ".conversations", ".transient", req.SessionKey)+ }workspace := ""if request.RunID != "" {var err errordiff --git a/internal/runner/daemon.go b/internal/runner/daemon.goindex c4ea0e8d..234f2d35 100644--- a/internal/runner/daemon.go+++ b/internal/runner/daemon.go@@ -46,6 +46,10 @@ type Daemon struct {wsOnline atomic.BoolupdateMu sync.RWMutexupdateReady atomic.Bool+ updateDownloadMu sync.Mutex+ cancelClaimLoop context.CancelFunc+ heartbeatWake chan struct{}+ maintenance runnerMaintenanceStaterunSandboxMu sync.MutexrunSandboxes map[string]*runSandboxmanagedTasks map[string]*managedTask@@ -129,7 +133,8 @@ func New(cfg Config) (*Daemon, error) {host, _ := os.Hostname()cfg.Name = host}- return &Daemon{cfg: cfg, client: NewClient(cfg.ServerURL), executor: runtime.NewExecutorRunner(), controls: map[string]chan string{}, pendingControls: map[string]string{}}, nil+ return &Daemon{cfg: cfg, client: NewClient(cfg.ServerURL), executor: runtime.NewExecutorRunner(),+ controls: map[string]chan string{}, pendingControls: map[string]string{}, heartbeatWake: make(chan struct{}, 1)}, nil}func trimTrailingSlash(s string) string {@@ -148,16 +153,23 @@ func (d *Daemon) Run(ctx context.Context) error {return err}d.refreshRuntimes(ctx)+ claimCtx, cancelClaim := context.WithCancel(ctx)+ defer cancelClaim()+ d.cancelClaimLoop = cancelClaimgo d.rescanLoop(ctx)heartbeatDone := make(chan struct{})go func() { defer close(heartbeatDone); d.heartbeatLoop(ctx) }()controlDone := make(chan struct{})go func() { defer close(controlDone); d.controlLoop(ctx) }()- err := d.claimLoop(ctx)+ err := d.claimLoop(claimCtx)+ if d.updateReady.Load() {+ err = ErrUpdateReady+ }// Workspace preparation runs on the control connection. Cancel and join it// before closing shared sandboxes, including on an automatic-update exit.stop()<-controlDone+ d.maintenance.jobs.Wait()<-heartbeatDonecloseCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)d.closeAllRunSandboxes(closeCtx)@@ -406,6 +418,7 @@ func (d *Daemon) heartbeatLoop(ctx context.Context) {case <-ctx.Done():returncase <-ticker.C:+ case <-d.heartbeatWake:}}}@@ -876,6 +889,21 @@ func (d *Daemon) executeInvocation(ctx context.Context, task domain.RunnerTask)if err != nil {return execResult{status: domain.RunnerTaskFailed, errMsg: err.Error()}, nil}+ } else if sandbox != nil && inv.CredentialSource == domain.RuntimeAuthLocal && prepared.Command.PrivateHome {+ loginEnv, cleanup, err := runtime.PrepareRunnerSandboxLogin(sandbox, prepared.Command.Provider, inv.RunID, inv.NodeID)+ if err != nil {+ return execResult{status: domain.RunnerTaskFailed, errMsg: err.Error()}, nil+ }+ if cleanup != nil {+ defer func() {+ if err := cleanup(); err != nil {+ log.Printf("task %s: clean sandbox CLI login: %v", task.ID, err)+ }+ }()+ }+ for key, value := range loginEnv {+ credentialEnv[key] = value+ }}commandEnv := runtime.CommandEnvironment(prepared.Command)for key, value := range d.taskManagedEnvironment(task) {@@ -1382,7 +1410,7 @@ func (d *Daemon) defaultWorkspace(taskID string) string {}// runnerVersion is reported at registration; it matches the module build.-var runnerVersion = "0.10.1"+var runnerVersion = domain.RunnerVersionCLISettings// Version returns the runner build version reported at registration.func Version() string { return runnerVersion }diff --git a/internal/runner/detect.go b/internal/runner/detect.goindex b7bd4da3..de5864a9 100644--- a/internal/runner/detect.go+++ b/internal/runner/detect.go@@ -21,27 +21,26 @@ import (type providerSpec struct {Kind stringBinary string+ Update string // non-interactive update subcommand for an unmanaged installation// VersionFlags precede --version. A CLI that rejects them is not the one// the platform drives (other tools share the name) and is not reported.VersionFlags []string}// defaultProviders lists the CLIs this runner drives in non-interactive-// mode. Codex and Claude Code authenticate with the machine's own login-// state; CodeBuddy cannot, so its tasks carry the responsible user's-// platform API key (injected as CODEBUDDY_API_KEY by the daemon). Additional-// providers can be added here without any protocol change: the server only-// matches on the provider name.+// mode. Runner tasks can reuse Codex or Claude Code's login. CodeBuddy tasks+// receive the configured CODEBUDDY_API_KEY from the daemon. Additional+// providers can be detected by name.var defaultProviders = []providerSpec{- {Kind: "claude-code", Binary: "claude"},- {Kind: "codex", Binary: "codex"},- {Kind: "codebuddy", Binary: "codebuddy"},+ {Kind: "claude-code", Binary: "claude", Update: "update"},+ {Kind: "codex", Binary: "codex", Update: "update"},+ {Kind: "codebuddy", Binary: "codebuddy", Update: "update"},// Agent CLIs (domain.AgentCLIExecutorKinds) always run with the// responsible user's key in a private HOME. cursor and agy have no npm// package and are found on PATH only.- {Kind: "opencode", Binary: "opencode"},- {Kind: "cursor", Binary: "cursor-agent"},- {Kind: "agy", Binary: "agy"},+ {Kind: "opencode", Binary: "opencode", Update: "upgrade"},+ {Kind: "cursor", Binary: "cursor-agent", Update: "update"},+ {Kind: "agy", Binary: "agy", Update: "update"},{Kind: "kimi", Binary: "kimi"},{Kind: "pi", Binary: "pi"},{Kind: "dsh", Binary: "dsh"},@@ -131,11 +130,18 @@ func detectRuntimes(ctx context.Context, extraBinaries map[string]string, inventif version == "" && len(spec.VersionFlags) > 0 {continue}+ capabilities := []string{"non_interactive"}+ if managed {+ capabilities = append(capabilities, domain.RuntimeCapabilityManagedUpdate)+ } else if spec.Update != "" {+ // Inspect the installed CLI's subcommands only when asked to update.+ capabilities = append(capabilities, domain.RuntimeCapabilityNativeUpdate)+ }out = append(out, domain.RunnerRuntime{Provider: spec.Kind,BinaryPath: path,Version: version,- Capabilities: []string{"non_interactive"},+ Capabilities: capabilities,Status: domain.RuntimeStatusOnline,})}diff --git a/internal/runner/login_models.go b/internal/runner/login_models.gonew file mode 100644index 00000000..ee3498c4--- /dev/null+++ b/internal/runner/login_models.go@@ -0,0 +1,23 @@+package runner++import (+ "context"+ "net/http"++ "agentflow/internal/domain"+ "agentflow/internal/runtime"+)++func (d *Daemon) runnerLoginModels(ctx context.Context, provider string) domain.RunnerWorkspaceResponse {+ for _, cli := range d.currentRuntimes() {+ if cli.Provider != provider || cli.BinaryPath == "" || cli.Status != domain.RuntimeStatusOnline {+ continue+ }+ models, err := runtime.DiscoverRunnerLoginModels(ctx, provider, cli.BinaryPath)+ if err != nil {+ return domain.RunnerWorkspaceResponse{Status: http.StatusBadGateway, Error: err.Error()}+ }+ return runnerWorkspacePayload(models)+ }+ return domain.RunnerWorkspaceResponse{Status: http.StatusNotFound, Error: "执行机器上的 CLI 当前不可用"}+}diff --git a/internal/runner/maintenance.go b/internal/runner/maintenance.gonew file mode 100644index 00000000..e543828a--- /dev/null+++ b/internal/runner/maintenance.go@@ -0,0 +1,198 @@+package runner++import (+ "context"+ "errors"+ "log"+ "net/http"+ "slices"+ "strings"+ "sync"+ "time"++ "agentflow/internal/domain"+ "agentflow/internal/managedcli"+)++const runnerMaintenanceKey = "runner"++type runnerMaintenanceState struct {+ mu sync.Mutex+ active string+ results map[string]domain.RunnerMaintenanceResult+ jobs sync.WaitGroup+}++func (d *Daemon) cliUpdateRuntime(provider string) (domain.RunnerRuntime, bool) {+ for _, rt := range d.currentRuntimes() {+ if rt.Provider == provider && rt.SupportsCLIUpdate() {+ return rt, true+ }+ }+ return domain.RunnerRuntime{}, false+}++// The callback starts work after the acceptance reply has been sent. A+// browser disconnect does not interrupt a CLI update or the Runner restart.+func (d *Daemon) maintenanceResponse(ctx, daemonCtx context.Context, request *domain.RunnerMaintenanceRequest) (domain.RunnerWorkspaceResponse, func()) {+ if request == nil {+ return domain.RunnerWorkspaceResponse{Status: http.StatusBadRequest, Error: "缺少更新请求"}, nil+ }+ provider := request.Provider+ key, version := runnerMaintenanceKey, runnerVersion+ updateAvailable := true+ if provider != "" {+ var rt domain.RunnerRuntime+ rt, updateAvailable = d.cliUpdateRuntime(provider)+ key, version = provider, rt.Version+ }++ if !request.Apply {+ d.maintenance.mu.Lock()+ result, found := d.maintenance.results[key]+ d.maintenance.mu.Unlock()+ if found && (provider != "" || request.StatusOnly || result.Status == "updating" || result.Status == "restarting") {+ return runnerWorkspacePayload(result), nil+ }+ if provider != "" {+ if !updateAvailable {+ return runnerWorkspacePayload(cliUpdateManualResult()), nil+ }+ return runnerWorkspacePayload(domain.RunnerMaintenanceResult{Status: "ready", Current: version, CanUpdate: true}), nil+ }+ return runnerWorkspacePayload(d.inspectRunnerUpdate(ctx)), nil+ }+ if !updateAvailable {+ return domain.RunnerWorkspaceResponse{Status: http.StatusConflict, Error: cliUpdateManualResult().Message}, nil+ }++ if provider == "" && d.cfg.DisableAutoUpdate {+ return domain.RunnerWorkspaceResponse{Status: http.StatusConflict, Error: "此 Runner 已关闭平台更新,请在执行机器上更新"}, nil+ }+ d.updateMu.RLock()+ defer d.updateMu.RUnlock()+ d.maintenance.mu.Lock()+ defer d.maintenance.mu.Unlock()+ if d.updateReady.Load() {+ return domain.RunnerWorkspaceResponse{Status: http.StatusConflict, Error: "Runner 正在重启,请稍后重试"}, nil+ }+ if d.maintenance.active != "" {+ if d.maintenance.active == key {+ return runnerWorkspacePayload(d.maintenance.results[key]), nil+ }+ return domain.RunnerWorkspaceResponse{Status: http.StatusConflict, Error: "此机器正在更新,请稍后重试"}, nil+ }+ if d.maintenance.results == nil {+ d.maintenance.results = make(map[string]domain.RunnerMaintenanceResult)+ }+ pending := domain.RunnerMaintenanceResult{Status: "updating", Current: version}+ d.maintenance.results[key], d.maintenance.active = pending, key+ return runnerWorkspacePayload(pending), func() {+ d.maintenance.jobs.Add(1)+ go d.runMaintenance(daemonCtx, key, provider, version)+ }+}++func (d *Daemon) inspectRunnerUpdate(ctx context.Context) domain.RunnerMaintenanceResult {+ binary, err := currentRunnerExecutable()+ if err == nil {+ var local, expected string+ local, expected, err = d.runnerUpdateHashes(ctx, binary)+ if err == nil {+ result := domain.RunnerMaintenanceResult{Status: "current", Current: runnerVersion}+ if !strings.EqualFold(local, expected) {+ result.Status, result.CanUpdate = "available", !d.cfg.DisableAutoUpdate+ if !result.CanUpdate {+ result.Message = "此 Runner 已关闭平台更新,请在执行机器上更新"+ }+ }+ return result+ }+ }+ if ctx.Err() == nil {+ log.Printf("runner maintenance check: %v", err)+ }+ return domain.RunnerMaintenanceResult{Status: "failed", Current: runnerVersion, Message: "无法检查平台提供的 Runner 构建"}+}++func (d *Daemon) runMaintenance(ctx context.Context, key, provider, version string) {+ defer d.maintenance.jobs.Done()+ var result domain.RunnerMaintenanceResult+ if provider == "" {+ updateCtx, cancel := context.WithTimeout(ctx, 7*time.Minute)+ defer cancel()+ result = d.applyRunnerUpdate(updateCtx)+ } else {+ updateCtx, cancel := context.WithTimeout(ctx, 45*time.Minute)+ defer cancel()+ result = d.applyCLIUpdate(updateCtx, provider)+ }+ result.Current = version+ d.maintenance.mu.Lock()+ d.maintenance.results[key], d.maintenance.active = result, ""+ d.maintenance.mu.Unlock()+ if result.Status == "restarting" && d.cancelClaimLoop != nil {+ d.cancelClaimLoop()+ }+}++func (d *Daemon) applyCLIUpdate(ctx context.Context, provider string) domain.RunnerMaintenanceResult {+ rt, ok := d.cliUpdateRuntime(provider)+ if !ok {+ return cliUpdateManualResult()+ }+ if slices.Contains(rt.Capabilities, domain.RuntimeCapabilityNativeUpdate) {+ if result := d.applyNativeCLIUpdate(ctx, rt); result.Status != "manual" {+ return result+ }+ }+ if d.cfg.ManagedCLIRoot != "" && slices.Contains(rt.Capabilities, domain.RuntimeCapabilityManagedUpdate) {+ return d.applyManagedCLIUpdate(ctx, provider)+ }+ return cliUpdateManualResult()+}++func (d *Daemon) applyRunnerUpdate(ctx context.Context) domain.RunnerMaintenanceResult {+ binary, err := currentRunnerExecutable()+ if err == nil {+ var updated bool+ updated, err = d.installRunnerUpdate(ctx, binary)+ if err == nil {+ if updated {+ return domain.RunnerMaintenanceResult{Status: "restarting"}+ }+ return domain.RunnerMaintenanceResult{Status: "current"}+ }+ }+ if errors.Is(err, errRunnerUpdateBusy) {+ return domain.RunnerMaintenanceResult{Status: "failed", Message: "机器上有运行中的工作,请空闲后重试"}+ }+ log.Printf("manual runner update: %v", err)+ return domain.RunnerMaintenanceResult{Status: "failed", Message: "Runner 下载、校验或安装失败,请查看执行机器日志"}+}++func (d *Daemon) applyManagedCLIUpdate(ctx context.Context, provider string) domain.RunnerMaintenanceResult {+ manager, err := managedcli.NewManager(d.cfg.ManagedCLIRoot)+ if err == nil {+ var report managedcli.Report+ report, err = manager.UpdateProvider(ctx, provider)+ if err == nil && len(report.Results) == 1 {+ result := report.Results[0]+ switch result.Status {+ case "updated":+ d.refreshRuntimes(ctx)+ select {+ case d.heartbeatWake <- struct{}{}:+ default:+ }+ return domain.RunnerMaintenanceResult{Status: "updated", Version: result.To}+ case "unchanged":+ return domain.RunnerMaintenanceResult{Status: "current", Version: result.From}+ case "skipped":+ return domain.RunnerMaintenanceResult{Status: "skipped", Message: "当前没有可安装的托管版本"}+ }+ }+ }+ log.Printf("manual CLI update (%s): %v", provider, err)+ return domain.RunnerMaintenanceResult{Status: "failed", Message: "CLI 更新失败,请查看执行机器日志"}+}diff --git a/internal/runner/update.go b/internal/runner/update.goindex 797726a4..fddfee92 100644--- a/internal/runner/update.go+++ b/internal/runner/update.go@@ -105,48 +105,85 @@ func currentRunnerExecutable() (string, error) {return binary, nil}-// checkForUpdate only commits while no task is running. The new binary is-// downloaded and verified before acquiring the claim lock, and a failed-// download leaves the previous executable untouched.+var errRunnerUpdateBusy = errors.New("runner is busy")++func (d *Daemon) runnerUpdateEndpoint() string {+ return fmt.Sprintf("%s/runners/agentflow-runner?os=%s&arch=%s", d.client.base, runtime.GOOS, runtime.GOARCH)+}++func (d *Daemon) runnerUpdateHashes(ctx context.Context, binary string) (local, expected string, err error) {+ local, err = hashFile(binary)+ if err != nil {+ return "", "", err+ }+ remote, err := runnerBinaryMetadata(ctx, d.runnerUpdateEndpoint())+ return local, remote.SHA256, err+}+func (d *Daemon) checkForUpdate(ctx context.Context, binary string) error {- if atomic.LoadInt32(&d.running) != 0 {+ _, err := d.installRunnerUpdate(ctx, binary)+ if errors.Is(err, errRunnerUpdateBusy) {return nil}- endpoint := fmt.Sprintf("%s/runners/agentflow-runner?os=%s&arch=%s", d.client.base, runtime.GOOS, runtime.GOARCH)- metadata, err := runnerBinaryMetadata(ctx, endpoint)- if err != nil {- return err+ return err+}++func (d *Daemon) runnerWorkActive() bool {+ d.maintenance.mu.Lock()+ updatingCLI := d.maintenance.active != "" && d.maintenance.active != runnerMaintenanceKey+ d.maintenance.mu.Unlock()+ return updatingCLI || d.runnerExecutionActive()+}++func (d *Daemon) runnerExecutionActive() bool {+ return atomic.LoadInt32(&d.running) != 0 || d.conversationProcesses.Active() ||+ d.workspaceTerminals.Active() || d.checkpointTransfers.Active()+}++// Download and verify outside the claim fence. Idle activity is checked+// again before replacing the binary, with new workspace requests excluded.+func (d *Daemon) installRunnerUpdate(ctx context.Context, binary string) (bool, error) {+ if d.runnerWorkActive() || !d.updateDownloadMu.TryLock() {+ return false, errRunnerUpdateBusy}- localHash, err := hashFile(binary)+ defer d.updateDownloadMu.Unlock()+ if d.updateReady.Load() {+ return true, nil+ }+ localHash, expectedHash, err := d.runnerUpdateHashes(ctx, binary)if err != nil {- return err+ return false, err}- if localHash == metadata.SHA256 {- return nil+ if strings.EqualFold(localHash, expectedHash) {+ return false, nil}- tmp, err := downloadRunnerBinary(ctx, endpoint, binary, metadata.SHA256)+ tmp, err := downloadRunnerBinary(ctx, d.runnerUpdateEndpoint(), binary, expectedHash)if err != nil {- return err+ return false, err}defer os.Remove(tmp)-- d.updateMu.Lock()+ if !d.updateMu.TryLock() {+ return false, errRunnerUpdateBusy+ }defer d.updateMu.Unlock()- if d.updateReady.Load() || atomic.LoadInt32(&d.running) != 0 || ctx.Err() != nil {- return nil+ if d.runnerWorkActive() {+ return false, errRunnerUpdateBusy+ }+ if err := ctx.Err(); err != nil {+ return false, err}// A manual upgrade may have happened while the download was in progress.if current, err := hashFile(binary); err != nil {- return fmt.Errorf("check runner executable before update: %w", err)+ return false, fmt.Errorf("check runner executable before update: %w", err)} else if current != localHash {- return errors.New("runner executable changed during update")+ return false, errors.New("runner executable changed during update")}if err := os.Rename(tmp, binary); err != nil {- return fmt.Errorf("replace runner executable: %w", err)+ return false, fmt.Errorf("replace runner executable: %w", err)}d.updateReady.Store(true)- log.Printf("runner update installed (%s); restarting", metadata.SHA256[:12])- return nil+ log.Printf("runner update installed (%s); restarting", expectedHash[:12])+ return true, nil}type binaryMetadata struct {diff --git a/internal/runner/update_test.go b/internal/runner/update_test.goindex 39780abe..6fe88879 100644--- a/internal/runner/update_test.go+++ b/internal/runner/update_test.go@@ -5,6 +5,7 @@ import ("crypto/sha256""encoding/hex""encoding/json"+ "errors""fmt""net/http""net/http/httptest"@@ -161,3 +162,36 @@ func TestGateMCPHelperUpdatesWhileRunnerIdle(t *testing.T) {}}}++func TestRunnerUpdateDefersWhileWorkspaceRequestIsActive(t *testing.T) {+ const updated = "new runner"+ hash := sha256.Sum256([]byte(updated))+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Query().Get("metadata") == "1" {+ fmt.Fprintf(w, `{"sha256":%q}`, hex.EncodeToString(hash[:]))+ return+ }+ _, _ = w.Write([]byte(updated))+ }))+ defer server.Close()+ d, err := New(Config{ServerURL: server.URL, BootstrapToken: "fixture"})+ if err != nil {+ t.Fatal(err)+ }+ binary := filepath.Join(t.TempDir(), "agentflow-runner")+ if err := os.WriteFile(binary, []byte("old runner"), 0700); err != nil {+ t.Fatal(err)+ }+ d.updateMu.RLock()+ installed, err := d.installRunnerUpdate(context.Background(), binary)+ d.updateMu.RUnlock()+ if installed || !errors.Is(err, errRunnerUpdateBusy) || d.updateReady.Load() {+ t.Fatalf("update while workspace is active: installed=%t err=%v", installed, err)+ }+ if data, err := os.ReadFile(binary); err != nil || string(data) != "old runner" {+ t.Fatalf("old executable was not preserved: %v", err)+ }+ if installed, err = d.installRunnerUpdate(context.Background(), binary); err != nil || !installed {+ t.Fatalf("idle update: installed=%t err=%v", installed, err)+ }+}diff --git a/internal/runner/workspace.go b/internal/runner/workspace.goindex 6e24221f..57842f0b 100644--- a/internal/runner/workspace.go+++ b/internal/runner/workspace.go@@ -115,9 +115,17 @@ func (d *Daemon) handleRunnerWorkspaceBrowser(ctx context.Context, request domai}func (d *Daemon) readRunnerWorkspace(ctx context.Context, request domain.RunnerWorkspaceRequest) domain.RunnerWorkspaceResponse {+ d.updateMu.RLock()+ defer d.updateMu.RUnlock()+ if d.updateReady.Load() {+ return domain.RunnerWorkspaceResponse{Status: http.StatusConflict, Error: "Runner 即将重启,请稍后重试"}+ }if request.Operation == "conversation_process" {return d.conversationProcess(ctx, request)}+ if request.Operation == domain.RunnerWorkspaceOperationLoginModels {+ return d.runnerLoginModels(ctx, request.ModelProvider)+ }if request.Operation == domain.RunnerWorkspaceOperationBrowser {return d.handleRunnerWorkspaceBrowser(ctx, request)}diff --git a/internal/runtime/conversation_assets.go b/internal/runtime/conversation_assets.goindex afb32a90..cd0288f4 100644--- a/internal/runtime/conversation_assets.go+++ b/internal/runtime/conversation_assets.go@@ -68,7 +68,7 @@ var conversationManagedFiles = []string{"home/.gemini/config/mcp_config.json", "home/.gemini/antigravity-cli/settings.json","home/.kimi-code/mcp.json", "home/.pi/agent/mcp.json", "home/.pi/agent/models.json","home/.dsh/agentflow-mcp.json", "home/.dsh/agentflow-model.json",- "home/.zcode/v2",+ "home/.zcode/v2", "home/.codex/auth.json", "home/.claude/.credentials.json",}// Only platform-generated inputs travel to the execution host. Nativediff --git a/internal/runtime/conversation_login_models.go b/internal/runtime/conversation_login_models.gonew file mode 100644index 00000000..fc887cd5--- /dev/null+++ b/internal/runtime/conversation_login_models.go@@ -0,0 +1,184 @@+package runtime++import (+ "bufio"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "time"++ "agentflow/internal/domain"+)++// DiscoverRunnerLoginModels uses the same login source as a conversation,+// with an empty working directory and a temporary private HOME.+func DiscoverRunnerLoginModels(ctx context.Context, provider, binary string) ([]domain.CLIModel, error) {+ login, ok := runnerLoginSpec(provider)+ if !ok {+ return nil, fmt.Errorf("该 CLI 暂不支持获取账号模型")+ }+ root, err := os.MkdirTemp("", "loopforge-login-models-")+ if err != nil {+ return nil, fmt.Errorf("无法创建模型查询目录")+ }+ defer os.RemoveAll(root)+ _, loginEnv, err := prepareConversationRunnerLogin(root, login, true)+ if err != nil {+ return nil, err+ }+ home := filepath.Join(root, "home")+ env := map[string]string{login.configEnv: filepath.Join(home, login.dir), "NO_COLOR": "1", "CI": "1"}+ for _, key := range []string{"HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "no_proxy", "SSL_CERT_FILE", "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS"} {+ if value, ok := os.LookupEnv(key); ok {+ env[key] = value+ }+ }+ path := filepath.Dir(binary) + string(os.PathListSeparator) + os.Getenv("PATH")+ env["PATH"] = path+ args := []string{"app-server"}+ if login.binding == BindClaudeCode {+ args = []string{"-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose", "--setting-sources", ""}+ }+ ctx, cancel := context.WithTimeout(ctx, 15*time.Second)+ defer cancel()+ environment := appendEnvironment(terminalBaseEnvironment(home), env, loginEnv)+ if login.binding == BindClaudeCode {+ status := exec.CommandContext(ctx, binary, "auth", "status")+ status.Dir, status.Env, status.WaitDelay = root, environment, time.Second+ output, err := status.Output()+ var auth struct {+ LoggedIn bool `json:"loggedIn"`+ }+ if err != nil || json.Unmarshal(output, &auth) != nil || !auth.LoggedIn {+ return nil, fmt.Errorf("执行机器上的 Claude Code 登录态不可用,请检查 CLI 版本和账号登录")+ }+ }+ cmd := exec.CommandContext(ctx, binary, args...)+ cmd.Dir, cmd.Env = root, environment+ cmd.WaitDelay = time.Second+ input, err := cmd.StdinPipe()+ if err != nil {+ return nil, fmt.Errorf("无法连接 %s 查询模型", login.label)+ }+ defer input.Close()+ output, err := cmd.StdoutPipe()+ if err != nil {+ return nil, fmt.Errorf("无法读取 %s 的模型列表", login.label)+ }+ defer output.Close()+ if err := cmd.Start(); err != nil {+ return nil, fmt.Errorf("无法启动 %s 查询模型", login.label)+ }+ defer func() { cancel(); _ = cmd.Wait() }()+ scanner := bufio.NewScanner(io.LimitReader(output, 2<<20))+ scanner.Buffer(make([]byte, 16<<10), 1<<20)+ send := json.NewEncoder(input)+ var models []domain.CLIModel+ if login.binding == BindCodex {+ models = codexLoginModels(send, scanner)+ } else {+ models = claudeLoginModels(send, scanner)+ }+ if err := ctx.Err(); err != nil {+ return nil, fmt.Errorf("查询 %s 模型超时", login.label)+ }+ if models == nil {+ return nil, fmt.Errorf("%s 无法返回账号模型,请检查执行机器上的 CLI 版本和登录状态", login.label)+ }+ return models, nil+}++func codexLoginModels(send *json.Encoder, scanner *bufio.Scanner) []domain.CLIModel {+ if send.Encode(map[string]any{+ "id": 1, "method": "initialize",+ "params": map[string]any{"clientInfo": map[string]string{"name": "loopforge", "version": "1.0.0"}},+ }) != nil || codexLoginResult(scanner, 1) == nil {+ return nil+ }+ if send.Encode(map[string]string{"method": "initialized"}) != nil ||+ send.Encode(map[string]any{"id": 2, "method": "account/read", "params": map[string]bool{"refreshToken": false}}) != nil {+ return nil+ }+ var account struct {+ Account *struct{} `json:"account"`+ }+ if json.Unmarshal(codexLoginResult(scanner, 2), &account) != nil || account.Account == nil {+ return nil+ }+ if send.Encode(map[string]any{"id": 3, "method": "model/list", "params": map[string]any{"limit": 100, "includeHidden": false}}) != nil {+ return nil+ }+ var result struct {+ Data []struct {+ Model string `json:"model"`+ DisplayName string `json:"displayName"`+ } `json:"data"`+ }+ if json.Unmarshal(codexLoginResult(scanner, 3), &result) != nil || result.Data == nil {+ return nil+ }+ models := make([]domain.CLIModel, 0, len(result.Data))+ for _, item := range result.Data {+ if id := strings.TrimSpace(item.Model); id != "" {+ models = append(models, domain.CLIModel{ID: id, Name: item.DisplayName})+ }+ }+ return models+}++func codexLoginResult(scanner *bufio.Scanner, id int) json.RawMessage {+ for scanner.Scan() {+ var message struct {+ ID int `json:"id"`+ Result json.RawMessage `json:"result"`+ }+ if json.Unmarshal(scanner.Bytes(), &message) == nil && message.ID == id {+ return message.Result+ }+ }+ return nil+}++func claudeLoginModels(send *json.Encoder, scanner *bufio.Scanner) []domain.CLIModel {+ const id = "loopforge-models"+ if send.Encode(map[string]any{+ "type": "control_request", "request_id": id,+ "request": map[string]string{"subtype": "initialize"},+ }) != nil {+ return nil+ }+ for scanner.Scan() {+ var message struct {+ Type string `json:"type"`+ Response struct {+ RequestID string `json:"request_id"`+ Subtype string `json:"subtype"`+ Response struct {+ Models []struct {+ Value string `json:"value"`+ DisplayName string `json:"displayName"`+ } `json:"models"`+ } `json:"response"`+ } `json:"response"`+ }+ if json.Unmarshal(scanner.Bytes(), &message) != nil || message.Type != "control_response" || message.Response.RequestID != id {+ continue+ }+ if message.Response.Subtype != "success" || message.Response.Response.Models == nil {+ return nil+ }+ models := make([]domain.CLIModel, 0, len(message.Response.Response.Models))+ for _, item := range message.Response.Response.Models {+ if id := strings.TrimSpace(item.Value); id != "" {+ models = append(models, domain.CLIModel{ID: id, Name: item.DisplayName})+ }+ }+ return models+ }+ return nil+}diff --git a/internal/runtime/conversation_login_models_test.go b/internal/runtime/conversation_login_models_test.gonew file mode 100644index 00000000..acd61bf3--- /dev/null+++ b/internal/runtime/conversation_login_models_test.go@@ -0,0 +1,69 @@+package runtime++import (+ "context"+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func TestDiscoverRunnerLoginModels(t *testing.T) {+ tests := []struct {+ provider, configEnv, loginFile, cli string+ }{+ {"codex", "CODEX_HOME", "auth.json", `+test "$1" = app-server+test -z "${OPENAI_API_KEY:-}"+test -f "$CODEX_HOME/auth.json"+read -r request; case "$request" in *'"method":"initialize"'*) ;; *) exit 2 ;; esac+printf '%s\n' '{"id":1,"result":{}}'+read -r request; case "$request" in *'"method":"initialized"'*) ;; *) exit 3 ;; esac+read -r request; case "$request" in *'"method":"account/read"'*) ;; *) exit 4 ;; esac+printf '%s\n' '{"id":2,"result":{"account":{"email":"[email protected]"}}}'+read -r request; case "$request" in *'"method":"model/list"'*) ;; *) exit 5 ;; esac+printf '%s\n' '{"id":3,"result":{"data":[{"id":"display-alias","model":"fixture-model","displayName":"Fixture Model"}]}}'+`},+ {"claude-code", "CLAUDE_CONFIG_DIR", ".credentials.json", `+test -z "${ANTHROPIC_API_KEY:-}"+test -f "$CLAUDE_CONFIG_DIR/.credentials.json"+if [ "$1" = auth ] && [ "$2" = status ]; then+ printf '%s\n' '{"loggedIn":true,"email":"[email protected]"}'+ exit+fi+read -r request; case "$request" in *'"subtype":"initialize"'*) ;; *) exit 2 ;; esac+printf '%s\n' '{"type":"control_response","response":{"subtype":"success","request_id":"loopforge-models","response":{"models":[{"value":"fixture-model","displayName":"Fixture Model"}]}}}'+`},+ }+ for _, tc := range tests {+ t.Run(tc.provider, func(t *testing.T) {+ dir, isolated := t.TempDir(), t.TempDir()+ t.Setenv("TMPDIR", isolated)+ t.Setenv(tc.configEnv, dir)+ t.Setenv("CLAUDE_CODE_OAUTH_TOKEN", "")+ t.Setenv("OPENAI_API_KEY", "must-stay-on-host")+ t.Setenv("ANTHROPIC_API_KEY", "must-stay-on-host")+ if err := os.WriteFile(filepath.Join(dir, tc.loginFile), []byte(`{"test":true}`), 0600); err != nil {+ t.Fatal(err)+ }+ bin := filepath.Join(dir, "cli")+ script := "#!/bin/sh\nset -eu\ncase \"$HOME\" in " + isolated + "/*/home) ;; *) exit 9 ;; esac\n" + tc.cli+ if err := os.WriteFile(bin, []byte(script), 0700); err != nil {+ t.Fatal(err)+ }+ models, err := DiscoverRunnerLoginModels(context.Background(), tc.provider, bin)+ if err != nil || len(models) != 1 || models[0].ID != "fixture-model" || models[0].Name != "Fixture Model" {+ t.Fatalf("models=%+v error=%v", models, err)+ }+ if dirs, err := os.ReadDir(isolated); err != nil || len(dirs) != 0 {+ t.Fatalf("lookup left its credential directory behind: %v %v", dirs, err)+ }+ if err := os.Remove(filepath.Join(dir, tc.loginFile)); err != nil {+ t.Fatal(err)+ }+ if _, err := DiscoverRunnerLoginModels(context.Background(), tc.provider, bin); err == nil || !strings.Contains(err.Error(), "登录态不可用") {+ t.Fatalf("missing login error = %v", err)+ }+ })+ }+}diff --git a/internal/runtime/conversation_process.go b/internal/runtime/conversation_process.goindex a9da017c..813bcdb2 100644--- a/internal/runtime/conversation_process.go+++ b/internal/runtime/conversation_process.go@@ -14,6 +14,7 @@ import ("os/exec""path/filepath"goruntime "runtime"+ "slices""strconv""strings""sync"@@ -29,6 +30,7 @@ var ErrConversationNotStarted = errors.New("conversation process was not started// ConversationProcessRequest travels only over the authenticated runner// control connection. Keys and process input never enter durable task rows.type ConversationProcessRequest struct {+ Transient bool `json:"transient,omitempty"`Operation string `json:"operation"`ID string `json:"id,omitempty"`SessionKey string `json:"sessionKey"`@@ -50,6 +52,7 @@ type ConversationFile struct {}type ConversationCommand struct {+ RunnerLogin bool `json:",omitempty"`Argv []stringProvider stringBindings []CredentialBinding@@ -88,6 +91,12 @@ type conversationAssetFence struct {users int}+func (p *ConversationProcessPool) Active() bool {+ p.mu.Lock()+ defer p.mu.Unlock()+ return len(p.roots) != 0+}+func (p *ConversationProcessPool) lockAssets(ctx context.Context, root string) (func(), error) {p.mu.Lock()if p.assets == nil {@@ -152,7 +161,7 @@ func (p *ConversationProcessPool) Handle(ctx context.Context, root, workspace stif req.Operation == "start" {return p.start(ctx, root, workspace, sandbox, req, forward, factories...)}- if req.Operation == "prepare" || req.Operation == "sync" || req.Operation == "resetAssets" {+ if req.Operation == "prepare" || req.Operation == "sync" || req.Operation == "resetAssets" || req.Operation == "discard" {// Serialize asset writes with reservation of a new process. Checking// roots and releasing the fence before a write allows start to race it.unlock, lockErr := p.lockAssets(ctx, root)@@ -169,6 +178,12 @@ func (p *ConversationProcessPool) Handle(ctx context.Context, root, workspace stif err = ValidateConversationRoot(root); err != nil {return ConversationProcessResult{}, err}+ if req.Operation == "discard" {+ if !req.Transient {+ return ConversationProcessResult{}, fmt.Errorf("only transient conversations can be discarded")+ }+ return ConversationProcessResult{}, os.RemoveAll(root)+ }if err = os.MkdirAll(filepath.Join(root, "home", "tmp"), 0700); err != nil {return ConversationProcessResult{}, err}@@ -410,11 +425,15 @@ func (p *ConversationProcessPool) start(ctx context.Context, root, workspace strvar sb Sandboxvar release func()var stdin io.Closer+ var cleanupLogin func() errorfinish := func(runErr error, notStarted bool) {cancel()// Cancellation can skip the shell EXIT trap. Clean ephemeral ZCode// credentials before publishing completion or releasing this root.credentialCleanupErr := cleanupConversationCredentialFiles(root, req.Command.Provider)+ if cleanupLogin != nil {+ credentialCleanupErr = errors.Join(credentialCleanupErr, cleanupLogin())+ }if stdin != nil {_ = stdin.Close()}@@ -589,11 +608,28 @@ func (p *ConversationProcessPool) start(ctx context.Context, root, workspace str} else {bindWorkspace = bindSandbox.Workspace()}+ var localEnv map[string]string+ login, supported := runnerLoginSpec(command.Provider)+ if req.Command.RunnerLogin && !supported {+ return ConversationProcessResult{}, fmt.Errorf("该 CLI 不支持使用执行机器的本机登录")+ }+ if supported {+ cleanupLogin, localEnv, err = prepareConversationRunnerLogin(root, login, req.Command.RunnerLogin)+ if err != nil {+ return ConversationProcessResult{}, err+ }+ if req.Command.RunnerLogin {+ command.CredentialBindings = slices.DeleteFunc(slices.Clone(command.CredentialBindings), func(binding CredentialBinding) bool {+ return binding == login.binding+ })+ }+ }nativeArgv := append([]string(nil), command.Argv...)command, err = bindCommand(bindSandbox, bindWorkspace, command, req.Command.Credentials)if err != nil {return ConversationProcessResult{}, err}+ command = WithCommandEnvironment(command, localEnv)if command.Provider == AgentCLIZCode {command.Argv = conversationZCodeResumeArgv(root, nativeArgv, command.Argv)}diff --git a/internal/runtime/conversation_runner_login.go b/internal/runtime/conversation_runner_login.gonew file mode 100644index 00000000..08ef227f--- /dev/null+++ b/internal/runtime/conversation_runner_login.go@@ -0,0 +1,258 @@+package runtime++import (+ "bytes"+ "crypto/sha256"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "log"+ "os"+ "path/filepath"+ "slices"+ "strings"+)++type conversationLoginSpec struct {+ label, dir, file, configEnv string+ binding CredentialBinding+}++func runnerLoginSpec(provider string) (conversationLoginSpec, bool) {+ switch provider {+ case "codex":+ return conversationLoginSpec{"Codex", ".codex", "auth.json", "CODEX_HOME", BindCodex}, true+ case "claude-code":+ return conversationLoginSpec{"Claude Code", ".claude", ".credentials.json", "CLAUDE_CONFIG_DIR", BindClaudeCode}, true+ default:+ return conversationLoginSpec{}, false+ }+}++// Copy only the native CLI's login file into its isolated conversation home.+// This runs on the executing machine. The file never goes through the control+// connection or enters the synchronized asset set.+func prepareConversationRunnerLogin(root string, login conversationLoginSpec, enabled bool) (func() error, map[string]string, error) {+ return prepareRunnerLogin(AgentCLIHome{Base: root, Rel: "home"}, login, enabled)+}++// PrepareRunnerSandboxLogin stages the selected CLI's login in the node's+// private home. The CLI can resume its session on a later attempt after the+// login file has been removed. Checkpoints exclude this control directory.+func PrepareRunnerSandboxLogin(sandbox Sandbox, provider, runID, nodeID string) (map[string]string, func() error, error) {+ login, supported := runnerLoginSpec(provider)+ if !supported {+ return nil, nil, nil+ }+ scope := sha256.Sum256([]byte(runID + "\x00" + nodeID))+ home := WorkspaceAgentCLIHome(sandbox.Workspace(), fmt.Sprintf("%s-login-%x", provider, scope[:12]))+ cleanup, env, err := prepareRunnerLogin(home, login, true)+ if err != nil {+ if cleanup != nil {+ err = errors.Join(err, cleanup())+ }+ return nil, nil, err+ }+ if env == nil {+ env = map[string]string{}+ }+ homePath := home.Path()+ if sandboxDriver(sandbox) == "docker" {+ homePath = filepath.ToSlash(filepath.Join("/workspace", home.Rel))+ }+ env["HOME"] = homePath+ env[login.configEnv] = filepath.ToSlash(filepath.Join(homePath, login.dir))+ return env, cleanup, nil+}++func prepareRunnerLogin(home AgentCLIHome, login conversationLoginSpec, enabled bool) (func() error, map[string]string, error) {+ home.Rel = filepath.Join(home.Rel, login.dir)+ target, err := openAgentCLIHome(home)+ if err != nil {+ return nil, nil, err+ }+ defer target.Close()+ remove := func(dir *os.Root) error {+ if err := dir.Remove(login.file); err != nil && !os.IsNotExist(err) {+ return err+ }+ return nil+ }+ // A runner restart can interrupt cleanup. Remove any previous copy even+ // when this invocation now uses a personal key.+ if err := remove(target); err != nil {+ return nil, nil, err+ }+ if !enabled {+ return nil, nil, nil+ }+ if login.binding == BindClaudeCode {+ if token := strings.TrimSpace(os.Getenv("CLAUDE_CODE_OAUTH_TOKEN")); token != "" {+ return nil, map[string]string{"CLAUDE_CODE_OAUTH_TOKEN": token}, nil+ }+ }+ configDir := strings.TrimSpace(os.Getenv(login.configEnv))+ if configDir == "" {+ base, _ := os.UserHomeDir()+ if base != "" {+ configDir = filepath.Join(base, login.dir)+ }+ }+ data, err := readRunnerLoginFile(configDir, login.file)+ if err != nil {+ return nil, nil, fmt.Errorf("执行机器上的 %s 本机登录态不可用,请检查 Runner 账户的 CLI 登录", login.label)+ }+ cleanup := func() error {+ dir, err := openAgentCLIHome(home)+ if err != nil {+ return err+ }+ defer dir.Close()+ // Codex and Claude Code rotate refresh tokens: a refresh inside the+ // sandbox invalidates the host's copy, so keep the refreshed login+ // before the copy is removed.+ if err := writeBackRefreshedLogin(dir, login, configDir, data); err != nil {+ log.Printf("runner login: keep refreshed %s login: %v", login.label, err)+ }+ return remove(dir)+ }+ if err := target.WriteFile(login.file, data, 0600); err != nil {+ return cleanup, nil, fmt.Errorf("无法准备 %s 的本机登录态", login.label)+ }+ return cleanup, nil, nil+}++func readRunnerLoginFile(dir, name string) ([]byte, error) {+ if dir == "" {+ return nil, os.ErrNotExist+ }+ const maxSize = 1 << 20+ path := filepath.Join(dir, name)+ fi, err := os.Stat(path)+ if err != nil {+ return nil, err+ }+ if !fi.Mode().IsRegular() || fi.Size() > maxSize {+ return nil, fmt.Errorf("invalid login file")+ }+ file, err := os.Open(path)+ if err != nil {+ return nil, err+ }+ defer file.Close()+ data, err := io.ReadAll(io.LimitReader(file, maxSize+1))+ if err != nil {+ return nil, err+ }+ if len(data) > maxSize || !json.Valid(data) {+ return nil, fmt.Errorf("invalid login file")+ }+ return data, nil+}++// writeBackRefreshedLogin copies a login the CLI refreshed in its isolated home+// back to the Runner account's file. It is a compare-and-swap on content: the+// host file must still be the one copied in (otherwise the host CLI or another+// session refreshed it first and stays authoritative), and the refreshed file+// must be the same kind of login (same top-level fields and, for Codex, the+// same account) so a sandboxed agent cannot swap in another account.+func writeBackRefreshedLogin(dir *os.Root, login conversationLoginSpec, configDir string, original []byte) error {+ refreshed, err := readRootLoginFile(dir, login.file)+ if err != nil || bytes.Equal(refreshed, original) {+ return nil+ }+ if !sameRunnerLogin(original, refreshed) {+ return fmt.Errorf("refreshed login does not match the original account; not written back")+ }+ if configDir == "" {+ return nil+ }+ path := filepath.Join(configDir, login.file)+ current, err := readRunnerLoginFile(configDir, login.file)+ if err != nil || !bytes.Equal(current, original) {+ return nil+ }+ info, err := os.Stat(path)+ if err != nil {+ return err+ }+ tmp, err := os.CreateTemp(configDir, "."+login.file+".refresh-*")+ if err != nil {+ return err+ }+ defer os.Remove(tmp.Name())+ if err := tmp.Chmod(info.Mode().Perm()); err != nil {+ tmp.Close()+ return err+ }+ if _, err := tmp.Write(refreshed); err != nil {+ tmp.Close()+ return err+ }+ if err := tmp.Sync(); err != nil {+ tmp.Close()+ return err+ }+ if err := tmp.Close(); err != nil {+ return err+ }+ // Re-check right before the swap to keep the window with a concurrent+ // host refresh as small as possible.+ if current, err := readRunnerLoginFile(configDir, login.file); err != nil || !bytes.Equal(current, original) {+ return nil+ }+ return os.Rename(tmp.Name(), path)+}++// readRootLoginFile reads the login file below the isolated home through+// os.Root, so a symlink planted by the sandbox cannot point elsewhere.+func readRootLoginFile(dir *os.Root, name string) ([]byte, error) {+ const maxSize = 1 << 20+ info, err := dir.Lstat(name)+ if err != nil {+ return nil, err+ }+ if !info.Mode().IsRegular() || info.Size() > maxSize {+ return nil, fmt.Errorf("invalid login file")+ }+ file, err := dir.Open(name)+ if err != nil {+ return nil, err+ }+ defer file.Close()+ data, err := io.ReadAll(io.LimitReader(file, maxSize+1))+ if err != nil {+ return nil, err+ }+ if len(data) > maxSize || !json.Valid(data) {+ return nil, fmt.Errorf("invalid login file")+ }+ return data, nil+}++func sameRunnerLogin(original, refreshed []byte) bool {+ var before, after map[string]json.RawMessage+ if json.Unmarshal(original, &before) != nil || json.Unmarshal(refreshed, &after) != nil {+ return false+ }+ keys := func(m map[string]json.RawMessage) []string {+ out := make([]string, 0, len(m))+ for key := range m {+ out = append(out, key)+ }+ slices.Sort(out)+ return out+ }+ if !slices.Equal(keys(before), keys(after)) {+ return false+ }+ account := func(m map[string]json.RawMessage) string {+ var tokens struct {+ AccountID string `json:"account_id"`+ }+ _ = json.Unmarshal(m["tokens"], &tokens)+ return tokens.AccountID+ }+ return account(before) == account(after)+}diff --git a/internal/runtime/conversation_runner_login_refresh_test.go b/internal/runtime/conversation_runner_login_refresh_test.gonew file mode 100644index 00000000..3eeb1208--- /dev/null+++ b/internal/runtime/conversation_runner_login_refresh_test.go@@ -0,0 +1,163 @@+package runtime++import (+ "context"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++// A CLI that refreshes its rotating OAuth token inside the isolated home must+// not leave the Runner account with an invalidated refresh token: the cleanup+// writes the refreshed login back unless the host changed meanwhile or the+// refreshed file is a different account.+func TestRunnerLoginWritesBackRefreshedToken(t *testing.T) {+ const original = `{"auth_mode":"chatgpt","tokens":{"account_id":"acct-1","refresh_token":"r1"},"last_refresh":"2026-11-01"}`+ const refreshed = `{"auth_mode":"chatgpt","tokens":{"account_id":"acct-1","refresh_token":"r2"},"last_refresh":"2026-11-17"}`+ setup := func(t *testing.T) (conversationLoginSpec, string, string, func() error) {+ t.Helper()+ login, _ := runnerLoginSpec("codex")+ host := t.TempDir()+ t.Setenv(login.configEnv, host)+ if err := os.WriteFile(filepath.Join(host, login.file), []byte(original), 0o600); err != nil {+ t.Fatal(err)+ }+ root := t.TempDir()+ cleanup, _, err := prepareConversationRunnerLogin(root, login, true)+ if err != nil {+ t.Fatal(err)+ }+ return login, host, filepath.Join(root, "home", login.dir, login.file), cleanup+ }+ read := func(t *testing.T, path string) string {+ t.Helper()+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ return string(data)+ }++ t.Run("refreshed", func(t *testing.T) {+ login, host, copy, cleanup := setup(t)+ if err := os.WriteFile(copy, []byte(refreshed), 0o600); err != nil {+ t.Fatal(err)+ }+ if err := cleanup(); err != nil {+ t.Fatal(err)+ }+ if got := read(t, filepath.Join(host, login.file)); got != refreshed {+ t.Fatalf("host login = %s, want the refreshed one", got)+ }+ if info, _ := os.Stat(filepath.Join(host, login.file)); info.Mode().Perm() != 0o600 {+ t.Fatalf("host login mode = %v", info.Mode().Perm())+ }+ if _, err := os.Stat(copy); !os.IsNotExist(err) {+ t.Fatal("isolated copy was not removed")+ }+ entries, _ := os.ReadDir(host)+ if len(entries) != 1 {+ t.Fatalf("temporary files left in the host config dir: %v", entries)+ }+ })+ t.Run("unchanged", func(t *testing.T) {+ login, host, _, cleanup := setup(t)+ before, _ := os.Stat(filepath.Join(host, login.file))+ if err := cleanup(); err != nil {+ t.Fatal(err)+ }+ after, _ := os.Stat(filepath.Join(host, login.file))+ if !after.ModTime().Equal(before.ModTime()) || read(t, filepath.Join(host, login.file)) != original {+ t.Fatal("an unchanged login was rewritten")+ }+ })+ t.Run("host refreshed first", func(t *testing.T) {+ login, host, copy, cleanup := setup(t)+ const hostRefresh = `{"auth_mode":"chatgpt","tokens":{"account_id":"acct-1","refresh_token":"host"},"last_refresh":"2026-11-17"}`+ if err := os.WriteFile(filepath.Join(host, login.file), []byte(hostRefresh), 0o600); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(copy, []byte(refreshed), 0o600); err != nil {+ t.Fatal(err)+ }+ if err := cleanup(); err != nil {+ t.Fatal(err)+ }+ if got := read(t, filepath.Join(host, login.file)); got != hostRefresh {+ t.Fatalf("host login overwritten: %s", got)+ }+ })+ t.Run("other account", func(t *testing.T) {+ login, host, copy, cleanup := setup(t)+ if err := os.WriteFile(copy, []byte(`{"auth_mode":"chatgpt","tokens":{"account_id":"acct-evil","refresh_token":"x"},"last_refresh":"2026-11-17"}`), 0o600); err != nil {+ t.Fatal(err)+ }+ if err := cleanup(); err != nil {+ t.Fatal(err)+ }+ if got := read(t, filepath.Join(host, login.file)); got != original {+ t.Fatalf("another account was written back: %s", got)+ }+ })+ t.Run("symlink", func(t *testing.T) {+ login, host, copy, cleanup := setup(t)+ elsewhere := filepath.Join(t.TempDir(), "auth.json")+ if err := os.WriteFile(elsewhere, []byte(refreshed), 0o600); err != nil {+ t.Fatal(err)+ }+ if err := os.Remove(copy); err != nil {+ t.Fatal(err)+ }+ if err := os.Symlink(elsewhere, copy); err != nil {+ t.Fatal(err)+ }+ if err := cleanup(); err != nil {+ t.Fatal(err)+ }+ if got := read(t, filepath.Join(host, login.file)); got != original {+ t.Fatalf("a planted symlink was followed: %s", got)+ }+ })+}++// The conversation process pool (the Runner's path) keeps a login the CLI+// refreshed while it ran.+func TestConversationRunnerLoginKeepsRefreshThroughProcessPool(t *testing.T) {+ login, _ := runnerLoginSpec("codex")+ host := t.TempDir()+ t.Setenv(login.configEnv, host)+ t.Setenv("OPENAI_API_KEY", "")+ const original = `{"auth_mode":"chatgpt","tokens":{"account_id":"acct-1","refresh_token":"r1"}}`+ const refreshed = `{"auth_mode":"chatgpt","tokens":{"account_id":"acct-1","refresh_token":"r2"}}`+ if err := os.WriteFile(filepath.Join(host, login.file), []byte(original), 0o600); err != nil {+ t.Fatal(err)+ }+ root := t.TempDir()+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ pool := &ConversationProcessPool{}+ // Like Codex refreshing its token: rewrite auth.json in the isolated home.+ script := `set -eu; printf '%s' "$1" > "$CODEX_HOME/auth.json"; printf 'refreshed\n'`+ started, err := pool.Handle(ctx, root, "", nil, ConversationProcessRequest{Operation: "start", Command: &ConversationCommand{+ Argv: []string{"sh", "-c", script, "refresh", refreshed}, Provider: "codex",+ Bindings: []CredentialBinding{login.binding}, RunnerLogin: true,+ }}, nil)+ if err != nil {+ t.Fatal(err)+ }+ if got := conversationPoll(t, pool, ctx, root, started.ID); strings.TrimSpace(got) != "refreshed" {+ t.Fatalf("CLI output = %q", got)+ }+ if _, err := pool.Handle(ctx, root, "", nil, ConversationProcessRequest{Operation: "stop", ID: started.ID}, nil); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(filepath.Join(root, "home", login.dir, login.file)); !os.IsNotExist(err) {+ t.Fatalf("isolated copy was not removed: %v", err)+ }+ data, err := os.ReadFile(filepath.Join(host, login.file))+ if err != nil || string(data) != refreshed {+ t.Fatalf("host login = %s, %v; want the refreshed login", data, err)+ }+}diff --git a/internal/runtime/conversation_runner_login_test.go b/internal/runtime/conversation_runner_login_test.gonew file mode 100644index 00000000..7e88430d--- /dev/null+++ b/internal/runtime/conversation_runner_login_test.go@@ -0,0 +1,106 @@+package runtime++import (+ "context"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++func TestConversationRunnerLoginUsesOnlyNativeAuthInIsolatedHome(t *testing.T) {+ for _, provider := range []string{"codex", "claude-code"} {+ t.Run(provider, func(t *testing.T) {+ if provider == "codex" {+ if _, err := exec.LookPath("python3"); err != nil {+ t.Skip("python3 unavailable")+ }+ }+ login, _ := runnerLoginSpec(provider)+ host := t.TempDir()+ root := t.TempDir()+ t.Setenv(login.configEnv, host)+ t.Setenv("CLAUDE_CODE_OAUTH_TOKEN", "")+ t.Setenv("ANTHROPIC_API_KEY", "host-key")+ t.Setenv("OPENAI_API_KEY", "host-key")+ file := filepath.Join(host, login.file)+ if err := os.WriteFile(file, []byte("{}"), 0600); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(host, "settings.json"), []byte("host settings"), 0600); err != nil {+ t.Fatal(err)+ }+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ pool := &ConversationProcessPool{}+ script := `set -eu+test -f "$HOME/$1/$2"+test ! -e "$HOME/$1/settings.json"+test -z "${OPENAI_API_KEY:-}${CODEX_API_KEY:-}${ANTHROPIC_API_KEY:-}"+printf 'local-auth-ok\n'`+ req := ConversationProcessRequest{Operation: "start", Command: &ConversationCommand{+ Argv: []string{"sh", "-c", script, "runner-login", login.dir, login.file}, Provider: provider,+ Bindings: []CredentialBinding{login.binding}, RunnerLogin: true,+ Credentials: RunCredentials{Codex: ProviderCredential{APIKey: "personal"}, ClaudeCode: ProviderCredential{APIKey: "personal"}},+ }}+ started, err := pool.Handle(ctx, root, "", nil, req, nil)+ if err != nil {+ t.Fatal(err)+ }+ if got := conversationPoll(t, pool, ctx, root, started.ID); strings.TrimSpace(got) != "local-auth-ok" {+ t.Fatalf("isolated CLI did not see expected login state: %q", got)+ }+ if _, err := pool.Handle(ctx, root, "", nil, ConversationProcessRequest{Operation: "stop", ID: started.ID}, nil); err != nil {+ t.Fatal(err)+ }+ if _, err := os.Stat(filepath.Join(root, "home", login.dir, login.file)); !os.IsNotExist(err) {+ t.Fatalf("local credential copy was not removed: %v", err)+ }+ if data, err := os.ReadFile(file); err != nil || string(data) != "{}" {+ t.Fatal("native CLI login file changed")+ }+ stale := filepath.Join(root, "home", login.dir, login.file)+ if err := os.WriteFile(stale, []byte("{}"), 0600); err != nil {+ t.Fatal(err)+ }+ req.Command.RunnerLogin = false+ req.Command.Credentials = RunCredentials{}+ if _, err := pool.Handle(ctx, root, "", nil, req, nil); err == nil || !strings.Contains(err.Error(), "API Key") {+ t.Fatalf("personal mode fell back to runner login: %v", err)+ }+ if _, err := os.Stat(stale); !os.IsNotExist(err) {+ t.Fatal("personal mode retained a stale login file")+ }+ req.Command.RunnerLogin = true++ if err := os.Remove(file); err != nil {+ t.Fatal(err)+ }+ if _, err := pool.Handle(ctx, root, "", nil, req, nil); err == nil || !strings.Contains(err.Error(), "本机登录态不可用") {+ t.Fatalf("missing native login did not report a runner-specific error: %v", err)+ }+ })+ }+}++func TestConversationRunnerLoginSupportsClaudeOAuthEnvironment(t *testing.T) {+ root := t.TempDir()+ t.Setenv("CLAUDE_CONFIG_DIR", t.TempDir())+ t.Setenv("CLAUDE_CODE_OAUTH_TOKEN", "runner-fixture")+ req := ConversationProcessRequest{Operation: "start", Command: &ConversationCommand{+ Provider: "claude-code", Bindings: []CredentialBinding{BindClaudeCode}, RunnerLogin: true,+ Argv: []string{"sh", "-c", `test "$CLAUDE_CODE_OAUTH_TOKEN" = runner-fixture && test ! -e "$CLAUDE_CONFIG_DIR/.credentials.json" && printf 'ok\n'`},+ }}+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ pool := &ConversationProcessPool{}+ started, err := pool.Handle(ctx, root, "", nil, req, nil)+ if err != nil {+ t.Fatal(err)+ }+ if got := conversationPoll(t, pool, ctx, root, started.ID); strings.TrimSpace(got) != "ok" {+ t.Fatal("CLI did not use the Runner OAuth environment")+ }+}diff --git a/internal/runtime/workspace_checkpoint_transfer.go b/internal/runtime/workspace_checkpoint_transfer.goindex dad472b7..0e72d92e 100644--- a/internal/runtime/workspace_checkpoint_transfer.go+++ b/internal/runtime/workspace_checkpoint_transfer.go@@ -54,6 +54,12 @@ func WorkspaceCheckpointStatus(root string) domain.RunnerWorkspaceResponse {return domain.RunnerWorkspaceResponse{Status: 200, Payload: payload}}+func (p *CheckpointTransfers) Active() bool {+ p.mu.Lock()+ defer p.mu.Unlock()+ return len(p.items) != 0 || p.pending != 0+}+func (p *CheckpointTransfers) Sweep(now time.Time) {p.mu.Lock()defer p.mu.Unlock()diff --git a/internal/runtime/workspace_terminal.go b/internal/runtime/workspace_terminal.goindex 5670a613..8f763de2 100644--- a/internal/runtime/workspace_terminal.go+++ b/internal/runtime/workspace_terminal.go@@ -283,6 +283,12 @@ func (p *TerminalPool) CloseScope(scope string) {}}+func (p *TerminalPool) Active() bool {+ p.mu.Lock()+ defer p.mu.Unlock()+ return len(p.sessions) != 0+}+func (p *TerminalPool) HasScope(scope string) bool {p.mu.Lock()defer p.mu.Unlock()diff --git a/migrations/035_codebuddy_model_catalog.sql b/migrations/035_codebuddy_model_catalog.sqlnew file mode 100644index 00000000..e3fe668e--- /dev/null+++ b/migrations/035_codebuddy_model_catalog.sql@@ -0,0 +1,5 @@+-- Personal CodeBuddy model catalog, next to the Codex and Claude Code catalogs+-- from 027. Apply manually; startup AutoMigrate also adds this column. Empty+-- follows the models the CodeBuddy CLI publishes for the account.++ALTER TABLE user_configs ADD COLUMN codebuddy_models TEXT NULL;diff --git a/web/app/agents.js b/web/app/agents.jsindex b8db2ed0..1371913d 100644--- a/web/app/agents.js+++ b/web/app/agents.js@@ -119,16 +119,25 @@ function pickerHTML(items,selected,prefix){return `<input class="input picker-fifunction 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)?`<option value="${escapeHTML(selected)}" selected disabled>历史执行器 ${escapeHTML(selected)}(请重新选择 CLI)</option>`:'';return legacy+items.map(x=>`<option value="${escapeHTML(x.id)}" ${x.id===selected?'selected':''}>${escapeHTML(x.name||x.id)}</option>`).join('')}const AGENT_CUSTOM_MODEL='__custom__';-function executorModelCatalogs(){return window.AgentFlowExecutorModels||{}}-async function loadExecutorModelCatalogs(){- // 未登录时接口 401,失败结果不缓存:下次打开向导会重试。- const cached=window.AgentFlowExecutorModels;- if(cached&&Object.keys(cached).length)return cached;- try{- const data=await api('/api/executor-models',{silent:true});- if(data&&data.codebuddy&&data.codex&&data.claude)window.AgentFlowExecutorModels=data;- }catch{}- return executorModelCatalogs();+let executorModelCatalogUser, executorModelCatalogRequest, agentModelRevision=0;+function executorModelCatalogs(){+ return executorModelCatalogUser===state.currentUser?.id?(window.AgentFlowExecutorModels||{}):{};+}+function loadExecutorModelCatalogs(){+ const user=state.currentUser?.id;+ if(executorModelCatalogRequest&&executorModelCatalogRequest.user===user)return executorModelCatalogRequest.pending;+ if(executorModelCatalogUser!==user)window.AgentFlowExecutorModels=null;+ 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){+ window.AgentFlowExecutorModels=data;+ }+ }).catch(()=>{}).finally(()=>{+ if(executorModelCatalogRequest===request)executorModelCatalogRequest=null;+ });+ executorModelCatalogRequest=request;+ return request.pending;}function agentModelAPI(){return window.AgentFlowAssistantModels}function currentAgentExecutorId(){return $('#agentForm')?.elements?.executorId?.value||'codebuddy'}@@ -198,7 +207,7 @@ function applyAgentModelUI(executorId,model,effort){if(customInput&&choice===AGENT_CUSTOM_MODEL)customInput.value=model||'';renderAgentModelPicker();const efforts=cat.efforts||[];- $('#agentEffortPicker').querySelector('[name="effort"]').value=efforts.some(e=>e.value===effort)?(effort||''):'';+ $('#agentEffortPicker').querySelector('[name="effort"]').value=(!cat.efforts||efforts.some(e=>e.value===effort))?(effort||''):'';renderAgentEffortPicker();}function bindAgentPicker(pickerId,render){@@ -235,8 +244,19 @@ function selectAgent(a,rerender=true){['id','name','description'].forEach(k=>{if(f.elements[k])f.elements[k].value=a[k]||''});if(f.elements.shared)f.elements.shared.checked=!!a.shared;if(f.elements.executorId)f.elements.executorId.innerHTML=executorOptions(a.executorId||'codebuddy');- const paintAgentModel=()=>applyAgentModelUI(a.executorId||f.elements.executorId?.value||'codebuddy',a.model||'',a.effort||'');- paintAgentModel();loadExecutorModelCatalogs().then(paintAgentModel).catch(()=>{});+ const modelRevision=++agentModelRevision;+ const modelUser=state.currentUser?.id;+ applyAgentModelUI(currentAgentExecutorId(),a.model||'',a.effort||'');+ loadExecutorModelCatalogs().then(()=>{+ if(modelRevision!==agentModelRevision||modelUser!==state.currentUser?.id)return;+ const model=agentEffectiveModel(f);+ if(!model&&f.elements.modelChoice?.value===AGENT_CUSTOM_MODEL){+ renderAgentModelPicker();+ renderAgentEffortPicker();+ return;+ }+ applyAgentModelUI(currentAgentExecutorId(),model,f.elements.effort?.value);+ });if(f.elements.id)f.elements.id.readOnly=!!a.id;renderAgentPresets();renderAgentTaskBook(a);renderAgentGovernance(a);renderAgentAssetsPanel(a);renderAgentSummary();$('#agentVersion').textContent=`v${a.version||1}`;diff --git a/web/app/assistant-models.js b/web/app/assistant-models.jsindex 5d580664..4d7dbfec 100644--- a/web/app/assistant-models.js+++ b/web/app/assistant-models.js@@ -40,12 +40,12 @@}// engineOf names the CLI that runs a model: catalog entries carry it, and a// saved "codex:…" id that the viewer cannot list still keeps its prefix.- function engineOf(id) {- const listed = (catalog.models || []).find(m => m.id === id);+ function engineOf(id, source = catalog) {+ const listed = (source.models || []).find(m => m.id === id);if (listed) return listed.engine || 'codebuddy';const value = String(id || '');const prefix = value.slice(0, Math.max(0, value.indexOf(':')));- return (catalog.engines || []).some(e => e.id === prefix) ? prefix : 'codebuddy';+ return (source.engines || []).some(e => e.id === prefix) ? prefix : 'codebuddy';}function modelMeta(id) {return (catalog.models || []).find(m => m.id === id) || {id: id || DEFAULT_MODEL, family: familyOf(id), name: id || DEFAULT_MODEL};diff --git a/web/app/hui-select.js b/web/app/hui-select.jsindex 46876150..ad563a85 100644--- a/web/app/hui-select.js+++ b/web/app/hui-select.js@@ -52,7 +52,8 @@const above = rect.top - 12;const height = Math.min(panel.scrollHeight || 320, opts.maxHeight ?? 360);const down = below >= height || below >= above;- const left = Math.min(Math.max(8, rect.left), Math.max(8, viewportW - width - 8));+ const anchorLeft = opts.align === 'end' ? rect.right - width : rect.left;+ const left = Math.min(Math.max(8, anchorLeft), Math.max(8, viewportW - width - 8));panel.style.width = width + 'px';panel.style.left = Math.round(left) + 'px';panel.style.maxHeight = Math.max(120, Math.floor(down ? below : above)) + 'px';diff --git a/web/app/runners.js b/web/app/runners.jsindex 9f464dcd..b9d70c4c 100644--- a/web/app/runners.js+++ b/web/app/runners.js@@ -2,6 +2,10 @@ function openRunModal(workflowId){const select=$('#runWorkflowChoice'),workflows// ---------- 执行机器(bind-cli,个人维度) ----------let runnerRefreshTimer=null;+const runnerRuntimeTests=new Set();+const runnerAuthChanges=new Map();+const runnerMaintenancePending=new Set();+let runnerRuntimeMenu=null,runnerRuntimeTrigger=null;async function refreshRunners(silent){try{await ensureRunnerBindCode(silent);@@ -47,16 +51,21 @@ async function saveRunnerRunLimit(runnerId,raw){toast(value>0?`已设置:最多同时运行 ${value} 条`:'已设为不限','ok');renderRunnersView();}catch(err){toast(err.message);refreshRunners(true)}}-function runnerStatusLabel(status){- switch(status){- case 'online':return '<span class="runner-status online"><i></i>在线</span>';- case 'offline':return '<span class="runner-status offline"><i></i>离线</span>';- default:return `<span class="runner-status"><i></i>${escapeHTML(status||'unknown')}</span>`;- }+function runnerStatusLabel(status,lastSeen){+ const label=status==='online'?'在线':status==='offline'?'离线':(status||'未知');+ const style=status==='online'?' online':status==='offline'?' offline':'';+ return `<span class="runner-status${style}" title="${escapeHTML(runnerLastSeen(lastSeen))}"><i></i>${escapeHTML(label)}</span>`;}const runnerCLILabels={'claude-code':'Claude Code','codex':'Codex','codebuddy':'CodeBuddy',opencode:'OpenCode',cursor:'Cursor CLI',agy:'Antigravity',kimi:'Kimi Code',pi:'Pi',dsh:'DeepSeek Harness',zcode:'ZCode'};-const runnerCLIGlyphs={'claude-code':'C','codex':'X','codebuddy':'B',opencode:'O',cursor:'Cu',agy:'A',kimi:'K',pi:'P',dsh:'D',zcode:'Z'};+const runnerCLIIcons={'claude-code':'claude',codex:'codex',codebuddy:'codebuddy',opencode:'opencode',cursor:'cursor',agy:'gemini',kimi:'kimi',pi:'pi',dsh:'deepseek',zcode:'glm'};+const runnerAuthLabel={local:'账号登录',personal:'API Key'};+const runnerAuthDescription={local:'Claude Code 和 Codex 可以使用运行 Runner 的系统账号在这台机器上的已有登录。共享对话中,只有机器所有者发言时会使用此登录。',personal:'读取「个人配置」中保存的 API Key。对话使用当前发言人的 Key,SOP 使用运行责任人的 Key。'};const runnerOSLabels={darwin:'macOS',linux:'Linux',windows:'Windows'};+function runnerKeyDescription(provider){+ if(provider==='agy')return 'LoopForge 沙箱目前无法复用 Antigravity 保存在系统凭据库中的登录。请在「个人配置」中填写 Gemini API Key。用量按 Gemini API 单独计费。';+ if(provider==='zcode')return 'GLM Coding Plan 的 API Key 配合套餐专用地址可使用订阅额度,请在「个人配置」中填写。Start Plan 额度需要登录 ZCode 账号,无法通过 API Key 使用。';+ return '该 CLI 支持 API Key。使用服务商订阅套餐提供的 Key,执行用量会计入对应的套餐额度。请在「个人配置」中填写 API Key。';+}function runnerPersonalCredentialConfigured(provider){const user=userById(state.currentUser?.id)||{};if(provider==='codex')return !!user.codexApiKeyConfigured;@@ -64,15 +73,39 @@ function runnerPersonalCredentialConfigured(provider){if(provider==='codebuddy')return !!user.codeBuddyApiKeyConfigured;return !!user.agentCliCredentials?.[provider]?.apiKeyConfigured;}-// CodeBuddy on a runner always uses the personal API Key, so the card shows-// the same network environment as 个人配置 → CodeBuddy. An iOA key used with-// the wrong environment fails with 401 on the machine.-function runnerCodeBuddyAuthHTML(credentialReady){- if(!credentialReady)return '<span class="runner-auth-fixed missing" title="到个人配置补充 CodeBuddy API Key 并选择网络环境">个人凭证(未配置)</span>';- const user=userById(state.currentUser?.id)||{};- const raw=String(user.codeBuddyInternetEnvironment||'').trim(),env=codeBuddyEnvironment(raw);- if(!env)return `<span class="runner-auth-fixed missing" title="网络环境「${escapeHTML(raw)}」无法识别,CodeBuddy 会按国际站连接。到个人配置重新选择网络环境">个人凭证 · 网络环境无法识别</span>`;- return `<span class="runner-auth-fixed" title="CodeBuddy 使用个人配置中保存的 API Key,网络环境:${escapeHTML(env.label)}">个人凭证 · ${escapeHTML(env.label)}</span>`;+function runnerRuntimeSupportsLogin(runtime){+ return runtime.provider==='codex'||runtime.provider==='claude-code';+}+function runnerRuntimeAuthMode(runtime){+ return runnerRuntimeSupportsLogin(runtime)&&runtime.authMode!=='personal'?'local':'personal';+}+function runnerAuthHTML(runtime,key,busy,shared){+ const supportsLogin=runnerRuntimeSupportsLogin(runtime);+ const mode=runnerAuthChanges.get(key)||runnerRuntimeAuthMode(runtime);+ const missing=mode==='personal'&&!runnerPersonalCredentialConfigured(runtime.provider);+ const title=missing?' title="请在个人配置中填写 API Key"':'';+ if(!shared&&supportsLogin)return `<select class="runner-auth-select${mode==='personal'?' is-personal':''}" data-runner-auth="${escapeHTML(key)}" aria-label="${runnerCLILabels[runtime.provider]} 认证方式"${title} ${busy?'disabled':''}>+ <option value="local" ${mode==='local'?'selected':''}>${runnerAuthLabel.local}</option>+ <option value="personal" ${mode==='personal'?'selected':''}>${runnerAuthLabel.personal}</option>+ </select>`;+ const keyHelp=supportsLogin?'':`<button class="runner-auth-tip" type="button" data-runner-key-help="${runtime.provider}" aria-label="${runnerCLILabels[runtime.provider]} API Key 说明" aria-haspopup="dialog" title="${escapeHTML(runnerKeyDescription(runtime.provider))}"><span aria-hidden="true">?</span></button>`;+ return `<span class="runner-auth-fixed"${title}><span>${runnerAuthLabel[mode]}</span>${keyHelp}</span>`;+}+function runnerRuntimeHTML(runner,runtime,shared){+ const provider=runtime.provider,label=runnerCLILabels[provider];+ const key=`${runner.id}|${provider}`,safeKey=escapeHTML(key);+ const testing=runnerRuntimeTests.has(key),updating=runnerMaintenancePending.has(key);+ const busy=testing||updating||runnerAuthChanges.has(key);+ const disabled=runtime.status==='disabled';+ return `<div class="runner-runtime-row ${disabled?'off':''}">+ <label class="runner-runtime-label">+ <input type="checkbox" data-runner-cli="${safeKey}" ${disabled?'':'checked'} ${shared?'disabled':''} aria-label="启用 ${label}">+ <span class="runner-runtime-icon ${provider}" aria-hidden="true"><img src="/images/credentials/${runnerCLIIcons[provider]}.svg" alt=""></span>+ <span class="runner-runtime-name"><b>${label}</b><small title="${escapeHTML(runtime.binaryPath||'')}">${escapeHTML(runtime.version||runtime.binaryPath||'已发现')}</small></span>+ </label>+ ${runnerAuthHTML(runtime,key,busy,shared)}+ ${shared?'':`<button class="runner-more" type="button" data-runner-runtime-menu="${safeKey}" aria-label="${label} 更多操作" aria-haspopup="menu" aria-expanded="false" aria-busy="${testing||updating}">${huiIcon(testing||updating?'arc-spinner':'more-horizontal')}</button>`}+ </div>`;}function runnerLastSeen(value){if(!value)return '尚无心跳';@@ -81,10 +114,6 @@ function runnerLastSeen(value){if(seconds<3600)return `${Math.floor(seconds/60)} 分钟前`;return new Date(value).toLocaleString();}-function runnerLastSeenHTML(value){- if(!value)return runnerLastSeen(value);- return `<span title="${escapeHTML(new Date(value).toLocaleString())}">${escapeHTML(runnerLastSeen(value))}</span>`;-}function runnerCopyCommand(btn,text,message){const done=()=>{toast(message,'ok');@@ -134,37 +163,31 @@ function renderRunnersView(){}poolStatus.textContent=text;poolStatus.classList.toggle('warn',warn);}+ const focusedMenu=document.activeElement?.dataset.runnerRuntimeMenu;+ const focusedUpdate=document.activeElement?.dataset.runnerCheckUpdate;+ closeRunnerRuntimeMenu();list.innerHTML=runners.map(r=>{const isDefault=r.id===defaultId;const discoveredCLIs=(r.runtimes||[]).filter(rt=>runnerCLILabels[rt.provider]);- const cliRows=discoveredCLIs.map(rt=>{- const authMode=rt.authMode||(rt.provider==='codebuddy'?'personal':'local');- const credentialReady=runnerPersonalCredentialConfigured(rt.provider);- const personalLabel=credentialReady?'个人凭证':'个人凭证(未配置)';- const credentialMissing=authMode==='personal'&&!credentialReady;- const authControl=rt.provider==='codebuddy'- ?runnerCodeBuddyAuthHTML(credentialReady)- :`<select class="runner-auth-select ${credentialMissing?'missing':''}" data-runner-auth="${escapeHTML(r.id)}|${escapeHTML(rt.provider)}" aria-label="${runnerCLILabels[rt.provider]} 认证来源"${credentialMissing?` title="到个人配置补充 ${runnerCLILabels[rt.provider]} API Key"`:''}>- <option value="local" ${authMode==='local'?'selected':''}>本机登录</option>- <option value="personal" ${authMode==='personal'?'selected':''}>${personalLabel}</option>- </select>`;- return `- <label class="runner-runtime-row ${rt.status==='disabled'?'off':''}">- <input type="checkbox" data-runner-cli="${escapeHTML(r.id)}|${escapeHTML(rt.provider)}" ${rt.status!=='disabled'?'checked':''}>- <span class="runner-runtime-icon ${escapeHTML(rt.provider)}" aria-hidden="true">${runnerCLIGlyphs[rt.provider]||'?'}</span>- <span class="runner-runtime-name"><b>${runnerCLILabels[rt.provider]}</b><small title="${escapeHTML(rt.binaryPath||'')}">${escapeHTML(rt.version||rt.binaryPath||'已发现')}</small></span>- ${authControl}- </label>`}).join('');- const cliSection=cliRows||'<div class="runner-runtime-empty">未发现支持的 Agent CLI</div>';const shared=!(Number(r.ownerUserId)>0);+ const cliRows=discoveredCLIs.map(rt=>runnerRuntimeHTML(r,rt,shared)).join('');+ const cliSection=cliRows||'<div class="runner-runtime-empty">未发现支持的 Agent CLI</div>';const osLabel=runnerOSLabels[r.os]||r.os||'?';const defaultBlocker=isDefault?'':runnerDefaultBlocker(r);+ const checking=runnerMaintenancePending.has(r.id);return `<article class="runner-card panel ${isDefault?'is-default':''}"><div class="runner-card-head">- <div class="runner-card-title"><div class="runner-card-name"><b title="${escapeHTML(r.id)}">${escapeHTML(r.name||r.id)}</b>${isDefault?'<span class="runner-tag default">默认</span>':''}${shared?'<span class="runner-tag">共享</span>':''}</div><small>${escapeHTML(osLabel)} · ${escapeHTML(r.arch||'?')} · Runner ${escapeHTML(r.runnerVersion||'未知')} · ${runnerLastSeenHTML(r.lastSeenAt)}</small></div>- ${runnerStatusLabel(r.status)}+ <span class="runner-machine-icon" aria-hidden="true">${huiIcon('monitor')}</span>+ <div class="runner-card-title">+ <div class="runner-card-name"><b title="${escapeHTML(r.name||r.id)}">${escapeHTML(r.name||r.id)}</b>${isDefault?'<span class="runner-tag default">默认</span>':''}${shared?'<span class="runner-tag">共享</span>':''}</div>+ <small>${escapeHTML(osLabel)} · ${escapeHTML(r.arch||'?')} · Runner ${escapeHTML(r.runnerVersion||'未知')}</small>+ </div>+ <div class="runner-head-actions">${runnerStatusLabel(r.status,r.lastSeenAt)}${shared?'':`<button class="button ghost runner-check-update" type="button" data-runner-check-update="${escapeHTML(r.id)}" ${r.status!=='online'?'disabled':checking?'aria-disabled="true"':''}>${huiIcon(checking?'arc-spinner':'refresh')}${checking?'处理中…':'检查更新'}</button>`}</div>+ </div>+ <div class="runner-runtime-list">+ ${cliRows?`<div class="runner-runtime-heading"><span>CLI</span><button class="runner-auth-help" type="button" data-runner-auth-help aria-label="模型认证说明" aria-haspopup="dialog">模型认证 ${huiIcon('info')}</button></div>`:''}+ ${cliSection}</div>- <div class="runner-runtime-list">${cliSection}</div><div class="runner-card-action">${runnerRunLimitHTML(r)}<span class="runner-card-spacer"></span>@@ -192,7 +215,30 @@ function renderRunnersView(){const [runnerId,provider]=select.dataset.runnerAuth.split('|');setRunnerRuntimeAuth(runnerId,provider,select.value);});- if(!runnerRefreshTimer)runnerRefreshTimer=setInterval(()=>{if(!document.hidden&&activeViewName()==='runners'&&!document.activeElement?.matches?.('[data-runner-run-limit]'))refreshRunners(true)},15000);+ list.querySelectorAll('[data-runner-auth-help]').forEach(btn=>btn.onclick=()=>afAlert({+ title:'模型认证方式',+ message:`${runnerAuthLabel.local}\n${runnerAuthDescription.local}\n\n${runnerAuthLabel.personal}\n${runnerAuthDescription.personal}`+ }));+ list.querySelectorAll('[data-runner-key-help]').forEach(btn=>btn.onclick=()=>{+ const provider=btn.dataset.runnerKeyHelp;+ return afAlert({+ title:`${runnerCLILabels[provider]} API Key 说明`,+ message:runnerKeyDescription(provider)+ });+ });+ list.querySelectorAll('[data-runner-runtime-menu]').forEach(btn=>{+ btn.onclick=()=>showRunnerRuntimeMenu(btn);+ btn.onkeydown=e=>{if(e.key==='ArrowDown'||e.key==='ArrowUp'){e.preventDefault();showRunnerRuntimeMenu(btn,e.key==='ArrowUp')}};+ if(btn.dataset.runnerRuntimeMenu===focusedMenu)btn.focus({preventScroll:true});+ });+ list.querySelectorAll('[data-runner-check-update]').forEach(btn=>{+ btn.onclick=()=>checkRunnerUpdate(btn.dataset.runnerCheckUpdate);+ if(!btn.disabled&&btn.dataset.runnerCheckUpdate===focusedUpdate)btn.focus({preventScroll:true});+ });+ window.AgentFlowHarnessIcons?.hydrate?.(list);+ if(!runnerRefreshTimer)runnerRefreshTimer=setInterval(()=>{+ if(!document.hidden&&activeViewName()==='runners'&&!runnerRuntimeTrigger&&!document.activeElement?.matches?.('[data-runner-run-limit],[data-runner-auth],[data-runner-key-help]'))refreshRunners(true);+ },15000);}async function removeRunner(runnerId){const runner=(state.runners||[]).find(r=>r.id===runnerId);@@ -234,9 +280,240 @@ async function runnerRuntimeRequest(runnerId,provider,status){}catch(err){toast(err.message);refreshRunners(true)}}async function setRunnerRuntimeAuth(runnerId,provider,authMode){+ const key=`${runnerId}|${provider}`;+ runnerAuthChanges.set(key,authMode);+ renderRunnersView();try{await api('/api/runners/runtimes',{method:'PUT',body:JSON.stringify({runnerId,provider,authMode})});const ready=runnerPersonalCredentialConfigured(provider);- toast(authMode==='personal'?(ready?'将使用个人配置中的 API 凭证':'已切换;请先到个人配置补充该 CLI 的 API Key'):'将使用执行机器上的 CLI 登录态',ready||authMode!=='personal'?'ok':undefined);refreshRunners(true);- }catch(err){toast(err.message);refreshRunners(true)}+ toast(authMode==='personal'?(ready?'将使用「个人配置」中的 API Key':'已切换,请先到「个人配置」补充该 CLI 的 API Key'):'将使用这台机器上已登录的 CLI 账号',ready||authMode!=='personal'?'ok':undefined);+ }catch(err){toast(err.message,'err')}+ finally{+ await refreshRunners(true);+ runnerAuthChanges.delete(key);+ renderRunnersView();+ }+}+async function testRunnerRuntime(runnerId,provider){+ const key=`${runnerId}|${provider}`;+ if(runnerRuntimeTests.has(key)||runnerAuthChanges.has(key))return;+ runnerRuntimeTests.add(key);+ renderRunnersView();+ try{+ await api('/api/runners/runtimes/test',{method:'POST',silent:true,body:JSON.stringify({runnerId,provider})});+ toast(`${runnerCLILabels[provider]} 测试通过`,'ok');+ }catch(err){toast(`${runnerCLILabels[provider]}:${err.message}`,'err',5000)}+ finally{+ runnerRuntimeTests.delete(key);+ renderRunnersView();+ }+}++function closeRunnerRuntimeMenu(restoreFocus=false){+ if(!runnerRuntimeTrigger)return;+ const trigger=runnerRuntimeTrigger;+ runnerRuntimeTrigger=null;+ runnerRuntimeMenu.hidden=true;+ trigger.setAttribute('aria-expanded','false');+ window.HuiPopover?.release(closeRunnerRuntimeMenu);+ if(restoreFocus&&trigger.isConnected)trigger.focus({preventScroll:true});+}+function showRunnerRuntimeMenu(trigger,last=false){+ if(runnerRuntimeTrigger===trigger)return closeRunnerRuntimeMenu(true);+ closeRunnerRuntimeMenu();+ const [id,provider]=trigger.dataset.runnerRuntimeMenu.split('|'),key=trigger.dataset.runnerRuntimeMenu;+ const runner=(state.runners||[]).find(item=>item.id===id);+ const runtime=runner?.runtimes?.find(item=>item.provider===provider);+ if(!runtime)return;+ if(!runnerRuntimeMenu){+ runnerRuntimeMenu=document.createElement('div');+ runnerRuntimeMenu.className='issue-action-popover runner-runtime-menu';+ runnerRuntimeMenu.setAttribute('role','menu');+ document.body.appendChild(runnerRuntimeMenu);+ }+ const menu=runnerRuntimeMenu;+ const testBusy=runnerRuntimeTests.has(key),updateBusy=runnerMaintenancePending.has(key);+ const actions=[+ {label:testBusy?'测试中…':'测试',icon:'flask',disabled:testBusy||runnerAuthChanges.has(key)||runner.status!=='online'||runtime.status==='disabled',run:()=>testRunnerRuntime(id,provider)},+ {label:updateBusy?'更新中…':'更新',icon:'download',disabled:updateBusy||runner.status!=='online',run:()=>updateRunnerCLI(runner,runtime)},+ {label:'模型列表',icon:'layers',disabled:runnerAuthChanges.has(key),run:()=>showRunnerModels(runner,runtime)}+ ];+ menu.innerHTML=actions.map((action,index)=>`<button type="button" role="menuitem" tabindex="-1" class="issue-popover-item" data-action="${index}" ${action.disabled?'disabled':''}>${huiIcon(action.icon)}${action.label}</button>`).join('');+ menu.setAttribute('aria-label',`${runnerCLILabels[provider]} 更多操作`);+ menu.hidden=false;+ runnerRuntimeTrigger=trigger;+ trigger.setAttribute('aria-expanded','true');+ const enabled=[...menu.querySelectorAll('button:not(:disabled)')];+ menu.onclick=e=>{+ const item=e.target.closest('[data-action]');+ if(!item||item.disabled)return;+ closeRunnerRuntimeMenu(true);+ actions[Number(item.dataset.action)].run();+ };+ menu.onkeydown=e=>{+ const at=enabled.indexOf(document.activeElement),step=e.key==='ArrowUp'?-1:1;+ if(e.key==='Escape'){e.preventDefault();e.stopPropagation();closeRunnerRuntimeMenu(true)}+ else if(e.key==='Tab'){closeRunnerRuntimeMenu(true)}+ else if(e.key==='ArrowDown'||e.key==='ArrowUp'){+ e.preventDefault();enabled[(at+step+enabled.length)%enabled.length]?.focus();+ }else if(e.key==='Home'||e.key==='End'){+ e.preventDefault();enabled[e.key==='Home'?0:enabled.length-1]?.focus();+ }+ };+ window.HuiPopover?.claim(closeRunnerRuntimeMenu,target=>menu.contains(target)||trigger.contains(target));+ window.HuiPopover?.place(trigger,menu,{width:166,align:'end'});+ window.AgentFlowHarnessIcons?.hydrate?.(menu);+ (last?enabled.at(-1):enabled[0])?.focus({preventScroll:true});+}+function showRunnerModels(runner,runtime){+ const provider=runtime.provider,local=runnerRuntimeAuthMode(runtime)==='local';+ const kind=CREDENTIAL_KINDS.find(item=>item.models?.engine===provider);+ if(!kind)return;+ return afOpenDialog(modal=>{+ $('#confirmTitle').textContent=`${runnerCLILabels[provider]} 模型列表`;+ const keySource=kind.extra?.url?'API Key 和服务地址':kind.extra?'API Key 和网络环境':'API Key';+ $('#confirmMessage').textContent=local+ ?'与个人配置共用模型目录。获取时使用这台机器的账号登录。'+ :`与个人配置共用模型目录。获取时使用个人配置里的 ${keySource}。`;+ const ok=$('#confirmOkBtn'),cancel=$('#confirmCancelBtn'),card=modal.querySelector('.confirm-modal-card');+ const panel=document.createElement('div');+ panel.className='credential-panel runner-model-editor';+ panel.dataset.credentialRow=kind.key;+ panel.innerHTML=credentialCatalogHTML(kind,credentialUser(),{runnerLogin:local,label:local?'账号登录':'API Key'});+ modal.querySelector('.confirm-modal-footer').before(panel);+ card.classList.add('runner-model-card');+ const catalog=panel.querySelector('[data-credential-catalog]');+ if(local){+ catalog.probeModels=()=>api(`/api/runners/${encodeURIComponent(runner.id)}/models/probe`,{+ method:'POST',body:JSON.stringify({provider}),silent:true+ });+ }+ ok.textContent='保存';ok.className='button primary';ok.disabled=true;+ cancel.textContent='取消';+ setConfirmIcon('info','layers');+ let saving=false;+ const syncSave=()=>{if(!saving)ok.disabled=!credentialCatalogDirty(catalog)};+ catalog.onCatalogChange=syncSave;+ catalog.oninput=event=>{+ if(event.target.closest('[data-catalog-probe]'))return syncCredentialCatalogProbe(catalog);+ event.target.closest('.credential-input')?.classList.remove('is-bad');+ syncSave();+ };+ catalog.onclick=event=>{+ const button=event.target.closest('[data-catalog-act]');+ if(button&&!button.disabled)credentialCatalogAction(button.dataset.catalogAct,panel,catalog,button);+ };+ catalog.onpointerdown=event=>{+ const grip=event.target.closest('[data-catalog-grip]');+ if(grip)startCredentialCatalogDrag(event,grip);+ };+ catalog.onkeydown=event=>{+ credentialCatalogKeydown(event);+ if(event.key==='Enter'&&event.target.tagName==='INPUT'){+ event.preventDefault();+ event.stopPropagation();+ if(event.target.matches('[data-catalog-field]')&&!ok.disabled)ok.click();+ }+ };+ const submit=async event=>{+ event.stopImmediatePropagation();+ if(saving)return;+ const models=credentialCatalogPayload(catalog);+ if(!models||!validateCredentialCatalog(catalog,models))return;+ saving=true;+ ok.disabled=true;+ cancel.disabled=true;+ ok.textContent='保存中…';+ catalog.inert=true;+ try{+ await saveCredential(kind.key,{models});+ toast('模型列表已保存','ok');+ if(panel.isConnected)confirmPromiseResolve?.(true);+ }catch(err){+ if(panel.isConnected){+ toast(err.message,'err');+ ok.textContent='保存';ok.disabled=false;cancel.disabled=false;catalog.inert=false;+ }+ }finally{saving=false}+ };+ hydrateCredentialIcons(panel);+ ok.addEventListener('click',submit,true);+ return {focus:catalog.querySelector('[data-catalog-act="probe"]'),value:()=>{+ ok.removeEventListener('click',submit,true);+ ok.disabled=false;cancel.disabled=false;+ panel.remove();+ card.classList.remove('runner-model-card');+ }};+ });+}+function runnerMaintenancePath(id,provider,status=false){+ const params=new URLSearchParams();+ if(provider)params.set('provider',provider);+ if(status)params.set('status','1');+ return `/api/runners/${encodeURIComponent(id)}/maintenance${params.size?'?'+params.toString():''}`;+}+async function checkRunnerUpdate(id){+ if(runnerMaintenancePending.has(id))return;+ runnerMaintenancePending.add(id);+ renderRunnersView();+ try{+ const result=await api(runnerMaintenancePath(id),{silent:true});+ if(result.status==='updating'||result.status==='restarting'){+ await followRunnerUpdate(id);+ }else if(result.status==='available'&&result.canUpdate){+ const confirmed=await afConfirm({title:'Runner 有可用更新',message:`当前版本 ${result.current||'未知'}。更新会重启空闲的 Runner。`,confirmText:'立即更新',info:true});+ if(confirmed){+ await api(runnerMaintenancePath(id),{method:'POST',silent:true});+ await followRunnerUpdate(id);+ }+ }else if(result.status==='current'){+ toast(`Runner ${result.current||''} 已是平台当前版本`.replace(' ',' '),'ok');+ }else{+ toast(result.message||'暂时无法检查更新','err',5000);+ }+ }catch(err){toast(err.message,'err',5000)}+ finally{+ runnerMaintenancePending.delete(id);+ renderRunnersView();+ }+}+async function updateRunnerCLI(runner,runtime){+ const id=runner.id,provider=runtime.provider,label=runnerCLILabels[provider],key=`${id}|${provider}`;+ if(!runtime.capabilities?.some(capability=>capability==='native_update'||capability==='managed_update')){+ await afAlert({title:`更新 ${label}`,message:'请在这台执行机器上使用原来的安装方式更新。更新后刷新机器列表即可看到版本。'});+ return;+ }+ if(runnerMaintenancePending.has(key))return;+ runnerMaintenancePending.add(key);+ renderRunnersView();+ try{+ await api(runnerMaintenancePath(id,provider),{method:'POST',silent:true});+ await followRunnerUpdate(id,provider);+ }catch(err){toast(err.message,'err',5000)}+ finally{+ runnerMaintenancePending.delete(key);+ renderRunnersView();+ }+}+async function followRunnerUpdate(id,provider){+ const label=provider?runnerCLILabels[provider]:'Runner';+ const deadline=Date.now()+(provider?45:8)*60000;+ while(Date.now()<deadline){+ await new Promise(resolve=>setTimeout(resolve,3000));+ const result=await api(runnerMaintenancePath(id,provider,true),{silent:true}).catch(()=>null);+ if(!result||result.status==='updating'||result.status==='restarting')continue;+ if(result.status==='current'||result.status==='updated'){+ const version=result.version||result.current;+ toast(`${label}${version?' '+version:''} 已就绪`,'ok');+ await refreshRunners(true);+ }else if(provider&&result.status==='manual'){+ await afAlert({title:`更新 ${label}`,message:result.message||'请在执行机器上使用该 CLI 原来的安装方式更新'});+ }else if(result.status==='ready'){+ toast(`${label} 更新状态已中断,请刷新确认版本`,'err',5000);+ }else{+ toast(result.message||`${label} 还有可用更新,请再次检查`,result.status==='failed'?'err':'info',5000);+ }+ return;+ }+ toast(`等待 ${label} 更新超时,请稍后检查版本`,'err',5000);}diff --git a/web/app/sync-schedule.js b/web/app/sync-schedule.jsindex 6f07377b..e24d844f 100644--- a/web/app/sync-schedule.js+++ b/web/app/sync-schedule.js@@ -152,24 +152,28 @@ function bindClarifyModelPicker(host){// 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// modal's scroll area cannot clip it, and opens toward the side with room.+let scheduleCatalog=null;+function scheduleModelCatalog(){+ return scheduleCatalog||scheduleModelAPI()?.catalog?.()||{};+}function scheduleEngineModels(engine){- return (scheduleModelAPI()?.catalog?.().models||[]).filter(m=>(m.engine||'codebuddy')===engine);+ return (scheduleModelCatalog().models||[]).filter(m=>(m.engine||'codebuddy')===engine);}function scheduleModelEngine(id){- return scheduleModelAPI()?.engineOf?.(id)||'codebuddy';+ return scheduleModelAPI()?.engineOf?.(id,scheduleModelCatalog())||'codebuddy';}function paintScheduleEngines(selected){const select=$('#scheduleEngine');if(!select)return;const current=scheduleModelEngine(selected);- const engines=scheduleModelAPI()?.catalog?.().engines||[];+ 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});- // A CLI without listed models has no key in this account; a saved task+ // A CLI without listed models lacks credentials in this account. A saved task// keeps its CLI selectable so editing it does not move it elsewhere.select.replaceChildren(...list.map(e=>{const usable=e.id===current||scheduleEngineModels(e.id).length>0;- const option=new Option(usable?e.name:`${e.name}(未配置 Key)`,e.id);+ const option=new Option(usable?e.name:`${e.name}(缺少凭据)`,e.id);option.disabled=!usable;return option;}));@@ -224,7 +228,7 @@ function bindScheduleModelPicker(){if(engine)engine.onchange=()=>{const api=scheduleModelAPI();const models=scheduleEngineModels(engine.value);- const fallback=engine.value==='codebuddy'?(api?.catalog?.().default||api?.DEFAULT):'';+ const fallback=engine.value==='codebuddy'?(scheduleModelCatalog().default||api?.DEFAULT):'';const next=models.some(m=>m.id===fallback)?fallback:models[0]?.id;if(next)paintScheduleModel(next);};@@ -235,20 +239,27 @@ function bindScheduleModelPicker(){window.addEventListener('resize',closeScheduleModelMenu);}async function loadScheduleModels(){- const api=scheduleModelAPI();- if(!api)return;- try{await api.load()}catch{}- paintScheduleModel($('#scheduleJobForm')?.elements.assistantModel.value||api.DEFAULT);+ const picker=scheduleModelAPI();+ if(!picker)return;+ try{+ scheduleCatalog=await api('/api/assistant/models?schedule=1',{silent:true});+ }catch{+ scheduleCatalog=await picker.load();+ }+ paintScheduleModel($('#scheduleJobForm')?.elements.assistantModel.value||picker.DEFAULT);}function paintScheduleModel(selected){const api=scheduleModelAPI();const host=$('#scheduleModelPicker');const f=$('#scheduleJobForm');if(!api||!host||!f)return;- const catalog=api.catalog?.()||{};+ const catalog=scheduleModelCatalog();const keep=selected||f.elements.assistantModel.value||catalog.default||api.DEFAULT;f.elements.assistantModel.value=keep;- api.paint(host.querySelector('[data-model-toggle]'), keep);+ const toggle=host.querySelector('[data-model-toggle]');+ const item=catalog.models?.find(model=>model.id===keep);+ if(item)api.paintItem(toggle,item);+ else api.paint(toggle,keep);paintScheduleEngines(keep);}function syncScheduleJobTiming(){@@ -275,7 +286,7 @@ function syncScheduleJobKind(){f.elements.name.required=kind==='assistant';const assistant=kind==='assistant';$('#scheduleModalTitle').textContent=assistant?'AI 定时任务':'触发配置';- $('#scheduleModalHint').textContent=assistant?'按计划用保存人的 Key 在所选 CLI 上执行提示词(没有个人 CodeBuddy Key 时用平台共享 Key),使用与主页 AI 对话相同的完全权限,可调用 SOP、平台工具、工作区及浏览器。':'按计划扫描本项目选定状态、尚未跑过 SOP 的需求,通过基线门禁后派发 SOP。基线冲突会先由对齐 Agent 解决并合入,期间暂停派发。';+ $('#scheduleModalHint').textContent=assistant?'按计划以保存人的身份和完全权限执行提示词,可调用 SOP、平台工具、工作区及浏览器。':'按计划扫描本项目选定状态、尚未跑过 SOP 的需求,通过基线门禁后派发 SOP。基线冲突会先由对齐 Agent 解决并合入,期间暂停派发。';$('#scheduleModal').querySelector('.schedule-head').hidden=assistant;$('#scheduleJobList').hidden=assistant||!projectTriggerJob();f.querySelector('[type="submit"]').textContent=assistant?'保存 AI 定时任务':'保存触发配置';@@ -455,7 +466,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?'使用最后保存任务的人在所选 CLI 上的 Key(没有个人 CodeBuddy Key 时用平台共享 Key,仅限管理员允许的模型),以完全权限执行,与主页 AI 对话相同。可调用 SOP、工作区及浏览器工具;关闭页面不会中断执行。':disabled;+ $('#aiScheduleRuntimeHint').textContent=!state.projectFilter?'请先在顶栏选择项目,再管理 AI 定时任务。':canRun?'以最后保存任务的人的身份和完全权限执行。默认执行机器离线时使用该用户的 API Key。CodeBuddy 缺少个人 Key 时可使用平台共享 Key。关闭页面不会中断执行。':disabled;$('#aiScheduleProjectName').textContent=currentProject()?.name||'当前项目';$('#aiScheduleCount').textContent=`${assistant.length} 个任务`;$('#newAISchedule').disabled=!state.projectFilter;diff --git a/web/app/workbench.js b/web/app/workbench.jsindex b2c7b93f..eea4f23c 100644--- a/web/app/workbench.js+++ b/web/app/workbench.js@@ -70,6 +70,7 @@ const CREDENTIAL_KINDS=[guide:[['先在下方选择 CodeBuddy 账号所在的网络环境:国际站、国内站或 iOA'],['登录该站点的 API Key 页面,新建 API Key',codeBuddyKeyURL,codeBuddyKeyLinkLabel],['复制以 <code>ck_</code> 开头的密钥粘贴到下方;DeepSeek、OpenAI 等第三方模型的 Key 不能填在这里']],placeholder:'请输入个人 ck_ key',extra:{name:'codeBuddyInternetEnvironment',label:'网络环境',options:CODEBUDDY_ENVIRONMENTS},+ models:{name:'codeBuddyModels',engine:'codebuddy'},impact:'AI 对话将只能使用默认模型,CodeBuddy 执行器节点会失败。'},{key:'codexApiKey',group:'model',name:'Codex',short:'Codex API Key',logo:'codex',monochrome:true,use:'AI 对话选择 Codex 执行器,以及以 Codex 运行的 SOP 节点',@@ -90,14 +91,14 @@ const CREDENTIAL_KINDS=[agentCliCredentialKind('opencode',{name:'OpenCode',logo:'opencode',baseUrl:'https://api.example.com/v1',required:()=>true,note:'OpenCode 没有自己的模型服务,需要填写 Base URL。',protocols:[['chat','Chat Completions'],['responses','Responses'],['messages','Messages(Anthropic)']]}),agentCliCredentialKind('cursor',{name:'Cursor CLI',logo:'cursor',monochrome:true,- note:'Cursor CLI 只连接 Cursor 官方服务,使用 Cursor 自带的模型。',+ note:'Cursor CLI 连接 Cursor 官方服务,可按账号获取模型。',guide:[['登录 Cursor 控制台,在「Integrations → User API Keys」新建 Key','https://cursor.com/dashboard?tab=integrations','前往 Cursor 创建 API Key'],['复制以 <code>crsr_</code> 开头的 Key'],['粘贴到下方保存']]}),agentCliCredentialKind('agy',{name:'Antigravity',logo:'gemini',baseUrl:'https://gateway.example.com/v1',required:protocol=>protocol==='chat',note:'默认连接 Gemini 官方服务;选择 OpenAI 兼容网关时需要填写 Base URL。',extraNote:'OpenAI 兼容网关必填',guide:[['在 Google AI Studio 创建 Gemini API Key,或准备 OpenAI 兼容网关的 Key','https://aistudio.google.com/apikey','前往 Google AI Studio'],['走网关时记下网关地址'],['粘贴 Key,选择协议;保存后可在模型目录里挑选 AI 对话的模型']],protocols:[['gemini','Gemini 官方 API'],['chat','OpenAI 兼容网关(Chat Completions)']]}),- agentCliCredentialKind('kimi',{name:'Kimi Code',logo:'kimi',baseUrl:'https://api.moonshot.cn/v1',- note:'未填写 Base URL 时连接 Moonshot 官方服务。',protocols:[['chat','Chat Completions'],['responses','Responses'],['messages','Messages(Anthropic)']]}),+ agentCliCredentialKind('kimi',{name:'Kimi Code',logo:'kimi',baseUrl:'https://api.kimi.com/coding/v1',+ note:'未填写 Base URL 时连接 Kimi Code 官方服务。',protocols:[['chat','Chat Completions'],['responses','Responses'],['messages','Messages(Anthropic)']]}),agentCliCredentialKind('pi',{name:'Pi',logo:'pi',monochrome:true,baseUrl:'https://api.example.com/v1',required:()=>true,note:'Pi 没有自己的模型服务,需要填写 Base URL。',protocols:[['chat','Chat Completions'],['responses','Responses'],['messages','Messages(Anthropic)']]}),agentCliCredentialKind('dsh',{name:'DeepSeek Harness',logo:'deepseek',baseUrl:'https://api.deepseek.com',@@ -115,8 +116,8 @@ function agentCliCredentialKind(cli,o){...(configurable?{extra:{name:field+'baseUrl',label:'Base URL',placeholder:o.baseUrl,url:true,clearWithKey:true,required:o.required,note:o.extraNote||(o.required?'必填':'')},protocol:{name:field+'protocol',options:o.protocols},- models:{name:field+'models',engine:cli},}:{}),+ models:{name:field+'models',engine:cli},impact:`AI 对话将不能再切换到 ${o.name},以 ${o.name} 运行的 SOP 节点将无法执行${configurable?',Base URL、协议与模型目录一并清空':''}。`};}function credentialValue(user,name){@@ -131,7 +132,9 @@ function credentialProtocolHTML(kind,value){return `<label class="credential-field"><span>接口协议<em>Base URL 提供的 API</em></span><div class="credential-input is-plain is-select"><select name="protocol" aria-label="接口协议">${kind.protocol.options.map(([id,label])=>`<option value="${id}"${id===value?' selected':''}>${escapeHTML(label)}</option>`).join('')}</select></div></label>`;}// The model list behind an Anthropic-style Base URL sits under /v1.-function credentialModelsEndpoint(kind,protocol){return kind.models.endpoint||(protocol==='messages'?'/v1/models':'/models')}+function credentialModelsEndpoint(kind,protocol){+ return kind.models.endpoint||({messages:'/v1/models',gemini:'/v1beta/models'}[protocol]||'/models');+}// ---- 模型目录(Codex / Claude Code / 可配置 Agent CLI) ----// A saved catalog is the chat list on the official endpoint and behind a Base URL.// An empty catalog follows the CLI's built-in models when there is no Base URL@@ -139,9 +142,13 @@ function credentialModelsEndpoint(kind,protocol){return kind.models.endpoint||(p// Edits stay in the DOM until 保存.const CREDENTIAL_CATALOG_MAX=100;function credentialCatalogModels(value){- return (Array.isArray(value)?value:[]).map(model=>{const id=String(model?.id||'').trim(),name=String(model?.name||'').trim();return {id,name:name===id?'':name}}).filter(model=>model.id||model.name);+ return (Array.isArray(value)?value:[]).map(model=>{+ const id=String(model?.id||'').trim(),name=String(model?.name||'').trim();+ const metadata=model?.efforts?{efforts:model.efforts,defaultEffort:model.defaultEffort}:{};+ return {id,name:name===id?'':name,...metadata};+ }).filter(model=>model.id||model.name);}-function credentialCatalogStored(models){return credentialCatalogModels(models).map(model=>model.name?model:{id:model.id})}+function credentialCatalogStored(models){return credentialCatalogModels(models).map(({name,...model})=>name?{...model,name}:model)}function credentialCatalogKey(models){return JSON.stringify(credentialCatalogModels(models).map(model=>[model.id,model.name]))}function credentialCatalogError(models){const seen=new Set();@@ -158,42 +165,51 @@ function credentialCatalogError(models){return null;}function credentialCatalogRowHTML(model={}){- return `<li class="credential-catalog-row" data-catalog-row><button type="button" class="credential-catalog-grip" data-catalog-grip aria-label="拖动排序,也可以按 ↑ ↓ 移动">${credentialGlyph('grip',14)}</button><span class="credential-input is-plain"><input class="credential-mono" data-catalog-field="id" value="${escapeHTML(model.id||'')}" placeholder="模型 ID,如 gpt-5.5" aria-label="模型 ID" autocomplete="off" spellcheck="false"></span><span class="credential-input is-plain"><input data-catalog-field="name" value="${escapeHTML(model.name||'')}" placeholder="显示名称(可选)" aria-label="显示名称" autocomplete="off"></span><button type="button" class="credential-btn ghost icon danger credential-ink" data-catalog-act="remove" aria-label="移除模型">${credentialGlyph('trash',14)}</button></li>`;+ const metadata=model.efforts?` data-catalog-metadata="${escapeHTML(JSON.stringify({id:model.id,efforts:model.efforts,defaultEffort:model.defaultEffort}))}"`:'';+ return `<li class="credential-catalog-row" data-catalog-row${metadata}><button type="button" class="credential-catalog-grip" data-catalog-grip aria-label="拖动排序,也可以按 ↑ ↓ 移动">${credentialGlyph('grip',14)}</button><span class="credential-input is-plain"><input class="credential-mono" data-catalog-field="id" value="${escapeHTML(model.id||'')}" placeholder="模型 ID,如 gpt-5.5" aria-label="模型 ID" autocomplete="off" spellcheck="false"></span><span class="credential-input is-plain"><input data-catalog-field="name" value="${escapeHTML(model.name||'')}" placeholder="显示名称(可选)" aria-label="显示名称" autocomplete="off"></span><button type="button" class="credential-btn ghost icon danger credential-ink" data-catalog-act="remove" aria-label="移除模型">${credentialGlyph('trash',14)}</button></li>`;}-function credentialCatalogCopy(official,kind){+function credentialCatalogCopy(mode,kind){const name=kind?.name||'该 CLI';- return official+ if(mode==='runner')return {title:'使用 CLI 默认模型',detail:'获取这台机器的账号模型,或手动添加。',reset:'清空自定义列表',restored:'已恢复默认,保存后生效'};+ return mode==='official'?{title:`使用 ${name} 自带的模型`,detail:`目录为空时,AI 对话列出 ${name} 支持的模型。获取可用模型可以改成自己的目录,也可以手动添加。`,reset:'清空目录,改回使用自带的模型',restored:'已恢复默认,保存后使用自带的模型'}:{title:'跟随服务发布的模型',reset:'清空目录,改回跟随服务发布的模型',restored:'已恢复默认,保存后跟随服务发布的模型'};}-function credentialCatalogDetailHTML(official,kind,protocol){- const copy=credentialCatalogCopy(official,kind);- return official?escapeHTML(copy.detail):`目录为空时,AI 对话列出 Base URL 的 <code data-catalog-endpoint>${escapeHTML(credentialModelsEndpoint(kind,protocol))}</code> 返回的模型。`;-}-function credentialCatalogHTML(kind,user){- const baseUrl=credentialValue(user,kind.extra.name),protocol=credentialProtocol(kind,user);- const models=credentialCatalogModels(credentialValue(user,kind.models.name)),empty=!models.length,official=!String(baseUrl||'').trim()||protocol==='gemini';- const copy=credentialCatalogCopy(official,kind);- return `<section class="credential-catalog" data-credential-catalog data-catalog-mode="${official?'official':'remote'}" data-original-key="${escapeHTML(credentialCatalogKey(models))}" data-catalog-source="${escapeHTML(credentialCatalogSource(baseUrl))}" aria-label="模型目录">+function credentialCatalogDetailHTML(mode,kind,protocol){+ const copy=credentialCatalogCopy(mode,kind);+ return mode!=='remote'?escapeHTML(copy.detail):`目录为空时,AI 对话列出 Base URL 的 <code data-catalog-endpoint>${escapeHTML(credentialModelsEndpoint(kind,protocol))}</code> 返回的模型。`;+}+function credentialCatalogHTML(kind,user,{runnerLogin=false,label='模型目录'}={}){+ const baseUrl=kind.extra?.url?credentialValue(user,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()||protocol==='gemini'?'official':'remote';+ const copy=credentialCatalogCopy(mode,kind);+ return `<section class="credential-catalog" data-credential-catalog data-catalog-mode="${mode}" data-catalog-protocol="${escapeHTML(protocol)}" data-original-key="${escapeHTML(credentialCatalogKey(models))}" data-catalog-source="${escapeHTML(credentialCatalogSource(baseUrl))}" aria-label="模型目录"><div class="credential-catalog-body" data-catalog-body>- <div class="credential-catalog-head"><div><b>模型目录</b><small data-catalog-count>${credentialCatalogCountText(models.length)}</small></div><div><button type="button" class="credential-btn secondary credential-ink" data-catalog-act="probe">${credentialGlyph('download',14)}<span>获取可用模型</span></button><button type="button" class="credential-btn secondary credential-ink" data-catalog-act="add"><span class="credential-turn">${credentialGlyph('plus',14)}</span><span>添加模型</span></button></div></div>+ <div class="credential-catalog-head"><div>${label?`<b>${escapeHTML(label)}</b>`:''}<small data-catalog-count>${credentialCatalogCountText(models.length)}</small></div><div><button type="button" class="credential-btn secondary credential-ink" data-catalog-act="probe">${credentialGlyph('download',14)}<span>获取可用模型</span></button><button type="button" class="credential-btn secondary credential-ink" data-catalog-act="add"><span class="credential-turn">${credentialGlyph('plus',14)}</span><span>添加模型</span></button></div></div><div class="credential-catalog-probe" data-catalog-probe hidden></div><ol class="credential-catalog-list" data-catalog-list${empty?' hidden':''}>${models.map(credentialCatalogRowHTML).join('')}</ol>- <div class="credential-catalog-empty" data-catalog-empty${empty?'':' hidden'}>${credentialGlyph('layers',16)}<div><b data-catalog-empty-title>${escapeHTML(copy.title)}</b><small data-catalog-empty-detail>${credentialCatalogDetailHTML(official,kind,protocol)}</small></div></div>+ <div class="credential-catalog-empty" data-catalog-empty${empty?'':' hidden'}>${credentialGlyph('layers',16)}<div><b data-catalog-empty-title>${escapeHTML(copy.title)}</b><small data-catalog-empty-detail>${credentialCatalogDetailHTML(mode,kind,protocol)}</small></div></div><div class="credential-catalog-foot" data-catalog-foot${empty?' hidden':''}><button type="button" class="credential-btn link credential-ink" data-catalog-act="reset">${credentialGlyph('undo',13)}<span>恢复默认</span></button><small data-catalog-reset-note>${escapeHTML(copy.reset)}</small></div></div><span class="credential-sr" data-catalog-live role="status" aria-live="polite"></span></section>`;}function credentialCatalogSource(baseUrl){return String(baseUrl||'').trim().replace(/\/+$/,'')}-function credentialCatalogCountText(count){return count?`${count} 个模型 · AI 对话按此顺序列出`:'未自定义'}+function credentialCatalogCountText(count){return count?`${count} 个模型`:'未自定义'}function credentialCatalogRows(catalog){return [...catalog.querySelectorAll('[data-catalog-row]')]}-function credentialCatalogRowModel(row){return {id:row.querySelector('[data-catalog-field="id"]').value,name:row.querySelector('[data-catalog-field="name"]').value}}+function credentialCatalogRowModel(row){+ const id=row.querySelector('[data-catalog-field="id"]').value,name=row.querySelector('[data-catalog-field="name"]').value;+ const metadata=row.dataset.catalogMetadata?JSON.parse(row.dataset.catalogMetadata):null;+ return metadata?.id===id.trim()?{...metadata,id,name}:{id,name};+}function credentialCatalogFilledRows(catalog){return credentialCatalogRows(catalog).filter(row=>credentialCatalogModels([credentialCatalogRowModel(row)]).length)}function readCredentialCatalog(catalog){return credentialCatalogModels(credentialCatalogRows(catalog).map(credentialCatalogRowModel))}-function credentialCatalogOfficial(catalog){+function credentialCatalogMode(catalog){const form=catalog?.closest('.credential-editor-form'),extra=form?.querySelector('input[name="extra"]');- return (!!extra&&!extra.value.trim())||form?.querySelector('select[name="protocol"]')?.value==='gemini';+ if(!extra)return catalog.dataset.catalogMode;+ return !extra.value.trim()||form.querySelector('select[name="protocol"]')?.value==='gemini'?'official':'remote';}function credentialCatalogDirty(catalog){return !!catalog&&credentialCatalogKey(readCredentialCatalog(catalog))!==catalog.dataset.originalKey}function credentialCatalogPayload(catalog){@@ -201,11 +217,11 @@ function credentialCatalogPayload(catalog){return credentialCatalogDirty(catalog)?readCredentialCatalog(catalog):undefined;}function syncCredentialCatalog(catalog){- const official=credentialCatalogOfficial(catalog),kind=credentialKind(catalog.closest('[data-credential-row]')?.dataset.credentialRow),protocol=catalog.closest('.credential-editor-form')?.querySelector('select[name="protocol"]')?.value;- const copy=credentialCatalogCopy(official,kind),mode=official?'official':'remote';+ const mode=credentialCatalogMode(catalog),kind=credentialKind(catalog.closest('[data-credential-row]')?.dataset.credentialRow),protocol=catalog.closest('.credential-editor-form')?.querySelector('select[name="protocol"]')?.value||catalog.dataset.catalogProtocol;+ const copy=credentialCatalogCopy(mode,kind);const title=catalog.querySelector('[data-catalog-empty-title]'),detail=catalog.querySelector('[data-catalog-empty-detail]'),note=catalog.querySelector('[data-catalog-reset-note]');if(title)title.textContent=copy.title;- if(detail)detail.innerHTML=credentialCatalogDetailHTML(official,kind,protocol);+ if(detail)detail.innerHTML=credentialCatalogDetailHTML(mode,kind,protocol);if(note)note.textContent=copy.reset;if(catalog.dataset.catalogMode&&catalog.dataset.catalogMode!==mode&&!catalog.querySelector('[data-catalog-probe]').hidden)closeCredentialCatalogProbe(catalog);catalog.dataset.catalogMode=mode;@@ -220,6 +236,7 @@ function announceCredentialCatalog(catalog,text){const live=catalog.querySelectofunction credentialCatalogChanged(catalog){syncCredentialCatalog(catalog);const form=catalog.closest('.credential-editor-form');if(form)updateCredentialEditorDirty(form);+ catalog.onCatalogChange?.();}function resetCredentialCatalog(row){const catalog=row.querySelector('[data-credential-catalog]'),kind=credentialKind(row.dataset.credentialRow);if(!catalog||!kind)return;@@ -279,8 +296,9 @@ function credentialCatalogProbeHTML(catalog,kind){const listed=current.has(model.id),checked=followAll||listed;return `<label class="credential-catalog-pick" data-pick="${escapeHTML((model.id+' '+(model.name||'')).toLowerCase())}"><input type="checkbox" value="${escapeHTML(model.id)}"${checked?' checked':''}><code>${escapeHTML(model.id)}</code>${model.name&&model.name!==model.id?`<small>${escapeHTML(model.name)}</small>`:''}${listed?'<em>已在目录</em>':''}</label>`;}).join('');- const protocol=catalog.closest('.credential-editor-form')?.querySelector('select[name="protocol"]')?.value;- const source=probe.source==='builtin'?'以下是内置模型':`来自 Base URL 的 ${escapeHTML(credentialModelsEndpoint(kind,protocol))}`;+ const protocol=catalog.closest('.credential-editor-form')?.querySelector('select[name="protocol"]')?.value||catalog.dataset.catalogProtocol;+ const sources={builtin:'CLI 内置模型',official:'来自官方服务',runner:'来自这台机器的账号登录'};+ const source=sources[probe.source]||`来自 Base URL 的 ${escapeHTML(credentialModelsEndpoint(kind,protocol))}`;return `<div class="credential-catalog-probe-top"><span class="credential-input is-plain is-search">${credentialGlyph('search',14)}<input data-catalog-search placeholder="搜索模型" aria-label="搜索模型" autocomplete="off" spellcheck="false"></span><span class="credential-catalog-picked" data-catalog-picked></span><button type="button" class="credential-btn link credential-ink" data-catalog-act="toggle-all">全选</button></div><div class="credential-catalog-probe-list" role="group" aria-label="可用模型">${items}</div><div class="credential-catalog-probe-foot"><small>${source} · 勾选的模型会加入目录,取消勾选会移出</small><div><button type="button" class="credential-btn ghost credential-ink" data-catalog-act="probe-close">取消</button><button type="button" class="credential-btn primary credential-ink" data-catalog-act="probe-apply">更新列表</button></div></div>`;@@ -301,7 +319,7 @@ 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;+ 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):'';if(extraError){toast(extraError,'err');extra.focus();return}const token=(catalog.probeToken||0)+1;catalog.probeToken=token;catalog.probe=null;@@ -310,7 +328,11 @@ async function probeCredentialCatalog(row,catalog,button){hydrateCredentialIcons(panel);setCredentialButtonBusy(button,'获取中');let result;- try{result=await api(`/api/users/${state.currentUser.id}/cli-models/probe`,{method:'POST',body:JSON.stringify({engine:kind.models.engine,apiKey:secret,...(extra?{baseUrl:extra.value.trim()}:{}),...(protocol?{protocol}:{})}),silent:true})}+ try{+ result=catalog.probeModels?await catalog.probeModels():await api(`/api/users/${state.currentUser.id}/cli-models/probe`,{method:'POST',body:JSON.stringify({+ engine:kind.models.engine,apiKey:secret,baseUrl:extra?.value.trim(),protocol,environment+ }),silent:true});+ }catch(err){result={error:err.message}}finally{setCredentialButtonBusy(button,'')}if(catalog.probeToken!==token||!catalog.isConnected)return;@@ -320,7 +342,7 @@ async function probeCredentialCatalog(row,catalog,button){return;}const source=credentialCatalogSource(extra?.value);- if(source!==catalog.dataset.catalogSource){+ if(extra&&source!==catalog.dataset.catalogSource){const cleared=credentialCatalogRows(catalog);cleared.forEach(item=>item.remove());catalog.dataset.catalogSource=source;@@ -350,7 +372,7 @@ function applyCredentialCatalogProbe(catalog){});const added=probe.models.filter(model=>picked.has(model.id)&&!kept.has(model.id));const room=Math.max(0,CREDENTIAL_CATALOG_MAX-kept.size),list=catalog.querySelector('[data-catalog-list]');- list.insertAdjacentHTML('beforeend',added.slice(0,room).map(model=>credentialCatalogRowHTML({id:model.id,name:model.name&&model.name!==model.id?model.name:''})).join(''));+ list.insertAdjacentHTML('beforeend',credentialCatalogModels(added.slice(0,room)).map(credentialCatalogRowHTML).join(''));hydrateCredentialIcons(list);closeCredentialCatalogProbe(catalog);credentialCatalogChanged(catalog);@@ -366,7 +388,7 @@ function credentialCatalogAction(action,row,catalog,button){if(action==='reset'){credentialCatalogRows(catalog).forEach(item=>item.remove());credentialCatalogChanged(catalog);- announceCredentialCatalog(catalog,credentialCatalogCopy(credentialCatalogOfficial(catalog),credentialKind(row?.dataset.credentialRow)).restored);+ announceCredentialCatalog(catalog,credentialCatalogCopy(credentialCatalogMode(catalog),credentialKind(row?.dataset.credentialRow)).restored);catalog.querySelector('[data-catalog-act="add"]')?.focus({preventScroll:true});return;}@@ -375,6 +397,27 @@ function credentialCatalogAction(action,row,catalog,button){if(action==='toggle-all')return toggleCredentialCatalogProbe(catalog);if(action==='probe-apply')return applyCredentialCatalogProbe(catalog);}+function credentialCatalogKeydown(event){+ const grip=event.target.closest?.('[data-catalog-grip]');+ if(!grip||!['ArrowUp','ArrowDown'].includes(event.key))return;+ event.preventDefault();+ moveCredentialCatalogRow(grip.closest('[data-credential-catalog]'),grip.closest('[data-catalog-row]'),event.key==='ArrowUp'?-1:1);+}+function validateCredentialCatalog(catalog,models){+ const error=models&&credentialCatalogError(models);+ if(!error)return true;+ toast(error.error,'err');+ const input=credentialCatalogFilledRows(catalog)[error.index]?.querySelector(`[data-catalog-field="${error.field||'id'}"]`);+ if(input){+ const box=input.closest('.credential-input');+ box.classList.add('is-bad');+ box.classList.remove('is-shake');+ void box.offsetWidth;+ box.classList.add('is-shake');+ input.focus();+ }+ return false;+}// Platform features depend on these, in the order people should configure them.const CREDENTIAL_RECOMMENDED=['gitToken','codeBuddyApiKey'];const CREDENTIAL_PAT_WARNING='请填写 GitHub <b>个人访问令牌(PAT)</b>,为目标仓库授予 <b>Contents</b> 和 <b>Pull requests</b> 的读写权限;少勾权限会导致克隆 / 推送仓库失败。';@@ -748,13 +791,7 @@ async function submitCredentialEditor(row,button){if(secretError){setCredentialHint(form,'secret',secretError,'err');return}if(extraError){toast(extraError,'err');extra.focus();return}const catalog=form.querySelector('[data-credential-catalog]'),models=credentialCatalogPayload(catalog);- const catalogError=models&&credentialCatalogError(models);- if(catalogError){- toast(catalogError.error,'err');- const input=credentialCatalogFilledRows(catalog)[catalogError.index]?.querySelector(`[data-catalog-field="${catalogError.field||'id'}"]`);- if(input){const box=input.closest('.credential-input');box.classList.add('is-bad');box.classList.remove('is-shake');void box.offsetWidth;box.classList.add('is-shake');input.focus()}- return;- }+ if(!validateCredentialCatalog(catalog,models))return;setCredentialButtonBusy(button,key==='gitToken'?'校验中':'保存中');try{if(key==='gitToken'){@@ -837,8 +874,8 @@ function bindCredentialPanel(panel){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]'))}- const grip=event.target.closest?.('[data-catalog-grip]');- if(grip&&(event.key==='ArrowUp'||event.key==='ArrowDown')){event.preventDefault();moveCredentialCatalogRow(grip.closest('[data-credential-catalog]'),grip.closest('[data-catalog-row]'),event.key==='ArrowUp'?-1:1);return}+ credentialCatalogKeydown(event);+ if(event.defaultPrevented)return;const probe=event.target.closest?.('[data-catalog-probe]');if(probe&&event.key==='Escape'){event.preventDefault();event.stopPropagation();credentialCatalogAction('probe-close',null,probe.closest('[data-credential-catalog]'));return}const input=event.target.closest?.('.credential-editor-form input, .credential-editor-form select');diff --git a/web/i18n-en.js b/web/i18n-en.jsindex 34ff798b..1f7e2c37 100644--- a/web/i18n-en.js+++ b/web/i18n-en.js@@ -180,4 +180,13 @@ Object.assign(window.LF_I18N_EN,{"外部原单会保留,后续同步可能重新导入。":"The original external record is kept, and a later sync may import it again.","需求已有执行记录或已完成,请确认强制删除":"This requirement has execution history or is already completed. Confirm force deletion."});++Object.assign(window.LF_I18N_EN,{+ "Claude Code 和 Codex 可用账号登录":"Account login for Claude Code and Codex",+ "Claude Code 和 Codex 可以使用运行 Runner 的系统账号在这台机器上的已有登录。共享对话中,只有机器所有者发言时会使用此登录。":"Claude Code and Codex can reuse the login of the system user running the Runner. In a shared chat, that login applies to messages from the machine owner.",+ "API Key 说明":"API Key help",+ "LoopForge 沙箱目前无法复用 Antigravity 保存在系统凭据库中的登录。请在「个人配置」中填写 Gemini API Key。用量按 Gemini API 单独计费。":"LoopForge sandboxes cannot currently access Antigravity's login in the system credential store. Enter a Gemini API Key in Personal Settings. Gemini API usage is billed separately.",+ "GLM Coding Plan 的 API Key 配合套餐专用地址可使用订阅额度,请在「个人配置」中填写。Start Plan 额度需要登录 ZCode 账号,无法通过 API Key 使用。":"Enter the GLM Coding Plan API key and its dedicated endpoint in Personal Settings to use your subscription allowance. Start Plan allowance requires signing in to ZCode.",+ "该 CLI 支持 API Key。使用服务商订阅套餐提供的 Key,执行用量会计入对应的套餐额度。请在「个人配置」中填写 API Key。":"This CLI supports API keys. With a key included in your provider's subscription, usage counts toward that plan's allowance. Enter the API key in Personal Settings."+});Object.assign(window.LF_I18N_EN,{"查看其他项目共享的技能;共享技能只读,会自动装入平台上所有对话和定时任务,也可绑定到本项目角色。": "Skills shared by other projects. Shared Skills are read-only, are installed automatically into every conversation and scheduled task on the platform, and can be bound to Roles in this project.", "共享后,这个技能会自动装入平台上所有用户的对话和定时任务(包括其他项目和无项目的对话),模型可以直接调用。继续?": "Once shared, this Skill is installed automatically into every user's conversations and scheduled tasks on the platform (including other projects and conversations without a project), and the model can call it directly. Continue?", "共享这个角色会同时共享它绑定的技能:": "Sharing this Role also shares the Skills bound to it: ", "已共享,所有对话和定时任务会自动装入": "Shared. Every conversation and scheduled task will install it automatically", "其他项目可在「共享角色」里选用;绑定的本项目技能会一起共享,并自动装入所有对话": "Other projects can pick it under Shared roles; the project Skills bound to it are shared too and installed into every conversation automatically", "共享技能": "Share Skill"});diff --git a/web/index.html b/web/index.htmlindex 4d3fe37e..264def9b 100644--- a/web/index.html+++ b/web/index.html@@ -774,7 +774,7 @@<ol class="runner-steps"><li><span class="runner-step-no">1</span><div><b>安装 CLI</b><small>claude / codex 等</small></div></li><li><span class="runner-step-no">2</span><div><b>执行接入命令</b><small>绑定码 10 分钟有效</small></div></li>- <li><span class="runner-step-no">3</span><div><b>选择认证来源</b><small>本机登录或个人凭证</small></div></li>+ <li><span class="runner-step-no">3</span><div><b>选择认证来源</b><small>Claude Code 和 Codex 可用账号登录</small></div></li></ol><div class="runner-command-box"><pre id="bindCliCommand" class="mono">(curl -fsSL --connect-timeout 5 <span id="bindHttpsOrigin">https://</span>/runners/install.sh || curl -fsSL <span id="bindHttpOrigin">http://</span>/runners/install.sh) | bash -s -- --server <span id="bindServerHost"></span> --token <span id="bindToken">生成中…</span> --service</pre>@@ -793,7 +793,6 @@</div><div class="runner-list-heading"><h2>我的机器</h2><span class="runner-count" id="runnerCount">0</span><p class="runner-pool-status" id="runnerPoolStatus" aria-live="polite"></p></div>- <aside id="runnerCLIUpdateNotice" class="runner-cli-update-notice" aria-labelledby="runnerCLIUpdateNoticeTitle"><b id="runnerCLIUpdateNoticeTitle">Agent CLI 需自行升级:</b>平台不会代为升级,版本过旧或无模型权限会导致任务失败。</aside><div id="runnersList" class="runner-grid"></div></section>@@ -1154,7 +1153,7 @@<div class="ai-model-menu" hidden role="listbox" aria-label="模型"></div></div></div>- <p class="schedule-field-hint" id="scheduleModelHint">与 AI 助手相同的 CLI 与模型,到点用保存人在所选 CLI 上配置的 Key 执行;没有个人 CodeBuddy Key 时使用平台共享 Key。</p>+ <p class="schedule-field-hint" id="scheduleModelHint">Codex 和 Claude Code 优先使用保存人默认执行机器的账号登录。机器离线时改用个人 API Key,Key 缺失或不可用时任务失败。CodeBuddy 缺少个人 Key 时可使用平台共享 Key。</p></div><div data-schedule-kind="assistant" hidden><label for="scheduleSessionMode">会话</label>diff --git a/web/platform.css b/web/platform.cssindex 29cae7e8..59aef1b8 100644--- a/web/platform.css+++ b/web/platform.css@@ -2236,7 +2236,7 @@ html[data-theme="light"] body{color-scheme:light}html[data-theme="light"] .platf.obs-card>.pager{margin:10px 0 2px;border:0;background:transparent;padding:8px 0 0}/* ================= 个人凭证(harness-ui 设计语言) ================= */-#personalSettingsContent,.credential-scrim,.github-connect,.git-ssh-dialog{+#personalSettingsContent,.credential-scrim,.github-connect,.git-ssh-dialog,.runner-model-editor{--cr-accent:var(--hui-accent);--cr-accent-hover:var(--hui-accent-hover);--cr-surface:var(--hui-surface);--cr-canvas:var(--hui-canvas);--cr-elevated:var(--hui-soft);--cr-text:var(--hui-text);--cr-text-2:var(--hui-secondary);--cr-muted:var(--hui-muted);--cr-tertiary:var(--hui-tertiary);diff --git a/web/product-v4.css b/web/product-v4.cssindex 792a2fe5..0c216dad 100644--- a/web/product-v4.css+++ b/web/product-v4.css@@ -2749,40 +2749,58 @@ html[data-theme="dark"] #runnersView{--rv-term:#0a0a0b;--rv-codex:#3f3f46}#runnersView .runner-pool-status:empty{display:none}#runnersView .runner-pool-status.warn{padding:3px 10px;border:1px solid var(--rv-warn-line);border-radius:8px;background:var(--rv-warn-fill);color:var(--rv-warn)}#runnersView .runner-pool-status.warn::before{background:var(--rv-warn);box-shadow:none}-#runnersView .runner-cli-update-notice{margin:0 0 12px;padding:0;border:0;background:none;color:var(--rv-muted-2);font-size:12px;line-height:1.6}-#runnersView .runner-cli-update-notice b{color:var(--rv-muted);font-weight:600}-#runnersView .runner-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(340px,100%),1fr));gap:14px}+#runnersView .runner-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(400px,100%),1fr));gap:16px}#runnersView .runner-empty{grid-column:1/-1;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:2px;min-height:96px;border:1px dashed var(--hui-border-strong);border-radius:14px;color:var(--rv-muted);font-size:12.5px;text-align:center}#runnersView .runner-empty b{color:var(--rv-text);font-size:13px;font-weight:500}-#runnersView .runner-card{position:relative;min-width:0;padding:16px 18px;overflow:visible;border:1px solid var(--rv-line);border-radius:14px;background:var(--rv-surface);box-shadow:none;transition:border-color .16s}-#runnersView .runner-card.is-default{border-color:color-mix(in srgb,var(--hui-accent) 45%,var(--rv-line));box-shadow:none}-#runnersView .runner-card-head{display:flex;align-items:center;gap:10px}+#runnersView .runner-card{--runner-auth-width:104px;min-width:0;padding:16px;overflow:visible;border:1px solid var(--rv-line);border-radius:14px;background:var(--rv-surface);box-shadow:none;transition:border-color .16s}+#runnersView .runner-card.is-default{border-color:color-mix(in srgb,var(--hui-accent) 42%,var(--rv-line))}+#runnersView .runner-card-head{display:flex;align-items:center;gap:10px;min-height:42px}+#runnersView .runner-machine-icon{flex:none;display:grid;place-items:center;width:34px;height:34px;border:1px solid var(--rv-line-soft);border-radius:9px;background:var(--rv-fill);color:var(--rv-muted)}+#runnersView .runner-machine-icon .harness-icon{width:17px;height:17px}#runnersView .runner-card-title{flex:1;min-width:0}#runnersView .runner-card-name{display:flex;align-items:center;gap:6px;min-width:0}#runnersView .runner-card-name b{overflow:hidden;color:var(--rv-text);font-size:14px;font-weight:650;text-overflow:ellipsis;white-space:nowrap}-#runnersView .runner-card-title small{display:block;margin-top:1px;color:var(--rv-muted);font-size:12px}+#runnersView .runner-card-title small{display:block;margin-top:3px;color:var(--rv-muted);font-size:11.5px;line-height:1.45}#runnersView .runner-tag{flex:none;padding:0 6px;border-radius:5px;background:var(--rv-hover);color:var(--rv-muted);font-size:11px;font-weight:600;line-height:18px}-#runnersView .runner-tag.default{background:var(--rv-btn-dark);color:var(--rv-btn-dark-text)}-#runnersView .runner-status{flex:none;display:inline-flex;align-items:center;gap:6px;color:var(--rv-muted);font-size:12px;font-weight:600}-#runnersView .runner-status i{width:7px;height:7px;border-radius:50%;background:var(--rv-muted-2)}+#runnersView .runner-tag.default{background:var(--hui-accent-soft);color:var(--hui-accent)}+#runnersView .runner-head-actions{display:flex;flex:none;flex-direction:column;align-items:flex-end;gap:4px}+#runnersView .runner-status{display:inline-flex;align-items:center;gap:6px;color:var(--rv-muted);font-size:11.5px;font-weight:600}+#runnersView .runner-status i{width:6px;height:6px;border-radius:50%;background:var(--rv-muted-2)}#runnersView .runner-status.online{color:var(--rv-ok)}-#runnersView .runner-status.online i{background:var(--rv-ok);box-shadow:0 0 0 3px var(--rv-ok-fill)}-#runnersView .runner-runtime-list{margin-top:12px;padding:0;border-top:1px solid var(--rv-line-soft);border-radius:0;background:none}-#runnersView .runner-runtime-row{display:flex;align-items:center;gap:10px;min-height:42px;margin:0;border-top:0;border-bottom:1px solid var(--rv-line-soft);color:var(--rv-text);font-size:13px;cursor:pointer}-#runnersView .runner-runtime-row input{flex:none;margin:0;cursor:pointer}-#runnersView .runner-runtime-icon{flex:none;display:grid;place-items:center;width:22px;height:22px;border:0;border-radius:6px;background:var(--rv-muted);color:#fff;font-size:11px;font-weight:700;transition:opacity .16s}-#runnersView .runner-runtime-icon.claude-code{background:#d97757}-#runnersView .runner-runtime-icon.codex{background:var(--rv-codex)}-#runnersView .runner-runtime-icon.codebuddy{background:#4f6ef7}-#runnersView .runner-runtime-name{flex:1;min-width:0;display:flex;flex-wrap:wrap;align-items:baseline;gap:0 8px;transition:opacity .16s}-#runnersView .runner-runtime-name b{font-size:13px;font-weight:600;white-space:nowrap}-#runnersView .runner-runtime-name small{min-width:min(100%,7ch);max-width:100%;margin:0;overflow:hidden;color:var(--rv-muted-2);font:11px ui-monospace,SFMono-Regular,Menlo,monospace;text-overflow:ellipsis;white-space:nowrap}-#runnersView .runner-runtime-row.off .runner-runtime-name,#runnersView .runner-runtime-row.off .runner-runtime-icon{opacity:.45}-#runnersView .runner-auth-select{flex:none;max-width:150px;height:28px;padding:0 22px 0 8px;border:1px solid var(--rv-line);border-radius:7px;background-color:var(--rv-surface);color:var(--rv-text);font-size:12px;cursor:pointer}-#runnersView .runner-auth-select.missing{border-color:var(--rv-warn-line);color:var(--rv-warn)}-#runnersView .runner-auth-fixed{flex:none;padding:0 8px;border-radius:0;background:none;color:var(--rv-muted);font-size:12px;font-weight:400}-#runnersView .runner-auth-fixed.missing{background:none;color:var(--rv-warn)}+#runnersView .runner-status.online i{background:var(--rv-ok);box-shadow:0 0 0 2px var(--rv-ok-fill)}+#runnersView .runner-check-update{display:inline-flex;align-items:center;gap:5px;min-height:26px;padding:0 7px;border:1px solid var(--rv-line);border-radius:7px;background:var(--rv-surface);color:var(--rv-muted);font-size:11.5px;white-space:nowrap}+#runnersView .runner-check-update:hover:not(:disabled){background:var(--rv-hover);color:var(--rv-text)}+#runnersView .runner-check-update .harness-icon{width:12px;height:12px}+#runnersView .runner-runtime-list{margin-top:14px;border-top:1px solid var(--rv-line-soft)}+#runnersView :is(.runner-runtime-heading,.runner-runtime-row){display:grid;grid-template-columns:minmax(0,1fr) var(--runner-auth-width) 30px;align-items:center;gap:8px}+#runnersView .runner-runtime-heading{min-height:30px;padding-top:4px;color:var(--rv-muted);font-size:11px;font-weight:500}+#runnersView .runner-auth-help{display:inline-flex;align-items:center;justify-self:start;gap:4px;min-height:24px;padding:0;border:0;border-radius:4px;background:none;color:inherit;font:inherit;cursor:pointer}+#runnersView .runner-auth-help:is(:hover,:focus-visible){color:var(--rv-text)}+#runnersView .runner-auth-help .harness-icon{width:13px;height:13px;color:var(--rv-muted-2)}+#runnersView .runner-runtime-row{min-height:51px;border-bottom:1px solid var(--rv-line-soft);color:var(--rv-text)}+#runnersView .runner-runtime-label{display:flex;align-items:center;gap:8px;min-width:0;cursor:pointer}+#runnersView .runner-runtime-label input{flex:none;margin:0;cursor:pointer}+#runnersView .runner-runtime-icon{flex:none;display:grid;place-items:center;width:26px;height:26px;border-radius:7px;background:var(--rv-fill);transition:opacity .16s}+#runnersView .runner-runtime-icon img{display:block;width:17px;height:17px;object-fit:contain}+html[data-theme="dark"] #runnersView .runner-runtime-icon:is(.codex,.claude-code,.cursor,.opencode,.pi) img{filter:invert(1)}+#runnersView .runner-runtime-name{min-width:0;display:grid;gap:3px;transition:opacity .16s}+#runnersView .runner-runtime-name :is(b,small){display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}+#runnersView .runner-runtime-name b{font-size:13px;font-weight:600;line-height:1.15}+#runnersView .runner-runtime-name small{color:var(--rv-muted-2);font:11px/1.15 var(--hui-mono,monospace)}+#runnersView .runner-runtime-row.off :is(.runner-runtime-name,.runner-runtime-icon){opacity:.48}+#runnersView :is(.runner-auth-select,.runner-auth-fixed){box-sizing:border-box;min-width:0;width:100%;height:32px;padding:0 8px;color:var(--rv-text);font:500 11.5px/1.2 var(--hui-sans)}+#runnersView .runner-auth-select{padding-right:23px;border:1px solid var(--rv-line);border-radius:7px;background-color:var(--rv-surface);text-overflow:ellipsis}+#runnersView .runner-auth-select.is-personal{border-color:transparent;background-color:transparent}+#runnersView .runner-auth-fixed{display:flex;align-items:center;justify-content:space-between;gap:4px;white-space:nowrap}+#runnersView .runner-auth-tip{display:grid;place-items:center;flex:none;width:24px;height:24px;margin-right:-4px;padding:0;border:0;border-radius:6px;background:none;color:var(--rv-muted);cursor:help}+#runnersView .runner-auth-tip span{box-sizing:border-box;display:grid;place-items:center;width:15px;height:15px;border:1px solid currentColor;border-radius:50%;font-size:10px;font-weight:700;line-height:1}+#runnersView .runner-auth-tip:is(:hover,:focus-visible){background:var(--rv-hover);color:var(--rv-text)}+#runnersView .runner-more{display:grid;place-items:center;width:30px;height:30px;padding:0;border:1px solid transparent;border-radius:7px;background:transparent;color:var(--rv-muted);cursor:pointer;transition:background .16s,color .16s}+#runnersView .runner-more:is(:hover,:focus-visible,[aria-expanded="true"]){background:var(--rv-hover);color:var(--rv-text)}+#runnersView .runner-more .harness-icon{width:16px;height:16px}#runnersView .runner-runtime-empty{padding:12px 0;border-bottom:1px solid var(--rv-line-soft);color:var(--rv-muted-2);font-size:12px}+#confirmModal .runner-model-card{box-sizing:border-box;width:min(660px,94vw)}+#confirmModal .runner-model-editor{max-height:min(55dvh,540px);overflow:auto;margin-top:14px}#runnersView .runner-card-action{display:flex;flex-wrap:wrap;align-items:center;gap:8px;margin-top:12px;padding:0;border:0}#runnersView .runner-card-spacer{flex:1}#runnersView .runner-card-action .button{height:28px;padding:0 10px;border-radius:8px;font-size:12px;font-weight:500;box-shadow:none;transition:background-color .16s,color .16s,opacity .16s}@@ -2807,6 +2825,12 @@ html[data-theme="dark"] #runnersView{--rv-term:#0a0a0b;--rv-codex:#3f3f46}#runnersView .runner-pool-status{flex-basis:100%;margin-left:0}#runnersView .runner-pool-status.warn{flex-basis:auto}}+@media(max-width:470px){+ #runnersView .runner-card{--runner-auth-width:90px;padding:13px}+ #runnersView .runner-machine-icon{width:28px;height:28px}+ #runnersView :is(.runner-runtime-heading,.runner-runtime-row){gap:5px}+ #runnersView .runner-runtime-label{gap:6px}+}@media(prefers-reduced-motion:reduce){#runnersView *,#runnersView *::after{transition:none !important}}/* 多仓库选择(复选框组):高优先级覆盖主题的 label/input 表单样式 */diff --git a/web/runner_cli_notice_test.go b/web/runner_cli_notice_test.goindex 5a7fa2c1..b3d6fc49 100644--- a/web/runner_cli_notice_test.go+++ b/web/runner_cli_notice_test.go@@ -3,57 +3,24 @@ package webimport ("bytes""os"- "strings""testing"-- "golang.org/x/net/html")-func TestRunnerCLIUpdateNotice(t *testing.T) {- data, err := os.ReadFile("index.html")+func TestRunnerUsesPerCLIMaintenanceControls(t *testing.T) {+ page, err := os.ReadFile("index.html")if err != nil {t.Fatal(err)}- doc, err := html.Parse(bytes.NewReader(data))- if err != nil {- t.Fatal(err)- }- nodes := map[string]*html.Node{}- for node := range doc.Descendants() {- for _, attr := range node.Attr {- if attr.Key == "id" {- nodes[attr.Val] = node- }- }- }- notice, list, view := nodes["runnerCLIUpdateNotice"], nodes["runnersList"], nodes["runnersView"]- if notice == nil || list == nil || view == nil || notice.Parent != view || list.Parent != view || bytes.Index(data, []byte(`id="runnerCLIUpdateNotice"`)) > bytes.Index(data, []byte(`id="runnersList"`)) {- t.Fatal("notice must be a static sibling above the machine list")- }- var markup bytes.Buffer- if err := html.Render(&markup, notice); err != nil {- t.Fatal(err)- }- for _, want := range []string{"需自行升级", "平台不会代为升级", "模型权限", "任务失败"} {- if !strings.Contains(markup.String(), want) {- t.Errorf("missing maintenance guidance: %s", want)- }- }- for _, hidden := range []string{"<button", "<details", " hidden", "aria-hidden", " style="} {- if strings.Contains(markup.String(), hidden) {- t.Errorf("notice must be persistent and non-interactive: %s", hidden)- }+ if bytes.Contains(page, []byte("runnerCLIUpdateNotice")) {+ t.Fatal("update guidance belongs to the CLI update action")}app, err := os.ReadFile("app/runners.js")if err != nil {t.Fatal(err)}- for _, forbidden := range []string{"runnerCLIUpdateNotice", "data-update-cli", "data-upgrade-cli", "/cli/update", "/cli/upgrade", "一键升级", "远程升级"} {- if bytes.Contains(app, []byte(forbidden)) {- t.Errorf("runner rendering must not hide the notice or upgrade user CLIs: %s", forbidden)+ for _, want := range []string{"data-runner-runtime-menu", "data-runner-check-update", "/images/credentials/", "runtime.version||runtime.binaryPath"} {+ if !bytes.Contains(app, []byte(want)) {+ t.Errorf("missing runner card control or status: %s", want)}}- if !bytes.Contains(app, []byte("rt.version||rt.binaryPath")) {- t.Fatal("keep discovered CLI version display")- }}diff --git a/web/syntax_test.go b/web/syntax_test.goindex 957becd8..404d38b9 100644--- a/web/syntax_test.go+++ b/web/syntax_test.go@@ -539,13 +539,13 @@ assert.deepEqual(credentialSavePayload(cred.kind('codexApiKey'), {secret: 'sk-1'assert.deepEqual(credentialSavePayload(cred.kind('claudeCodeApiKey'), {secret: '', extra: '', models: [{id: ' hy4 ', name: '混元 4'}, {id: 'glm-5', name: 'glm-5'}]}), {claudeCodeApiKey: '', claudeCodeBaseUrl: '', claudeCodeModels: [{id: 'hy4', name: '混元 4'}, {id: 'glm-5'}]});assert.deepEqual(credentialSavePayload(cred.kind('codexApiKey'), {secret: '', extra: '', models: []}), {codexApiKey: '', codexBaseUrl: '', codexModels: []}, '恢复默认 sends an empty catalog');assert.deepEqual(credentialSavePayload(cred.kind('agentCli.opencode'), {secret: 'k', extra: 'https://gw.example/v1', protocol: 'messages', models: [{id: 'a', name: 'A'}]}), {agentCliCredentials: {opencode: {apiKey: 'k', baseUrl: 'https://gw.example/v1', protocol: 'messages', models: [{id: 'a', name: 'A'}]}}});-assert.equal(cred.kind('agentCli.cursor').models, undefined, 'Cursor stays on its official models');+assert.equal(cred.kind('agentCli.cursor').models.engine, 'cursor', 'Cursor keeps a per-account model catalog');assert.equal(cred.kind('agentCli.zcode').models.engine, 'zcode');assert.ok(credentialSubline(cred.kind('codexApiKey'), {codexApiKeyConfigured: true, codexModels: [{id: 'hy4'}, {id: 'gpt-5.5'}]}).includes('2 个自定义模型'));assert.deepEqual(credentialClearPayload(cred.kind('codexApiKey')), {codexApiKeyClear: true, codexBaseUrl: '', codexModels: []});assert.deepEqual(credentialClearPayload(cred.kind('claudeCodeApiKey')), {claudeCodeApiKeyClear: true, claudeCodeBaseUrl: '', claudeCodeModels: []});assert.deepEqual(credentialClearPayload(cred.kind('agentCli.opencode')), {agentCliCredentials: {opencode: {apiKeyClear: true, baseUrl: '', protocol: '', models: []}}});-assert.deepEqual(credentialClearPayload(cred.kind('agentCli.cursor')), {agentCliCredentials: {cursor: {apiKeyClear: true, baseUrl: '', protocol: ''}}});+assert.deepEqual(credentialClearPayload(cred.kind('agentCli.cursor')), {agentCliCredentials: {cursor: {apiKeyClear: true, baseUrl: '', protocol: '', models: []}}}, 'deleting the Cursor key drops the model catalog of that account');const catalogUser = {codexApiKeyConfigured: true, codexBaseUrl: 'https://gw.example/v1', codexModels: [{id: 'hy4', name: '混元 4'}, {id: 'gpt-5.5'}]};const catalogHTML = credentialCatalogHTML(cred.kind('codexApiKey'), catalogUser);assert.equal(count(catalogHTML, 'data-catalog-row'), 2);@@ -563,14 +563,14 @@ assert.ok(officialEmpty.includes('使用 Codex 自带的模型') && officialEmptconst geminiCatalog = credentialCatalogHTML(cred.kind('agentCli.agy'), {agentCliCredentials: {agy: {baseUrl: 'https://gw.example/v1', protocol: 'gemini'}}});assert.ok(geminiCatalog.includes('使用 Antigravity 自带的模型') && geminiCatalog.includes('data-catalog-act="probe"') && !geminiCatalog.includes('data-catalog-body hidden'), 'Gemini official API can still keep a custom catalog');assert.ok(credentialEditorHTML(cred.kind('codexApiKey'), catalogUser).includes('data-credential-catalog') && credentialEditorHTML(cred.kind('codexApiKey'), catalogUser).includes('has-catalog'));-assert.ok(!credentialEditorHTML(cred.kind('agentCli.cursor'), {agentCliCredentials: {cursor: {apiKeyConfigured: true}}}).includes('data-credential-catalog'));+assert.ok(credentialEditorHTML(cred.kind('agentCli.cursor'), {agentCliCredentials: {cursor: {apiKeyConfigured: true}}}).includes('data-credential-catalog'), 'Cursor can fetch the models of its account');assert.equal(credentialCatalogKey([{id: 'a', name: 'a'}, {id: '', name: ''}]), credentialCatalogKey([{id: 'a'}]));assert.equal(credentialCatalogError([{id: 'a'}, {id: 'b', name: 'B'}]), null);assert.deepEqual(credentialCatalogError([{id: 'a'}, {id: '', name: 'x'}]), {index: 1, field: 'id', error: '模型 ID 不能为空'});assert.ok(credentialCatalogError([{id: 'a b'}]).error.includes('空格'));assert.ok(credentialCatalogError([{id: 'a'}, {id: 'a'}]).error.includes('重复'));assert.equal(credentialCatalogError([{id: 'a', name: 'n'.repeat(65)}]).field, 'name');-assert.deepEqual(credentialClearPayload(cred.kind('codeBuddyApiKey')), {codeBuddyApiKeyClear: true});+assert.deepEqual(credentialClearPayload(cred.kind('codeBuddyApiKey')), {codeBuddyApiKeyClear: true, codeBuddyModels: []});assert.deepEqual(credentialClearPayload(cred.kind('gitToken')), {gitTokenClear: true});assert.equal(credentialSecretError(cred.kind('gitToken'), 'github_pat_1'), '');assert.ok(credentialExtraError(cred.kind('codexApiKey'), 'ftp://proxy'));@@ -733,7 +733,7 @@ const assert = require('node:assert/strict');const code = require('node:fs').readFileSync('` + appBundlePath(t) + `', 'utf8');const opened = [], toggled = [], acted = [];const openCredentialWizard = key => opened.push(key), toggleCredentialRow = key => toggled.push(key);-const credentialRowAction = act => acted.push(act);+const credentialRowAction = act => acted.push(act), credentialCatalogKeydown = () => {};eval(code.slice(code.indexOf('function activateCredentialRow('), code.indexOf('// gotoCredential lands here')));const panel = {};bindCredentialPanel(panel);diff --git a/webtest/tests/assets-agents.test.mjs b/webtest/tests/assets-agents.test.mjsindex ab6680d6..d767b208 100644--- a/webtest/tests/assets-agents.test.mjs+++ b/webtest/tests/assets-agents.test.mjs@@ -93,3 +93,39 @@ test('agent catalog search, presets, validation, persistence, clone, and deleteawait app.evaluate(`deleteAgent('agent-copy')`);assert.equal(app.evaluate(`state.data.agents.some(a=>a.id==='agent-copy')`), false);});++test('role model picker reloads the editor catalog and preserves a CLI change while loading', async (t) => {+ const app = await loadApp();+ t.after(app.close);+ let complete;+ const delayed = new Promise(resolve => { complete = resolve; });+ const catalog = (models) => ({+ codebuddy: { models: [], efforts: [] },+ claude: { models: [], efforts: [] },+ codex: { customModel: true, models, efforts: [] },+ });+ app.router.get('/api/executor-models', () => delayed);+ app.evaluate(`+ state.data.executors=[+ {id:'codebuddy',name:'CodeBuddy'},{id:'codex',name:'Codex'},{id:'claude',name:'Claude Code'}+ ];+ openAgentWizard();+ `);+ const f = app.document.querySelector('#agentForm');+ f.elements.executorId.value = 'codex';+ f.elements.executorId.dispatchEvent(new app.window.Event('change', { bubbles: true }));+ 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.equal(f.elements.executorId.value, 'codex');+ menu()[1].click();+ 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.equal(app.document.querySelector('#agentModelPicker [data-model-label]').textContent, 'Renamed model');+});diff --git a/webtest/tests/runner-codebuddy-environment.test.mjs b/webtest/tests/runner-codebuddy-environment.test.mjsindex ca40553e..ba737d04 100644--- a/webtest/tests/runner-codebuddy-environment.test.mjs+++ b/webtest/tests/runner-codebuddy-environment.test.mjs@@ -1,10 +1,7 @@import test from 'node:test';import assert from 'node:assert/strict';-import { loadApp } from '../lib/load-app.mjs';+import { loadApp, settle } from '../lib/load-app.mjs';-// #198 item 7: the CodeBuddy row on a runner card shows the same network-// environment as 个人配置 → CodeBuddy, so an iOA key used with the wrong-// environment is visible before the machine answers 401.function renderCodeBuddyRow(app, user) {const runner = {id: 'runner-cb', name: 'Laptop', ownerUserId: 1, status: 'online', os: 'linux', arch: 'amd64',@@ -27,31 +24,172 @@ function renderCodeBuddyRow(app, user) {return fixed[0];}-test('runner card shows the CodeBuddy network environment from personal config', async (t) => {+test('runner card uses the same short CodeBuddy authentication label in all network environments', async (t) => {const app = await loadApp();t.after(app.close);- for (const [value, label] of [['', '国际站'], ['internal', '国内站'], ['ioa', 'iOA']]) {+ for (const value of ['', 'internal', 'ioa', 'china<b>']) {const el = renderCodeBuddyRow(app, { codeBuddyApiKeyConfigured: true, codeBuddyInternetEnvironment: value });- assert.equal(el.textContent, `个人凭证 · ${label}`);- assert.equal(el.classList.contains('missing'), false);- assert.match(el.getAttribute('title'), new RegExp(`网络环境:${label}`));+ assert.equal(el.firstElementChild.textContent, 'API Key');+ assert.equal(el.hasAttribute('title'), false);}});-test('runner card flags an unrecognized CodeBuddy network environment', async (t) => {+test('runner card offers the short authentication labels with a separate explanation', async (t) => {const app = await loadApp();t.after(app.close);- const el = renderCodeBuddyRow(app, { codeBuddyApiKeyConfigured: true, codeBuddyInternetEnvironment: 'china<b>' });- assert.equal(el.textContent, '个人凭证 · 网络环境无法识别');- assert.ok(el.classList.contains('missing'));- assert.match(el.getAttribute('title'), /「china<b>」无法识别,CodeBuddy 会按国际站连接/);- assert.equal(el.querySelector('b'), null, 'stored value is escaped');+ renderCodeBuddyRow(app, {});+ const select = app.document.querySelector('[data-runner-auth="runner-cb|codex"]');+ assert.deepEqual([...select.options].map(option=>option.textContent), ['账号登录', 'API Key']);+ app.document.querySelector('[data-runner-auth-help]').click();+ assert.match(app.document.querySelector('#confirmMessage').textContent, /Claude Code 和 Codex.*已有登录/);+ assert.match(app.document.querySelector('#confirmMessage').textContent, /当前发言人的 Key/);});-test('runner card keeps the missing-key label when CodeBuddy is not configured', async (t) => {+test('runner card indicates a missing CodeBuddy key on its single-line label', async (t) => {const app = await loadApp();t.after(app.close);const el = renderCodeBuddyRow(app, { codeBuddyApiKeyConfigured: false, codeBuddyInternetEnvironment: 'ioa' });- assert.equal(el.textContent, '个人凭证(未配置)');- assert.ok(el.classList.contains('missing'));+ assert.equal(el.firstElementChild.textContent, 'API Key');+ assert.match(el.getAttribute('title'), /个人配置/);+ assert.equal(el.classList.contains('missing'), false);+});++test('only Claude Code and Codex offer account login and API Key rows explain their credentials', async (t) => {+ const app = await loadApp();+ t.after(app.close);+ renderCodeBuddyRow(app, {});+ app.evaluate(`+ state.runners[0].runtimes.push(+ {provider:'claude-code',authMode:'local',status:'online'},+ {provider:'cursor',authMode:'personal',status:'online'},+ {provider:'agy',authMode:'personal',status:'online'},+ {provider:'zcode',authMode:'personal',status:'online'}+ );+ renderRunnersView();+ `);+ const choices = [...app.document.querySelectorAll('[data-runner-auth]')];+ assert.deepEqual(choices.map(select => select.dataset.runnerAuth), ['runner-cb|codex', 'runner-cb|claude-code']);+ for (const select of choices) {+ assert.deepEqual([...select.options].map(option => option.textContent), ['账号登录', 'API Key']);+ }+ const help = [...app.document.querySelectorAll('[data-runner-key-help]')];+ assert.deepEqual(help.map(button => button.dataset.runnerKeyHelp), ['codebuddy', 'cursor', 'agy', 'zcode']);+ const commonHelp = /支持 API Key.*订阅套餐.*计入对应的套餐额度.*个人配置/;+ const providerHelp = {+ agy: /系统凭据库.*Gemini API Key.*单独计费/,+ zcode: /GLM Coding Plan.*订阅额度.*Start Plan.*无法通过 API Key 使用/,+ };+ for (const button of help) {+ assert.equal(button.parentElement.firstElementChild.textContent, 'API Key');+ const tooltip = providerHelp[button.dataset.runnerKeyHelp] || commonHelp;+ assert.match(button.title, tooltip);+ button.click();+ assert.match(app.document.querySelector('#confirmMessage').textContent, tooltip);+ app.document.querySelector('#confirmOkBtn').click();+ await settle();+ }+});++test('testing a CLI sends its machine and provider and shows the result', async (t) => {+ const app = await loadApp();+ t.after(app.close);+ renderCodeBuddyRow(app, {});+ let finish;+ app.router.post('/api/runners/runtimes/test', () => new Promise(resolve => { finish = resolve; }));+ const trigger = () => app.document.querySelector('[data-runner-runtime-menu="runner-cb|codex"]');+ trigger().click();+ const items = [...app.document.querySelectorAll('.runner-runtime-menu [role="menuitem"]')];+ assert.deepEqual(items.map(item => item.textContent.trim()), ['测试', '更新', '模型列表']);+ assert.equal(items[0], app.document.activeElement);+ items[0].click();+ assert.equal(trigger().getAttribute('aria-busy'), 'true');+ assert.ok(app.document.querySelector('img[src="/images/credentials/codex.svg"]'));+ const request = app.router.calls.find(c => c.path === '/api/runners/runtimes/test');+ assert.deepEqual(request.body, { runnerId: 'runner-cb', provider: 'codex' });+ finish({ ok: true });+ await settle();+ assert.equal(trigger().getAttribute('aria-busy'), 'false');+ assert.match(app.document.querySelector('#toastContainer').textContent, /Codex 测试通过/);+});++test('Runner update checks first and applies after the user chooses to update', async t => {+ const app = await loadApp();+ t.after(app.close);+ renderCodeBuddyRow(app, {});+ app.router.get('/api/runners/runner-cb/maintenance', {status: 'available', current: '0.10.2', canUpdate: true});+ app.router.post('/api/runners/runner-cb/maintenance', {status: 'updating'});+ app.evaluate(`followRunnerUpdate=async()=>{}`);+ app.document.querySelector('[data-runner-check-update]').click();+ await settle();+ assert.equal(app.router.calls.filter(c => c.method === 'POST' && c.path.endsWith('/maintenance')).length, 0);+ assert.equal(app.document.querySelector('#confirmOkBtn').textContent, '立即更新');+ app.document.querySelector('#confirmOkBtn').click();+ await settle();+ assert.equal(app.router.calls.filter(c => c.method === 'POST' && c.path.endsWith('/maintenance')).length, 1);+});++test('CLI model editor uses the selected auth source and saves the personal catalog', async t => {+ const app = await loadApp();+ t.after(app.close);+ const model = {id:'gateway/model',name:'Personal model'};+ renderCodeBuddyRow(app, { codeBuddyApiKeyConfigured: true, codeBuddyModels: [model] });+ app.router.post('/api/runners/runner-cb/models/probe', {+ source:'runner', models:[{id:'codex/account-model',name:'Account model'}],+ });+ app.router.post('/api/users/1/cli-models/probe', {+ source:'official', models:[model,{id:'another-model',name:'Another model'}],+ });+ app.router.put('/api/users/1/credentials', ({body}) => ({+ id:1, codeBuddyApiKeyConfigured:true, codeBuddyModels:[model], ...body,+ }));+ const show = provider => {+ app.document.querySelector(`[data-runner-runtime-menu="runner-cb|${provider}"]`).click();+ [...app.document.querySelectorAll('.runner-runtime-menu button')].find(b => b.textContent.trim()==='模型列表').click();+ };+ const picker = action => app.document.querySelector(`.runner-model-editor [data-catalog-act="${action}"]`);+ const modelIDs = () => [...app.document.querySelectorAll('.runner-model-editor [data-catalog-field="id"]')].map(input => input.value);+ show('codex');+ assert.match(app.document.querySelector('#confirmMessage').textContent, /个人配置共用.*机器的账号登录/);+ picker('probe').click();+ await settle();+ assert.deepEqual(app.router.calls.find(c => c.path.endsWith('/models/probe')).body, {provider:'codex'});+ picker('probe-apply').click();+ assert.deepEqual(modelIDs(), ['codex/account-model']);+ app.document.querySelector('#confirmOkBtn').click();+ await settle();+ const saved = {id:'codex/account-model',name:'Account model'};+ assert.deepEqual(app.router.calls.find(c => c.method==='PUT').body, {codexApiKey:'',codexModels:[saved]});+ show('codex');+ assert.deepEqual(modelIDs(), [saved.id]);+ app.document.querySelector('#confirmCancelBtn').click();++ show('codebuddy');+ assert.match(app.document.querySelector('#confirmMessage').textContent, /个人配置共用.*API Key/);+ assert.deepEqual(modelIDs(), [model.id]);+ picker('probe').click();+ await settle();+ assert.match(app.document.querySelector('.runner-model-editor').textContent, /来自官方服务/);+ assert.deepEqual(app.router.calls.find(c => c.path.endsWith('/cli-models/probe')).body, {engine:'codebuddy',apiKey:''});+ app.document.querySelector('#confirmCancelBtn').click();+});++test('CLI update runs the Runner action for native updates and guides unsupported installations locally', async t => {+ const app = await loadApp();+ t.after(app.close);+ renderCodeBuddyRow(app, {});+ const update = () => {+ app.document.querySelector('[data-runner-runtime-menu="runner-cb|codex"]').click();+ [...app.document.querySelectorAll('.runner-runtime-menu button')].find(b => b.textContent.trim()==='更新').click();+ };+ update();+ assert.match(app.document.querySelector('#confirmMessage').textContent,/原来的安装方式/);+ assert.equal(app.router.calls.filter(c => c.path.endsWith('/maintenance')).length,0);+ app.document.querySelector('#confirmOkBtn').click();+ app.evaluate(`state.runners[0].runtimes[1].capabilities=['native_update'];renderRunnersView();followRunnerUpdate=async()=>{}`);+ app.router.post('/api/runners/runner-cb/maintenance', {status:'updating'});+ update();+ await settle();+ const request=app.router.calls.find(c=>c.path.endsWith('/maintenance'));+ assert.equal(request.method,'POST');+ assert.equal(request.search,'?provider=codex');});diff --git a/webtest/tests/sync-schedule.test.mjs b/webtest/tests/sync-schedule.test.mjsindex 6294a9e7..9b398502 100644--- a/webtest/tests/sync-schedule.test.mjs+++ b/webtest/tests/sync-schedule.test.mjs@@ -254,8 +254,7 @@ test('an AI job runs with the saver\'s key without asking whose key to use', asyconst form = app.document.querySelector('#scheduleJobForm');assert.equal(form.elements.runAs, undefined, 'there is no run-as picker');assert.equal(app.document.querySelector('#scheduleRunAsHint'), null);- assert.match(app.document.querySelector('#scheduleModalHint').textContent, /保存人的 Key/);- assert.match(app.document.querySelector('#scheduleModalHint').textContent, /平台共享 Key/);+ assert.match(app.document.querySelector('#scheduleModalHint').textContent, /保存人的身份/);form.elements.name.value = 'Mine';form.elements.assistantPrompt.value = 'check';form.dispatchEvent(new app.window.Event('submit', { bubbles: true, cancelable: true }));@@ -391,7 +390,7 @@ test('AI schedule navigation separates existing tasks and preserves editor kindassert.equal(form.elements.jobKind.value, 'assistant');assert.equal(app.document.querySelector('#scheduleModalTitle').textContent, 'AI 定时任务');assert.match(app.document.querySelector('#scheduleModalHint').textContent, /完全权限/);- assert.match(app.document.querySelector('#scheduleModalHint').textContent, /保存人的 Key.*平台共享 Key/);+ assert.match(app.document.querySelector('#scheduleModalHint').textContent, /保存人的身份/);assert.doesNotMatch(app.document.querySelector('#aiScheduleRuntimeHint').textContent, /不直接运行|不会派发/);assert.equal(app.document.querySelector('#scheduleJobList').hidden, true);app.evaluate('resetScheduleJobForm()');@@ -538,19 +537,19 @@ test('late save responses cannot close a newly opened editor',async t=>{assert.equal(form.querySelector('[type=submit]').disabled,false);});-test('AI schedule model picker narrows models to the chosen CLI and keeps a saved CLI model', async (t) => {+test('AI schedule model picker includes account login CLI models and keeps a saved CLI model', async (t) => {const app = await loadApp();t.after(app.close);- app.router.get('/api/assistant/models', () => ({+ app.router.get('/api/assistant/models', call => ({default: 'glm-test',models: [{ id: 'glm-test', name: 'GLM Test', family: 'glm' },{ id: 'claude-test', name: 'Claude Test', family: 'claude' },- { id: 'codex:gpt-6-sol', name: 'GPT-6-Sol', family: 'gpt', engine: 'codex' },+ ...(call.search === '?schedule=1' ? [{ id: 'codex:gpt-6-sol', name: 'GPT-6-Sol', family: 'gpt', engine: 'codex' }] : []),],engines: [{ id: 'codebuddy', name: 'CodeBuddy', configured: true },- { id: 'codex', name: 'Codex', configured: true },+ { id: 'codex', name: 'Codex', configured: call.search === '?schedule=1' },{ id: 'claude-code', name: 'Claude Code', configured: false },],}));@@ -564,7 +563,7 @@ test('AI schedule model picker narrows models to the chosen CLI and keeps a saveconst form = doc.querySelector('#scheduleJobForm');const engine = doc.querySelector('#scheduleEngine');assert.deepEqual([...engine.options].map(o => [o.value, o.disabled]), [['codebuddy', false], ['codex', false], ['claude-code', true]]);- assert.match(engine.options[2].textContent, /未配置 Key/);+ assert.match(engine.options[2].textContent, /缺少凭据/);assert.equal(engine.value, 'codebuddy');const toggle = doc.querySelector('#scheduleModelPicker [data-model-toggle]');@@ -579,6 +578,7 @@ test('AI schedule model picker narrows models to the chosen CLI and keeps a saveengine.value = 'codex';engine.dispatchEvent(new app.window.Event('change'));assert.equal(form.elements.assistantModel.value, 'codex:gpt-6-sol');+ assert.equal(toggle.querySelector('[data-model-label]').textContent, 'GPT-6-Sol');toggle.click();assert.deepEqual([...menu.querySelectorAll('.ai-model-option')].map(o => o.dataset.id), ['codex:gpt-6-sol']);menu.querySelector('.ai-model-option').click();@@ -593,6 +593,5 @@ test('AI schedule model picker narrows models to the chosen CLI and keeps a saveassert.equal(engine.value, 'claude-code');assert.equal(engine.selectedOptions[0].disabled, false);assert.equal(form.elements.assistantModel.value, 'claude-code:opus');- assert.match(doc.querySelector('#scheduleModelHint').textContent, /所选 CLI/);- assert.match(doc.querySelector('#scheduleModelHint').textContent, /保存人.*平台共享 Key/);+ assert.match(doc.querySelector('#scheduleModelHint').textContent, /默认执行机器的账号登录.*离线时改用个人 API Key.*Key 缺失或不可用时任务失败.*平台共享 Key/);});