Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.
JavaScript agent-orchestrationagentic-workflowai-agentsai-codingclaude-codecode-reviewcodebuddycodexcoding-agentscursordeveloper-toolshuman-on-the-loopllmmcpmulti-agentsdlcself-hostedsopworkflow-automationworkflow-engine
fix(bind-cli): start the systemd user bus before installing the service (#208)
crispinhu27ad08f28e1e13
diff --git a/deploy/bind-cli.sh b/deploy/bind-cli.shindex 323d5e53..93d24914 100755--- a/deploy/bind-cli.sh+++ b/deploy/bind-cli.sh@@ -17,7 +17,8 @@# --download-url <URL> 从指定 URL 下载二进制(含 {os} {arch} 占位符)# --source <目录> 平台未分发二进制时,从本地 AgentFlow 源码构建(需要 Go)# --strict-https 禁止在 HTTPS 网络不可达时降级到 HTTP-# --service 安装 launchd (macOS) / systemd (Linux) 常驻服务+# --service 安装 launchd (macOS) / systemd (Linux) 常驻服务。+# Linux 上没有用户会话时会自动拉起 systemd 用户实例。# --no-start 只安装配置,不立即启动# --no-auto-update 禁止从平台自动更新(自定义二进制默认禁用)# --upgrade 原地升级已绑定的 runner,保留配置、机器绑定和工作区@@ -72,6 +73,100 @@ fifail() { echo "[bind-cli] 错误: $*" >&2; exit 1; }info() { echo "[bind-cli] $*"; }+# systemctl --user 走用户 D-Bus。SSH 进 CVM、以 root 执行,或当前 shell+# 没有登录会话时,这条总线还不存在,会报 Failed to connect to bus。+# 系统总线这时通常仍可用:用它启用 linger 并启动 user@<uid>,再把+# XDG_RUNTIME_DIR 指到 /run/user/<uid>,用户总线就会出现。+prepare_systemd_user_env() {+ local uid runtime+ uid="$(id -u)"+ runtime="/run/user/${uid}"+ if [[ -z "${XDG_RUNTIME_DIR:-}" && -d "${runtime}" ]]; then+ export XDG_RUNTIME_DIR="${runtime}"+ fi+ if [[ -n "${XDG_RUNTIME_DIR:-}" && -z "${DBUS_SESSION_BUS_ADDRESS:-}" && -S "${XDG_RUNTIME_DIR}/bus" ]]; then+ export DBUS_SESSION_BUS_ADDRESS="unix:path=${XDG_RUNTIME_DIR}/bus"+ fi+}++systemd_user_reachable() {+ systemctl --user show-environment >/dev/null 2>&1+}++# 先以当前用户执行。失败后再试免密 sudo:安装命令常通过 curl|bash 进入,+# 没有终端可以输入密码。+run_privileged() {+ if [[ "$(id -u)" -eq 0 ]]; then+ SYSTEMD_ASK_PASSWORD=0 "$@"+ return+ fi+ if SYSTEMD_ASK_PASSWORD=0 "$@" >/dev/null 2>&1; then+ return 0+ fi+ if command -v sudo >/dev/null 2>&1; then+ sudo -n "$@"+ return+ fi+ return 1+}++# 参数 quiet:连上总线,但不打印说明。返回 0 表示 systemctl --user 可用。+ensure_systemd_user_bus() {+ local announce="${1:-announce}" uid runtime user_name linger_ok attempt+ uid="$(id -u)"+ user_name="$(id -un)"+ runtime="/run/user/${uid}"+ linger_ok=0+ command -v systemctl >/dev/null 2>&1 || return 1+ SYSTEMD_ASK_PASSWORD=0 systemctl show --property=Version >/dev/null 2>&1 || return 1+ prepare_systemd_user_env+ if systemd_user_reachable; then+ return 0+ fi+ if [[ "${announce}" == announce ]]; then+ info "当前没有 systemd 用户总线,正在为 ${user_name} 启动用户实例..."+ fi+ if command -v loginctl >/dev/null 2>&1 && run_privileged loginctl enable-linger "${user_name}" >/dev/null 2>&1; then+ linger_ok=1+ fi+ run_privileged systemctl start "user@${uid}.service" >/dev/null 2>&1 || true+ if [[ -z "${XDG_RUNTIME_DIR:-}" || -S "${runtime}/bus" ]]; then+ export XDG_RUNTIME_DIR="${runtime}"+ fi+ attempt=0+ while [[ "${attempt}" -lt 10 ]]; do+ attempt=$((attempt + 1))+ if [[ -S "${runtime}/bus" && -z "${DBUS_SESSION_BUS_ADDRESS:-}" ]]; then+ export DBUS_SESSION_BUS_ADDRESS="unix:path=${runtime}/bus"+ fi+ if systemd_user_reachable; then+ if [[ "${announce}" == announce ]]; then+ if [[ "${linger_ok}" -eq 1 ]]; then+ info "已接通 systemd 用户总线;退出登录后服务仍会保持运行"+ else+ info "已接通 systemd 用户总线"+ fi+ fi+ return 0+ fi+ sleep 0.2+ done+ return 1+}++require_systemd_user_bus() {+ if ensure_systemd_user_bus; then+ return 0+ fi+ if ! command -v systemctl >/dev/null 2>&1 || ! SYSTEMD_ASK_PASSWORD=0 systemctl show --property=Version >/dev/null 2>&1; then+ fail "当前系统没有可用的 systemd,不能安装常驻服务。去掉 --service 可以在当前终端前台运行"+ fi+ if [[ "$(id -u)" -eq 0 ]]; then+ fail "无法启动 systemd 用户实例。请确认 systemd-logind 正在运行后重新安装"+ fi+ fail "无法连接 systemd 用户总线。请在终端执行:sudo loginctl enable-linger $(id -un),然后再运行安装命令"+}+OS="$(uname -s | tr '[:upper:]' '[:lower:]')"ARCH="$(uname -m)"case "$ARCH" in@@ -98,6 +193,7 @@ if [[ "$UNINSTALL" == "1" ]]; thenif [[ "$OS" == "darwin" ]]; then[[ -f "$PLIST" ]] && launchctl unload "$PLIST" >/dev/null 2>&1 || trueelse+ ensure_systemd_user_bus quiet || truesystemctl --user stop agentflow-runner.service >/dev/null 2>&1 || truefipkill -f 'agentflow-runner -server' >/dev/null 2>&1 || true@@ -131,6 +227,7 @@ if [[ "$UNINSTALL" == "1" ]]; theninfo "已移除 launchd 服务"fielse+ ensure_systemd_user_bus quiet || truesystemctl --user disable --now agentflow-runner.service >/dev/null 2>&1 || truerm -f "$UNIT"systemctl --user daemon-reload >/dev/null 2>&1 || true@@ -339,6 +436,7 @@ if [[ "$UPGRADE" == "1" ]]; thenlaunchctl load "$PLIST"info "已原地升级并重启 launchd 服务;机器绑定和工作区保持不变"elif [[ "$OS" == "linux" && -f "$UNIT" ]]; then+ require_systemd_user_bussystemctl --user restart agentflow-runner.serviceinfo "已原地升级并重启 systemd 服务;机器绑定和工作区保持不变"else@@ -423,6 +521,7 @@ EOFecho "[Install]"echo "WantedBy=default.target"} > "$UNIT"+ require_systemd_user_bussystemctl --user daemon-reloadsystemctl --user enable agentflow-runner.servicesystemctl --user restart agentflow-runner.servicediff --git a/deploy/deploy_test.go b/deploy/deploy_test.gonew file mode 100644index 00000000..b4458bb5--- /dev/null+++ b/deploy/deploy_test.go@@ -0,0 +1,270 @@+package deploy++import (+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"+)++func TestBindCLIServiceStartsUserBusWhenSessionMissing(t *testing.T) {+ home := t.TempDir()+ binDir := filepath.Join(home, "bin")+ runner := filepath.Join(home, "runner-source")+ if err := os.WriteFile(runner, []byte("runner"), 0o755); err != nil {+ t.Fatal(err)+ }+ fakeBin := filepath.Join(home, "fake-bin")+ if err := os.MkdirAll(fakeBin, 0o755); err != nil {+ t.Fatal(err)+ }+ serviceLog := filepath.Join(home, "service.log")+ busReady := filepath.Join(home, "bus-ready")+ for name, script := 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+ *runners/health*) exit 0 ;;+ *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+`,+ "loginctl": "#!/bin/sh\nprintf '%s\\n' \"$*\" >> \"$TEST_SERVICE_LOG\"\nexit 0\n",+ "sudo": "#!/bin/sh\nprintf 'sudo %s\\n' \"$*\" >> \"$TEST_SERVICE_LOG\"\nexit 1\n",+ "systemctl": `#!/bin/sh+printf '%s\n' "$*" >> "$TEST_SERVICE_LOG"+case "$1" in+ --user)+ if [ ! -f "$TEST_BUS_READY" ] || [ -z "${XDG_RUNTIME_DIR:-}" ]; then+ echo 'Failed to connect to bus: $DBUS_SESSION_BUS_ADDRESS and $XDG_RUNTIME_DIR not defined' >&2+ exit 1+ fi+ exit 0+ ;;+esac+case " $* " in+ *" start user@"*)+ : > "$TEST_BUS_READY"+ exit 0+ ;;+esac+exit 0+`,+ } {+ if err := os.WriteFile(filepath.Join(fakeBin, name), []byte(script), 0o755); err != nil {+ t.Fatal(err)+ }+ }+ env := make([]string, 0, len(os.Environ())+6)+ 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_SERVICE_LOG="+serviceLog,+ "TEST_BUS_READY="+busReady,+ )+ 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") {+ t.Fatalf("dbus error leaked to the installer output:\n%s", text)+ }+ if !strings.Contains(text, "已接通 systemd 用户总线") || !strings.Contains(text, "systemd 服务已安装并启动") {+ t.Fatalf("user bus was not brought up:\n%s", text)+ }+ log, err := os.ReadFile(serviceLog)+ if err != nil {+ t.Fatal(err)+ }+ logText := string(log)+ if strings.Contains(logText, "sudo ") {+ t.Fatalf("installer invoked sudo: %s", logText)+ }+ if !strings.Contains(logText, "enable-linger") || !strings.Contains(logText, "start user@") || !strings.Contains(logText, "--user enable") {+ t.Fatalf("user manager was not started before enable: %s", logText)+ }+ unit, err := os.ReadFile(filepath.Join(home, ".config/systemd/user/agentflow-runner.service"))+ if err != nil || !strings.Contains(string(unit), "Restart=always") {+ t.Fatalf("user unit missing: %q %v", unit, err)+ }+}++// runBindCLIService runs `bind-cli.sh --service` with fake uname, curl, id+// and the given systemctl/loginctl/sudo scripts. It returns the combined+// output, the exit error and the commands the fakes recorded.+func runBindCLIService(t *testing.T, fakes map[string]string) (string, error, string) {+ t.Helper()+ home := t.TempDir()+ runner := filepath.Join(home, "runner-source")+ if err := os.WriteFile(runner, []byte("runner"), 0o755); err != nil {+ t.Fatal(err)+ }+ fakeBin := filepath.Join(home, "fake-bin")+ if err := os.MkdirAll(fakeBin, 0o755); err != nil {+ t.Fatal(err)+ }+ scripts := map[string]string{+ "uname": "#!/bin/sh\ncase \"$1\" in -s) echo Linux ;; -m) echo x86_64 ;; *) echo Linux ;; esac\n",+ "id": "#!/bin/sh\ncase \"$1\" in -u) echo 4242 ;; -un) echo tester ;; *) /usr/bin/id \"$@\" ;; esac\n",+ "curl": `#!/bin/sh+case "$*" in+ *runners/health*) exit 0 ;;+ *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+`,+ }+ for name, script := range fakes {+ scripts[name] = script+ }+ for name, script := range scripts {+ if err := os.WriteFile(filepath.Join(fakeBin, name), []byte(script), 0o755); err != nil {+ t.Fatal(err)+ }+ }+ serviceLog := filepath.Join(home, "service.log")+ env := make([]string, 0, len(os.Environ())+6)+ 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_SERVICE_LOG="+serviceLog,+ "TEST_BUS_READY="+filepath.Join(home, "bus-ready"),+ )+ cmd := exec.Command("/bin/bash", "bind-cli.sh",+ "--server", "http://isolated.example",+ "--token", "bind-test",+ "--from", runner,+ "--bin-dir", filepath.Join(home, "bin"),+ "--service",+ )+ cmd.Env = env+ out, err := cmd.CombinedOutput()+ log, _ := os.ReadFile(serviceLog)+ return string(out), err, string(log)+}++// When neither the user nor passwordless sudo can start user@<uid>, the+// installer stops with the enable-linger hint instead of a raw dbus error.+func TestBindCLIServiceFailsWithLingerHintWhenUserBusUnavailable(t *testing.T) {+ out, err, log := runBindCLIService(t, map[string]string{+ "loginctl": "#!/bin/sh\nprintf 'loginctl %s\\n' \"$*\" >> \"$TEST_SERVICE_LOG\"\nexit 1\n",+ "sudo": "#!/bin/sh\nprintf 'sudo %s\\n' \"$*\" >> \"$TEST_SERVICE_LOG\"\nexit 1\n",+ "systemctl": `#!/bin/sh+printf 'systemctl %s\n' "$*" >> "$TEST_SERVICE_LOG"+case "$1" in+ --user) echo 'Failed to connect to bus: No medium found' >&2; exit 1 ;;+esac+case " $* " in+ *" start user@"*) exit 1 ;;+esac+exit 0+`,+ })+ if err == nil {+ t.Fatalf("install succeeded without a user bus:\n%s", out)+ }+ if !strings.Contains(out, "sudo loginctl enable-linger tester") {+ t.Fatalf("missing enable-linger hint:\n%s", out)+ }+ if strings.Contains(out, "Failed to connect to bus") {+ t.Fatalf("dbus error leaked to the installer output:\n%s", out)+ }+ if !strings.Contains(log, "sudo -n loginctl enable-linger tester") || !strings.Contains(log, "sudo -n systemctl start [email protected]") {+ t.Fatalf("passwordless sudo was not tried after the user call failed: %s", log)+ }+ for _, unwanted := range []string{"--user daemon-reload", "--user enable", "--user restart"} {+ if strings.Contains(log, unwanted) {+ t.Fatalf("installer ran %q without a user bus: %s", unwanted, log)+ }+ }+}++// 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",+ })+ if err == nil || !strings.Contains(out, "当前系统没有可用的 systemd") {+ t.Fatalf("want the no-systemd error, got err=%v:\n%s", err, out)+ }+ if strings.Contains(log, "start user@") {+ t.Fatalf("tried to start a user manager without systemd: %s", log)+ }+}++// A non-root user whose own loginctl call is refused still gets the bus+// through passwordless sudo, and linger keeps the service after logout.+func TestBindCLIServiceUsesPasswordlessSudoForLinger(t *testing.T) {+ out, err, log := runBindCLIService(t, map[string]string{+ "sudo": `#!/bin/sh+printf 'sudo %s\n' "$*" >> "$TEST_SERVICE_LOG"+[ "$1" = -n ] && shift+TEST_AS_ROOT=1 exec "$@"+`,+ "loginctl": "#!/bin/sh\n[ -n \"${TEST_AS_ROOT:-}\" ] || exit 1\nprintf 'loginctl %s\\n' \"$*\" >> \"$TEST_SERVICE_LOG\"\n",+ "systemctl": `#!/bin/sh+printf 'systemctl %s\n' "$*" >> "$TEST_SERVICE_LOG"+case "$1" in+ --user)+ [ -f "$TEST_BUS_READY" ] && [ -n "${XDG_RUNTIME_DIR:-}" ] && exit 0+ echo 'Failed to connect to bus' >&2; exit 1 ;;+esac+case " $* " in+ *" start user@"*)+ [ -n "${TEST_AS_ROOT:-}" ] || exit 1+ : > "$TEST_BUS_READY"+ ;;+esac+exit 0+`,+ })+ if err != nil {+ t.Fatalf("service install failed: %v\n%s", err, out)+ }+ if !strings.Contains(out, "退出登录后服务仍会保持运行") || !strings.Contains(out, "systemd 服务已安装并启动") {+ t.Fatalf("linger was not reported:\n%s", out)+ }+ if !strings.Contains(log, "loginctl enable-linger tester") || !strings.Contains(log, "sudo -n systemctl start [email protected]") || !strings.Contains(log, "systemctl --user enable agentflow-runner.service") {+ t.Fatalf("unexpected service commands: %s", log)+ }+}