Skip to content

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

fix: sync recent chat, SOP, and runner fixes (#829)

crispinhu27500a5e969680
diff --git a/chatbot/src/App.jsx b/chatbot/src/App.jsx
index 0949ba34..e567a4c3 100644
--- a/chatbot/src/App.jsx
+++ b/chatbot/src/App.jsx
@@ -75,7 +75,7 @@ import HomeWelcome from "./HomeWelcome";
import ModelPicker from "./ModelPicker";
import ModelProviderIcon, { hasProviderLogo } from "./ModelProviderIcon";
import PermissionPicker from "./PermissionPicker";
-import { engineBrand } from "./engines.js";
+import { conversationEngine, engineBrand } from "./engines.js";
import { effortOptions } from "./effort.js";
import QuickAccessWizard from "./QuickAccessWizard";
import HarnessSelect from "./HarnessSelect";
@@ -448,6 +448,15 @@ export default function App() {
const selectedModel = chat.models.find((m) => m.id === chat.model);
const modelLabel =
selectedModel?.name?.replace(/^Claude-/, "").replace(/^GPT-/, "") || "模型";
+ // The CLI switch is only for a conversation that has not started. A reply
+ // in flight, or one already saved, keeps that CLI; another CLI needs a new chat.
+ const lockedExecutorId = chat.session
+ ? conversationEngine(chat.session.messages, chat.models, chat.session.executor) ||
+ (chat.busy ? chat.executor : "")
+ : "";
+ const pinnedExecutor = lockedExecutorId
+ ? (chat.executors || []).find((item) => item.id === lockedExecutorId)
+ : undefined;
const projectOptions = projectPickerOptions(
chat.projects,
chat.user,
@@ -1170,6 +1179,18 @@ export default function App() {
<HarnessIcon name="edit" size={13} />
</IconButton>
) : null}
+ {pinnedExecutor ? (
+ <span
+ className="conversation-engine"
+ title={`本对话使用 ${pinnedExecutor.label},对话开始后不能切换 CLI;换 CLI 请新建对话`}
+ >
+ <ModelProviderIcon
+ brand={engineBrand(pinnedExecutor.id)}
+ size={12}
+ />
+ {pinnedExecutor.label}
+ </span>
+ ) : null}
{chat.local ? <span className="preview-badge">示例</span> : null}
</>
) : null}
@@ -2032,25 +2053,27 @@ export default function App() {
e.target.value = "";
}}
/>
- <PermissionPicker
- label="CLI"
- options={chat.executors.map((executor) => {
- const brand = engineBrand(executor.id);
- return {
- ...executor,
- glyph: hasProviderLogo(brand)
- ? <ModelProviderIcon brand={brand} size={16} />
- : null,
- };
- })}
- value={chat.executor}
- onSelect={(id) => {
- chat.setExecutor(id);
- input.current?.focus();
- }}
- open={menu?.type === "executor"}
- onOpenChange={(open) => setMenu(open ? { type: "executor" } : null)}
- />
+ {chat.executors.length > 1 && !pinnedExecutor ? (
+ <PermissionPicker
+ label="CLI"
+ options={chat.executors.map((executor) => {
+ const brand = engineBrand(executor.id);
+ return {
+ ...executor,
+ glyph: hasProviderLogo(brand)
+ ? <ModelProviderIcon brand={brand} size={16} />
+ : null,
+ };
+ })}
+ value={chat.executor}
+ onSelect={(id) => {
+ chat.setExecutor(id);
+ input.current?.focus();
+ }}
+ open={menu?.type === "executor"}
+ onOpenChange={(open) => setMenu(open ? { type: "executor" } : null)}
+ />
+ ) : null}
<ModelPicker
models={chat.models}
value={chat.model}
diff --git a/chatbot/src/styles.css b/chatbot/src/styles.css
index 5f6b3372..4637eabd 100644
--- a/chatbot/src/styles.css
+++ b/chatbot/src/styles.css
@@ -207,6 +207,20 @@ small {
.conversation-title > .preview-badge {
flex-shrink: 0;
}
+.conversation-engine {
+ display: inline-flex;
+ flex-shrink: 0;
+ align-items: center;
+ gap: 4px;
+ height: 20px;
+ padding: 0 6px;
+ border: 1px solid var(--line);
+ border-radius: 6px;
+ color: var(--muted);
+ font-size: 11px;
+ line-height: 1;
+ cursor: default;
+}
.conversation-status {
position: relative;
flex-shrink: 0;
diff --git a/chatbot/tests/app-render.test.jsx b/chatbot/tests/app-render.test.jsx
index 7dfa03f6..779a298c 100644
--- a/chatbot/tests/app-render.test.jsx
+++ b/chatbot/tests/app-render.test.jsx
@@ -383,6 +383,28 @@ describe("App", () => {
chat.executor = "codex";
view.rerender(<App />);
expect(screen.getByRole("button", { name: "思考强度" })).toBeInTheDocument();
+ // A saved reply locks the CLI: the switch leaves the composer and the
+ // title shows which CLI this conversation uses.
+ Object.assign(chat, {
+ session: {
+ id: "s1",
+ title: "已开始",
+ executor: "codex",
+ messages: [{ id: "a1", role: "assistant", model: "m1", content: "hi" }],
+ },
+ });
+ view.rerender(<App />);
+ expect(screen.queryByRole("button", { name: "CLI" })).not.toBeInTheDocument();
+ expect(document.querySelector(".conversation-engine")).toHaveTextContent("Codex");
+ // The first reply, still running, locks it the same way.
+ Object.assign(chat, {
+ busy: true,
+ executor: "codebuddy",
+ session: { id: "s2", title: "生成中", executor: "codebuddy", messages: [] },
+ });
+ view.rerender(<App />);
+ expect(screen.queryByRole("button", { name: "CLI" })).not.toBeInTheDocument();
+ expect(document.querySelector(".conversation-engine")).toHaveTextContent("CodeBuddy");
Object.assign(chat, previous);
});
diff --git a/deploy/bind-cli.sh b/deploy/bind-cli.sh
index 93d24914..a9d0233c 100755
--- a/deploy/bind-cli.sh
+++ b/deploy/bind-cli.sh
@@ -17,8 +17,8 @@
# --download-url <URL> 从指定 URL 下载二进制(含 {os} {arch} 占位符)
# --source <目录> 平台未分发二进制时,从本地 AgentFlow 源码构建(需要 Go)
# --strict-https 禁止在 HTTPS 网络不可达时降级到 HTTP
-# --service 安装 launchd (macOS) / systemd (Linux) 常驻服务。
-# Linux 上没有用户会话时会自动拉起 systemd 用户实例。
+# --service 安装常驻服务。macOS 用 launchd;Linux 有 systemd 时用用户服务,
+# 没有用户会话时会先拉起 systemd 用户实例。没有 systemd 时改为后台运行。
# --no-start 只安装配置,不立即启动
# --no-auto-update 禁止从平台自动更新(自定义二进制默认禁用)
# --upgrade 原地升级已绑定的 runner,保留配置、机器绑定和工作区
@@ -72,6 +72,7 @@ fi
fail() { echo "[bind-cli] 错误: $*" >&2; exit 1; }
info() { echo "[bind-cli] $*"; }
+warn() { echo "[bind-cli] 警告: $*" >&2; }
# systemctl --user 走用户 D-Bus。SSH 进 CVM、以 root 执行,或当前 shell
# 没有登录会话时,这条总线还不存在,会报 Failed to connect to bus。
@@ -167,6 +168,168 @@ require_systemd_user_bus() {
fail "无法连接 systemd 用户总线。请在终端执行:sudo loginctl enable-linger $(id -un),然后再运行安装命令"
}
+# 容器和云开发机里经常装着 systemctl,但 1 号进程不是 systemd。
+linux_has_systemd() {
+ command -v systemctl >/dev/null 2>&1 || return 1
+ SYSTEMD_ASK_PASSWORD=0 systemctl show --property=Version >/dev/null 2>&1
+}
+
+shell_quote() { printf '%q' "$1"; }
+
+# 判断 pid 是不是正在执行 run-service.sh 的进程:argv[0] 就是这个脚本,或 argv[0]
+# 是 bash/sh、argv[1] 是这个脚本。PID 文件可能是重启前留下的旧值,那个 PID 已被
+# 别的进程复用;查看或编辑这个脚本的进程(less、vim …)命令行里也带着路径,都不能算。
+is_background_runner_pid() {
+ local pid="$1"
+ local -a args=()
+ [[ "$pid" =~ ^[0-9]+$ ]] || return 1
+ if [[ -r "/proc/${pid}/cmdline" ]]; then
+ mapfile -d '' -t args < "/proc/${pid}/cmdline" 2>/dev/null || return 1
+ else
+ read -r -a args <<< "$(ps -o args= -p "$pid" 2>/dev/null || true)" || true
+ fi
+ [[ "${#args[@]}" -gt 0 ]] || return 1
+ [[ "${args[0]}" == "$BACKGROUND_SCRIPT" ]] && return 0
+ case "${args[0]##*/}" in
+ bash|sh) [[ "${args[1]:-}" == "$BACKGROUND_SCRIPT" ]] ;;
+ *) return 1 ;;
+ esac
+}
+
+# 只给核对过命令行的 run-service.sh 进程发信号。PID 文件里的旧 PID 不匹配时只删文件;
+# PID 文件丢失或过期时,再按 /proc 里的命令行找仍在运行的 run-service.sh。
+stop_background_runner() {
+ local pid="" proc
+ local -a pids=()
+ if [[ -f "$BACKGROUND_PID" ]]; then
+ pid="$(tr -d '[:space:]' < "$BACKGROUND_PID" 2>/dev/null || true)"
+ rm -f "$BACKGROUND_PID"
+ fi
+ if [[ -n "$pid" ]] && is_background_runner_pid "$pid"; then
+ pids+=("$pid")
+ fi
+ if [[ -n "$BACKGROUND_SCRIPT" && -d /proc ]]; then
+ for proc in /proc/[0-9]*; do
+ proc="${proc#/proc/}"
+ [[ "$proc" == "$pid" || "$proc" == "$$" ]] && continue
+ is_background_runner_pid "$proc" && pids+=("$proc")
+ done
+ fi
+ [[ "${#pids[@]}" -gt 0 ]] || return 0
+ for proc in "${pids[@]}"; do
+ kill -TERM "$proc" >/dev/null 2>&1 || true
+ done
+ sleep 0.2
+ for proc in "${pids[@]}"; do
+ pkill -P "$proc" >/dev/null 2>&1 || true
+ done
+}
+
+# 读当前用户的 crontab 到 CRONTAB_CURRENT。读取成功,或明确是「还没有 crontab」时
+# 返回 0;其他失败(权限、spool 读不了等)返回 1 并把原因放进 CRONTAB_ERROR。
+# 调用方必须在失败时放弃改写:把读失败当成空表写回,会覆盖用户原有的定时任务。
+read_user_crontab() {
+ local err_file status=0
+ CRONTAB_CURRENT=""
+ CRONTAB_ERROR=""
+ err_file="$(mktemp "${TMPDIR:-/tmp}/bind-cli-crontab.XXXXXX")" || {
+ CRONTAB_ERROR="无法创建临时文件"
+ return 1
+ }
+ CRONTAB_CURRENT="$(crontab -l 2>"$err_file")" || status=$?
+ CRONTAB_ERROR="$(head -n 1 "$err_file" 2>/dev/null || true)"
+ rm -f "$err_file"
+ [[ "$status" -eq 0 ]] && return 0
+ CRONTAB_CURRENT=""
+ if [[ "$CRONTAB_ERROR" == *"no crontab for"* ]]; then
+ CRONTAB_ERROR=""
+ return 0
+ fi
+ [[ -n "$CRONTAB_ERROR" ]] || CRONTAB_ERROR="crontab -l 退出码 ${status}"
+ return 1
+}
+
+remove_background_reboot_hook() {
+ command -v crontab >/dev/null 2>&1 || return 0
+ local filtered
+ if ! read_user_crontab; then
+ warn "读取 crontab 失败(${CRONTAB_ERROR}),未改动 crontab;如有 # agentflow-runner 开机项请手动删除"
+ return 0
+ fi
+ [[ "$CRONTAB_CURRENT" == *"# agentflow-runner"* ]] || return 0
+ filtered="$(printf '%s\n' "$CRONTAB_CURRENT" | grep -v '# agentflow-runner' || true)"
+ printf '%s\n' "$filtered" | crontab - >/dev/null 2>&1 ||
+ warn "写回 crontab 失败,请手动删除 # agentflow-runner 开机项"
+}
+
+install_background_reboot_hook() {
+ command -v crontab >/dev/null 2>&1 || return 0
+ [[ "$BACKGROUND_SCRIPT" != *" "* && "$RUNNER_HOME" != *" "* ]] || return 0
+ local entry
+ if ! read_user_crontab; then
+ warn "读取 crontab 失败(${CRONTAB_ERROR}),为免覆盖已有定时任务,未安装开机自启;runner 本次仍在后台运行"
+ return 0
+ fi
+ entry="@reboot ${BACKGROUND_SCRIPT} >> ${RUNNER_HOME}/runner.log 2>&1 # agentflow-runner"
+ {
+ if [[ -n "$CRONTAB_CURRENT" ]]; then
+ printf '%s\n' "$CRONTAB_CURRENT" | grep -v '# agentflow-runner' || true
+ fi
+ printf '%s\n' "$entry"
+ } | crontab - >/dev/null 2>&1 ||
+ warn "写入 crontab 失败,未安装开机自启;runner 本次仍在后台运行"
+}
+
+launch_background_wrapper() {
+ mkdir -p "$RUNNER_HOME"
+ if command -v nohup >/dev/null 2>&1; then
+ nohup "$BACKGROUND_SCRIPT" >> "${RUNNER_HOME}/runner.log" 2>&1 < /dev/null &
+ else
+ "$BACKGROUND_SCRIPT" >> "${RUNNER_HOME}/runner.log" 2>&1 < /dev/null &
+ fi
+ echo "$!" > "$BACKGROUND_PID"
+ disown "$!" >/dev/null 2>&1 || true
+}
+
+# 没有 systemd 时仍把 runner 留在后台,避免安装停在用户看不懂的报错上。
+start_background_runner() {
+ local arg
+ stop_background_runner
+ {
+ echo '#!/usr/bin/env bash'
+ # @reboot 直接执行本脚本、不经过 launch_background_wrapper,由脚本自己写 PID 文件,
+ # 重启后 PID 文件里也是当前进程。
+ echo "echo \$\$ > $(shell_quote "$BACKGROUND_PID")"
+ echo "trap '' HUP"
+ echo 'child=0'
+ echo 'trap '\''if [[ "$child" != 0 ]]; then kill "$child" 2>/dev/null || true; fi; exit 0'\'' TERM INT'
+ echo "export PATH=$(shell_quote "$USER_PATH")"
+ echo "export AGENTFLOW_GATE_MCP_BINARY=$(shell_quote "$GATE_BINARY_PATTERN")"
+ echo 'while true; do'
+ printf ' %s' "$(shell_quote "$BINARY")"
+ for arg in "${RUN_ARGS[@]}"; do
+ printf ' %s' "$(shell_quote "$arg")"
+ done
+ echo ' &'
+ echo ' child=$!'
+ echo ' wait "$child" || true'
+ echo ' sleep 5'
+ echo 'done'
+ } > "$BACKGROUND_SCRIPT"
+ chmod 700 "$BACKGROUND_SCRIPT"
+ launch_background_wrapper
+ install_background_reboot_hook
+ info "安装完成,已在后台运行。日志: ${RUNNER_HOME}/runner.log"
+}
+
+restart_background_runner() {
+ [[ -x "$BACKGROUND_SCRIPT" ]] || fail "未找到后台启动脚本,无法原地升级"
+ stop_background_runner
+ launch_background_wrapper
+ install_background_reboot_hook
+ info "已原地升级并重启后台进程;机器绑定和工作区保持不变"
+}
+
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"
case "$ARCH" in
@@ -183,6 +346,8 @@ BINARY="${BIN_DIR}/agentflow-runner"
GATE_BINARY_PATTERN="${BIN_DIR}/agentflow-gate-mcp-{os}-{arch}"
PLIST="${HOME}/Library/LaunchAgents/com.agentflow.runner.plist"
UNIT="${HOME}/.config/systemd/user/agentflow-runner.service"
+BACKGROUND_SCRIPT="${RUNNER_HOME}/run-service.sh"
+BACKGROUND_PID="${RUNNER_HOME}/service.pid"
# ---------- 卸载 ----------
if [[ "$UNINSTALL" == "1" ]]; then
@@ -193,6 +358,7 @@ if [[ "$UNINSTALL" == "1" ]]; then
if [[ "$OS" == "darwin" ]]; then
[[ -f "$PLIST" ]] && launchctl unload "$PLIST" >/dev/null 2>&1 || true
else
+ stop_background_runner
ensure_systemd_user_bus quiet || true
systemctl --user stop agentflow-runner.service >/dev/null 2>&1 || true
fi
@@ -227,11 +393,19 @@ if [[ "$UNINSTALL" == "1" ]]; then
info "已移除 launchd 服务"
fi
else
- ensure_systemd_user_bus quiet || true
- systemctl --user disable --now agentflow-runner.service >/dev/null 2>&1 || true
- rm -f "$UNIT"
- systemctl --user daemon-reload >/dev/null 2>&1 || true
- info "已移除 systemd 服务"
+ if [[ -f "$BACKGROUND_SCRIPT" || -f "$BACKGROUND_PID" ]]; then
+ stop_background_runner
+ remove_background_reboot_hook
+ rm -f "$BACKGROUND_SCRIPT"
+ info "已停止后台运行"
+ fi
+ if [[ -f "$UNIT" ]]; then
+ ensure_systemd_user_bus quiet || true
+ systemctl --user disable --now agentflow-runner.service >/dev/null 2>&1 || true
+ rm -f "$UNIT"
+ systemctl --user daemon-reload >/dev/null 2>&1 || true
+ info "已移除 systemd 服务"
+ fi
fi
# 回收异常退出时可能遗留的 runner 专属容器和临时镜像。名称严格
# 限定为 agentflow-rt-*,不会碰同机控制面或用户自己的容器。
@@ -435,10 +609,12 @@ if [[ "$UPGRADE" == "1" ]]; then
launchctl unload "$PLIST"
launchctl load "$PLIST"
info "已原地升级并重启 launchd 服务;机器绑定和工作区保持不变"
- elif [[ "$OS" == "linux" && -f "$UNIT" ]]; then
+ elif [[ "$OS" == "linux" && -f "$UNIT" ]] && linux_has_systemd; then
require_systemd_user_bus
systemctl --user restart agentflow-runner.service
info "已原地升级并重启 systemd 服务;机器绑定和工作区保持不变"
+ elif [[ "$OS" == "linux" && -x "$BACKGROUND_SCRIPT" ]]; then
+ restart_background_runner
else
info "已原地升级 runner;请重启前台运行的旧进程以启用新版"
fi
@@ -502,7 +678,7 @@ EOF
launchctl unload "$PLIST" >/dev/null 2>&1 || true
launchctl load "$PLIST"
info "launchd 服务已安装并启动(日志: ${RUNNER_HOME}/runner.log)"
- else
+ elif linux_has_systemd; then
mkdir -p "$(dirname "$UNIT")"
{
echo "[Unit]"
@@ -526,6 +702,8 @@ EOF
systemctl --user enable agentflow-runner.service
systemctl --user restart agentflow-runner.service
info "systemd 服务已安装并启动(journalctl --user -u agentflow-runner -f 查看日志)"
+ else
+ start_background_runner
fi
info "卸载方式:curl -fsSL ${SERVER}/runners/install.sh | bash -s -- --uninstall"
else
diff --git a/deploy/bind_cli_crontab_test.go b/deploy/bind_cli_crontab_test.go
new file mode 100644
index 00000000..2388ff04
--- /dev/null
+++ b/deploy/bind_cli_crontab_test.go
@@ -0,0 +1,135 @@
+package deploy
+
+import (
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// Uninstalling drops only the runner's @reboot hook and writes every other
+// crontab entry back unchanged.
+func TestBindCLIUninstallRemovesOnlyRunnerCrontabEntry(t *testing.T) {
+ text, cronFile := runBindCLIUninstall(t, "#!/bin/sh\nif [ \"${1:-}\" = -l ]; then printf '0 3 * * * /usr/local/bin/backup\\n@reboot /home/u/.agentflow-runner/run-service.sh # agentflow-runner\\n*/5 * * * * /usr/local/bin/sync\\n'; exit 0; fi\ncat > \"$TEST_CRON_FILE\"\nexit 0\n")
+ if strings.Contains(text, "crontab") {
+ t.Fatalf("unexpected crontab warning:\n%s", text)
+ }
+ cron, err := os.ReadFile(cronFile)
+ if err != nil {
+ t.Fatalf("crontab not rewritten on uninstall: %v\n%s", err, text)
+ }
+ body := string(cron)
+ if strings.Contains(body, "agentflow-runner") {
+ t.Fatalf("runner hook survived uninstall: %q", body)
+ }
+ for _, entry := range []string{"0 3 * * * /usr/local/bin/backup", "*/5 * * * * /usr/local/bin/sync"} {
+ if !strings.Contains(body, entry) {
+ t.Fatalf("uninstall dropped user entry %q: %q", entry, body)
+ }
+ }
+}
+
+// Without a runner hook in the crontab, uninstall leaves the crontab alone.
+func TestBindCLIUninstallSkipsCrontabWithoutRunnerHook(t *testing.T) {
+ text, cronFile := runBindCLIUninstall(t, "#!/bin/sh\nif [ \"${1:-}\" = -l ]; then printf '0 3 * * * /usr/local/bin/backup\\n'; exit 0; fi\ncat > \"$TEST_CRON_FILE\"\nexit 0\n")
+ if _, err := os.Stat(cronFile); !os.IsNotExist(err) {
+ body, _ := os.ReadFile(cronFile)
+ t.Fatalf("crontab rewritten although it had no runner hook: %q\n%s", body, text)
+ }
+}
+
+// When `crontab -l` fails on uninstall, the crontab is not rewritten and the
+// user is told to remove the hook by hand.
+func TestBindCLIUninstallLeavesCrontabAloneWhenReadFails(t *testing.T) {
+ text, cronFile := runBindCLIUninstall(t, "#!/bin/sh\nif [ \"${1:-}\" = -l ]; then echo 'crontab: cannot open spool file: Permission denied' >&2; exit 1; fi\ncat > \"$TEST_CRON_FILE\"\nexit 0\n")
+ if _, err := os.Stat(cronFile); !os.IsNotExist(err) {
+ body, _ := os.ReadFile(cronFile)
+ t.Fatalf("crontab rewritten after a failed read: %q\n%s", body, text)
+ }
+ if !strings.Contains(text, "读取 crontab 失败") || !strings.Contains(text, "Permission denied") || !strings.Contains(text, "手动删除") {
+ t.Fatalf("read failure not reported on uninstall:\n%s", text)
+ }
+}
+
+// A failed `crontab -` write on uninstall is reported instead of swallowed.
+func TestBindCLIUninstallWarnsWhenCrontabWriteFails(t *testing.T) {
+ text, _ := runBindCLIUninstall(t, "#!/bin/sh\nif [ \"${1:-}\" = -l ]; then printf '@reboot /x/run-service.sh # agentflow-runner\\n'; exit 0; fi\ncat >/dev/null\nexit 1\n")
+ if !strings.Contains(text, "写回 crontab 失败") {
+ t.Fatalf("write failure not reported on uninstall:\n%s", text)
+ }
+}
+
+// A failed `crontab -` write during install is reported, and the install
+// still finishes with the runner in the background.
+func TestBindCLIServiceWarnsWhenCrontabWriteFails(t *testing.T) {
+ text, cronFile := runBindCLIWithoutSystemd(t, "#!/bin/sh\nif [ \"${1:-}\" = -l ]; then printf '0 3 * * * /usr/local/bin/backup\\n'; exit 0; fi\ncat >/dev/null\nexit 1\n")
+ if !strings.Contains(text, "写入 crontab 失败") {
+ t.Fatalf("write failure not reported:\n%s", text)
+ }
+ if _, err := os.Stat(cronFile); !os.IsNotExist(err) {
+ t.Fatalf("fake crontab unexpectedly stored a write: %v", err)
+ }
+}
+
+// runBindCLIUninstall runs `bind-cli.sh --uninstall` against a Linux
+// background install (run-service.sh present, no systemd) with crontabScript
+// as the fake crontab. It returns the output and the file a `crontab -` write
+// lands in. docker and pkill are stubbed so the test cannot touch real
+// runner containers or processes on the machine running it.
+func runBindCLIUninstall(t *testing.T, crontabScript string) (string, string) {
+ t.Helper()
+ home := t.TempDir()
+ binDir := filepath.Join(home, "bin")
+ runnerHome := filepath.Join(home, ".agentflow-runner")
+ if err := os.MkdirAll(runnerHome, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ script := filepath.Join(runnerHome, "run-service.sh")
+ if err := os.WriteFile(script, []byte("#!/bin/sh\nexit 0\n"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ fakeBin := filepath.Join(home, "fake-bin")
+ if err := os.MkdirAll(fakeBin, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ cronFile := filepath.Join(home, "crontab")
+ for name, body := range map[string]string{
+ "uname": "#!/bin/sh\ncase \"$1\" in -s) echo Linux ;; -m) echo x86_64 ;; *) echo Linux ;; esac\n",
+ "curl": "#!/bin/sh\nexit 22\n",
+ "systemctl": "#!/bin/sh\necho 'Failed to connect to bus: Host is down' >&2\nexit 1\n",
+ "docker": "#!/bin/sh\nexit 0\n",
+ "pkill": "#!/bin/sh\nexit 1\n",
+ "crontab": crontabScript,
+ } {
+ if err := os.WriteFile(filepath.Join(fakeBin, name), []byte(body), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ env := make([]string, 0, len(os.Environ())+4)
+ for _, entry := range os.Environ() {
+ if strings.HasPrefix(entry, "XDG_RUNTIME_DIR=") || strings.HasPrefix(entry, "DBUS_SESSION_BUS_ADDRESS=") {
+ continue
+ }
+ env = append(env, entry)
+ }
+ env = append(env,
+ "HOME="+home,
+ "PATH="+fakeBin+":/usr/bin:/bin",
+ "TEST_CRON_FILE="+cronFile,
+ )
+ cmd := exec.Command("/bin/bash", "bind-cli.sh", "--uninstall", "--bin-dir", binDir)
+ cmd.Env = env
+ out, err := cmd.CombinedOutput()
+ text := string(out)
+ if err != nil {
+ t.Fatalf("uninstall failed: %v\n%s", err, text)
+ }
+ if !strings.Contains(text, "已停止后台运行") || !strings.Contains(text, "卸载完成") {
+ t.Fatalf("background uninstall not reported:\n%s", text)
+ }
+ if _, err := os.Stat(runnerHome); !os.IsNotExist(err) {
+ t.Fatalf("runner home not removed: %v", err)
+ }
+ return text, cronFile
+}
diff --git a/deploy/bind_cli_runner_pid_test.go b/deploy/bind_cli_runner_pid_test.go
new file mode 100644
index 00000000..3539f8f4
--- /dev/null
+++ b/deploy/bind_cli_runner_pid_test.go
@@ -0,0 +1,179 @@
+package deploy
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "syscall"
+ "testing"
+ "time"
+)
+
+const runnerPIDNoCrontab = "#!/bin/sh\nif [ \"${1:-}\" = -l ]; then echo \"no crontab for $(id -un)\" >&2; exit 1; fi\ncat > \"$TEST_CRON_FILE\"\nexit 0\n"
+
+// runnerProcessAlive reports whether pid is a live, non-zombie process.
+func runnerProcessAlive(pid int) bool {
+ state, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
+ if err != nil {
+ return false
+ }
+ fields := strings.Fields(string(state))
+ return len(fields) > 2 && fields[2] != "Z"
+}
+
+func waitRunnerProcessGone(t *testing.T, pid int, what string) {
+ t.Helper()
+ deadline := time.Now().Add(5 * time.Second)
+ for runnerProcessAlive(pid) {
+ if time.Now().After(deadline) {
+ t.Fatalf("%s (pid %d) kept running", what, pid)
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+}
+
+func readRunnerPID(t *testing.T, pidFile string) int {
+ t.Helper()
+ raw, err := os.ReadFile(pidFile)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pid, err := strconv.Atoi(strings.TrimSpace(string(raw)))
+ if err != nil {
+ t.Fatalf("service.pid = %q", raw)
+ }
+ return pid
+}
+
+func uninstallBindCLI(t *testing.T, env []string) {
+ t.Helper()
+ cmd := exec.Command("/bin/bash", "bind-cli.sh", "--uninstall")
+ cmd.Env = env
+ if out, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("uninstall failed: %v\n%s", err, out)
+ }
+}
+
+// The usual case: service.pid still names the running wrapper. Uninstall must
+// stop it and remove the PID file.
+func TestBindCLIUninstallStopsTheRunnerNamedInServicePID(t *testing.T) {
+ _, home, env := installBindCLIWithoutSystemd(t, runnerPIDNoCrontab)
+ pidFile := filepath.Join(home, ".agentflow-runner", "service.pid")
+ wrapper := readRunnerPID(t, pidFile)
+ if !runnerProcessAlive(wrapper) {
+ t.Fatalf("service.pid %d is not running before uninstall", wrapper)
+ }
+
+ uninstallBindCLI(t, env)
+
+ waitRunnerProcessGone(t, wrapper, "the runner named in service.pid")
+ if _, err := os.Stat(pidFile); !os.IsNotExist(err) {
+ t.Fatalf("service.pid not removed: %v", err)
+ }
+}
+
+// Running --service again stops the runner once before starting the new one.
+// The PID named in service.pid is left out of the /proc scan, so the old
+// wrapper is stopped only because the checked PID from the file is kept;
+// otherwise the reinstall leaves two runners behind. (Uninstall stops twice,
+// so it does not notice this on its own.)
+func TestBindCLIReinstallStopsTheRunnerNamedInServicePID(t *testing.T) {
+ _, home, env := installBindCLIWithoutSystemd(t, runnerPIDNoCrontab)
+ pidFile := filepath.Join(home, ".agentflow-runner", "service.pid")
+ previous := readRunnerPID(t, pidFile)
+
+ cmd := exec.Command("/bin/bash", "bind-cli.sh",
+ "--server", "http://isolated.example",
+ "--token", "bind-test",
+ "--from", filepath.Join(home, "runner-source"),
+ "--bin-dir", filepath.Join(home, "bin"),
+ "--service",
+ )
+ cmd.Env = env
+ if out, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("second service install failed: %v\n%s", err, out)
+ }
+
+ waitRunnerProcessGone(t, previous, "the runner from the first install")
+ if current := readRunnerPID(t, pidFile); current == previous || !runnerProcessAlive(current) {
+ t.Fatalf("service.pid = %d after reinstall, want a new running wrapper (previous %d)", current, previous)
+ }
+}
+
+// The @reboot hook runs run-service.sh directly, without the installer's
+// launcher that records $!. The wrapper itself must then write its own PID,
+// otherwise service.pid keeps the value from before the reboot.
+func TestBindCLIRunnerScriptStartedDirectlyRecordsItsOwnPID(t *testing.T) {
+ _, home, env := installBindCLIWithoutSystemd(t, runnerPIDNoCrontab)
+ script := filepath.Join(home, ".agentflow-runner", "run-service.sh")
+ pidFile := filepath.Join(home, ".agentflow-runner", "service.pid")
+
+ // Simulate the reboot: the installer's wrapper is gone and service.pid
+ // holds a PID that no longer belongs to it.
+ installed := readRunnerPID(t, pidFile)
+ if p, err := os.FindProcess(installed); err == nil {
+ _ = p.Signal(syscall.SIGTERM)
+ }
+ waitRunnerProcessGone(t, installed, "the installed wrapper")
+ if err := os.WriteFile(pidFile, []byte("999999999\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ cmd := exec.Command(script)
+ cmd.Env = env
+ if err := cmd.Start(); err != nil {
+ t.Fatal(err)
+ }
+ // TERM rather than KILL, so the wrapper's trap also stops its child.
+ t.Cleanup(func() { _ = cmd.Process.Signal(syscall.SIGTERM); _, _ = cmd.Process.Wait() })
+
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ raw, _ := os.ReadFile(pidFile)
+ if strings.TrimSpace(string(raw)) == strconv.Itoa(cmd.Process.Pid) {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("service.pid = %q after a direct start, want the wrapper's pid %d", raw, cmd.Process.Pid)
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+}
+
+// A process whose argv[0] is run-service.sh itself counts as the runner too,
+// so uninstall finds and stops it through /proc even though service.pid does
+// not name it.
+func TestBindCLIUninstallStopsARunnerWhoseArgv0IsTheScript(t *testing.T) {
+ _, home, env := installBindCLIWithoutSystemd(t, runnerPIDNoCrontab)
+ script := filepath.Join(home, ".agentflow-runner", "run-service.sh")
+
+ named := exec.Command("/bin/bash", "-c", `exec -a "$0" sleep 300`, script)
+ if err := named.Start(); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = named.Process.Kill(); _, _ = named.Process.Wait() })
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ cmdline, _ := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", named.Process.Pid))
+ if strings.HasPrefix(string(cmdline), script+"\x00") {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("argv[0] was not set to the script: %q", cmdline)
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ exited := make(chan struct{})
+ go func() { _, _ = named.Process.Wait(); close(exited) }()
+
+ uninstallBindCLI(t, env)
+
+ select {
+ case <-exited:
+ case <-time.After(5 * time.Second):
+ t.Fatal("uninstall left running a process whose argv[0] is run-service.sh")
+ }
+}
diff --git a/deploy/deploy_test.go b/deploy/deploy_test.go
index b4458bb5..8bfd28a9 100644
--- a/deploy/deploy_test.go
+++ b/deploy/deploy_test.go
@@ -1,11 +1,14 @@
package deploy
import (
+ "fmt"
"os"
"os/exec"
"path/filepath"
+ "strconv"
"strings"
"testing"
+ "time"
)
func TestBindCLIServiceStartsUserBusWhenSessionMissing(t *testing.T) {
@@ -217,18 +220,216 @@ exit 0
}
}
-// Without systemd the installer explains that --service cannot be used.
-func TestBindCLIServiceFailsClearlyWithoutSystemd(t *testing.T) {
- out, err, log := runBindCLIService(t, map[string]string{
- "loginctl": "#!/bin/sh\nexit 1\n",
- "sudo": "#!/bin/sh\nexit 1\n",
- "systemctl": "#!/bin/sh\nprintf 'systemctl %s\\n' \"$*\" >> \"$TEST_SERVICE_LOG\"\necho 'System has not been booted with systemd' >&2\nexit 1\n",
+// Without systemd, --service keeps the runner in the background instead of
+// stopping with an init-system error.
+func TestBindCLIServiceRunsInBackgroundWithoutSystemd(t *testing.T) {
+ // A user without a crontab: `crontab -l` exits 1 with "no crontab for".
+ text, cronFile := runBindCLIWithoutSystemd(t, "#!/bin/sh\nif [ \"${1:-}\" = -l ]; then echo \"no crontab for $(id -un)\" >&2; exit 1; fi\ncat > \"$TEST_CRON_FILE\"\nexit 0\n")
+ if strings.Contains(text, "crontab") {
+ t.Fatalf("a missing crontab must not produce a crontab warning:\n%s", text)
+ }
+ cron, err := os.ReadFile(cronFile)
+ if err != nil || !strings.Contains(string(cron), "@reboot") || !strings.Contains(string(cron), "run-service.sh") {
+ t.Fatalf("reboot hook missing: %q %v", cron, err)
+ }
+}
+
+// Installing the reboot hook keeps every existing crontab entry.
+func TestBindCLIServiceKeepsExistingCrontabEntries(t *testing.T) {
+ text, cronFile := runBindCLIWithoutSystemd(t, "#!/bin/sh\nif [ \"${1:-}\" = -l ]; then printf '0 3 * * * /usr/local/bin/backup\\n@reboot /old/run-service.sh # agentflow-runner\\n'; exit 0; fi\ncat > \"$TEST_CRON_FILE\"\nexit 0\n")
+ if strings.Contains(text, "crontab") {
+ t.Fatalf("unexpected crontab warning:\n%s", text)
+ }
+ cron, err := os.ReadFile(cronFile)
+ if err != nil {
+ t.Fatalf("crontab not written: %v\n%s", err, text)
+ }
+ body := string(cron)
+ if !strings.Contains(body, "0 3 * * * /usr/local/bin/backup") {
+ t.Fatalf("existing entry dropped: %q", body)
+ }
+ if strings.Contains(body, "/old/run-service.sh") || strings.Count(body, "# agentflow-runner") != 1 {
+ t.Fatalf("stale reboot hook not replaced exactly once: %q", body)
+ }
+}
+
+// When `crontab -l` fails for any reason other than "no crontab", the
+// installer must not write a crontab: doing so would replace the user's
+// existing entries with only the runner hook.
+func TestBindCLIServiceLeavesCrontabAloneWhenReadFails(t *testing.T) {
+ text, cronFile := runBindCLIWithoutSystemd(t, "#!/bin/sh\nif [ \"${1:-}\" = -l ]; then echo 'crontab: cannot open spool file: Permission denied' >&2; exit 1; fi\ncat > \"$TEST_CRON_FILE\"\nexit 0\n")
+ if _, err := os.Stat(cronFile); !os.IsNotExist(err) {
+ body, _ := os.ReadFile(cronFile)
+ t.Fatalf("crontab was rewritten after a failed read: %q\n%s", body, text)
+ }
+ if !strings.Contains(text, "读取 crontab 失败") || !strings.Contains(text, "Permission denied") {
+ t.Fatalf("read failure not reported:\n%s", text)
+ }
+}
+
+// runBindCLIWithoutSystemd installs with --service on a machine whose
+// systemctl cannot reach a bus, using crontabScript as the fake crontab. It
+// returns the installer output and the file a `crontab -` write lands in.
+func runBindCLIWithoutSystemd(t *testing.T, crontabScript string) (string, string) {
+ t.Helper()
+ text, home, _ := installBindCLIWithoutSystemd(t, crontabScript)
+ return text, filepath.Join(home, "crontab")
+}
+
+// installBindCLIWithoutSystemd is runBindCLIWithoutSystemd that also returns
+// HOME and the environment, so a test can run the installer again (for
+// example with --uninstall) on the same machine.
+func installBindCLIWithoutSystemd(t *testing.T, crontabScript string) (string, string, []string) {
+ t.Helper()
+ home := t.TempDir()
+ binDir := filepath.Join(home, "bin")
+ marker := filepath.Join(home, "started")
+ runner := filepath.Join(home, "runner-source")
+ if err := os.WriteFile(runner, []byte("#!/bin/sh\necho started >> "+marker+"\nsleep 60\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ script := filepath.Join(home, ".agentflow-runner", "run-service.sh")
+ t.Cleanup(func() {
+ _ = exec.Command("pkill", "-f", script).Run()
})
- if err == nil || !strings.Contains(out, "当前系统没有可用的 systemd") {
- t.Fatalf("want the no-systemd error, got err=%v:\n%s", err, out)
+ fakeBin := filepath.Join(home, "fake-bin")
+ if err := os.MkdirAll(fakeBin, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ cronFile := filepath.Join(home, "crontab")
+ for name, body := range map[string]string{
+ "uname": "#!/bin/sh\ncase \"$1\" in -s) echo Linux ;; -m) echo x86_64 ;; *) echo Linux ;; esac\n",
+ "curl": `#!/bin/sh
+case "$*" in
+ *agentflow-gate-mcp*)
+ previous=""
+ for argument in "$@"; do
+ if [ "$previous" = -o ]; then printf gate-helper > "$argument"; exit 0; fi
+ previous="$argument"
+ done
+ exit 2
+ ;;
+esac
+exit 22
+`,
+ "systemctl": "#!/bin/sh\necho 'Failed to connect to bus: Host is down' >&2\nexit 1\n",
+ "crontab": crontabScript,
+ } {
+ if err := os.WriteFile(filepath.Join(fakeBin, name), []byte(body), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ env := make([]string, 0, len(os.Environ())+5)
+ for _, entry := range os.Environ() {
+ if strings.HasPrefix(entry, "XDG_RUNTIME_DIR=") || strings.HasPrefix(entry, "DBUS_SESSION_BUS_ADDRESS=") {
+ continue
+ }
+ env = append(env, entry)
+ }
+ env = append(env,
+ "HOME="+home,
+ "PATH="+fakeBin+":/usr/bin:/bin",
+ "AGENTFLOW_BROWSER=off",
+ "TEST_CRON_FILE="+cronFile,
+ )
+ cmd := exec.Command("/bin/bash", "bind-cli.sh",
+ "--server", "http://isolated.example",
+ "--token", "bind-test",
+ "--from", runner,
+ "--bin-dir", binDir,
+ "--service",
+ )
+ cmd.Env = env
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("service install failed: %v\n%s", err, out)
+ }
+ text := string(out)
+ if strings.Contains(text, "Failed to connect to bus") || strings.Contains(text, "不能安装常驻服务") {
+ t.Fatalf("installer stopped on a missing init system:\n%s", text)
+ }
+ if !strings.Contains(text, "安装完成,已在后台运行") {
+ t.Fatalf("background start not reported:\n%s", text)
+ }
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ if body, readErr := os.ReadFile(marker); readErr == nil && strings.Contains(string(body), "started") {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("runner was not started:\n%s", text)
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+ if _, err := os.Stat(filepath.Join(home, ".config/systemd/user/agentflow-runner.service")); !os.IsNotExist(err) {
+ t.Fatal("wrote a systemd unit on a machine without systemd")
+ }
+ return text, home, env
+}
+
+// service.pid survives a reboot, and its PID may then belong to an unrelated
+// process. Stopping the runner must signal only a process that is executing
+// run-service.sh: not the stale PID, and not a process that merely has the
+// script path on its command line (a pager or an editor). The wrapper writes
+// its own PID, so a start from the @reboot hook leaves a correct PID file.
+func TestBindCLIUninstallSignalsOnlyTheBackgroundRunner(t *testing.T) {
+ _, home, env := installBindCLIWithoutSystemd(t, "#!/bin/sh\nif [ \"${1:-}\" = -l ]; then echo \"no crontab for $(id -un)\" >&2; exit 1; fi\ncat > \"$TEST_CRON_FILE\"\nexit 0\n")
+ script := filepath.Join(home, ".agentflow-runner", "run-service.sh")
+ pidFile := filepath.Join(home, ".agentflow-runner", "service.pid")
+ raw, err := os.ReadFile(pidFile)
+ if err != nil {
+ t.Fatal(err)
+ }
+ wrapper, err := strconv.Atoi(strings.TrimSpace(string(raw)))
+ if err != nil {
+ t.Fatalf("service.pid = %q", raw)
+ }
+ cmdline, _ := os.ReadFile(fmt.Sprintf("/proc/%d/cmdline", wrapper))
+ if !strings.Contains(string(cmdline), script) {
+ t.Fatalf("service.pid %d is not the wrapper: %q", wrapper, cmdline)
+ }
+ start := func(name string, args ...string) *exec.Cmd {
+ cmd := exec.Command(name, args...)
+ if err := cmd.Start(); err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = cmd.Process.Kill(); _, _ = cmd.Process.Wait() })
+ return cmd
+ }
+ unrelated := start("sleep", "300")
+ viewer := start("tail", "-f", script)
+ // A reboot left the PID of a process that is not the runner.
+ if err := os.WriteFile(pidFile, []byte(strconv.Itoa(unrelated.Process.Pid)+"\n"), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ cmd := exec.Command("/bin/bash", "bind-cli.sh", "--uninstall")
+ cmd.Env = env
+ if out, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("uninstall failed: %v\n%s", err, out)
+ }
+ alive := func(pid int) bool {
+ state, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
+ if err != nil {
+ return false
+ }
+ fields := strings.Fields(string(state))
+ return len(fields) > 2 && fields[2] != "Z"
+ }
+ if !alive(unrelated.Process.Pid) {
+ t.Fatal("uninstall killed the unrelated process whose PID was left in service.pid")
+ }
+ if !alive(viewer.Process.Pid) {
+ t.Fatal("uninstall killed a process that only had the script path on its command line")
+ }
+ deadline := time.Now().Add(5 * time.Second)
+ for alive(wrapper) {
+ if time.Now().After(deadline) {
+ t.Fatal("the background runner kept running after uninstall")
+ }
+ time.Sleep(50 * time.Millisecond)
}
- if strings.Contains(log, "start user@") {
- t.Fatalf("tried to start a user manager without systemd: %s", log)
+ if _, err := os.Stat(pidFile); !os.IsNotExist(err) {
+ t.Fatalf("service.pid not removed: %v", err)
}
}
diff --git a/internal/engine/misc_helpers_cases_test.go b/internal/engine/misc_helpers_cases_test.go
index dadf7470..7b15e586 100644
--- a/internal/engine/misc_helpers_cases_test.go
+++ b/internal/engine/misc_helpers_cases_test.go
@@ -209,6 +209,9 @@ func TestObservationQueuesRunStateAndFlushLoopBranches(t *testing.T) {
if e.updateRunAt("missing", false, nil) {
t.Fatal("missing run update succeeded")
}
+ if updated, err := e.updateRunAtErr("missing", false, nil); updated || err != nil {
+ t.Fatalf("missing run update returned updated=%t, err=%v", updated, err)
+ }
if _, _, err := e.Subscribe("missing"); err == nil {
t.Fatal("missing subscription succeeded")
}
diff --git a/internal/engine/node_outcome.go b/internal/engine/node_outcome.go
index 994f10cb..72f6e24b 100644
--- a/internal/engine/node_outcome.go
+++ b/internal/engine/node_outcome.go
@@ -87,7 +87,8 @@ func (e *Engine) nodeFailedAt(runID string, node domain.WorkflowNode, attempt, g
}
func shouldRetryFailedAttempt(node domain.WorkflowNode, attempt int, err error) bool {
- if errors.Is(err, ErrWorkspaceControlConfiguration) {
+ // A failed artifact write must not repeat a child that already succeeded.
+ if errors.Is(err, ErrWorkspaceControlConfiguration) || errors.Is(err, errSOPArtifactWrite) {
return false
}
if err != nil && (isMaxTurnsErr(err) || strings.Contains(err.Error(), "verification ") || runtime.IsCwdMountFailure(err)) {
diff --git a/internal/engine/run_state.go b/internal/engine/run_state.go
index 0cd2623a..8955e933 100644
--- a/internal/engine/run_state.go
+++ b/internal/engine/run_state.go
@@ -12,25 +12,40 @@ func (e *Engine) updateRun(id string, mutate func(*domain.Run)) {
_ = e.updateRunAt(id, false, mutate)
}
+// updateRunErr is updateRun for callers that must react to a failed write,
+// such as a SOP node whose artifact handoff did not reach the store.
+func (e *Engine) updateRunErr(id string, mutate func(*domain.Run)) error {
+ _, err := e.updateRunAtErr(id, false, mutate)
+ return err
+}
+
func (e *Engine) updateRunSettling(id string, mutate func(*domain.Run)) bool {
return e.updateRunAt(id, true, mutate)
}
func (e *Engine) updateRunAt(id string, allowExpiredLease bool, mutate func(*domain.Run)) bool {
+ updated, _ := e.updateRunAtErr(id, allowExpiredLease, mutate)
+ return updated
+}
+
+// updateRunAtErr reports whether the run was stored and, when the store
+// rejected the write, that error. A skipped update (missing run or a lease
+// held elsewhere) is not an error.
+func (e *Engine) updateRunAtErr(id string, allowExpiredLease bool, mutate func(*domain.Run)) (bool, error) {
e.stateMu.Lock()
defer e.stateMu.Unlock()
r, ok := e.repo.RunState(id)
if !ok {
_ = e.takePendingObservations(id)
- return false
+ return false, nil
}
if isLiveStatus(r.Status) && r.OwnerInstanceID != "" && !e.ownsRun(r) && !allowExpiredLease {
_ = e.takePendingObservations(id)
- return false
+ return false, nil
}
pending := e.takePendingObservations(id)
if mutate == nil && len(pending) == 0 {
- return true
+ return true, nil
}
for _, item := range pending {
e.applyObservation(&r, item.nodeID, item.event)
@@ -40,12 +55,12 @@ func (e *Engine) updateRunAt(id string, allowExpiredLease bool, mutate func(*dom
}
if err := e.repo.PutRun(r); err != nil {
log.Printf("put run %s: %v", id, err)
- return false
+ return false, err
}
if current, ok := e.repo.RunStreamView(id); ok {
e.publishRun(current)
}
- return true
+ return true, nil
}
// Subscribe provides provider-neutral live run snapshots. Slow clients receive
diff --git a/internal/engine/run_state_err_guard_test.go b/internal/engine/run_state_err_guard_test.go
new file mode 100644
index 00000000..dd0fea29
--- /dev/null
+++ b/internal/engine/run_state_err_guard_test.go
@@ -0,0 +1,132 @@
+package engine
+
+import (
+ "strings"
+ "testing"
+ "time"
+
+ "agentflow/internal/domain"
+ "agentflow/internal/repo"
+)
+
+// The run-state helpers split into an error-swallowing pair (updateRun,
+// updateRunAt) and an error-returning pair (updateRunErr, updateRunAtErr).
+// These tests pin the contract each caller relies on.
+
+func rejectRunWrites(t *testing.T, s *repo.Store, runID string) {
+ t.Helper()
+ for _, op := range []string{"INSERT", "UPDATE"} {
+ stmt := "CREATE TRIGGER reject_run_" + strings.ToLower(op) + " BEFORE " + op + " ON runs " +
+ "WHEN NEW.id = '" + runID + "' BEGIN SELECT RAISE(ABORT, 'run write rejected'); END"
+ if err := s.DB.Exec(stmt).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+func TestUpdateRunErrReportsStoreRejection(t *testing.T) {
+ s, err := repo.OpenTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ e := leaseEngine(t, s, "self")
+ leaseRun(t, s, "run-store-reject", "waiting", "pending")
+ rejectRunWrites(t, s, "run-store-reject")
+
+ mutated := 0
+ mutate := func(r *domain.Run) { mutated++; r.Nodes["node"].Activity = "should not persist" }
+
+ if err := e.updateRunErr("run-store-reject", mutate); err == nil || !strings.Contains(err.Error(), "run write rejected") {
+ t.Fatalf("updateRunErr err = %v, want the store rejection", err)
+ }
+ if updated, err := e.updateRunAtErr("run-store-reject", false, mutate); updated || err == nil {
+ t.Fatalf("updateRunAtErr = (%t, %v), want (false, store error)", updated, err)
+ }
+ if e.updateRunAt("run-store-reject", false, mutate) {
+ t.Fatal("updateRunAt reported success for a rejected write")
+ }
+ if e.updateRunSettling("run-store-reject", mutate) {
+ t.Fatal("updateRunSettling reported success for a rejected write")
+ }
+ e.updateRun("run-store-reject", mutate) // must not panic; the error is only logged
+ if mutated != 5 {
+ t.Fatalf("mutate ran %d times, want 5 (once per attempted write)", mutated)
+ }
+ stored, ok := s.RunState("run-store-reject")
+ if !ok {
+ t.Fatal("run missing")
+ }
+ if got := stored.Nodes["node"].Activity; got != "" {
+ t.Fatalf("rejected write leaked into the store: activity = %q", got)
+ }
+}
+
+func TestUpdateRunHelpersRespectForeignLease(t *testing.T) {
+ s, err := repo.OpenTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ e := leaseEngine(t, s, "self")
+ leaseRun(t, s, "run-foreign", "running", "running")
+ if err := s.TryAcquireRunLease("run-foreign", "other", 1, time.Minute); err != nil {
+ t.Fatal(err)
+ }
+ before, ok := s.RunState("run-foreign")
+ if !ok || before.OwnerInstanceID != "other" {
+ t.Fatalf("run must be leased by another instance: %+v", before)
+ }
+
+ mutate := func(r *domain.Run) { r.Nodes["node"].Activity = "self wrote" }
+
+ // A lease held elsewhere is a skipped update, not an error.
+ if err := e.updateRunErr("run-foreign", mutate); err != nil {
+ t.Fatalf("updateRunErr err = %v, want nil for a foreign lease", err)
+ }
+ if updated, err := e.updateRunAtErr("run-foreign", false, mutate); updated || err != nil {
+ t.Fatalf("updateRunAtErr = (%t, %v), want (false, nil)", updated, err)
+ }
+ if e.updateRunAt("run-foreign", false, mutate) {
+ t.Fatal("updateRunAt wrote through a foreign lease")
+ }
+ e.updateRun("run-foreign", mutate)
+ if got, _ := s.RunState("run-foreign"); got.Nodes["node"].Activity != "" {
+ t.Fatalf("lease-respecting helpers wrote a foreign run: activity = %q", got.Nodes["node"].Activity)
+ }
+
+ // Settling writes are allowed to land on an expired or foreign lease.
+ if !e.updateRunSettling("run-foreign", mutate) {
+ t.Fatal("updateRunSettling skipped a foreign-leased run")
+ }
+ if got, _ := s.RunState("run-foreign"); got.Nodes["node"].Activity != "self wrote" {
+ t.Fatalf("settling write missing: activity = %q", got.Nodes["node"].Activity)
+ }
+}
+
+func TestUpdateRunHelpersReportStoredWrite(t *testing.T) {
+ s, err := repo.OpenTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ e := leaseEngine(t, s, "self")
+ leaseRun(t, s, "run-ok", "waiting", "pending")
+
+ if err := e.updateRunErr("run-ok", func(r *domain.Run) { r.Nodes["node"].Activity = "a" }); err != nil {
+ t.Fatalf("updateRunErr err = %v", err)
+ }
+ if !e.updateRunAt("run-ok", false, func(r *domain.Run) { r.Nodes["node"].Activity += "b" }) {
+ t.Fatal("updateRunAt did not report a stored write")
+ }
+ e.updateRun("run-ok", func(r *domain.Run) { r.Nodes["node"].Activity += "c" })
+ if got, _ := s.RunState("run-ok"); got.Nodes["node"].Activity != "abc" {
+ t.Fatalf("activity = %q, want abc", got.Nodes["node"].Activity)
+ }
+ if e.updateRunAt("missing", false, func(*domain.Run) { t.Fatal("mutate ran for a missing run") }) {
+ t.Fatal("updateRunAt reported a write for a missing run")
+ }
+ if err := e.updateRunErr("missing", func(*domain.Run) { t.Fatal("mutate ran for a missing run") }); err != nil {
+ t.Fatalf("missing run is a skipped update, got err %v", err)
+ }
+}
diff --git a/internal/engine/sop_node.go b/internal/engine/sop_node.go
index f1898f86..4f6f3e89 100644
--- a/internal/engine/sop_node.go
+++ b/internal/engine/sop_node.go
@@ -2,6 +2,8 @@ package engine
import (
"context"
+ "crypto/sha256"
+ "errors"
"fmt"
"strings"
"time"
@@ -11,6 +13,8 @@ import (
const maxSOPNesting = 6
+var errSOPArtifactWrite = errors.New("保存子 SOP 产物失败")
+
func (e *Engine) executeSOPNode(ctx context.Context, runID string, wf domain.WorkflowDefinition, node domain.WorkflowNode, attempt, generation int) {
fail := func(err error) {
if err == nil {
@@ -118,14 +122,14 @@ func (e *Engine) executeSOPNode(ctx context.Context, runID string, wf domain.Wor
fail(err)
return
}
- e.updateRun(runID, func(r *domain.Run) {
+ applied := false
+ err = e.updateRunErr(runID, func(r *domain.Run) {
nr := r.Nodes[node.ID]
if !shouldCommitNodeOutcome(*r, nr, generation, attempt, true) {
return
}
- if nr != nil {
- nr.ChildRunID = finished.ID
- }
+ applied = true
+ nr.ChildRunID = finished.ID
r.Artifacts = append(r.Artifacts, imported...)
nr.Output = fmt.Sprintf("子 SOP %s 已完成,交接 %d 个产物", childID, len(imported))
nr.Error = ""
@@ -133,6 +137,15 @@ func (e *Engine) executeSOPNode(ctx context.Context, runID string, wf domain.Wor
nr.FinishedAt = time.Now().UTC()
e.event(r, node.ID, "node.succeeded", node.Name+" 已完成")
})
+ if !applied {
+ return
+ }
+ if err != nil {
+ if ctx.Err() == nil {
+ e.nodeFailedAt(runID, node, attempt, generation, fmt.Errorf("%w:%w", errSOPArtifactWrite, err), false)
+ }
+ return
+ }
for _, artifact := range imported {
e.observe(runID, node.ID, domain.TelemetryEvent{
Category: "artifact", Name: "artifact.published", Phase: "finish",
@@ -275,7 +288,10 @@ func importChildArtifacts(parentID string, node domain.WorkflowNode, attempt int
for _, name := range order {
art := latest[name]
have[name] = true
- art.ID = fmt.Sprintf("art-%s-%s-%d", parentID, name, now.UnixNano())
+ // Keep the key stable for this handoff and within run_artifacts.id's 64 characters.
+ key := fmt.Sprintf("%q/%q/%d/%q/%q", parentID, node.ID, attempt, child.ID, name)
+ sum := sha256.Sum256([]byte(key))
+ art.ID = fmt.Sprintf("art-%x", sum[:20])
art.RunID = parentID
art.NodeID = node.ID
art.Attempt = attempt
diff --git a/internal/engine/sop_node_test.go b/internal/engine/sop_node_test.go
index 05e0eee8..4b55bafc 100644
--- a/internal/engine/sop_node_test.go
+++ b/internal/engine/sop_node_test.go
@@ -20,24 +20,78 @@ func TestSOPNodeRunsChildAndHandsOffArtifacts(t *testing.T) {
t.Fatal(err)
}
defer s.Close()
+ run := startSOPArtifactHandoff(t, s)
+ waitFor(t, s, run.ID, "succeeded")
+ finished, _ := s.Run(run.ID)
+ if finished.Nodes["prd-sop"].Status != "succeeded" || strings.TrimSpace(finished.Nodes["prd-sop"].ChildRunID) == "" {
+ t.Fatalf("sop node=%#v", finished.Nodes["prd-sop"])
+ }
+ if finished.Nodes["use"].Status != "succeeded" {
+ t.Fatalf("downstream node=%#v", finished.Nodes["use"])
+ }
+ for _, art := range finished.Artifacts {
+ if art.NodeID == "prd-sop" && art.Name == "test-branch-merge" && strings.Contains(art.Content, "ready") {
+ if len(art.ID) > 64 {
+ t.Fatalf("imported artifact ID exceeds run_artifacts.id width: %q", art.ID)
+ }
+ return
+ }
+ }
+ t.Fatalf("parent did not inherit child artifact: %+v", finished.Artifacts)
+}
+
+func TestSOPNodeArtifactWriteFailureKeepsSuccessfulChild(t *testing.T) {
+ t.Parallel()
+ s, err := repo.OpenTest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+ if err := s.DB.Exec("CREATE TRIGGER reject_import BEFORE INSERT ON run_artifacts " +
+ "WHEN NEW.node_id = 'prd-sop' BEGIN SELECT RAISE(ABORT, 'artifact write rejected'); END").Error; err != nil {
+ t.Fatal(err)
+ }
+ run := startSOPArtifactHandoff(t, s)
+ finished := waitRun(t, s, run.ID, 5*time.Second, func(r domain.Run) bool { return r.Status == "failed" })
+ node := finished.Nodes["prd-sop"]
+ if node.Status != "failed" || node.Attempt != 1 || !strings.Contains(node.Error, "artifact write rejected") {
+ t.Fatalf("sop node did not report the first attempt's write error: %#v", node)
+ }
+ child, ok := s.RunState(node.ChildRunID)
+ if !ok || child.Status != "succeeded" || childRunsOf(s, run.ID) != 1 {
+ t.Fatalf("parent did not retain its only successful child: %q (%s)", node.ChildRunID, child.Status)
+ }
+ page, err := s.QueryRunTelemetry(run.ID, "prd-sop", "", 0, 0, false, false, 200)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, event := range page.Events {
+ if event.Name == "artifact.published" {
+ t.Fatalf("rolled back artifact was reported as published: %+v", event)
+ }
+ }
+}
+
+func startSOPArtifactHandoff(t *testing.T, s *repo.Store) domain.Run {
+ t.Helper()
child := domain.WorkflowDefinition{
ID: "child-prd", Name: "Child PRD", SandboxProfileID: "local",
Nodes: []domain.WorkflowNode{{
ID: "write", Name: "Write", Type: "script", ScriptLanguage: "shell",
Script: "printf '# PRD\\nready\\n' > prd.md", MaxAttempts: 1,
- ArtifactOutputs: []domain.ArtifactContract{{Name: "prd", Path: "prd.md", Required: true}},
+ ArtifactOutputs: []domain.ArtifactContract{{Name: "test-branch-merge", Path: "prd.md", Required: true}},
}},
}
parent := domain.WorkflowDefinition{
ID: "req-flow", Name: "Requirement flow", SandboxProfileID: "local",
Nodes: []domain.WorkflowNode{
{
- ID: "prd-sop", Name: "产品 SOP", Type: "sop", SOPWorkflowID: child.ID, MaxAttempts: 1,
- ArtifactOutputs: []domain.ArtifactContract{{Name: "prd", Path: "prd.md", Required: true}},
+ ID: "prd-sop", Name: "产品 SOP", Type: "sop", SOPWorkflowID: child.ID, MaxAttempts: 2,
+ ArtifactOutputs: []domain.ArtifactContract{{Name: "test-branch-merge", Path: "prd.md", Required: true}},
},
{
ID: "use", Name: "Use", Type: "script", ScriptLanguage: "shell",
- Script: "test -f .agentflow/inputs/prd-sop/prd.md", MaxAttempts: 1,
+ Script: "test -f .agentflow/inputs/prd-sop/test-branch-merge.md", MaxAttempts: 1,
},
},
Edges: []domain.WorkflowEdge{{ID: "e1", Source: "prd-sop", Target: "use", When: "success"}},
@@ -53,23 +107,7 @@ func TestSOPNodeRunsChildAndHandsOffArtifacts(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- waitFor(t, s, run.ID, "succeeded")
- finished, _ := s.Run(run.ID)
- if finished.Nodes["prd-sop"].Status != "succeeded" || strings.TrimSpace(finished.Nodes["prd-sop"].ChildRunID) == "" {
- t.Fatalf("sop node=%#v", finished.Nodes["prd-sop"])
- }
- if finished.Nodes["use"].Status != "succeeded" {
- t.Fatalf("downstream node=%#v", finished.Nodes["use"])
- }
- found := false
- for _, art := range finished.Artifacts {
- if art.NodeID == "prd-sop" && art.Name == "prd" && strings.Contains(art.Content, "ready") {
- found = true
- }
- }
- if !found {
- t.Fatalf("parent did not inherit child artifact: %+v", finished.Artifacts)
- }
+ return run
}
// 子 SOP 成功不能把整条需求标成已交付;父流程失败时需求仍要能重试。
diff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.go
index 1624372e..32a1143c 100644
--- a/internal/httpapi/assistant.go
+++ b/internal/httpapi/assistant.go
@@ -25,6 +25,10 @@ import (
type assistantMessage = domain.AssistantMessage
type assistantConversation = domain.AssistantSession
+
+// assistantRequestBodyLimit accommodates long multi-turn sessions with deep thinking and tool activities.
+const assistantRequestBodyLimit = 32 << 20
+
type assistantDraft struct {
Tool string `json:"tool"`
Path map[string]any `json:"path,omitempty"`
@@ -101,7 +105,7 @@ func (h *assistantHandlers) chat(c *gin.Context) {
return
}
var req assistantRequest
- if !decode(c, &req) {
+ if !decodeLimit(c, &req, assistantRequestBodyLimit) {
return
}
req.Executor = assistantExecutor(req.Executor)
diff --git a/internal/httpapi/assistant_generation.go b/internal/httpapi/assistant_generation.go
index 7759e4f6..e5548c78 100644
--- a/internal/httpapi/assistant_generation.go
+++ b/internal/httpapi/assistant_generation.go
@@ -29,9 +29,8 @@ func (h *assistantHandlers) startGeneration(c *gin.Context) {
c.JSON(400, gin.H{"error": "请先配置个人 CodeBuddy API Key"})
return
}
- c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4<<20)
var req assistantRequest
- if !decode(c, &req) {
+ if !decodeLimit(c, &req, assistantRequestBodyLimit) {
return
}
req.Model = assistantRequestModel(req.Executor, req.Model)
diff --git a/internal/httpapi/assistant_generation_test.go b/internal/httpapi/assistant_generation_test.go
index b4202591..944ed25b 100644
--- a/internal/httpapi/assistant_generation_test.go
+++ b/internal/httpapi/assistant_generation_test.go
@@ -7,6 +7,7 @@ import (
"encoding/json"
"github.com/gin-gonic/gin"
"net/http/httptest"
+ "strings"
"testing"
"time"
)
@@ -159,3 +160,88 @@ func TestGenerationCompletedReplyAndSnapshot(t *testing.T) {
time.Sleep(20 * time.Millisecond)
}
}
+
+func TestStartGenerationAcceptsLargeRequestBody(t *testing.T) {
+ h, u := workbenchFixture(t)
+ h.generate = func(ctx context.Context, _ string, _ domain.User) (string, error) {
+ return "回复", nil
+ }
+ largeActivityText := strings.Repeat("thinking step\n", 200000)
+ largeMessages := []assistantMessage{
+ {Role: "user", Content: "帮我做实验"},
+ {
+ Role: "assistant",
+ Content: "好的,正在执行实验",
+ Activity: []domain.AssistantActivityEvent{
+ {Kind: "thinking", Text: largeActivityText},
+ },
+ },
+ {Role: "user", Content: "继续推进"},
+ }
+ _ = saveAssistantConversation(h.repo, u.ID, assistantConversation{
+ ID: "large-session",
+ ProjectID: "workbench",
+ Messages: largeMessages[:2],
+ })
+ reqBody, err := json.Marshal(assistantRequest{
+ ProjectID: "workbench",
+ SessionID: "large-session",
+ Messages: largeMessages,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(reqBody) <= 2<<20 {
+ t.Fatalf("expected payload > 2MB, got %d", len(reqBody))
+ }
+ c, rec := workbenchContext(u, "POST", "/api/assistant/generations", bytes.NewBuffer(reqBody))
+ h.startGeneration(c)
+ if rec.Code != 202 {
+ t.Fatalf("expected 202 Accepted, got %d %s", rec.Code, rec.Body.String())
+ }
+}
+
+func TestSessionUpdateAcceptsLargeRequestBody(t *testing.T) {
+ h, u := workbenchFixture(t)
+ largeActivityText := strings.Repeat("thinking step\n", 200000)
+ largeMessages := []assistantMessage{
+ {Role: "user", Content: "帮我做实验"},
+ {
+ Role: "assistant",
+ Content: "好的,正在执行实验",
+ Activity: []domain.AssistantActivityEvent{
+ {Kind: "thinking", Text: largeActivityText},
+ },
+ },
+ }
+ _ = saveAssistantConversation(h.repo, u.ID, assistantConversation{
+ ID: "large-session-put",
+ ProjectID: "workbench",
+ Title: "原标题",
+ Messages: largeMessages,
+ })
+ saved, _ := loadAssistantConversation(h.repo, u.ID, "large-session-put")
+ body := struct {
+ assistantConversation
+ Title string `json:"title"`
+ }{
+ assistantConversation: assistantConversation{
+ ID: "large-session-put",
+ ProjectID: "workbench",
+ Title: "新标题",
+ Messages: largeMessages,
+ UpdatedAt: saved.UpdatedAt,
+ },
+ Title: "新标题",
+ }
+ reqBody, _ := json.Marshal(body)
+ if len(reqBody) <= 2<<20 {
+ t.Fatalf("expected payload > 2MB, got %d", len(reqBody))
+ }
+ c, rec := workbenchContext(u, "PUT", "/api/assistant/sessions/large-session-put", bytes.NewBuffer(reqBody))
+ c.Params = gin.Params{{Key: "id", Value: "large-session-put"}}
+ h.session(c)
+ if rec.Code != 200 {
+ t.Fatalf("expected 200 OK, got %d %s", rec.Code, rec.Body.String())
+ }
+}
diff --git a/internal/httpapi/assistant_session.go b/internal/httpapi/assistant_session.go
index 5d6ded0c..bef0bc4b 100644
--- a/internal/httpapi/assistant_session.go
+++ b/internal/httpapi/assistant_session.go
@@ -288,7 +288,7 @@ func (h *assistantHandlers) session(c *gin.Context) {
assistantConversation
Effort *string `json:"effort"`
}
- if !decode(c, &body) {
+ if !decodeLimit(c, &body, assistantRequestBodyLimit) {
return
}
conv := body.assistantConversation
diff --git a/internal/httpapi/gin_helpers.go b/internal/httpapi/gin_helpers.go
index 5c652744..7e5b88d4 100644
--- a/internal/httpapi/gin_helpers.go
+++ b/internal/httpapi/gin_helpers.go
@@ -71,8 +71,15 @@ func appErrStatus(kind apperr.Kind) int {
}
// decode binds the JSON request body, answering 400 on malformed input.
+// It always caps the body at 2 MiB; a handler that accepts more calls
+// decodeLimit with its own limit.
func decode(c *gin.Context, v any) bool {
- c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 2<<20)
+ return decodeLimit(c, v, 2<<20)
+}
+
+// decodeLimit binds the JSON request body with an explicit size limit.
+func decodeLimit(c *gin.Context, v any, limit int64) bool {
+ c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, limit)
if err := json.NewDecoder(c.Request.Body).Decode(v); err != nil {
c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
return false
diff --git a/internal/httpapi/gin_helpers_decode_guard_test.go b/internal/httpapi/gin_helpers_decode_guard_test.go
new file mode 100644
index 00000000..a1b8f770
--- /dev/null
+++ b/internal/httpapi/gin_helpers_decode_guard_test.go
@@ -0,0 +1,99 @@
+package httpapi
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+)
+
+func decodeGuardContext(body string) (*gin.Context, *httptest.ResponseRecorder) {
+ gin.SetMode(gin.TestMode)
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodPost, "/test", strings.NewReader(body))
+ return c, rec
+}
+
+func decodeGuardError(t *testing.T, rec *httptest.ResponseRecorder) string {
+ t.Helper()
+ var body map[string]string
+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
+ t.Fatalf("error body %q: %v", rec.Body.String(), err)
+ }
+ return body["error"]
+}
+
+// An explicit decodeLimit is enforced, not just the 2 MiB default.
+func TestDecodeLimitRejectsBodyOverExplicitLimit(t *testing.T) {
+ c, rec := decodeGuardContext(fmt.Sprintf(`{"data":"%s"}`, strings.Repeat("a", 2048)))
+ var small map[string]string
+ if decodeLimit(c, &small, 1024) || rec.Code != http.StatusBadRequest {
+ t.Fatalf("2KB body under 1KB limit = %d", rec.Code)
+ }
+ if got := decodeGuardError(t, rec); got != "http: request body too large" {
+ t.Fatalf("2KB body under 1KB limit error = %q", got)
+ }
+}
+
+// chat, startGeneration and session PUT raise the limit to
+// assistantRequestBodyLimit, not remove it: a body just over it is rejected
+// before any work starts.
+func TestAssistantHandlersRejectBodyOverAssistantLimit(t *testing.T) {
+ h, u := workbenchFixture(t)
+ oversized := func() *bytes.Buffer {
+ payload := fmt.Sprintf(`{"projectId":"workbench","sessionId":"too-large","messages":[{"role":"user","content":"%s"}]}`,
+ strings.Repeat("a", assistantRequestBodyLimit+1024))
+ return bytes.NewBufferString(payload)
+ }
+ for _, tc := range []struct {
+ name string
+ method string
+ path string
+ handler func(*gin.Context)
+ }{
+ {"chat", http.MethodPost, "/api/assistant/chat", h.chat},
+ {"startGeneration", http.MethodPost, "/api/assistant/generations", h.startGeneration},
+ {"session PUT", http.MethodPut, "/api/assistant/sessions/too-large", h.session},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ c, rec := workbenchContext(u, tc.method, tc.path, oversized())
+ c.Params = gin.Params{{Key: "id", Value: "too-large"}}
+ tc.handler(c)
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("over-limit body = %d %s", rec.Code, truncateForTest(rec.Body.String()))
+ }
+ if got := decodeGuardError(t, rec); got != "http: request body too large" {
+ t.Fatalf("over-limit body error = %q", got)
+ }
+ })
+ }
+ if _, err := loadAssistantConversation(h.repo, u.ID, "too-large"); err == nil {
+ t.Fatal("rejected over-limit request still stored a session")
+ }
+}
+
+// chat itself (not only startGeneration) decodes with the assistant limit: a
+// 3 MiB body gets past decoding instead of hitting the 2 MiB default.
+func TestAssistantChatDecodesBodyOverDefaultLimit(t *testing.T) {
+ h, u := workbenchFixture(t)
+ payload := fmt.Sprintf(`{"projectId":"workbench","sessionId":"large-chat","messages":[{"role":"user","content":"%s"}]}`,
+ strings.Repeat("a", 3<<20))
+ c, rec := workbenchContext(u, http.MethodPost, "/api/assistant/chat", bytes.NewBufferString(payload))
+ h.chat(c)
+ if strings.Contains(rec.Body.String(), "http: request body too large") {
+ t.Fatalf("3MiB chat body hit the default limit: %d %s", rec.Code, truncateForTest(rec.Body.String()))
+ }
+}
+
+func truncateForTest(s string) string {
+ if len(s) > 200 {
+ return s[:200] + "..."
+ }
+ return s
+}
diff --git a/internal/httpapi/gin_helpers_decode_optional_guard_test.go b/internal/httpapi/gin_helpers_decode_optional_guard_test.go
new file mode 100644
index 00000000..5e13c2f0
--- /dev/null
+++ b/internal/httpapi/gin_helpers_decode_optional_guard_test.go
@@ -0,0 +1,91 @@
+package httpapi
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+)
+
+// decodeOptional only tolerates an empty body; anything else that fails to
+// parse must still answer 400 with the decoder error, like decode does.
+func TestDecodeOptionalRejectsMalformedBodyWith400(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest("POST", "/test", strings.NewReader(`{"data":`))
+
+ var v map[string]string
+ if decodeOptional(c, &v) {
+ t.Fatal("expected decodeOptional to reject a truncated JSON body")
+ }
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400, got %d", rec.Code)
+ }
+ var errBody map[string]string
+ if err := json.Unmarshal(rec.Body.Bytes(), &errBody); err != nil || errBody["error"] == "" {
+ t.Fatalf("expected a JSON error body, got %q (%v)", rec.Body.String(), err)
+ }
+}
+
+// An oversized optional body is rejected with the same 400 and message as
+// decode, not silently accepted or reported differently.
+func TestDecodeOptionalTooLargeAnswersBodyTooLarge(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest("POST", "/test", strings.NewReader(fmt.Sprintf(`{"data":"%s"}`, strings.Repeat("a", 2500000))))
+
+ var v map[string]string
+ if decodeOptional(c, &v) {
+ t.Fatal("expected decodeOptional to reject a 2.5 MB body")
+ }
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400, got %d", rec.Code)
+ }
+ var errBody map[string]string
+ _ = json.Unmarshal(rec.Body.Bytes(), &errBody)
+ if errBody["error"] != "http: request body too large" {
+ t.Fatalf("expected 'http: request body too large', got %q", errBody["error"])
+ }
+}
+
+// Like decode, decodeOptional keeps its own 2 MiB cap even when the caller
+// already wrapped the body with a larger MaxBytesReader.
+func TestDecodeOptionalDoesNotWidenToCallerLimit(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest("POST", "/test", strings.NewReader(fmt.Sprintf(`{"data":"%s"}`, strings.Repeat("a", 2500000))))
+ c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4<<20)
+
+ var v map[string]string
+ if decodeOptional(c, &v) {
+ t.Fatal("expected decodeOptional to keep its 2 MiB limit")
+ }
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400, got %d", rec.Code)
+ }
+}
+
+// Bodies within the default cap still decode through both helpers.
+func TestDecodeHelpersAcceptBodyWithinDefaultLimit(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ payload := fmt.Sprintf(`{"data":"%s"}`, strings.Repeat("a", 1<<20))
+ for name, fn := range map[string]func(*gin.Context, any) bool{"decode": decode, "decodeOptional": decodeOptional} {
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest("POST", "/test", strings.NewReader(payload))
+ var v map[string]string
+ if !fn(c, &v) {
+ t.Fatalf("%s rejected a 1 MiB body: %s", name, rec.Body.String())
+ }
+ if len(v["data"]) != 1<<20 {
+ t.Fatalf("%s data length = %d", name, len(v["data"]))
+ }
+ }
+}
diff --git a/internal/httpapi/gin_helpers_decode_test.go b/internal/httpapi/gin_helpers_decode_test.go
new file mode 100644
index 00000000..acab4a97
--- /dev/null
+++ b/internal/httpapi/gin_helpers_decode_test.go
@@ -0,0 +1,98 @@
+package httpapi
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+)
+
+func TestDecodeDefaultLimit(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ largeJSON := fmt.Sprintf(`{"data":"%s"}`, strings.Repeat("a", 2500000))
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest("POST", "/test", strings.NewReader(largeJSON))
+
+ var v map[string]string
+ if decode(c, &v) {
+ t.Fatal("expected decode to fail on 2.5MB payload")
+ }
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400, got %d", rec.Code)
+ }
+ var errBody map[string]string
+ _ = json.Unmarshal(rec.Body.Bytes(), &errBody)
+ if errBody["error"] != "http: request body too large" {
+ t.Fatalf("expected 'http: request body too large', got %q", errBody["error"])
+ }
+}
+
+// A handler that set a stricter limit before decode keeps it: decode wraps the
+// body again, and the inner reader still stops at the smaller limit.
+func TestDecodeKeepsCallerStricterLimit(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ payload := fmt.Sprintf(`{"data":"%s"}`, strings.Repeat("a", 8<<10))
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest("POST", "/test", strings.NewReader(payload))
+ c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4<<10)
+
+ var v map[string]string
+ if decode(c, &v) {
+ t.Fatal("expected decode to honour the caller's 4 KiB limit")
+ }
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400, got %d", rec.Code)
+ }
+}
+
+// decode never inherits a larger limit from a pre-wrapped body; handlers that
+// accept more than 2 MiB must say so with decodeLimit.
+func TestDecodeDoesNotWidenToCallerLimit(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ largeJSON := fmt.Sprintf(`{"data":"%s"}`, strings.Repeat("a", 2500000))
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest("POST", "/test", strings.NewReader(largeJSON))
+ c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4<<20)
+
+ var v map[string]string
+ if decode(c, &v) {
+ t.Fatal("expected decode to keep its 2 MiB limit")
+ }
+}
+
+func TestDecodeOptionalAcceptsEmptyBodyWithinDefaultLimit(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ for name, body := range map[string]string{"empty": "", "large": fmt.Sprintf(`{"data":"%s"}`, strings.Repeat("a", 2500000))} {
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest("POST", "/test", strings.NewReader(body))
+ var v map[string]string
+ ok := decodeOptional(c, &v)
+ if want := name == "empty"; ok != want {
+ t.Fatalf("%s body: decodeOptional = %t, want %t (%s)", name, ok, want, rec.Body.String())
+ }
+ }
+}
+
+func TestDecodeLimitExplicit(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ largeJSON := fmt.Sprintf(`{"data":"%s"}`, strings.Repeat("a", 3000000))
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest("POST", "/test", strings.NewReader(largeJSON))
+
+ var v map[string]string
+ if !decodeLimit(c, &v, 5<<20) {
+ t.Fatalf("expected decodeLimit to succeed for 3MB payload with 5MB limit, got: %s", rec.Body.String())
+ }
+ if len(v["data"]) != 3000000 {
+ t.Fatalf("data length mismatch: %d", len(v["data"]))
+ }
+}
diff --git a/internal/runtime/browser_devserver.go b/internal/runtime/browser_devserver.go
index 6102903e..9dbdb59e 100644
--- a/internal/runtime/browser_devserver.go
+++ b/internal/runtime/browser_devserver.go
@@ -61,16 +61,31 @@ var devServerDial = func(ctx context.Context, endpoint browserEndpoint, port int
var devServerLookup = lookupBrowserEndpoint
func handleDevServerHTTP(ctx context.Context, runID string, req *domain.BrowserHTTPRequest) (domain.BrowserState, error) {
- if req == nil || req.Port <= 0 || req.Port > 65535 || !strings.HasPrefix(req.Path, "/") {
+ if req == nil || req.Port <= 0 || req.Port > 65535 || !strings.HasPrefix(req.Path, "/") || strings.ContainsAny(req.Path, "\r\n") {
return domain.BrowserState{}, errors.New("无效的开发服务器请求")
}
client, endpoint, ok := devServerClientFor(ctx, runID)
if !ok {
return domain.BrowserState{Available: false, Reason: "Agent 浏览器尚未启动:开发服务器预览需要它所在的沙箱网络"}, nil
}
- method := strings.ToUpper(strings.TrimSpace(req.Method))
- if method == "" {
+ var method string
+ switch strings.ToUpper(strings.TrimSpace(req.Method)) {
+ case "", http.MethodGet:
method = http.MethodGet
+ case http.MethodHead:
+ method = http.MethodHead
+ case http.MethodPost:
+ method = http.MethodPost
+ case http.MethodPut:
+ method = http.MethodPut
+ case http.MethodPatch:
+ method = http.MethodPatch
+ case http.MethodDelete:
+ method = http.MethodDelete
+ case http.MethodOptions:
+ method = http.MethodOptions
+ default:
+ return domain.BrowserState{}, errors.New("无效或不支持的 HTTP 请求方法")
}
target := "http://localhost:" + strconv.Itoa(req.Port) + req.Path
out, err := http.NewRequestWithContext(ctx, method, target, bytes.NewReader(req.Body))
diff --git a/internal/runtime/browser_devserver_method_guard_test.go b/internal/runtime/browser_devserver_method_guard_test.go
new file mode 100644
index 00000000..0cb26633
--- /dev/null
+++ b/internal/runtime/browser_devserver_method_guard_test.go
@@ -0,0 +1,72 @@
+package runtime
+
+import (
+ "context"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "strings"
+ "sync/atomic"
+ "testing"
+
+ "agentflow/internal/domain"
+)
+
+// The dev-server proxy maps every allowed method (any case, padded) to its
+// canonical name, and refuses everything else or a CR/LF path before any
+// request reaches the dev server.
+func TestHandleDevServerHTTPMethodAllowlistAndPathGuard(t *testing.T) {
+ var hits atomic.Int32
+ dev := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hits.Add(1)
+ w.Header().Set("X-Seen-Method", r.Method)
+ }))
+ defer dev.Close()
+ _, rawPort, _ := net.SplitHostPort(strings.TrimPrefix(dev.URL, "http://"))
+ port, _ := strconv.Atoi(rawPort)
+ lookup := devServerLookup
+ devServerLookup = func(context.Context, string) (browserEndpoint, bool) { return browserEndpoint{Kind: "local"}, true }
+ t.Cleanup(func() { devServerLookup = lookup })
+ devServerClients.Lock()
+ delete(devServerClients.items, "dev-method-run")
+ devServerClients.Unlock()
+ send := func(method, path string) (domain.BrowserState, error) {
+ return HandleBrowser(context.Background(), "dev-method-run", domain.BrowserRequest{Operation: "http",
+ HTTP: &domain.BrowserHTTPRequest{Port: port, Method: method, Path: path}})
+ }
+
+ for raw, want := range map[string]string{
+ "": http.MethodGet,
+ "get": http.MethodGet,
+ " head ": http.MethodHead,
+ "post": http.MethodPost,
+ "Put": http.MethodPut,
+ "patch": http.MethodPatch,
+ "DELETE": http.MethodDelete,
+ "\toptions": http.MethodOptions,
+ } {
+ state, err := send(raw, "/")
+ if err != nil || state.HTTP == nil {
+ t.Fatalf("method %q: state=%+v err=%v", raw, state, err)
+ }
+ if got := http.Header(state.HTTP.Header).Get("X-Seen-Method"); got != want {
+ t.Fatalf("method %q reached dev server as %q, want %q", raw, got, want)
+ }
+ }
+
+ before := hits.Load()
+ for _, method := range []string{"CONNECT", "trace", "PROPFIND", "GET\r\nX-Injected: 1", "G ET"} {
+ if _, err := send(method, "/"); err == nil {
+ t.Fatalf("method %q accepted", method)
+ }
+ }
+ for _, path := range []string{"/a\nb", "/a\rb", "/\r\n"} {
+ if _, err := send("GET", path); err == nil {
+ t.Fatalf("path %q accepted", path)
+ }
+ }
+ if after := hits.Load(); after != before {
+ t.Fatalf("rejected requests reached the dev server %d times", after-before)
+ }
+}
diff --git a/internal/runtime/browser_devserver_test.go b/internal/runtime/browser_devserver_test.go
index f8b99f07..dd532b66 100644
--- a/internal/runtime/browser_devserver_test.go
+++ b/internal/runtime/browser_devserver_test.go
@@ -81,6 +81,15 @@ func TestHandleDevServerHTTPThroughEndpoint(t *testing.T) {
if _, err := HandleBrowser(context.Background(), "dev-run", domain.BrowserRequest{Operation: "http", HTTP: &domain.BrowserHTTPRequest{Port: port, Path: "no-slash"}}); err == nil {
t.Fatal("invalid path accepted")
}
+ if _, err := HandleBrowser(context.Background(), "dev-run", domain.BrowserRequest{Operation: "http", HTTP: &domain.BrowserHTTPRequest{Port: port, Path: "/a\r\nb: c"}}); err == nil {
+ t.Fatal("CRLF path accepted")
+ }
+ if _, err := HandleBrowser(context.Background(), "dev-run", domain.BrowserRequest{Operation: "http", HTTP: &domain.BrowserHTTPRequest{Port: port, Method: "INVALID", Path: "/"}}); err == nil {
+ t.Fatal("invalid method accepted")
+ }
+ if _, err := HandleBrowser(context.Background(), "dev-run", domain.BrowserRequest{Operation: "http", HTTP: &domain.BrowserHTTPRequest{Port: port, Method: "TRACE", Path: "/"}}); err == nil {
+ t.Fatal("TRACE method accepted")
+ }
devServerLookup = func(context.Context, string) (browserEndpoint, bool) { return browserEndpoint{}, false }
devServerClients.Lock()
delete(devServerClients.items, "other-run")