Skip to content

Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.

feat(chat): install a missing CLI from the conversation failure (#183)

crispinhu27dfebabcbf99f
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 7bedabfb..99b659da 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -48,6 +48,6 @@ SOFTWARE.
## Executor CLI packages
-The Docker build downloads pinned Codex and CodeBuddy CLI packages from their provider registries. Claude Code is proprietary and is not included in published images: when a user first selects it, the platform installs the pinned `@anthropic-ai/claude-code` package from npm into the installation's data directory, subject to Anthropic's terms. These packages and their bundled dependencies retain the licenses/notices shipped by their providers; they are not relicensed under LoopForge's MIT license. Provider accounts, credentials and service terms apply separately. The installed packages retain their original license/readme files in the image's npm package directories.
+The Docker build downloads pinned Codex and CodeBuddy CLI packages from their provider registries. Claude Code is proprietary and is not included in published images. When a conversation asks to install a missing CLI, the platform downloads the pinned `@anthropic-ai/claude-code` package, or the public npm package for OpenCode, Kimi Code, Pi or DeepSeek Harness, into the installation's data directory. Cursor CLI and Antigravity are installed with their providers' installers. An SOP sandbox that selects Claude Code installs the same pinned release on first use. These packages and their bundled dependencies retain the licenses/notices shipped by their providers and are subject to those providers' terms; they are not relicensed under LoopForge's MIT license. Provider accounts, credentials and service terms apply separately. The installed packages retain their original license/readme files.
The platform source was contributed by the repository owner from the recorded upstream master and is distributed under the root MIT license.
diff --git a/chatbot/src/App.jsx b/chatbot/src/App.jsx
index bae07622..e7f73116 100644
--- a/chatbot/src/App.jsx
+++ b/chatbot/src/App.jsx
@@ -47,6 +47,7 @@ import { runProblems, useConversationRuns } from "./runs.js";
import { reconcileOperation, visibleSidebarArtifact } from "./platform.js";
import { isGeneratedArtifact, shouldRevealArtifactPanel } from "./artifact-autoreveal.js";
import { IconButton, Dialog, Menu, SelectMenu, CredentialAction } from "./ui";
+import { CLIInstallAction } from "./cli-install.jsx";
import { credentialHint, openCredentialSettings } from "./credentials";
import { groupSessionHistory, scheduledSession, sessionProjectName } from "./session-history.js";
import { runSessionState, sessionReplyStatus, sessionTooltip, sidebarReplyStatus } from "./session-status.js";
@@ -1676,6 +1677,7 @@ export default function App() {
<div role="alert" className="chat-error">
<span>{chat.error}</span>
<CredentialAction text={chat.error} />
+ <CLIInstallAction text={chat.error} onResult={chat.adoptCLIInstall} />
<IconButton label="关闭提示" onClick={() => chat.setError("")}>
<HarnessIcon name="close" size={15} />
</IconButton>
diff --git a/chatbot/src/cli-install.jsx b/chatbot/src/cli-install.jsx
new file mode 100644
index 00000000..6f8a1724
--- /dev/null
+++ b/chatbot/src/cli-install.jsx
@@ -0,0 +1,151 @@
+import { useEffect, useRef, useState } from "react";
+import { api, write } from "./api.js";
+import HarnessIcon from "./HarnessIcon";
+
+// Keep the sentence in sync with assistantCLIMissingError. The engine id in
+// the parentheses is what the install request sends; it is not a package name.
+const missingCLI =
+ /^(.+)(([a-z0-9-]+))没有安装在当前服务器上。安装后即可在对话里使用。/;
+
+export function cliInstallHint(text) {
+ const match = missingCLI.exec(String(text || "").trim());
+ if (!match) return null;
+ return { label: match[1], engine: match[2] };
+}
+
+export function cliInstallNotice(label) {
+ return `${label} 已安装,请重新发送。`;
+}
+
+function installMemory(engine) {
+ return `loopforge.cli-install.${engine}`;
+}
+
+function rememberedInstall(engine) {
+ try {
+ return sessionStorage.getItem(installMemory(engine)) === "installing";
+ } catch {
+ return false;
+ }
+}
+
+function rememberInstall(engine, installing) {
+ try {
+ if (installing) sessionStorage.setItem(installMemory(engine), "installing");
+ else sessionStorage.removeItem(installMemory(engine));
+ } catch {
+ // A private window can reject storage. The server status still restores it.
+ }
+}
+
+// A finished install replaces the missing-CLI sentence and the generic
+// generation failure that the same turn may have kept.
+export function cliFailureSettles(text) {
+ const value = String(text || "").trim();
+ return (
+ value === "AI 助手生成失败,请稍后重试" ||
+ /([a-z0-9-]+)没有安装在当前服务器上/.test(value)
+ );
+}
+
+// CLIInstallAction installs the CLI named by a conversation failure.
+// The server keeps the download after a reload, so the button asks for the
+// current status instead of trusting a click that only this page remembers.
+export function CLIInstallAction({ text, onResult }) {
+ const hint = cliInstallHint(text);
+ const onResultRef = useRef(onResult);
+ onResultRef.current = onResult;
+ const pending = useRef(hint ? rememberedInstall(hint.engine) : false);
+ const [phase, setPhase] = useState(() =>
+ hint && rememberedInstall(hint.engine) ? "installing" : "checking",
+ );
+ const [failure, setFailure] = useState("");
+ useEffect(() => {
+ if (!hint) return undefined;
+ let cancelled = false;
+ let timer;
+ let misses = 0;
+ const finish = (message) => {
+ pending.current = false;
+ rememberInstall(hint.engine, false);
+ onResultRef.current?.(message);
+ };
+ const watch = async () => {
+ try {
+ const status = await api(
+ `/api/assistant/cli-install?engine=${encodeURIComponent(hint.engine)}`,
+ );
+ if (cancelled) return;
+ if (status.status === "installed") {
+ finish(cliInstallNotice(hint.label));
+ return;
+ }
+ if (status.status === "installing") {
+ misses = 0;
+ pending.current = true;
+ rememberInstall(hint.engine, true);
+ setPhase("installing");
+ setFailure("");
+ timer = setTimeout(watch, 1000);
+ return;
+ }
+ if (status.status === "missing" && pending.current && misses < 2) {
+ misses += 1;
+ setPhase("installing");
+ timer = setTimeout(watch, 1000);
+ return;
+ }
+ pending.current = false;
+ rememberInstall(hint.engine, false);
+ if (status.status === "failed") setFailure(status.error || "安装失败");
+ setPhase("ready");
+ } catch {
+ if (cancelled) return;
+ if (pending.current) {
+ timer = setTimeout(watch, 1000);
+ return;
+ }
+ setPhase("ready");
+ }
+ };
+ watch();
+ return () => {
+ cancelled = true;
+ clearTimeout(timer);
+ };
+ }, [hint?.engine, hint?.label]);
+ if (!hint) return null;
+ const installing = phase === "installing";
+ const label = installing ? "自动安装" : `安装 ${hint.label}`;
+ return (
+ <span className="credential-action">
+ <button
+ type="button"
+ disabled={phase !== "ready"}
+ onClick={() => {
+ pending.current = true;
+ rememberInstall(hint.engine, true);
+ setPhase("installing");
+ setFailure("");
+ write("/api/assistant/cli-install", { engine: hint.engine })
+ .then(() => {
+ pending.current = false;
+ rememberInstall(hint.engine, false);
+ onResultRef.current?.(cliInstallNotice(hint.label));
+ })
+ .catch((error) => {
+ pending.current = false;
+ rememberInstall(hint.engine, false);
+ setFailure(error.message || "安装失败");
+ setPhase("ready");
+ });
+ }}
+ >
+ <HarnessIcon name="download" size={13} />
+ {label}
+ </button>
+ <small>安装在服务器上继续,关闭页面也不会中断。</small>
+ {failure ? <small>{failure}</small> : null}
+ </span>
+ );
+}
diff --git a/chatbot/src/styles.css b/chatbot/src/styles.css
index b66f489b..5f6b3372 100644
--- a/chatbot/src/styles.css
+++ b/chatbot/src/styles.css
@@ -1567,6 +1567,10 @@ small {
.credential-action button:hover {
background: var(--hover);
}
+.credential-action button:disabled {
+ opacity: 0.6;
+ cursor: progress;
+}
.credential-action small {
color: var(--muted);
font-size: 11px;
diff --git a/chatbot/src/useChat.js b/chatbot/src/useChat.js
index 90fb2be0..2339a811 100644
--- a/chatbot/src/useChat.js
+++ b/chatbot/src/useChat.js
@@ -12,6 +12,7 @@ import {
} from "./api";
import { reviewedOperation, operationError } from "./operations.js";
import { credentialHint } from "./credentials.js";
+import { cliFailureSettles } from "./cli-install.jsx";
import { modelEffort } from "./effort.js";
import { conversationEngine, engineModels } from "./engines.js";
import {
@@ -1133,6 +1134,26 @@ export function useChat() {
}
await refreshSessions();
}
+ const adoptCLIInstall = useCallback((message) => {
+ setError(message);
+ setGeneration((current) =>
+ current?.error && cliFailureSettles(current.error)
+ ? { ...current, error: message }
+ : current,
+ );
+ setSession((current) => {
+ if (!current?.messages?.some((item) => cliFailureSettles(item.unfinished)))
+ return current;
+ return {
+ ...current,
+ messages: current.messages.map((item) =>
+ cliFailureSettles(item.unfinished)
+ ? { ...item, unfinished: message }
+ : item,
+ ),
+ };
+ });
+ }, []);
return {
user,
refreshUser,
@@ -1175,6 +1196,7 @@ export function useChat() {
steering: (steering?.sessionId === activeId && steering.item) || null,
readOnly: !!session?.readOnly,
setError,
+ adoptCLIInstall,
setModel: chooseModel,
setSession,
open,
diff --git a/chatbot/tests/cli-install.test.jsx b/chatbot/tests/cli-install.test.jsx
new file mode 100644
index 00000000..a09712e1
--- /dev/null
+++ b/chatbot/tests/cli-install.test.jsx
@@ -0,0 +1,105 @@
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { afterEach, expect, test, vi } from "vitest";
+import { CLIInstallAction, cliInstallHint } from "../src/cli-install.jsx";
+
+afterEach(() => {
+ sessionStorage.clear();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+function jsonResponse(body, status = 200) {
+ return { ok: status < 400, status, json: async () => body };
+}
+
+test("offers install only for a missing CLI failure", () => {
+ expect(cliInstallHint("请先在个人配置中配置自己的 CodeBuddy API Key")).toBeNull();
+ expect(
+ cliInstallHint(
+ "Claude Code(claude-code)没有安装在当前服务器上。安装后即可在对话里使用。",
+ ),
+ ).toEqual({ label: "Claude Code", engine: "claude-code" });
+});
+
+test("installs the named CLI and asks to send again", async () => {
+ const fetchMock = vi.fn(async (_url, options) =>
+ options?.method === "POST"
+ ? jsonResponse({ engine: "opencode", installed: true })
+ : jsonResponse({ engine: "opencode", status: "missing" }),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const done = vi.fn();
+ render(
+ <CLIInstallAction
+ text="OpenCode(opencode)没有安装在当前服务器上。安装后即可在对话里使用。"
+ onResult={done}
+ />,
+ );
+ expect(screen.getByText("安装在服务器上继续,关闭页面也不会中断。")).toBeInTheDocument();
+ const install = await screen.findByRole("button", { name: "安装 OpenCode" });
+ await waitFor(() => expect(install).toBeEnabled());
+ await userEvent.click(install);
+ expect(fetchMock).toHaveBeenCalledWith(
+ "/api/assistant/cli-install",
+ expect.objectContaining({ method: "POST", credentials: "same-origin" }),
+ );
+ expect(JSON.parse(fetchMock.mock.calls.find((call) => call[1]?.method === "POST")[1].body)).toEqual({
+ engine: "opencode",
+ });
+ expect(done).toHaveBeenCalledWith("OpenCode 已安装,请重新发送。");
+});
+
+test("stays on automatic install when a reload finds the download still running", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => jsonResponse({ engine: "pi", status: "installing" })),
+ );
+ render(
+ <CLIInstallAction text="Pi(pi)没有安装在当前服务器上。安装后即可在对话里使用。" />,
+ );
+ expect(await screen.findByRole("button", { name: "自动安装" })).toBeDisabled();
+});
+
+test("a reload shows automatic install before the status request returns", () => {
+ sessionStorage.setItem("loopforge.cli-install.opencode", "installing");
+ vi.stubGlobal("fetch", vi.fn(() => new Promise(() => {})));
+ render(
+ <CLIInstallAction text="OpenCode(opencode)没有安装在当前服务器上。安装后即可在对话里使用。" />,
+ );
+ expect(screen.getByRole("button", { name: "自动安装" })).toBeDisabled();
+});
+
+test("a finished install replaces the generation failure", async () => {
+ const done = vi.fn();
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => jsonResponse({ engine: "opencode", status: "installed" })),
+ );
+ render(
+ <CLIInstallAction
+ text="OpenCode(opencode)没有安装在当前服务器上。安装后即可在对话里使用。"
+ onResult={done}
+ />,
+ );
+ await waitFor(() => expect(done).toHaveBeenCalledWith("OpenCode 已安装,请重新发送。"));
+});
+
+test("keeps the install button when the download fails", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (_url, options) =>
+ options?.method === "POST"
+ ? jsonResponse({ error: "安装失败:registry unreachable" }, 502)
+ : jsonResponse({ engine: "pi", status: "missing" }),
+ ),
+ );
+ render(
+ <CLIInstallAction text="Pi(pi)没有安装在当前服务器上。安装后即可在对话里使用。" />,
+ );
+ const install = await screen.findByRole("button", { name: "安装 Pi" });
+ await waitFor(() => expect(install).toBeEnabled());
+ await userEvent.click(install);
+ expect(await screen.findByText("安装失败:registry unreachable")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "安装 Pi" })).toBeEnabled();
+});
diff --git a/design.md b/design.md
index ff0c1a07..0fedebbf 100644
--- a/design.md
+++ b/design.md
@@ -54,6 +54,7 @@
- 流程设计页 SOP 名称旁有一枚不占视觉重心的复制按钮(`#copyWorkflowName`,Harness `copy`,14px,默认弱化色)。它只把当前 SOP 名称写入剪贴板;点击不打开切换菜单。没有打开流程时按钮隐藏。悬停提示只用 `data-tip` 一处,不再同时写浏览器 `title`。切换列表里每个 SOP 名称右侧也有同样的复制按钮(`.fd-pop-copy`),只复制该行名称,不切换 SOP、不关闭菜单;这一处只用 `title`。
- 设置模式与工作台模式切换通过共享过渡控制器衔接;过渡副本不得接受点击、键盘焦点或提交操作。
- 凭据定位等跳转应在目标页面挂载后聚焦;用户已切换到其他页面时取消旧的焦点请求。
+- 对话失败如果是因为当前服务器没有安装所选 CLI,错误写明「没有安装」,并在同一条提示里提供「安装」按钮。点击后按钮变为「自动安装」,刷新页面也保持这个状态,直到安装结束。安装完成后,原来的「没有安装」或「AI 助手生成失败」改为可以重新发送。按钮只安装平台允许的 CLI。安装在服务器上继续,关闭页面也不会中断。
- 个人配置里,Codex、Claude Code,以及带协议的 Agent CLI,可以维护模型目录:获取可用模型,勾选、排序、修改显示名。目录为空时,未填 Base URL 或协议是 Gemini 官方 API 则使用该 CLI 自带模型,填写了 Base URL 则跟随服务公布的模型。保存过的目录在官方服务和自定义地址上都生效。Cursor CLI 只使用官方模型。
- 主题入口在左下角头像卡片(`#userProfilePopover`)的「外观」行:「浅色 / 深色 / 跟随系统」三段开关(`.upp-theme-seg`,`role="radiogroup"`),访客与登录卡片都显示,选项文案与 chatbot 设置一致,偏好写入共享键 `agentflow.theme.v3`。三段前分别是 Harness `sun`、`moon`、`monitor` 图标,悬停、聚焦或点击时播放一次动效;选中滑块由 SlidingTabs 驱动,卡片展开时立即对准当前选项。切换时页面颜色约 280ms 渐变,减少动态效果时直接切换。
- 顶栏 `#themeToggle` 只在宽度 ≤1000px(图标栏隐藏)时显示,作为浅色、深色一键切换的兜底;宽屏下仅隐藏,DOM 节点保留给 AI 助手按钮定位。
diff --git a/docs/deployment.md b/docs/deployment.md
index 9b52c50a..d750e03d 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -13,7 +13,7 @@ codebuddy --version
npm install --global @openai/[email protected] @anthropic-ai/[email protected]
```
-Ensure the service can find `codebuddy` and Node.js on its PATH, or set `AGENTFLOW_CODEBUDDY_BIN` to the installed executable. Configure the model key and its network environment in personal settings. The no-key script demo does not need the CLI. The production Docker image includes CodeBuddy and Codex. Claude Code is not redistributed: the first Main Bot conversation or SOP role that selects it installs the pinned `@anthropic-ai/claude-code` from npm into `$LOOPFORGE_DATA_DIR/cli`, so that first run waits for the download and later runs reuse it; Docker sandboxes and connected runners have their own CLI requirements.
+Ensure the service can find `codebuddy` and Node.js on its PATH, or set `AGENTFLOW_CODEBUDDY_BIN` to the installed executable. Configure the model key and its network environment in personal settings. The no-key script demo does not need the CLI. The production Docker image includes CodeBuddy and Codex. Claude Code and the other agent CLIs are not bundled. When a conversation fails because one is missing, the error says it is not installed and offers an install button. That downloads the pinned `@anthropic-ai/claude-code` release, or the public package for OpenCode, Kimi Code, Pi and DeepSeek Harness, into `$LOOPFORGE_DATA_DIR/cli`. Cursor CLI and Antigravity use their providers' installers and land in the service user's `~/.local/bin`. Closing or reloading the browser does not stop an install that has already started, and the button stays on “自动安装” until it finishes. A finished install replaces the earlier generation failure with a prompt to send the message again. The next message reuses the installation. An SOP sandbox that selects Claude Code still installs that pinned release on first use. Connected runners keep their own CLI requirements.
Stop the foreground service with Ctrl-C. Start it again with the same command. MySQL data stays in its Compose volume. `docker compose stop mysql` stops the database without deleting it.
diff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.go
index 2159f44e..e674c72a 100644
--- a/internal/httpapi/assistant.go
+++ b/internal/httpapi/assistant.go
@@ -454,6 +454,10 @@ func (h *assistantHandlers) chat(c *gin.Context) {
fail(400, err.Error())
return
}
+ if errors.Is(err, errAssistantCLIMissing) {
+ fail(503, err.Error())
+ return
+ }
if err != nil && !(toolSession != nil && toolSession.finished()) {
// A failed process may already have executed tools. Report the cause
// instead of treating it as a missing draft submission and rerunning it.
diff --git a/internal/httpapi/assistant_cli_install.go b/internal/httpapi/assistant_cli_install.go
new file mode 100644
index 00000000..b19300fb
--- /dev/null
+++ b/internal/httpapi/assistant_cli_install.go
@@ -0,0 +1,165 @@
+package httpapi
+
+import (
+ "context"
+ "log"
+ "net/http"
+ "strings"
+ "sync"
+ "time"
+
+ "agentflow/internal/runtime"
+
+ "github.com/gin-gonic/gin"
+)
+
+// A CLI install outlives the browser request. Closing the page cancels the
+// request context, and the download must keep going on the server.
+const cliInstallTimeout = 10 * time.Minute
+
+type cliInstallJob struct {
+ done chan struct{}
+ err error
+}
+
+var (
+ cliInstallJobsMu sync.Mutex
+ cliInstallJobs = map[string]*cliInstallJob{}
+)
+
+// installCLI downloads one allowlisted CLI onto this server after a conversation
+// failed because it was missing. The body selects an engine id, not a package.
+func (h *assistantHandlers) installCLI(c *gin.Context) {
+ if _, ok := h.requestUser(c.Request, true); !ok {
+ c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录后再安装 CLI"})
+ return
+ }
+ var body struct {
+ Engine string `json:"engine"`
+ }
+ if !decode(c, &body) {
+ return
+ }
+ h.answerCLIInstall(c, body.Engine, true)
+}
+
+// cliInstallStatus reports an install that continues after the page is closed
+// or reloaded. The button reads this instead of remembering the click locally.
+func (h *assistantHandlers) cliInstallStatus(c *gin.Context) {
+ if _, ok := h.requestUser(c.Request, true); !ok {
+ c.JSON(http.StatusUnauthorized, gin.H{"error": "请先登录后再安装 CLI"})
+ return
+ }
+ h.answerCLIInstall(c, c.Query("engine"), false)
+}
+
+func (h *assistantHandlers) answerCLIInstall(c *gin.Context, raw string, start bool) {
+ engine := assistantInstallEngine(raw)
+ if !runtime.OnDemandInstallable(engine) {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "这个 CLI 不能从对话里安装"})
+ return
+ }
+ if !start {
+ status, errText := h.cliInstallState(engine)
+ body := gin.H{"engine": engine, "status": status}
+ if errText != "" {
+ body["error"] = errText
+ }
+ c.JSON(http.StatusOK, body)
+ return
+ }
+ job := h.startCLIInstall(engine)
+ select {
+ case <-job.done:
+ if job.err != nil {
+ c.JSON(http.StatusBadGateway, gin.H{"error": job.err.Error()})
+ return
+ }
+ c.JSON(http.StatusOK, gin.H{"engine": engine, "installed": true})
+ case <-c.Request.Context().Done():
+ // The browser went away. startCLIInstall already detached the download.
+ }
+}
+
+// cliInstallState is what a reloaded page should show for engine.
+func (h *assistantHandlers) cliInstallState(engine string) (string, string) {
+ if _, err := resolveAssistantEngineBin(engine); err == nil {
+ return "installed", ""
+ }
+ cliInstallJobsMu.Lock()
+ job := cliInstallJobs[engine]
+ cliInstallJobsMu.Unlock()
+ if job == nil {
+ return "missing", ""
+ }
+ select {
+ case <-job.done:
+ if job.err != nil {
+ return "failed", job.err.Error()
+ }
+ // The executable was resolved above and is gone now (removed after a
+ // successful install): report it missing so the button can reinstall.
+ return "missing", ""
+ default:
+ return "installing", ""
+ }
+}
+
+// startCLIInstall returns the in-flight install for engine, starting one when
+// none is running. A finished attempt does not block the next click. The work
+// uses a background context, so a disconnected browser does not stop npm or
+// the provider installer.
+func (h *assistantHandlers) startCLIInstall(engine string) *cliInstallJob {
+ cliInstallJobsMu.Lock()
+ defer cliInstallJobsMu.Unlock()
+ if job, ok := cliInstallJobs[engine]; ok {
+ select {
+ case <-job.done:
+ default:
+ return job
+ }
+ }
+ job := &cliInstallJob{done: make(chan struct{})}
+ cliInstallJobs[engine] = job
+ go h.runCLIInstall(engine, job)
+ return job
+}
+
+func (h *assistantHandlers) runCLIInstall(engine string, job *cliInstallJob) {
+ ctx, cancel := context.WithTimeout(context.Background(), cliInstallTimeout)
+ defer cancel()
+ _, err := runtime.InstallOnDemandCLI(ctx, engine)
+ if err != nil {
+ log.Printf("assistant CLI install %s: %v", engine, err)
+ } else {
+ h.noteCLIInstalled(engine)
+ }
+ job.err = err
+ close(job.done)
+}
+
+// noteCLIInstalled replaces the failure the conversation stored before the
+// CLI existed, including the generic generation message for that engine.
+func (h *assistantHandlers) noteCLIInstalled(engine string) {
+ if h == nil || h.repo == nil {
+ return
+ }
+ missing := (assistantCLIMissingError{engine: engine}).Error()
+ notice := assistantCLIInstalledNotice(engine)
+ if err := h.repo.ReplaceInstalledCLIFailure(engine, missing, assistantGenerationFailedMessage, notice); err != nil {
+ log.Printf("assistant CLI install notice %s: %v", engine, err)
+ }
+}
+
+func assistantCLIInstalledNotice(engine string) string {
+ return assistantEngineLabel(engine) + " 已安装,请重新发送。"
+}
+
+func assistantInstallEngine(id string) string {
+ switch strings.TrimSpace(id) {
+ case "claude", assistantEngineClaude:
+ return assistantEngineClaude
+ default:
+ return strings.TrimSpace(id)
+ }
+}
diff --git a/internal/httpapi/assistant_cli_install_test.go b/internal/httpapi/assistant_cli_install_test.go
new file mode 100644
index 00000000..8fef1124
--- /dev/null
+++ b/internal/httpapi/assistant_cli_install_test.go
@@ -0,0 +1,381 @@
+package httpapi
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "agentflow/internal/auth"
+ "agentflow/internal/domain"
+ "agentflow/internal/repo"
+
+ "github.com/gin-gonic/gin"
+)
+
+func TestMissingCLIErrorOffersInstall(t *testing.T) {
+ bin := t.TempDir()
+ t.Setenv("PATH", bin)
+ t.Setenv("HOME", t.TempDir())
+ t.Setenv("AGENTFLOW_MANAGED_CLI_ROOT", "")
+ t.Setenv("AGENTFLOW_CODEBUDDY_BIN", "")
+ t.Setenv("AGENTFLOW_OPENCODE_BIN", "")
+ t.Setenv("AGENTFLOW_RUNTIME_CLI_DIR", t.TempDir())
+
+ _, err := resolveAssistantEngineBin("opencode")
+ if hostHas("opencode") {
+ t.Log("host already has opencode; checking the error text directly")
+ err = assistantCLIMissingError{engine: "opencode", binary: "opencode"}
+ }
+ if !errors.Is(err, errAssistantCLIMissing) || err.Error() != "OpenCode(opencode)没有安装在当前服务器上。安装后即可在对话里使用。" {
+ t.Fatalf("opencode: %v", err)
+ }
+ _, err = resolveCodeBuddyBin()
+ if hostHas("codebuddy") {
+ err = assistantCLIMissingError{engine: "codebuddy", binary: "codebuddy"}
+ }
+ if !errors.Is(err, errAssistantCLIMissing) || err.Error() != "CodeBuddy(codebuddy)没有安装在当前服务器上。安装后即可在对话里使用。" {
+ t.Fatalf("codebuddy: %v", err)
+ }
+}
+
+func hostHas(binary string) bool {
+ for _, dir := range []string{"/usr/local/bin", "/usr/bin", "/opt/homebrew/bin"} {
+ if fileExecutable(filepath.Join(dir, binary)) {
+ return true
+ }
+ }
+ return false
+}
+
+func TestInstallCLIRequiresLoginAndAllowlist(t *testing.T) {
+ h := &assistantHandlers{deps: &deps{}}
+ rec := postCLIInstall(t, h, nil, `{"engine":"opencode"}`)
+ if rec.Code != http.StatusUnauthorized || !strings.Contains(rec.Body.String(), "请先登录") {
+ t.Fatalf("guest: %d %s", rec.Code, rec.Body.String())
+ }
+ user := domainUserToAuth(domain.User{ID: 1, LoginName: "lab"})
+ rec = postCLIInstall(t, h, user, `{"engine":"not-a-cli"}`)
+ if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "不能从对话里安装") {
+ t.Fatalf("unknown: %d %s", rec.Code, rec.Body.String())
+ }
+ if assistantInstallEngine("claude") != "claude-code" {
+ t.Fatal("claude alias")
+ }
+}
+
+func TestInstallCLIPutsOpenCodeOnTheConversationPath(t *testing.T) {
+ if hostHas("opencode") {
+ t.Skip("host opencode would hide the on-demand installation")
+ }
+ root := t.TempDir()
+ log := filepath.Join(t.TempDir(), "npm.log")
+ npm := t.TempDir()
+ if err := os.WriteFile(filepath.Join(npm, "npm"), []byte(genericInstallNPM), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("PATH", npm+string(os.PathListSeparator)+"/usr/bin:/bin")
+ t.Setenv("HOME", t.TempDir())
+ t.Setenv("AGENTFLOW_MANAGED_CLI_ROOT", "")
+ t.Setenv("AGENTFLOW_OPENCODE_BIN", "")
+ t.Setenv("AGENTFLOW_RUNTIME_CLI_DIR", root)
+ t.Setenv("NPM_TEST_LOG", log)
+ t.Setenv("NPM_TEST_BIN", "opencode")
+
+ h := &assistantHandlers{deps: &deps{}}
+ user := domainUserToAuth(domain.User{ID: 1, LoginName: "lab"})
+ rec := postCLIInstall(t, h, user, `{"engine":"opencode"}`)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("install: %d %s", rec.Code, rec.Body.String())
+ }
+ var body struct {
+ Engine string `json:"engine"`
+ Installed bool `json:"installed"`
+ }
+ if json.Unmarshal(rec.Body.Bytes(), &body) != nil || body.Engine != "opencode" || !body.Installed {
+ t.Fatalf("body %s", rec.Body.String())
+ }
+ path, err := resolveAssistantEngineBin("opencode")
+ if err != nil || path != filepath.Join(root, "opencode", "current", "node_modules", ".bin", "opencode") {
+ t.Fatalf("resolve %q %v", path, err)
+ }
+}
+
+func TestInstallCLIContinuesAfterTheBrowserGoesAway(t *testing.T) {
+ root := t.TempDir()
+ npm := t.TempDir()
+ script := `#!/bin/sh
+sleep 0.4
+prefix=""
+prev=""
+for arg in "$@"; do
+ if [ "$prev" = "--prefix" ]; then prefix=$arg; fi
+ prev=$arg
+done
+mkdir -p "$prefix/node_modules/.bin"
+printf '#!/bin/sh\necho ok\n' > "$prefix/node_modules/.bin/$NPM_TEST_BIN"
+chmod 755 "$prefix/node_modules/.bin/$NPM_TEST_BIN"
+`
+ if err := os.WriteFile(filepath.Join(npm, "npm"), []byte(script), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("PATH", npm+string(os.PathListSeparator)+"/usr/bin:/bin")
+ t.Setenv("HOME", t.TempDir())
+ t.Setenv("AGENTFLOW_MANAGED_CLI_ROOT", "")
+ t.Setenv("AGENTFLOW_PI_BIN", "")
+ t.Setenv("AGENTFLOW_RUNTIME_CLI_DIR", root)
+ t.Setenv("NPM_TEST_BIN", "pi")
+
+ h := &assistantHandlers{deps: &deps{}}
+ user := domainUserToAuth(domain.User{ID: 1, LoginName: "lab"})
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ req := httptest.NewRequest(http.MethodPost, "/api/assistant/cli-install", strings.NewReader(`{"engine":"pi"}`))
+ req.Header.Set("Content-Type", "application/json")
+ req = req.WithContext(context.WithValue(ctx, requestUserContextKey{}, user))
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = req
+ returned := make(chan struct{})
+ go func() {
+ h.installCLI(c)
+ close(returned)
+ }()
+ select {
+ case <-returned:
+ case <-time.After(time.Second):
+ t.Fatal("handler waited for the install after the browser left")
+ }
+ binary := filepath.Join(root, "pi", "current", "node_modules", ".bin", "pi")
+ deadline := time.Now().Add(3 * time.Second)
+ for time.Now().Before(deadline) {
+ if fileExecutable(binary) {
+ return
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+ t.Fatal("install stopped when the browser left")
+}
+
+func TestInstallStatusSurvivesAReload(t *testing.T) {
+ resetCLIInstallJobs(t)
+ root := t.TempDir()
+ npm := t.TempDir()
+ script := `#!/bin/sh
+sleep 0.4
+prefix=""
+prev=""
+for arg in "$@"; do
+ if [ "$prev" = "--prefix" ]; then prefix=$arg; fi
+ prev=$arg
+done
+mkdir -p "$prefix/node_modules/.bin"
+printf '#!/bin/sh\necho ok\n' > "$prefix/node_modules/.bin/$NPM_TEST_BIN"
+chmod 755 "$prefix/node_modules/.bin/$NPM_TEST_BIN"
+`
+ if err := os.WriteFile(filepath.Join(npm, "npm"), []byte(script), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("PATH", npm+string(os.PathListSeparator)+"/usr/bin:/bin")
+ t.Setenv("HOME", t.TempDir())
+ t.Setenv("AGENTFLOW_MANAGED_CLI_ROOT", "")
+ t.Setenv("AGENTFLOW_DSH_BIN", "")
+ t.Setenv("AGENTFLOW_RUNTIME_CLI_DIR", root)
+ t.Setenv("NPM_TEST_BIN", "dsh")
+
+ h := &assistantHandlers{deps: &deps{}}
+ user := domainUserToAuth(domain.User{ID: 1, LoginName: "lab"})
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ req := httptest.NewRequest(http.MethodPost, "/api/assistant/cli-install", strings.NewReader(`{"engine":"dsh"}`))
+ req.Header.Set("Content-Type", "application/json")
+ req = req.WithContext(context.WithValue(ctx, requestUserContextKey{}, user))
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = req
+ returned := make(chan struct{})
+ go func() {
+ h.installCLI(c)
+ close(returned)
+ }()
+ select {
+ case <-returned:
+ case <-time.After(time.Second):
+ t.Fatal("handler waited for the install after the browser left")
+ }
+ status := getCLIInstall(t, h, user, "dsh")
+ if status.Code != http.StatusOK || !strings.Contains(status.Body.String(), `"status":"installing"`) {
+ t.Fatalf("reload during install: %d %s", status.Code, status.Body.String())
+ }
+ binary := filepath.Join(root, "dsh", "current", "node_modules", ".bin", "dsh")
+ deadline := time.Now().Add(3 * time.Second)
+ for time.Now().Before(deadline) {
+ if fileExecutable(binary) {
+ status = getCLIInstall(t, h, user, "dsh")
+ if status.Code != http.StatusOK || !strings.Contains(status.Body.String(), `"status":"installed"`) {
+ t.Fatalf("after install: %d %s", status.Code, status.Body.String())
+ }
+ // A finished install does not outlive its executable: once it is
+ // removed the status is missing again, so the button can reinstall.
+ cliInstallJobsMu.Lock()
+ job := cliInstallJobs["dsh"]
+ cliInstallJobsMu.Unlock()
+ <-job.done
+ if err := os.RemoveAll(filepath.Join(root, "dsh", "current")); err != nil {
+ t.Fatal(err)
+ }
+ status = getCLIInstall(t, h, user, "dsh")
+ if status.Code != http.StatusOK || !strings.Contains(status.Body.String(), `"status":"missing"`) {
+ t.Fatalf("after the executable was removed: %d %s", status.Code, status.Body.String())
+ }
+ return
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+ t.Fatal("install stopped when the page reloaded")
+}
+
+func TestInstallCLIClearsTheStoredGenerationFailure(t *testing.T) {
+ resetCLIInstallJobs(t)
+ if hostHas("kimi") {
+ t.Skip("host kimi would hide the on-demand installation")
+ }
+ root := t.TempDir()
+ npm := t.TempDir()
+ if err := os.WriteFile(filepath.Join(npm, "npm"), []byte(genericInstallNPM), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("PATH", npm+string(os.PathListSeparator)+"/usr/bin:/bin")
+ t.Setenv("HOME", t.TempDir())
+ t.Setenv("AGENTFLOW_MANAGED_CLI_ROOT", "")
+ t.Setenv("AGENTFLOW_KIMI_BIN", "")
+ t.Setenv("AGENTFLOW_RUNTIME_CLI_DIR", root)
+ t.Setenv("NPM_TEST_BIN", "kimi")
+
+ store, err := repo.OpenTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { store.Close() })
+ user, err := store.CreateLocalAccount("cli-notice", "secret1", true)
+ if err != nil {
+ t.Fatal(err)
+ }
+ missing := "Kimi Code(kimi)没有安装在当前服务器上。安装后即可在对话里使用。"
+ notice := "Kimi Code 已安装,请重新发送。"
+ if err = store.PutAssistantSession(user.ID, domain.AssistantSession{
+ ID: "cli-notice", Model: "kimi:test-model", Executor: "kimi", Title: "hello",
+ Messages: []domain.AssistantMessage{
+ {Role: "user", Content: "hello"},
+ {Role: "assistant", Content: `{"message":""}`, Unfinished: assistantGenerationFailedMessage},
+ },
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if err = store.PutAssistantSession(user.ID, domain.AssistantSession{
+ ID: "other-chat", Model: "codebuddy", Executor: "codebuddy", Title: "other",
+ Messages: []domain.AssistantMessage{{Role: "assistant", Content: `{"message":""}`, Unfinished: assistantGenerationFailedMessage}},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ failed := func(id, sessionID, text string) {
+ t.Helper()
+ g := domain.AssistantGeneration{ID: id, SessionID: sessionID, UserID: user.ID, Status: "running", StartedAt: time.Now().UTC()}
+ if err := store.BeginAssistantGeneration(g); err != nil {
+ t.Fatal(err)
+ }
+ g.Status = "failed"
+ g.Error = text
+ if err := store.CheckpointAssistantGeneration(g); err != nil {
+ t.Fatal(err)
+ }
+ }
+ failed("g1", "cli-notice", missing)
+ failed("g2", "other-chat", assistantGenerationFailedMessage)
+
+ h := &assistantHandlers{deps: &deps{repo: store}}
+ actor := domainUserToAuth(user)
+ before := getCLIInstall(t, h, actor, "kimi")
+ if before.Code != http.StatusOK || !strings.Contains(before.Body.String(), `"status":"missing"`) {
+ t.Fatalf("before: %d %s", before.Code, before.Body.String())
+ }
+ rec := postCLIInstall(t, h, actor, `{"engine":"kimi"}`)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("install: %d %s", rec.Code, rec.Body.String())
+ }
+ saved, ok := store.AssistantGeneration(user.ID, "cli-notice")
+ if !ok || saved.Error != notice {
+ t.Fatalf("generation failure stayed %q", saved.Error)
+ }
+ session, ok := store.AssistantSession(user.ID, "cli-notice")
+ if !ok || len(session.Messages) != 2 || session.Messages[1].Unfinished != notice {
+ t.Fatalf("transcript failure stayed %+v", session.Messages)
+ }
+ otherGen, _ := store.AssistantGeneration(user.ID, "other-chat")
+ otherSession, _ := store.AssistantSession(user.ID, "other-chat")
+ if otherGen.Error != assistantGenerationFailedMessage || otherSession.Messages[0].Unfinished != assistantGenerationFailedMessage {
+ t.Fatalf("unrelated failure changed: %q %+v", otherGen.Error, otherSession.Messages)
+ }
+ after := getCLIInstall(t, h, actor, "kimi")
+ if after.Code != http.StatusOK || !strings.Contains(after.Body.String(), `"status":"installed"`) {
+ t.Fatalf("after: %d %s", after.Code, after.Body.String())
+ }
+}
+
+func resetCLIInstallJobs(t *testing.T) {
+ t.Helper()
+ cliInstallJobsMu.Lock()
+ cliInstallJobs = map[string]*cliInstallJob{}
+ cliInstallJobsMu.Unlock()
+ t.Cleanup(func() {
+ cliInstallJobsMu.Lock()
+ cliInstallJobs = map[string]*cliInstallJob{}
+ cliInstallJobsMu.Unlock()
+ })
+}
+
+func getCLIInstall(t *testing.T, h *assistantHandlers, user *auth.User, engine string) *httptest.ResponseRecorder {
+ t.Helper()
+ req := httptest.NewRequest(http.MethodGet, "/api/assistant/cli-install?engine="+engine, nil)
+ if user != nil {
+ req = req.WithContext(context.WithValue(req.Context(), requestUserContextKey{}, user))
+ }
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = req
+ h.cliInstallStatus(c)
+ return rec
+}
+
+func postCLIInstall(t *testing.T, h *assistantHandlers, user *auth.User, body string) *httptest.ResponseRecorder {
+ t.Helper()
+ req := httptest.NewRequest(http.MethodPost, "/api/assistant/cli-install", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ if user != nil {
+ req = req.WithContext(context.WithValue(req.Context(), requestUserContextKey{}, user))
+ }
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = req
+ h.installCLI(c)
+ return rec
+}
+
+const genericInstallNPM = `#!/bin/sh
+printf '%s\n' "$*" >> "$NPM_TEST_LOG"
+prefix=""
+prev=""
+for arg in "$@"; do
+ if [ "$prev" = "--prefix" ]; then prefix=$arg; fi
+ prev=$arg
+done
+mkdir -p "$prefix/node_modules/.bin"
+printf '#!/bin/sh\necho ok\n' > "$prefix/node_modules/.bin/$NPM_TEST_BIN"
+chmod 755 "$prefix/node_modules/.bin/$NPM_TEST_BIN"
+`
diff --git a/internal/httpapi/assistant_engine_cli.go b/internal/httpapi/assistant_engine_cli.go
index ff674ced..aa479378 100644
--- a/internal/httpapi/assistant_engine_cli.go
+++ b/internal/httpapi/assistant_engine_cli.go
@@ -57,7 +57,7 @@ func assistantEngineConfigDir(engine string) string {
// resolveAssistantEngineBin locates the codex / claude executable the same
// way resolveCodeBuddyBin does: explicit override, managed inventory, PATH,
-// then well-known install locations.
+// well-known install locations, then a CLI installed from a failed conversation.
func resolveAssistantEngineBin(engine string) (string, error) {
if engine == assistantEngineCodeBuddy {
return resolveCodeBuddyBin()
@@ -90,6 +90,9 @@ func resolveAssistantEngineBin(engine string) (string, error) {
return candidate, nil
}
}
+ if path, ok := runtime.OnDemandCLIPath(engine); ok {
+ return path, nil
+ }
return "", assistantCLIMissingError{engine: engine, binary: binary}
}
@@ -101,7 +104,10 @@ type assistantCLIMissingError struct{ engine, binary string }
func (e assistantCLIMissingError) Error() string {
label := assistantEngineLabel(e.engine)
- return fmt.Sprintf("服务器未安装 %s CLI(%s),请联系管理员安装后再使用 %s 模型", label, e.binary, label)
+ if runtime.OnDemandInstallable(e.engine) {
+ return fmt.Sprintf("%s(%s)没有安装在当前服务器上。安装后即可在对话里使用。", label, e.engine)
+ }
+ return fmt.Sprintf("服务器没有安装 %s(%s)。请联系管理员安装后再使用。", label, e.binary)
}
func (e assistantCLIMissingError) Is(target error) bool {
diff --git a/internal/httpapi/assistant_failure.go b/internal/httpapi/assistant_failure.go
index 44091cd2..dcb2e92f 100644
--- a/internal/httpapi/assistant_failure.go
+++ b/internal/httpapi/assistant_failure.go
@@ -74,5 +74,10 @@ func assistantGenerationFailure(ctx context.Context, err error) (int, string) {
if errors.Is(err, errAssistantMissingResult) {
return http.StatusBadGateway, "AI 助手生成中断,未返回完整回答,请重试"
}
- return http.StatusBadGateway, "AI 助手生成失败,请稍后重试"
+ return http.StatusBadGateway, assistantGenerationFailedMessage
}
+
+// assistantGenerationFailedMessage is the generic generation failure. A CLI
+// that was missing is reported separately, and a finished install replaces
+// both that report and this generic text.
+const assistantGenerationFailedMessage = "AI 助手生成失败,请稍后重试"
diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go
index 515a49ec..3ac5a35d 100644
--- a/internal/httpapi/server.go
+++ b/internal/httpapi/server.go
@@ -305,6 +305,8 @@ func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Serv
g.GET("/api/assistant/preferences", asst.preferences)
g.PUT("/api/assistant/preferences", asst.preferences)
g.GET("/api/assistant/models", asst.models)
+ g.POST("/api/assistant/cli-install", asst.installCLI)
+ g.GET("/api/assistant/cli-install", asst.cliInstallStatus)
g.POST("/api/assistant/attachments", asst.uploadAttachment)
g.GET("/api/assistant/attachments/:id", asst.downloadAttachment)
g.GET("/api/assistant/references", asst.workbenchReferences)
diff --git a/internal/httpapi/stream.go b/internal/httpapi/stream.go
index 68168d33..e1bbc75a 100644
--- a/internal/httpapi/stream.go
+++ b/internal/httpapi/stream.go
@@ -224,7 +224,10 @@ func resolveCodeBuddyBin() (string, error) {
return c, nil
}
}
- return "", fmt.Errorf("codebuddy 可执行文件未找到(PATH 及常见安装路径均无);可设置 AGENTFLOW_CODEBUDDY_BIN 指定绝对路径")
+ if path, ok := runtime.OnDemandCLIPath("codebuddy"); ok {
+ return path, nil
+ }
+ return "", assistantCLIMissingError{engine: assistantEngineCodeBuddy, binary: "codebuddy"}
}
// fileExecutable reports whether path is a regular file with an executable bit.
diff --git a/internal/repo/assistant_cli_notice.go b/internal/repo/assistant_cli_notice.go
new file mode 100644
index 00000000..00ff62c8
--- /dev/null
+++ b/internal/repo/assistant_cli_notice.go
@@ -0,0 +1,145 @@
+package repo
+
+import (
+ "errors"
+ "strings"
+
+ "agentflow/internal/domain"
+
+ "gorm.io/gorm"
+ "gorm.io/gorm/clause"
+)
+
+// ReplaceInstalledCLIFailure rewrites the failure a conversation kept while a
+// CLI was absent. The install keeps running after the browser leaves, so the
+// stored "not installed" or generic generation failure has to change with it.
+// missing is the sentence for this engine. generic is replaced only when the
+// conversation was using that engine.
+func (r *AssistantRepo) ReplaceInstalledCLIFailure(engine, missing, generic, next string) error {
+ engine = strings.TrimSpace(engine)
+ missing = strings.TrimSpace(missing)
+ next = strings.TrimSpace(next)
+ if r == nil || r.DB == nil || engine == "" || missing == "" || next == "" {
+ return nil
+ }
+ if err := r.replaceGenerationCLIFailure(engine, missing, generic, next); err != nil {
+ return err
+ }
+ return r.replaceSessionCLIFailure(engine, missing, generic, next)
+}
+
+// Both rewrites only use the first query to find candidates. Each row is then
+// re-read under a row lock in its own transaction and only the stored failure
+// is changed, so a message, rename or sandbox switch that landed while the
+// install ran is kept instead of being overwritten by a stale snapshot.
+func (r *AssistantRepo) replaceGenerationCLIFailure(engine, missing, generic, next string) error {
+ var rows []assistantGenerationRow
+ query := wherePayloadHas(r.DB.Select("session_id", "generation_id").Where("status <> ?", "running"), r.DB, missing, generic)
+ if err := query.Find(&rows).Error; err != nil {
+ return err
+ }
+ for _, candidate := range rows {
+ sameEngine := r.sessionUsesEngine(candidate.SessionID, engine)
+ err := r.DB.Transaction(func(tx *gorm.DB) error {
+ var row assistantGenerationRow
+ err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("session_id = ? AND generation_id = ? AND status <> ?", candidate.SessionID, candidate.GenerationID, "running").Take(&row).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ g := decodeGeneration(row)
+ if !cliFailureMatches(g.Error, missing, generic, sameEngine) {
+ return nil
+ }
+ g.Error = next
+ return tx.Model(&assistantGenerationRow{}).Where("session_id = ? AND generation_id = ?", row.SessionID, row.GenerationID).Update("payload", mustJSON(g)).Error
+ })
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (r *AssistantRepo) replaceSessionCLIFailure(engine, missing, generic, next string) error {
+ var rows []assistantSessionRow
+ query := wherePayloadHas(r.DB.Table("assistant_sessions").Select("id"), r.DB, missing, generic)
+ if err := query.Find(&rows).Error; err != nil {
+ return err
+ }
+ for _, candidate := range rows {
+ err := r.DB.Transaction(func(tx *gorm.DB) error {
+ var row assistantSessionRow
+ err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("id = ?", candidate.ID).Take(&row).Error
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ item := decodeAssistantSession(row)
+ if !rewriteCLIFailureMessages(&item, missing, generic, next, sessionUsesEngine(item, engine)) {
+ return nil
+ }
+ return tx.Model(&assistantSessionRow{}).Where("id = ? AND user_id = ?", row.ID, row.UserID).Update("payload", mustJSON(item)).Error
+ })
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// wherePayloadHas matches JSON payloads that contain the failure text.
+// LIKE does not see the sqlite JSON blob, so both drivers search the cast text.
+func wherePayloadHas(query *gorm.DB, db *gorm.DB, missing, generic string) *gorm.DB {
+ expr := "instr(CAST(payload AS TEXT), ?) > 0"
+ if db.Dialector.Name() == "mysql" {
+ expr = "INSTR(CAST(payload AS CHAR), ?) > 0"
+ }
+ if strings.TrimSpace(generic) == "" {
+ return query.Where(expr, missing)
+ }
+ return query.Where(expr+" OR "+expr, missing, generic)
+}
+
+func (r *AssistantRepo) sessionUsesEngine(sessionID, engine string) bool {
+ var row assistantSessionRow
+ if err := r.DB.Table("assistant_sessions").Where("id = ?", sessionID).Take(&row).Error; err != nil {
+ return false
+ }
+ return sessionUsesEngine(decodeAssistantSession(row), engine)
+}
+
+func sessionUsesEngine(item domain.AssistantSession, engine string) bool {
+ if strings.TrimSpace(item.Executor) == engine {
+ return true
+ }
+ model := strings.TrimSpace(item.Model)
+ return model == engine || strings.HasPrefix(model, engine+":")
+}
+
+func cliFailureMatches(text, missing, generic string, sameEngine bool) bool {
+ text = strings.TrimSpace(text)
+ if text == "" {
+ return false
+ }
+ if text == missing {
+ return true
+ }
+ return sameEngine && generic != "" && text == generic
+}
+
+func rewriteCLIFailureMessages(item *domain.AssistantSession, missing, generic, next string, sameEngine bool) bool {
+ changed := false
+ for i := range item.Messages {
+ if !cliFailureMatches(item.Messages[i].Unfinished, missing, generic, sameEngine) {
+ continue
+ }
+ item.Messages[i].Unfinished = next
+ changed = true
+ }
+ return changed
+}
diff --git a/internal/repo/assistant_cli_notice_test.go b/internal/repo/assistant_cli_notice_test.go
new file mode 100644
index 00000000..44775d58
--- /dev/null
+++ b/internal/repo/assistant_cli_notice_test.go
@@ -0,0 +1,95 @@
+package repo
+
+import (
+ "strings"
+ "testing"
+
+ "agentflow/internal/domain"
+
+ "gorm.io/gorm"
+)
+
+// A message or rename that lands while the install runs (between finding the
+// stale failure and rewriting it) must survive the rewrite.
+func TestReplaceInstalledCLIFailureKeepsConcurrentEdits(t *testing.T) {
+ s, err := OpenTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ const (
+ owner = int64(11)
+ missing = "Codex CLI 未安装"
+ generic = "生成失败"
+ next = "Codex 已安装,请重新发送。"
+ )
+ session := domain.AssistantSession{ID: "chat", Title: "original", Executor: "codex", Messages: []domain.AssistantMessage{
+ {Role: "user", Content: "hi"},
+ {Role: "assistant", Unfinished: missing},
+ }}
+ if err := s.PutAssistantSession(owner, session); err != nil {
+ t.Fatal(err)
+ }
+ g := domain.AssistantGeneration{ID: "gen", SessionID: "chat", UserID: owner, Status: "running"}
+ if err := s.BeginAssistantGeneration(g); err != nil {
+ t.Fatal(err)
+ }
+ g.Status, g.Error = "failed", generic
+ if err := s.CheckpointAssistantGeneration(g); err != nil {
+ t.Fatal(err)
+ }
+
+ // Fire the user's edit right after the failing conversations are looked
+ // up: that is the moment a stale snapshot used to be held.
+ // fired is only touched on this goroutine; the edit's own queries re-enter
+ // the callback and must not trigger it again.
+ fired := false
+ concurrent := func(tx *gorm.DB) {
+ // The lookup of conversations that still show the failure.
+ if fired || tx.Statement.Table != "assistant_sessions" || !strings.Contains(strings.ToLower(tx.Statement.SQL.String()), "instr(") {
+ return
+ }
+ fired = true
+ edited, ok := s.AssistantSession(owner, "chat")
+ if !ok {
+ t.Error("session missing")
+ return
+ }
+ edited.Title = "renamed by user"
+ edited.TitleEdited = true
+ edited.Messages = append(edited.Messages, domain.AssistantMessage{Role: "user", Content: "still there?"})
+ if err := s.PutAssistantSession(owner, edited); err != nil {
+ t.Error(err)
+ }
+ }
+ if err := s.DB.Callback().Query().After("gorm:query").Register("test:concurrent_edit", concurrent); err != nil {
+ t.Fatal(err)
+ }
+ defer s.DB.Callback().Query().Remove("test:concurrent_edit")
+
+ if err := s.ReplaceInstalledCLIFailure("codex", missing, generic, next); err != nil {
+ t.Fatal(err)
+ }
+ if !fired {
+ t.Fatal("the concurrent edit never ran")
+ }
+ s.DB.Callback().Query().Remove("test:concurrent_edit")
+
+ got, ok := s.AssistantSession(owner, "chat")
+ if !ok {
+ t.Fatal("session missing")
+ }
+ if got.Title != "renamed by user" || len(got.Messages) != 3 || got.Messages[2].Content != "still there?" {
+ t.Fatalf("concurrent edit lost: title=%q messages=%d", got.Title, len(got.Messages))
+ }
+ if got.Messages[1].Unfinished != next {
+ t.Fatalf("failure not rewritten: %q", got.Messages[1].Unfinished)
+ }
+ var row assistantGenerationRow
+ if err := s.DB.Where("session_id = ?", "chat").Take(&row).Error; err != nil {
+ t.Fatal(err)
+ }
+ if gen := decodeGeneration(row); gen.Error != next {
+ t.Fatalf("generation failure not rewritten: %q", gen.Error)
+ }
+}
diff --git a/internal/runtime/cli_ondemand.go b/internal/runtime/cli_ondemand.go
new file mode 100644
index 00000000..e9bce6b3
--- /dev/null
+++ b/internal/runtime/cli_ondemand.go
@@ -0,0 +1,205 @@
+package runtime
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "sync"
+)
+
+// CLIs the published platform image does not guarantee. Codex and CodeBuddy
+// are baked into that image; the rest are installed only after a person asks
+// from a failed conversation. Package names and installer URLs are fixed:
+// the request may choose an engine, never a URL or a package.
+const (
+ cursorInstallScript = "curl -fsSL --proto '=https' --tlsv1.2 https://cursor.com/install | bash"
+ agyInstallScript = "curl -fsSL --proto '=https' --tlsv1.2 https://antigravity.google/cli/install.sh | bash"
+)
+
+type onDemandCLI struct {
+ Engine string
+ Binary string
+ Package string
+ Script string
+ RelaxEngines bool
+}
+
+var onDemandInstallMu sync.Mutex
+
+func onDemandCLICatalog() map[string]onDemandCLI {
+ return map[string]onDemandCLI{
+ "codex": {Engine: "codex", Binary: "codex", Package: "@openai/codex"},
+ "codebuddy": {Engine: "codebuddy", Binary: "codebuddy", Package: "@tencent-ai/codebuddy-code"},
+ "claude-code": {Engine: "claude-code", Binary: "claude"},
+ "opencode": {Engine: "opencode", Binary: "opencode", Package: "opencode-ai"},
+ "cursor": {Engine: "cursor", Binary: "cursor-agent", Script: cursorInstallScript},
+ "agy": {Engine: "agy", Binary: "agy", Script: agyInstallScript},
+ "kimi": {Engine: "kimi", Binary: "kimi", Package: "@moonshot-ai/kimi-code"},
+ "pi": {Engine: "pi", Binary: "pi", Package: "@earendil-works/pi-coding-agent"},
+ "dsh": {Engine: "dsh", Binary: "dsh", Package: "@deepseek-ai/dsh", RelaxEngines: true},
+ }
+}
+
+// OnDemandInstallable reports whether a failed conversation may offer to
+// install this CLI. The set is the chat executors, not a caller-supplied name.
+func OnDemandInstallable(engine string) bool {
+ _, ok := onDemandCLICatalog()[engine]
+ return ok
+}
+
+// OnDemandCLIPath returns the executable installed for engine, when one is
+// already on disk. It does not download anything.
+func OnDemandCLIPath(engine string) (string, bool) {
+ spec, ok := onDemandCLICatalog()[engine]
+ if !ok {
+ return "", false
+ }
+ path := onDemandBinary(spec)
+ if path == "" || !fileIsExecutable(path) {
+ return "", false
+ }
+ return path, true
+}
+
+func onDemandBinary(spec onDemandCLI) string {
+ if spec.Script != "" {
+ home, err := os.UserHomeDir()
+ if err != nil || strings.TrimSpace(home) == "" {
+ return ""
+ }
+ return filepath.Join(home, ".local", "bin", spec.Binary)
+ }
+ root := RuntimeCLIDir()
+ if root == "" {
+ return ""
+ }
+ if spec.Engine == "claude-code" {
+ return claudeCodeBinary(root)
+ }
+ return filepath.Join(root, spec.Engine, "current", "node_modules", ".bin", spec.Binary)
+}
+
+// InstallOnDemandCLI installs one allowlisted CLI and returns its executable
+// path. A second call reuses the first installation.
+func InstallOnDemandCLI(ctx context.Context, engine string) (string, error) {
+ spec, ok := onDemandCLICatalog()[engine]
+ if !ok {
+ return "", fmt.Errorf("不能从对话安装 %s", engine)
+ }
+ onDemandInstallMu.Lock()
+ defer onDemandInstallMu.Unlock()
+ if path, ok := OnDemandCLIPath(engine); ok {
+ return path, nil
+ }
+ var path string
+ var err error
+ switch {
+ case spec.Engine == "claude-code":
+ path, err = EnsureClaudeCode(ctx)
+ case spec.Script != "":
+ path, err = installScriptCLI(ctx, spec)
+ default:
+ path, err = installNPMCLI(ctx, spec)
+ }
+ if err != nil {
+ return "", fmt.Errorf("安装 %s 失败:%w", onDemandCLILabel(spec.Engine), err)
+ }
+ return path, nil
+}
+
+func onDemandCLILabel(engine string) string {
+ switch engine {
+ case "codex":
+ return "Codex"
+ case "codebuddy":
+ return "CodeBuddy"
+ case "claude-code":
+ return "Claude Code"
+ default:
+ return AgentCLILabel(engine)
+ }
+}
+
+func installNPMCLI(ctx context.Context, spec onDemandCLI) (string, error) {
+ root := RuntimeCLIDir()
+ if root == "" {
+ return "", errors.New("没有配置 CLI 安装目录")
+ }
+ if _, err := exec.LookPath("npm"); err != nil {
+ return "", errors.New("服务器上没有 npm,无法安装")
+ }
+ parent := filepath.Join(root, spec.Engine)
+ if err := os.MkdirAll(parent, 0o755); err != nil {
+ return "", fmt.Errorf("准备安装目录失败:%w", err)
+ }
+ stage, err := os.MkdirTemp(parent, ".install-")
+ if err != nil {
+ return "", fmt.Errorf("准备安装目录失败:%w", err)
+ }
+ defer os.RemoveAll(stage)
+ if err := os.Chmod(stage, 0o755); err != nil {
+ return "", err
+ }
+ args := []string{"install", "--prefix", stage, "--no-audit", "--no-fund", "--omit=dev", "--save-exact"}
+ if spec.RelaxEngines {
+ args = append(args, "--engine-strict=false")
+ } else {
+ args = append(args, "--engine-strict")
+ }
+ args = append(args, spec.Package)
+ cmd := exec.CommandContext(ctx, "npm", args...)
+ cmd.Dir = stage
+ if out, err := cmd.CombinedOutput(); err != nil {
+ return "", errors.New(installCommandError(ctx, err, out))
+ }
+ staged := filepath.Join(stage, "node_modules", ".bin", spec.Binary)
+ if !fileIsExecutable(staged) {
+ return "", fmt.Errorf("安装后没有找到可执行文件 %s", spec.Binary)
+ }
+ target := filepath.Join(parent, "current")
+ if err := os.RemoveAll(target); err != nil {
+ return "", err
+ }
+ if err := os.Rename(stage, target); err != nil {
+ return "", fmt.Errorf("启用安装结果失败:%w", err)
+ }
+ return filepath.Join(target, "node_modules", ".bin", spec.Binary), nil
+}
+
+func installScriptCLI(ctx context.Context, spec onDemandCLI) (string, error) {
+ if _, err := exec.LookPath("bash"); err != nil {
+ return "", errors.New("服务器上没有 bash,无法安装")
+ }
+ home, err := os.UserHomeDir()
+ if err != nil || strings.TrimSpace(home) == "" {
+ return "", errors.New("无法确定安装用户的主目录")
+ }
+ cmd := exec.CommandContext(ctx, "bash", "-c", spec.Script)
+ cmd.Env = append(os.Environ(), "HOME="+home)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ return "", errors.New(installCommandError(ctx, err, out))
+ }
+ path := filepath.Join(home, ".local", "bin", spec.Binary)
+ if !fileIsExecutable(path) {
+ return "", fmt.Errorf("安装后没有找到可执行文件 %s", spec.Binary)
+ }
+ return path, nil
+}
+
+func installCommandError(ctx context.Context, err error, out []byte) string {
+ if ctx.Err() != nil || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
+ return "安装超时或已取消"
+ }
+ text := strings.Join(strings.Fields(tailOutput(out)), " ")
+ if text == "" {
+ text = err.Error()
+ }
+ if len(text) > 180 {
+ text = text[:180] + "…"
+ }
+ return text
+}
diff --git a/internal/runtime/cli_ondemand_test.go b/internal/runtime/cli_ondemand_test.go
new file mode 100644
index 00000000..e7d14473
--- /dev/null
+++ b/internal/runtime/cli_ondemand_test.go
@@ -0,0 +1,151 @@
+package runtime
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+const genericFakeNPM = `#!/bin/sh
+printf '%s\n' "$*" >> "$NPM_TEST_LOG"
+[ "$NPM_TEST_FAIL" = 1 ] && { echo 'npm ERR! registry unreachable'; exit 1; }
+prefix=""
+prev=""
+for arg in "$@"; do
+ if [ "$prev" = "--prefix" ]; then prefix=$arg; fi
+ prev=$arg
+done
+[ -n "$prefix" ] || { echo 'npm ERR! missing prefix'; exit 1; }
+mkdir -p "$prefix/node_modules/.bin"
+printf '#!/bin/sh\necho ok\n' > "$prefix/node_modules/.bin/$NPM_TEST_BIN"
+chmod 755 "$prefix/node_modules/.bin/$NPM_TEST_BIN"
+`
+
+func TestInstallOnDemandCLIInstallsNPMPackageOnce(t *testing.T) {
+ root := t.TempDir()
+ log := filepath.Join(t.TempDir(), "npm.log")
+ t.Setenv("AGENTFLOW_RUNTIME_CLI_DIR", root)
+ t.Setenv("NPM_TEST_LOG", log)
+ t.Setenv("NPM_TEST_BIN", "opencode")
+ useFakeCommands(t, map[string]string{"npm": genericFakeNPM})
+
+ first, err := InstallOnDemandCLI(context.Background(), "opencode")
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := filepath.Join(root, "opencode", "current", "node_modules", ".bin", "opencode")
+ if first != want {
+ t.Fatalf("binary %q", first)
+ }
+ if got, ok := OnDemandCLIPath("opencode"); !ok || got != want {
+ t.Fatalf("installed path %q %v", got, ok)
+ }
+ second, err := InstallOnDemandCLI(context.Background(), "opencode")
+ if err != nil || second != want {
+ t.Fatalf("reuse %q %v", second, err)
+ }
+ calls, _ := os.ReadFile(log)
+ if strings.Count(string(calls), "\n") != 1 || !strings.Contains(string(calls), "opencode-ai") || !strings.Contains(string(calls), "--engine-strict") || strings.Contains(string(calls), "--engine-strict=false") {
+ t.Fatalf("npm calls: %s", calls)
+ }
+ if staged, _ := filepath.Glob(filepath.Join(root, "opencode", ".install-*")); len(staged) != 0 {
+ t.Fatalf("staging directories left behind: %v", staged)
+ }
+}
+
+func TestInstallOnDemandCLIKeepsDeepSeekEngineRelaxation(t *testing.T) {
+ root := t.TempDir()
+ log := filepath.Join(t.TempDir(), "npm.log")
+ t.Setenv("AGENTFLOW_RUNTIME_CLI_DIR", root)
+ t.Setenv("NPM_TEST_LOG", log)
+ t.Setenv("NPM_TEST_BIN", "dsh")
+ useFakeCommands(t, map[string]string{"npm": genericFakeNPM})
+ if _, err := InstallOnDemandCLI(context.Background(), "dsh"); err != nil {
+ t.Fatal(err)
+ }
+ calls, _ := os.ReadFile(log)
+ if !strings.Contains(string(calls), "@deepseek-ai/dsh") || !strings.Contains(string(calls), "--engine-strict=false") {
+ t.Fatalf("npm calls: %s", calls)
+ }
+}
+
+func TestInstallOnDemandCLIReportsNPMFailureWithoutActivating(t *testing.T) {
+ root := t.TempDir()
+ t.Setenv("AGENTFLOW_RUNTIME_CLI_DIR", root)
+ t.Setenv("NPM_TEST_LOG", filepath.Join(t.TempDir(), "npm.log"))
+ t.Setenv("NPM_TEST_FAIL", "1")
+ t.Setenv("NPM_TEST_BIN", "kimi")
+ useFakeCommands(t, map[string]string{"npm": genericFakeNPM})
+ if _, err := InstallOnDemandCLI(context.Background(), "kimi"); err == nil || !strings.Contains(err.Error(), "registry unreachable") {
+ t.Fatalf("error %v", err)
+ }
+ if _, err := os.Stat(filepath.Join(root, "kimi", "current")); !os.IsNotExist(err) {
+ t.Fatalf("failed install was activated: %v", err)
+ }
+}
+
+func TestInstallOnDemandCLIInstallsCursorWithOfficialInstaller(t *testing.T) {
+ home := t.TempDir()
+ log := filepath.Join(t.TempDir(), "bash.log")
+ t.Setenv("HOME", home)
+ t.Setenv("BASH_TEST_LOG", log)
+ useFakeCommands(t, map[string]string{"bash": `#!/bin/sh
+printf '%s\n' "$*" >> "$BASH_TEST_LOG"
+mkdir -p "$HOME/.local/bin"
+printf '#!/bin/sh\necho cursor\n' > "$HOME/.local/bin/cursor-agent"
+chmod 755 "$HOME/.local/bin/cursor-agent"
+`})
+ path, err := InstallOnDemandCLI(context.Background(), "cursor")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if path != filepath.Join(home, ".local", "bin", "cursor-agent") {
+ t.Fatalf("binary %q", path)
+ }
+ calls, _ := os.ReadFile(log)
+ if !strings.Contains(string(calls), "https://cursor.com/install") {
+ t.Fatalf("installer: %s", calls)
+ }
+ if _, err := InstallOnDemandCLI(context.Background(), "cursor"); err != nil {
+ t.Fatal(err)
+ }
+ calls, _ = os.ReadFile(log)
+ if strings.Count(string(calls), "\n") != 1 {
+ t.Fatalf("installer ran twice: %s", calls)
+ }
+}
+
+func TestInstallOnDemandCLIRejectsUnknownEngineAndEmptyDirectory(t *testing.T) {
+ if OnDemandInstallable("not-a-cli") {
+ t.Fatal("unknown engine must not be installable")
+ }
+ if _, err := InstallOnDemandCLI(context.Background(), "not-a-cli"); err == nil || !strings.Contains(err.Error(), "不能从对话安装") {
+ t.Fatalf("error %v", err)
+ }
+ t.Setenv("AGENTFLOW_RUNTIME_CLI_DIR", "")
+ useFakeCommands(t, map[string]string{"npm": genericFakeNPM})
+ if _, err := InstallOnDemandCLI(context.Background(), "pi"); err == nil || !strings.Contains(err.Error(), "没有配置 CLI 安装目录") {
+ t.Fatalf("error %v", err)
+ }
+}
+
+func TestInstallOnDemandClaudeCodeUsesPinnedRelease(t *testing.T) {
+ root := t.TempDir()
+ log := filepath.Join(t.TempDir(), "npm.log")
+ t.Setenv("AGENTFLOW_RUNTIME_CLI_DIR", root)
+ t.Setenv("NPM_TEST_LOG", log)
+ useFakeCommands(t, map[string]string{"npm": fakeNPM})
+ path, err := InstallOnDemandCLI(context.Background(), "claude-code")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if path != claudeCodeBinary(root) {
+ t.Fatalf("binary %q", path)
+ }
+ calls, _ := os.ReadFile(log)
+ if !strings.Contains(string(calls), "@anthropic-ai/claude-code@"+ClaudeCodeVersion) {
+ t.Fatalf("npm calls: %s", calls)
+ }
+}