From 74cbeeeae65a27bc014fd7db8a35ae80d79c89e0 Mon Sep 17 00:00:00 2001 From: Kris <2040188027@qq.com> Date: Fri, 20 Nov 2026 10:10:11 +0800 Subject: [PATCH] fix(runner): compare semantic versions for capability gates --- docs/deployment.md | 2 + go.mod | 1 + go.sum | 2 + internal/domain/runner.go | 42 ++++++------------- internal/domain/runner_version_test.go | 41 ++++++++++++++++++ .../domain/testdata/runner-version-cases.json | 28 +++++++++++++ web/app/runners.js | 33 ++++++++++++--- web/runner_default_rule_test.js | 11 +++-- webtest/tests/mcp-sops-runners.test.mjs | 21 ++++++++++ 9 files changed, 143 insertions(+), 38 deletions(-) create mode 100644 internal/domain/runner_version_test.go create mode 100644 internal/domain/testdata/runner-version-cases.json diff --git a/docs/deployment.md b/docs/deployment.md index 0d1c79995..46b0df33b 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -129,6 +129,8 @@ Use `-admin` only when granting platform administration. Running the command aga ## Workers and runners +Runner capabilities and default-machine selection use semantic-version precedence. A custom build based on a release can append build metadata, for example `0.11.0+internal.42`; metadata does not change compatibility. A prerelease such as `0.11.0-rc.1` sorts below `0.11.0`, so it does not satisfy a capability introduced in that release. Numeric `v1` and `v1.2` shorthand remains accepted. Unknown or malformed versions (for example `dev`) do not enable version-gated capabilities; the default-machine selector asks you to confirm the version rather than reporting it as an older release. This comparison does not certify compatibility of custom protocol changes. + The upstream process roles remain `-role api`, `-role worker` and `-role all`. API and worker instances must share the MySQL database and configuration appropriate to their deployment. Set `AGENTFLOW_CONTROL_TOKEN`, `AGENTFLOW_CONTROL_URL` and `AGENTFLOW_WORKER_URL` when separating control and execution. Set `AGENTFLOW_PLATFORM_MCP_URL` to the actual platform URL reachable from execution containers. Personal runners are connected from the execution-machine page with a short-lived binding code. The installer is served at `/runners/install.sh`. `AGENTFLOW_RUNNER_BINARY` can point to binaries with `{os}` and `{arch}` substitutions. Container images bundle Linux/macOS amd64/arm64 runner and gate binaries. Native source installations can build on demand with Go. diff --git a/go.mod b/go.mod index 2704c933f..fb1e47ca2 100644 --- a/go.mod +++ b/go.mod @@ -12,6 +12,7 @@ require ( github.com/klauspost/compress v1.20.3 github.com/zalando/go-keyring v0.2.8 golang.org/x/crypto v0.58.0 + golang.org/x/mod v0.43.0 golang.org/x/net v0.62.0 golang.org/x/sys v0.49.0 gorm.io/driver/mysql v1.6.0 diff --git a/go.sum b/go.sum index 6cc183153..248fd545c 100644 --- a/go.sum +++ b/go.sum @@ -110,6 +110,8 @@ golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI= golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A= golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= +golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg= +golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY= golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= diff --git a/internal/domain/runner.go b/internal/domain/runner.go index acee4c600..afe328386 100644 --- a/internal/domain/runner.go +++ b/internal/domain/runner.go @@ -3,9 +3,10 @@ package domain import ( "fmt" "path" - "strconv" "strings" "time" + + "golang.org/x/mod/semver" ) // Runner connection model (docs: cli-connect.md). @@ -114,6 +115,9 @@ func (r Runner) DefaultSelectionBlocker() string { if version == "" { version = "未知" } + if !semver.IsValid(runnerSemanticVersion(r.RunnerVersion)) { + return fmt.Sprintf("无法判断执行机器版本 %s 的兼容性,请确认版本(需 %s 及以上才能设为默认)", version, RunnerVersionDefaultSelection) + } return fmt.Sprintf("执行机器版本 %s 过低,需升级至 %s 及以上才能设为默认", version, RunnerVersionDefaultSelection) } return "" @@ -237,35 +241,15 @@ func (r Runner) SupportsReportedOutputs() bool { return versionAtLeast(r.RunnerVersion, RunnerVersionReportedOutputs) } -// versionAtLeast compares dotted numeric versions; malformed input is older. +func runnerSemanticVersion(version string) string { + return "v" + strings.TrimPrefix(strings.TrimSpace(version), "v") +} + +// versionAtLeast ignores semantic-version build metadata and orders prereleases +// below the corresponding release. Unknown versions never enable a capability. func versionAtLeast(have, want string) bool { - parse := func(v string) ([]int, bool) { - parts := strings.Split(strings.TrimPrefix(strings.TrimSpace(v), "v"), ".") - out := make([]int, len(parts)) - for i, part := range parts { - n, err := strconv.Atoi(part) - if err != nil { - return nil, false - } - out[i] = n - } - return out, true - } - h, ok := parse(have) - if !ok { - return false - } - w, _ := parse(want) - for i := 0; i < len(w); i++ { - hv := 0 - if i < len(h) { - hv = h[i] - } - if hv != w[i] { - return hv > w[i] - } - } - return true + h, w := runnerSemanticVersion(have), runnerSemanticVersion(want) + return semver.IsValid(h) && semver.IsValid(w) && semver.Compare(h, w) >= 0 } // SupportsProvider reports whether the runner last reported a runtime for the diff --git a/internal/domain/runner_version_test.go b/internal/domain/runner_version_test.go new file mode 100644 index 000000000..cb19a0a47 --- /dev/null +++ b/internal/domain/runner_version_test.go @@ -0,0 +1,41 @@ +package domain + +import ( + "encoding/json" + "os" + "strings" + "testing" +) + +func TestRunnerSemanticVersionCompatibility(t *testing.T) { + data, err := os.ReadFile("testdata/runner-version-cases.json") + if err != nil { + t.Fatal(err) + } + var cases []struct { + Have, Want string + OK bool + } + if err := json.Unmarshal(data, &cases); err != nil { + t.Fatal(err) + } + for _, tc := range cases { + t.Run(tc.Have+"/"+tc.Want, func(t *testing.T) { + if got := versionAtLeast(tc.Have, tc.Want); got != tc.OK { + t.Errorf("versionAtLeast(%q,%q)=%v, want %v", tc.Have, tc.Want, got, tc.OK) + } + }) + } +} + +func TestRunnerDefaultSelectionDistinguishesUnknownVersion(t *testing.T) { + for _, version := range []string{"", "dev", "0.8.0+bad!"} { + got := (Runner{Status: RunnerStatusOnline, RunnerVersion: version}).DefaultSelectionBlocker() + if !strings.Contains(got, "无法判断") || strings.Contains(got, "过低") { + t.Errorf("%q: %s", version, got) + } + } + if got := (Runner{Status: RunnerStatusOnline, RunnerVersion: "0.8.0+internal"}).DefaultSelectionBlocker(); got != "" { + t.Errorf("build metadata rejected: %s", got) + } +} diff --git a/internal/domain/testdata/runner-version-cases.json b/internal/domain/testdata/runner-version-cases.json new file mode 100644 index 000000000..8fbc3e359 --- /dev/null +++ b/internal/domain/testdata/runner-version-cases.json @@ -0,0 +1,28 @@ +[ + {"have":"0.8.0","want":"0.8.0","ok":true}, + {"have":"v0.9.2","want":"0.8.0","ok":true}, + {"have":" v0.8.0+internal.42 ","want":"0.8.0","ok":true}, + {"have":"0.8.0+build-01","want":"0.8.0+build-99","ok":true}, + {"have":"0.7.9+internal","want":"0.8.0","ok":false}, + {"have":"0.8.0-custom","want":"0.8.0","ok":false}, + {"have":"0.9.0-custom","want":"0.8.0","ok":true}, + {"have":"0.8.0-rc.2","want":"0.8.0-rc.10","ok":false}, + {"have":"0.8.0-rc.10","want":"0.8.0-rc.2","ok":true}, + {"have":"0.8.0-1","want":"0.8.0-alpha","ok":false}, + {"have":"0.8.0-alpha.1","want":"0.8.0-alpha","ok":true}, + {"have":"0.8.0","want":"0.8.0-rc.1","ok":true}, + {"have":"0.8","want":"0.8.0","ok":true}, + {"have":"1","want":"0.8.0","ok":true}, + {"have":"0.8.0.1","want":"0.8.0","ok":false}, + {"have":"dev","want":"0.8.0","ok":false}, + {"have":"","want":"0.8.0","ok":false}, + {"have":"-1.8.0","want":"0.8.0","ok":false}, + {"have":"01.8.0","want":"0.8.0","ok":false}, + {"have":"0.8.0-01","want":"0.8.0","ok":false}, + {"have":"0.8.0+","want":"0.8.0","ok":false}, + {"have":"0.8.0+bad!","want":"0.8.0","ok":false}, + {"have":"0.8+build","want":"0.8.0","ok":false}, + {"have":"0.8.0","want":"dev","ok":false}, + {"have":"9007199254740992.0.0","want":"9007199254740993.0.0","ok":false}, + {"have":"0.8.0-9007199254740992","want":"0.8.0-9007199254740993","ok":false} +] diff --git a/web/app/runners.js b/web/app/runners.js index f625de4da..2eb140325 100644 --- a/web/app/runners.js +++ b/web/app/runners.js @@ -249,18 +249,39 @@ async function removeRunner(runnerId){ } // Mirrors domain.Runner.DefaultSelectionBlocker so the page and // PUT /api/runners/default refuse the same machines with the same reason. +function runnerSemanticVersion(value){ + // Match golang.org/x/mod/semver, including v1/v1.2 shorthand only without suffixes. + const match=String(value||'').trim().replace(/^v/,'').match(/^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?)?)?$/); + if(!match)return null; + const pre=match[4]?match[4].split('.'):[]; + if(pre.some(part=>/^\d+$/.test(part)&&part.length>1&&part[0]==='0'))return null; + return {core:[match[1],match[2]||'0',match[3]||'0'],pre}; +} function runnerVersionAtLeast(have,want){ - const parse=v=>{const parts=String(v||'').trim().replace(/^v/,'').split('.');return parts.every(p=>/^\d+$/.test(p))?parts.map(Number):null}; - const h=parse(have),w=parse(want); - if(!w)return true; + const h=runnerSemanticVersion(have),w=runnerSemanticVersion(want); + if(!w)return false; if(!h)return false; - for(let i=0;iw[i]} - return true; + // Compare numeric strings without Number's integer precision limit. + const numeric=(a,b)=>a.length!==b.length?a.length-b.length:a===b?0:a>b?1:-1; + for(let i=0;i<3;i++){const c=numeric(h.core[i],w.core[i]);if(c)return c>0} + if(!h.pre.length||!w.pre.length)return !h.pre.length; + for(let i=0;i0; + if(an!==bn)return !an; + return a>b; + } + return h.pre.length>=w.pre.length; } function runnerDefaultBlocker(r){ if(r.status!=='online')return '机器离线'; const min=state.minRunnerVersion||''; - if(min&&!runnerVersionAtLeast(r.runnerVersion,min))return `执行机器版本 ${r.runnerVersion||'未知'} 过低,需升级至 ${min} 及以上`; + if(min&&!runnerVersionAtLeast(r.runnerVersion,min)){ + if(!runnerSemanticVersion(r.runnerVersion))return `无法判断执行机器版本 ${r.runnerVersion||'未知'} 的兼容性,请确认版本(需 ${min} 及以上)`; + return `执行机器版本 ${r.runnerVersion||'未知'} 过低,需升级至 ${min} 及以上`; + } return ''; } async function setDefaultRunner(runnerId){ diff --git a/web/runner_default_rule_test.js b/web/runner_default_rule_test.js index 7290a652a..4071d55b1 100644 --- a/web/runner_default_rule_test.js +++ b/web/runner_default_rule_test.js @@ -10,15 +10,20 @@ function extract(name) { const context = {state: {minRunnerVersion: '0.8.0'}}; vm.createContext(context); -vm.runInContext(extract('runnerVersionAtLeast') + extract('runnerDefaultBlocker'), context); +vm.runInContext(extract('runnerSemanticVersion') + extract('runnerVersionAtLeast') + extract('runnerDefaultBlocker'), context); const blocker = r => context.runnerDefaultBlocker(r); +const cases = JSON.parse(fs.readFileSync(require('node:path').join(__dirname, '../internal/domain/testdata/runner-version-cases.json'), 'utf8')); +for (const {have, want, ok} of cases) { + assert.equal(context.runnerVersionAtLeast(have, want), ok, `${have} >= ${want}`); +} assert.equal(blocker({status: 'online', runnerVersion: '0.8.0'}), ''); assert.equal(blocker({status: 'online', runnerVersion: 'v0.9.2'}), ''); assert.equal(blocker({status: 'offline', runnerVersion: '0.9.2'}), '机器离线'); assert.match(blocker({status: 'online', runnerVersion: '0.1.0'}), /0\.1\.0 过低,需升级至 0\.8\.0/); -assert.match(blocker({status: 'online', runnerVersion: ''}), /未知 过低/); -assert.match(blocker({status: 'online', runnerVersion: 'dev'}), /过低/); +assert.match(blocker({status: 'online', runnerVersion: ''}), /无法判断.*未知.*兼容性/); +assert.match(blocker({status: 'online', runnerVersion: 'dev'}), /无法判断.*dev.*兼容性/); +assert.equal(blocker({status: 'online', runnerVersion: '0.8.0+internal'}), ''); // Before GET /api/runners/default answers, only the offline rule applies. context.state.minRunnerVersion = ''; assert.equal(blocker({status: 'online', runnerVersion: '0.1.0'}), ''); diff --git a/webtest/tests/mcp-sops-runners.test.mjs b/webtest/tests/mcp-sops-runners.test.mjs index 22567c541..26df0e117 100644 --- a/webtest/tests/mcp-sops-runners.test.mjs +++ b/webtest/tests/mcp-sops-runners.test.mjs @@ -126,3 +126,24 @@ test('runner cards expose runtime controls and persist limits, defaults, and aut await app.evaluate(`window.__removeRunner`); assert.ok(app.router.calls.some(c => c.method === 'DELETE' && c.path === '/api/runners/runner-local')); }); + +test('runner cards distinguish compatible metadata, prereleases, and unknown versions', async (t) => { + const app = await loadApp(); + t.after(app.close); + const runners = [ + {id:'metadata',runnerVersion:'0.8.0+internal',status:'online'}, + {id:'prerelease',runnerVersion:'0.8.0-rc.1',status:'online'}, + {id:'unknown',runnerVersion:'dev',status:'online'}, + {id:'offline',runnerVersion:'0.9.0+internal',status:'offline'}, + ].map(r=>({...r,name:r.id,ownerUserId:1,os:'linux',arch:'amd64',runtimes:[]})); + app.evaluate(`state.currentUser={id:1,loginName:'owner'};state.data.users=[state.currentUser];state.minRunnerVersion='0.8.0';state.runners=${JSON.stringify(runners)};state.defaultRunnerId='';renderRunnersView()`); + const button = id => app.document.querySelector(`[data-set-default="${id}"]`); + assert.equal(button('metadata').disabled, false); + assert.equal(button('prerelease').disabled, true); + assert.match(button('prerelease').title, /过低/); + assert.equal(button('unknown').disabled, true); + assert.match(button('unknown').title, /无法判断.*兼容性/); + assert.doesNotMatch(button('unknown').title, /过低/); + assert.equal(button('offline').disabled, true); + assert.match(button('offline').title, /离线/); +});