Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(daemon): auto-update CLI when idle (MUL-2100) (#2679)

Bohan Jiangfcd13aece94f
diff --git a/server/cmd/multica/cmd_daemon.go b/server/cmd/multica/cmd_daemon.go
index 7e59a098a0..0a6a3a5d4c 100644
--- a/server/cmd/multica/cmd_daemon.go
+++ b/server/cmd/multica/cmd_daemon.go
@@ -81,6 +81,8 @@ func init() {
f.Duration("agent-timeout", 0, "Per-task timeout (env: MULTICA_AGENT_TIMEOUT)")
f.Duration("codex-semantic-inactivity-timeout", 0, "Codex semantic inactivity timeout (env: MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT)")
f.Int("max-concurrent-tasks", 0, "Max tasks running in parallel (env: MULTICA_DAEMON_MAX_CONCURRENT_TASKS)")
+ f.Bool("no-auto-update", false, "Disable periodic CLI self-update (env: MULTICA_DAEMON_AUTO_UPDATE=false)")
+ f.Duration("auto-update-interval", 0, "How often to poll GitHub for a newer release (env: MULTICA_DAEMON_AUTO_UPDATE_INTERVAL)")
daemonLogsCmd.Flags().BoolP("follow", "f", false, "Follow log output")
daemonLogsCmd.Flags().IntP("lines", "n", 50, "Number of lines to show")
@@ -98,6 +100,8 @@ func init() {
rf.Duration("agent-timeout", 0, "Per-task timeout (env: MULTICA_AGENT_TIMEOUT)")
rf.Duration("codex-semantic-inactivity-timeout", 0, "Codex semantic inactivity timeout (env: MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT)")
rf.Int("max-concurrent-tasks", 0, "Max tasks running in parallel (env: MULTICA_DAEMON_MAX_CONCURRENT_TASKS)")
+ rf.Bool("no-auto-update", false, "Disable periodic CLI self-update (env: MULTICA_DAEMON_AUTO_UPDATE=false)")
+ rf.Duration("auto-update-interval", 0, "How often to poll GitHub for a newer release (env: MULTICA_DAEMON_AUTO_UPDATE_INTERVAL)")
df := daemonDiskUsageCmd.Flags()
df.Bool("by-workspace", false, "Aggregate output by workspace instead of by task")
@@ -289,6 +293,12 @@ func buildDaemonStartArgs(cmd *cobra.Command) []string {
if n, _ := cmd.Flags().GetInt("max-concurrent-tasks"); n > 0 {
args = append(args, "--max-concurrent-tasks", strconv.Itoa(n))
}
+ if b, _ := cmd.Flags().GetBool("no-auto-update"); b {
+ args = append(args, "--no-auto-update")
+ }
+ if d, _ := cmd.Flags().GetDuration("auto-update-interval"); d > 0 {
+ args = append(args, "--auto-update-interval", d.String())
+ }
// Forward global persistent flags.
if v, _ := cmd.Flags().GetString("server-url"); v != "" {
@@ -335,6 +345,12 @@ func runDaemonForeground(cmd *cobra.Command) error {
if n, _ := cmd.Flags().GetInt("max-concurrent-tasks"); n > 0 {
overrides.MaxConcurrentTasks = n
}
+ if b, _ := cmd.Flags().GetBool("no-auto-update"); b {
+ overrides.DisableAutoUpdate = true
+ }
+ if d, _ := cmd.Flags().GetDuration("auto-update-interval"); d > 0 {
+ overrides.AutoUpdateCheckInterval = d
+ }
cfg, err := daemon.LoadConfig(overrides)
if err != nil {
diff --git a/server/internal/cli/update.go b/server/internal/cli/update.go
index 378bf5f52d..cb02999272 100644
--- a/server/internal/cli/update.go
+++ b/server/internal/cli/update.go
@@ -3,8 +3,11 @@ package cli
import (
"archive/tar"
"archive/zip"
+ "bufio"
"bytes"
"compress/gzip"
+ "crypto/sha256"
+ "encoding/hex"
"encoding/json"
"fmt"
"io"
@@ -13,10 +16,17 @@ import (
"os/exec"
"path/filepath"
"runtime"
+ "strconv"
"strings"
"time"
)
+// ChecksumManifestName is the asset name GoReleaser publishes for the
+// checksum manifest (`checksum.name_template: "checksums.txt"` in
+// .goreleaser.yml). Kept as a constant rather than inlined so a future rename
+// changes one place.
+const ChecksumManifestName = "checksums.txt"
+
const DefaultUpdateDownloadTimeout = 120 * time.Second
// GitHubRelease is the subset of the GitHub releases API response we need.
@@ -26,6 +36,89 @@ type GitHubRelease struct {
Assets []GitHubReleaseAsset `json:"assets"`
}
+// IsReleaseVersion reports whether v looks like a tagged release version
+// (e.g. "0.1.13", "v0.1.13") rather than a dev build (e.g. an empty version
+// or a `git describe`–style "v0.2.15-235-gdaf0e935"). The auto-update poller
+// uses this to skip self-update for source builds, where downgrading to a
+// public release would clobber unreleased changes.
+func IsReleaseVersion(v string) bool {
+ s := strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(v), "v"))
+ if s == "" {
+ return false
+ }
+ parts := strings.Split(s, ".")
+ if len(parts) != 3 {
+ return false
+ }
+ for _, p := range parts {
+ if p == "" {
+ return false
+ }
+ for _, r := range p {
+ if r < '0' || r > '9' {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+// IsNewerVersion reports whether latest is strictly newer than current. Both
+// arguments may carry an optional "v" prefix; non-numeric tails are ignored
+// (a 4th component, pre-release tag, etc.). Returns false if either side
+// cannot be parsed — the caller treats that as "stay on current".
+func IsNewerVersion(latest, current string) bool {
+ l, ok := parseReleaseVersion(latest)
+ if !ok {
+ return false
+ }
+ c, ok := parseReleaseVersion(current)
+ if !ok {
+ return false
+ }
+ for i := 0; i < 3; i++ {
+ if l[i] != c[i] {
+ return l[i] > c[i]
+ }
+ }
+ return false
+}
+
+// parseReleaseVersion extracts the three numeric components of v. Returns
+// (parts, true) on success; (_, false) when v is missing, malformed, or
+// carries any non-numeric tail (a dev-describe suffix, a 4th component, a
+// pre-release tag, etc.). The strict shape is intentional: this is the only
+// parser used by IsNewerVersion, and the autoUpdateLoop must never silently
+// downgrade a developer build to a public release just because the
+// dev-describe patch happened to look numeric after trimming.
+func parseReleaseVersion(v string) ([3]int, bool) {
+ s := strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(v), "v"))
+ if s == "" {
+ return [3]int{}, false
+ }
+ parts := strings.Split(s, ".")
+ if len(parts) != 3 {
+ return [3]int{}, false
+ }
+ var out [3]int
+ for i, p := range parts {
+ if p == "" {
+ return [3]int{}, false
+ }
+ for _, r := range p {
+ if r < '0' || r > '9' {
+ return [3]int{}, false
+ }
+ }
+ n, err := strconv.Atoi(p)
+ if err != nil {
+ return [3]int{}, false
+ }
+ out[i] = n
+ }
+ return out, true
+}
+
type GitHubReleaseAsset struct {
Name string `json:"name"`
BrowserDownloadURL string `json:"browser_download_url"`
@@ -71,6 +164,63 @@ func findReleaseAsset(assets []GitHubReleaseAsset, targetVersion, goos, goarch s
return nil, fmt.Errorf("no matching release asset for %s/%s (tried: %s)", goos, goarch, candidates)
}
+// findChecksumManifestAsset locates the GoReleaser-generated checksums.txt
+// among a release's assets. Required for the direct-download path's SHA-256
+// verification — if it is missing we refuse to replace the binary rather
+// than fall back to unverified install, because the auto-update poller runs
+// unattended and an unverified binary swap is a supply-chain risk.
+func findChecksumManifestAsset(assets []GitHubReleaseAsset) (*GitHubReleaseAsset, error) {
+ for i := range assets {
+ if assets[i].Name == ChecksumManifestName {
+ return &assets[i], nil
+ }
+ }
+ return nil, fmt.Errorf("checksum manifest %q not present in release", ChecksumManifestName)
+}
+
+// parseChecksumManifest reads a GoReleaser-style "<sha256> <filename>"
+// manifest and returns the lowercase hex SHA-256 for assetName. Returns an
+// error if the asset is absent so a typo (or the wrong manifest from a
+// different release) fails closed rather than silently disabling
+// verification.
+func parseChecksumManifest(manifest []byte, assetName string) (string, error) {
+ scanner := bufio.NewScanner(bytes.NewReader(manifest))
+ for scanner.Scan() {
+ line := strings.TrimSpace(scanner.Text())
+ if line == "" || strings.HasPrefix(line, "#") {
+ continue
+ }
+ fields := strings.Fields(line)
+ // GoReleaser's default separator is two spaces; some tools use one
+ // or pad with tabs. strings.Fields handles all of those at once.
+ if len(fields) < 2 {
+ continue
+ }
+ if fields[1] == assetName {
+ return strings.ToLower(fields[0]), nil
+ }
+ }
+ if err := scanner.Err(); err != nil {
+ return "", fmt.Errorf("read checksum manifest: %w", err)
+ }
+ return "", fmt.Errorf("checksum for %q not found in manifest", assetName)
+}
+
+// verifyAssetSHA256 returns nil when the SHA-256 of data matches the lowercase
+// hex expected value, or an error otherwise. The error includes both digests
+// so a corrupted asset is diagnosable from the log without re-downloading.
+func verifyAssetSHA256(data []byte, expectedHex, assetName string) error {
+ if expectedHex == "" {
+ return fmt.Errorf("empty expected checksum for %q", assetName)
+ }
+ sum := sha256.Sum256(data)
+ actual := hex.EncodeToString(sum[:])
+ if !strings.EqualFold(actual, expectedHex) {
+ return fmt.Errorf("checksum mismatch for %q: expected %s, got %s", assetName, expectedHex, actual)
+ }
+ return nil
+}
+
func fetchReleaseByTag(tag string) (*GitHubRelease, error) {
client := &http.Client{Timeout: 10 * time.Second}
req, err := http.NewRequest(http.MethodGet, "https://api.github.com/repos/multica-ai/multica/releases/tags/"+tag, nil)
@@ -185,6 +335,23 @@ func updateDownloadTimeoutOrDefault(timeout time.Duration) time.Duration {
return timeout
}
+// fetchURLBytes does a GET with the given timeout and returns the response
+// body in full. Used for the checksum manifest (tiny) and the release
+// archive (single-digit MB). The checksum verification path requires buffered
+// bytes so streaming would just push the buffer into the caller anyway.
+func fetchURLBytes(url string, timeout time.Duration) ([]byte, error) {
+ client := &http.Client{Timeout: updateDownloadTimeoutOrDefault(timeout)}
+ resp, err := client.Get(url)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("HTTP %d from %s", resp.StatusCode, url)
+ }
+ return io.ReadAll(resp.Body)
+}
+
// UpdateViaDownload downloads the latest release binary from GitHub and replaces
// the current executable in-place. Returns the combined output message and any error.
func UpdateViaDownload(targetVersion string) (string, error) {
@@ -212,19 +379,43 @@ func UpdateViaDownloadWithTimeout(targetVersion string, downloadTimeout time.Dur
if err != nil {
return "", err
}
+ manifestAsset, err := findChecksumManifestAsset(release.Assets)
+ if err != nil {
+ return "", err
+ }
downloadURL := asset.BrowserDownloadURL
assetName := asset.Name
- // Download the archive.
- client := &http.Client{Timeout: updateDownloadTimeoutOrDefault(downloadTimeout)}
- resp, err := client.Get(downloadURL)
+ // Pull the checksum manifest first so a release that is half-published
+ // (archives uploaded but checksums.txt not yet) fails before we eat the
+ // archive's bandwidth.
+ timeout := updateDownloadTimeoutOrDefault(downloadTimeout)
+ manifestData, err := fetchURLBytes(manifestAsset.BrowserDownloadURL, timeout)
+ if err != nil {
+ return "", fmt.Errorf("download checksum manifest: %w", err)
+ }
+ expectedSum, err := parseChecksumManifest(manifestData, assetName)
+ if err != nil {
+ return "", fmt.Errorf("parse checksum manifest: %w", err)
+ }
+
+ // Buffer the archive into memory so we can verify the full SHA-256
+ // before writing anything to disk. Release archives are ~10–30 MB; the
+ // extraction code already buffers zip archives in full (random access
+ // requirement), so this is not a new memory cost on Windows. For tar.gz
+ // it adds a single in-RAM copy, which is preferable to running the
+ // untrusted bytes through gzip+tar extraction before the SHA-256 check.
+ archiveData, err := fetchURLBytes(downloadURL, timeout)
if err != nil {
return "", fmt.Errorf("download failed: %w", err)
}
- defer resp.Body.Close()
- if resp.StatusCode != http.StatusOK {
- return "", fmt.Errorf("download failed: HTTP %d from %s", resp.StatusCode, downloadURL)
+ if err := verifyAssetSHA256(archiveData, expectedSum, assetName); err != nil {
+ // Do NOT extract or replace; the next poll tick will retry. A
+ // corrupted asset is rare enough that retrying through the same
+ // CDN is the right default; persistent failures will surface in
+ // the daemon log.
+ return "", fmt.Errorf("verify download: %w", err)
}
// Extract the binary from the archive.
@@ -234,9 +425,9 @@ func UpdateViaDownloadWithTimeout(targetVersion string, downloadTimeout time.Dur
}
var binaryData []byte
if runtime.GOOS == "windows" {
- binaryData, err = extractBinaryFromZip(resp.Body, binaryName)
+ binaryData, err = extractBinaryFromZip(bytes.NewReader(archiveData), binaryName)
} else {
- binaryData, err = extractBinaryFromTarGz(resp.Body, binaryName)
+ binaryData, err = extractBinaryFromTarGz(bytes.NewReader(archiveData), binaryName)
}
if err != nil {
return "", fmt.Errorf("extract binary: %w", err)
diff --git a/server/internal/cli/update_test.go b/server/internal/cli/update_test.go
index f2f8e05881..176cf9a8dc 100644
--- a/server/internal/cli/update_test.go
+++ b/server/internal/cli/update_test.go
@@ -1,6 +1,9 @@
package cli
import (
+ "crypto/sha256"
+ "encoding/hex"
+ "strings"
"testing"
"time"
)
@@ -98,6 +101,175 @@ func TestFindReleaseAsset(t *testing.T) {
})
}
+func TestIsReleaseVersion(t *testing.T) {
+ tests := []struct {
+ name string
+ in string
+ want bool
+ }{
+ {"bare release", "0.1.13", true},
+ {"v-prefixed release", "v0.1.13", true},
+ {"surrounding whitespace", " v0.1.13 ", true},
+ {"dev describe", "v0.2.15-235-gdaf0e935", false},
+ {"dirty dev describe", "v0.2.15-235-gdaf0e935-dirty", false},
+ {"empty", "", false},
+ {"two components", "0.1", false},
+ {"four components", "0.1.2.3", false},
+ {"non-numeric", "1.0.x", false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := IsReleaseVersion(tt.in); got != tt.want {
+ t.Fatalf("IsReleaseVersion(%q) = %v, want %v", tt.in, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestIsNewerVersion(t *testing.T) {
+ tests := []struct {
+ name string
+ latest, current string
+ want bool
+ }{
+ {"patch bump", "v0.1.14", "v0.1.13", true},
+ {"minor bump", "v0.2.0", "v0.1.99", true},
+ {"major bump", "v1.0.0", "v0.99.99", true},
+ {"same version", "v0.1.13", "v0.1.13", false},
+ {"older latest", "v0.1.12", "v0.1.13", false},
+ {"mixed v prefix", "0.1.14", "v0.1.13", true},
+ {"current is dev describe → unparseable → false", "v0.1.14", "v0.1.13-5-gabcdef0", false},
+ {"latest is dev describe → unparseable → false", "v0.1.14-1-gabcdef0", "v0.1.13", false},
+ {"latest unparseable → false", "garbage", "v0.1.13", false},
+ {"current unparseable → false", "v0.1.14", "garbage", false},
+ {"empty latest", "", "v0.1.13", false},
+ {"empty current", "v0.1.14", "", false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := IsNewerVersion(tt.latest, tt.current); got != tt.want {
+ t.Fatalf("IsNewerVersion(%q, %q) = %v, want %v", tt.latest, tt.current, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestFindChecksumManifestAsset(t *testing.T) {
+ t.Run("finds checksums.txt among assets", func(t *testing.T) {
+ assets := []GitHubReleaseAsset{
+ {Name: "multica-cli-1.2.3-darwin-arm64.tar.gz"},
+ {Name: "checksums.txt", BrowserDownloadURL: "https://example/checksums.txt"},
+ {Name: "multica-cli-1.2.3-linux-amd64.tar.gz"},
+ }
+ got, err := findChecksumManifestAsset(assets)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got.Name != "checksums.txt" || got.BrowserDownloadURL != "https://example/checksums.txt" {
+ t.Fatalf("got %+v", got)
+ }
+ })
+
+ t.Run("returns error when manifest missing", func(t *testing.T) {
+ _, err := findChecksumManifestAsset([]GitHubReleaseAsset{
+ {Name: "multica-cli-1.2.3-darwin-arm64.tar.gz"},
+ })
+ if err == nil {
+ t.Fatal("expected error when checksums.txt is absent")
+ }
+ })
+}
+
+func TestParseChecksumManifest(t *testing.T) {
+ manifest := []byte(strings.Join([]string{
+ "# generated by GoReleaser",
+ "",
+ "aaaa1111 multica-cli-1.2.3-darwin-arm64.tar.gz",
+ "bbbb2222 multica-cli-1.2.3-darwin-amd64.tar.gz",
+ "cccc3333\tmulti-tab-separator.tar.gz",
+ "DDDD4444 multica_linux_amd64.tar.gz",
+ }, "\n"))
+
+ t.Run("returns lowercase sha for matched entry", func(t *testing.T) {
+ got, err := parseChecksumManifest(manifest, "multica-cli-1.2.3-darwin-arm64.tar.gz")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != "aaaa1111" {
+ t.Fatalf("sha = %q, want aaaa1111", got)
+ }
+ })
+
+ t.Run("matches a tab-separated entry", func(t *testing.T) {
+ got, err := parseChecksumManifest(manifest, "multi-tab-separator.tar.gz")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != "cccc3333" {
+ t.Fatalf("sha = %q, want cccc3333", got)
+ }
+ })
+
+ t.Run("downcases an uppercase entry", func(t *testing.T) {
+ got, err := parseChecksumManifest(manifest, "multica_linux_amd64.tar.gz")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != "dddd4444" {
+ t.Fatalf("sha = %q, want dddd4444", got)
+ }
+ })
+
+ t.Run("returns error when asset is absent", func(t *testing.T) {
+ _, err := parseChecksumManifest(manifest, "not-in-manifest.tar.gz")
+ if err == nil {
+ t.Fatal("expected error for missing asset")
+ }
+ })
+
+ t.Run("skips blank lines and comments", func(t *testing.T) {
+ // If parsing broke on blank/comment lines we'd never reach the
+ // matching entry below them.
+ if _, err := parseChecksumManifest(manifest, "multica-cli-1.2.3-darwin-arm64.tar.gz"); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ })
+}
+
+func TestVerifyAssetSHA256(t *testing.T) {
+ data := []byte("hello multica")
+ sum := sha256.Sum256(data)
+ good := hex.EncodeToString(sum[:])
+
+ t.Run("accepts matching sha", func(t *testing.T) {
+ if err := verifyAssetSHA256(data, good, "asset.tar.gz"); err != nil {
+ t.Fatalf("expected ok, got %v", err)
+ }
+ })
+
+ t.Run("accepts uppercase expected hex", func(t *testing.T) {
+ if err := verifyAssetSHA256(data, strings.ToUpper(good), "asset.tar.gz"); err != nil {
+ t.Fatalf("expected ok with uppercase expected, got %v", err)
+ }
+ })
+
+ t.Run("rejects mismatched sha", func(t *testing.T) {
+ err := verifyAssetSHA256([]byte("tampered"), good, "asset.tar.gz")
+ if err == nil {
+ t.Fatal("expected mismatch error")
+ }
+ if !strings.Contains(err.Error(), "asset.tar.gz") {
+ t.Fatalf("error should name the asset: %v", err)
+ }
+ })
+
+ t.Run("rejects empty expected", func(t *testing.T) {
+ if err := verifyAssetSHA256(data, "", "asset.tar.gz"); err == nil {
+ t.Fatal("expected error for empty expected sha")
+ }
+ })
+}
+
func TestUpdateDownloadTimeoutOrDefault(t *testing.T) {
tests := []struct {
name string
diff --git a/server/internal/daemon/auto_update.go b/server/internal/daemon/auto_update.go
new file mode 100644
index 0000000000..532a725948
--- /dev/null
+++ b/server/internal/daemon/auto_update.go
@@ -0,0 +1,174 @@
+package daemon
+
+import (
+ "context"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/cli"
+)
+
+// Indirections over the real release / version helpers so tests can run the
+// auto-update loop deterministically without reaching out to GitHub or
+// shelling out to brew/curl. Mirrors the pattern used at the top of daemon.go
+// for `isBrewInstall` / `getBrewPrefix` / `matchKnownBrewPrefix`.
+var (
+ fetchLatestRelease = cli.FetchLatestRelease
+ isReleaseVersion = cli.IsReleaseVersion
+ isNewerVersion = cli.IsNewerVersion
+)
+
+// autoUpdateInitialDelay is how long the loop waits after Run() returns before
+// performing its first version check. The daemon has plenty to do at startup
+// (auth, register, sync workspaces, kick off heartbeats); we don't want to add
+// an outbound HTTPS call to GitHub on top of that. The delay is also short
+// enough that a brand-new install with an available update still self-updates
+// within a couple of minutes rather than after the full check interval.
+var autoUpdateInitialDelay = 2 * time.Minute
+
+// autoUpdateLoop periodically polls GitHub for a newer CLI release and, when
+// one is available and the daemon is idle, runs the same brew-or-download
+// upgrade path as the server-triggered update. On success it triggers a
+// graceful restart into the new binary.
+//
+// Disabled when:
+// - the operator opted out via --no-auto-update / MULTICA_DAEMON_AUTO_UPDATE=false;
+// - the daemon was spawned by Desktop (the Electron app owns the binary);
+// - the running version doesn't look like a tagged release (dev builds).
+//
+// Each tick is silent on the happy path of "already on latest" so the log
+// stays uncluttered for users who run the daemon for weeks at a time.
+func (d *Daemon) autoUpdateLoop(ctx context.Context) {
+ if !d.cfg.AutoUpdateEnabled {
+ d.logger.Info("auto-update: disabled")
+ return
+ }
+ if d.cfg.LaunchedBy == "desktop" {
+ // Desktop ships and replaces the CLI binary itself; self-update would
+ // be clobbered on the next launch. Stay quiet but don't run.
+ d.logger.Info("auto-update: skipped (managed by Desktop)")
+ return
+ }
+ if !isReleaseVersion(d.cfg.CLIVersion) {
+ // Source builds (`make daemon`) and ad-hoc builds report a
+ // `git describe`-style version; auto-upgrading them to a public
+ // release would silently downgrade the dev work checked out on the
+ // machine. Skip and let the developer drive their own version.
+ d.logger.Info("auto-update: skipped (not a release build)", "version", d.cfg.CLIVersion)
+ return
+ }
+
+ interval := d.cfg.AutoUpdateCheckInterval
+ if interval <= 0 {
+ interval = DefaultAutoUpdateCheckInterval
+ }
+ d.logger.Info("auto-update: started", "interval", interval, "current", d.cfg.CLIVersion)
+
+ if err := sleepWithContext(ctx, autoUpdateInitialDelay); err != nil {
+ return
+ }
+ d.tryAutoUpdate(ctx)
+
+ ticker := time.NewTicker(interval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ d.tryAutoUpdate(ctx)
+ }
+ }
+}
+
+// tryAutoUpdate runs one check-and-maybe-upgrade cycle. Bails early on any of:
+// already updating (server-triggered upgrade in flight), active tasks (defer
+// to next tick — we never interrupt running agents), version fetch failure,
+// or no newer release. The function never returns an error: a check that
+// fails today will be retried at the next tick, and we don't want a transient
+// network blip to escalate to a process-level shutdown.
+func (d *Daemon) tryAutoUpdate(ctx context.Context) {
+ if ctx.Err() != nil {
+ return
+ }
+ // Don't race the server-triggered update path. If a manual update from
+ // the Runtimes page is already in flight, let it finish and re-check next
+ // tick (by which time we'll either be on the new binary or it failed and
+ // we can retry).
+ if d.updating.Load() {
+ d.logger.Debug("auto-update: skip — update already in progress")
+ return
+ }
+ // Cheap pre-fetch idle check: the release-metadata fetch below makes an
+ // HTTPS call to GitHub, and there is no point paying that cost (or the
+ // rate-limit budget) when we already know we are going to defer. A task
+ // that starts between this load and the barrier check below is caught
+ // by the strict re-check under claimMu inside trySetClaimBarrier.
+ if running := d.activeTasks.Load(); running > 0 {
+ d.logger.Debug("auto-update: skip — tasks running", "active", running)
+ return
+ }
+
+ release, err := fetchLatestRelease()
+ if err != nil {
+ d.logger.Warn("auto-update: fetch latest release failed — will retry", "error", err)
+ return
+ }
+ if release == nil || release.TagName == "" {
+ return
+ }
+ if !isNewerVersion(release.TagName, d.cfg.CLIVersion) {
+ return
+ }
+
+ // CAS the updating flag so a concurrent server-triggered handleUpdate
+ // dropped onto a heartbeat tick can't double-fire. Release on every exit
+ // path before triggerRestart — once that lands, the daemon ctx is
+ // cancelled and the flag dies with the process.
+ if !d.updating.CompareAndSwap(false, true) {
+ d.logger.Debug("auto-update: skip — update already in progress (raced)")
+ return
+ }
+ released := false
+ defer func() {
+ if !released {
+ d.updating.Store(false)
+ }
+ }()
+
+ // Strict barrier: between the cheap pre-fetch idle check and now the
+ // release fetch took anywhere from tens of milliseconds (typical) to
+ // seconds (slow link, GitHub hiccup), plenty of time for a poller to
+ // claim a fresh task. trySetClaimBarrier checks claimsInFlight +
+ // activeTasks under claimMu and only flips pauseClaims to true if both
+ // are zero, so once it returns true we can run the upgrade knowing that
+ // no in-flight task will be cancelled by triggerRestart.
+ if !d.trySetClaimBarrier() {
+ d.logger.Info("auto-update: deferring — task or claim in flight at barrier check")
+ return
+ }
+ barrierReleased := false
+ defer func() {
+ if !barrierReleased {
+ d.releaseClaimBarrier()
+ }
+ }()
+
+ d.logger.Info("auto-update: newer release available, upgrading",
+ "current", d.cfg.CLIVersion, "target", release.TagName)
+
+ output, err := d.runUpdateFn(release.TagName)
+ if err != nil {
+ d.logger.Warn("auto-update: upgrade failed — will retry", "error", err, "output", output)
+ return
+ }
+
+ d.logger.Info("auto-update: upgrade completed, restarting", "target", release.TagName, "output", output)
+ // triggerRestart cancels the root context, which causes Run() to return
+ // and the parent (cmd_daemon.go) to re-exec the new binary. Leave both
+ // the updating flag and the claim barrier held — process exit is
+ // imminent and clearing either would open a window for new claims / a
+ // second auto-update tick to fire mid-shutdown.
+ released = true
+ barrierReleased = true
+ d.triggerRestart()
+}
diff --git a/server/internal/daemon/auto_update_test.go b/server/internal/daemon/auto_update_test.go
new file mode 100644
index 0000000000..ad7f54f63a
--- /dev/null
+++ b/server/internal/daemon/auto_update_test.go
@@ -0,0 +1,258 @@
+package daemon
+
+import (
+ "context"
+ "errors"
+ "log/slog"
+ "sync/atomic"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/cli"
+)
+
+// newAutoUpdateTestDaemon returns a Daemon stripped to just the pieces
+// tryAutoUpdate touches, plus a sentinel cancelFunc the test can assert on to
+// detect that triggerRestart fired. The caller is expected to install its own
+// runUpdateFn before calling tryAutoUpdate when it wants to exercise the
+// upgrade-success path.
+func newAutoUpdateTestDaemon(t *testing.T, currentVersion string) (*Daemon, *atomic.Int32) {
+ t.Helper()
+ var restartCalls atomic.Int32
+ d := &Daemon{
+ cfg: Config{CLIVersion: currentVersion, AutoUpdateEnabled: true},
+ logger: slog.Default(),
+ cancelFunc: func() {
+ restartCalls.Add(1)
+ },
+ }
+ d.runUpdateFn = func(string) (string, error) {
+ t.Fatalf("runUpdateFn called unexpectedly")
+ return "", nil
+ }
+ return d, &restartCalls
+}
+
+func withStubRelease(t *testing.T, release *cli.GitHubRelease, err error) {
+ t.Helper()
+ prev := fetchLatestRelease
+ fetchLatestRelease = func() (*cli.GitHubRelease, error) { return release, err }
+ t.Cleanup(func() { fetchLatestRelease = prev })
+}
+
+func TestTryAutoUpdate_SkipsWhenUpdating(t *testing.T) {
+ d, restartCalls := newAutoUpdateTestDaemon(t, "v0.1.13")
+ d.updating.Store(true)
+ withStubRelease(t, &cli.GitHubRelease{TagName: "v0.1.14"}, nil)
+
+ d.tryAutoUpdate(context.Background())
+
+ if restartCalls.Load() != 0 {
+ t.Fatalf("triggerRestart called while another update was in progress")
+ }
+}
+
+func TestTryAutoUpdate_SkipsWhenTasksRunning(t *testing.T) {
+ d, restartCalls := newAutoUpdateTestDaemon(t, "v0.1.13")
+ d.activeTasks.Store(1)
+ withStubRelease(t, &cli.GitHubRelease{TagName: "v0.1.14"}, nil)
+
+ d.tryAutoUpdate(context.Background())
+
+ if restartCalls.Load() != 0 {
+ t.Fatalf("triggerRestart fired with active tasks; auto-update must defer")
+ }
+ if d.updating.Load() {
+ t.Fatalf("updating flag should not have been claimed while tasks were running")
+ }
+}
+
+// TestTryAutoUpdate_DefersWhenClaimInFlightAtBarrier covers the race the
+// review flagged: cheap pre-fetch idle check passes (activeTasks == 0), then
+// during the release fetch a poller decides to claim and bumps
+// claimsInFlight. trySetClaimBarrier must observe that and defer rather than
+// proceed into runUpdate (which would lead to a triggerRestart cancelling
+// the just-claimed task mid-run).
+func TestTryAutoUpdate_DefersWhenClaimInFlightAtBarrier(t *testing.T) {
+ d, restartCalls := newAutoUpdateTestDaemon(t, "v0.1.13")
+ withStubRelease(t, &cli.GitHubRelease{TagName: "v0.1.14"}, nil)
+
+ d.claimsInFlight = 1 // poller is mid-ClaimTask while activeTasks is still 0
+
+ d.tryAutoUpdate(context.Background())
+
+ if restartCalls.Load() != 0 {
+ t.Fatalf("triggerRestart fired despite a claim being in flight at the barrier")
+ }
+ if d.updating.Load() {
+ t.Fatalf("updating flag must be released after a deferred upgrade so the next tick can retry")
+ }
+ if d.pauseClaims {
+ t.Fatalf("pauseClaims must be cleared after a deferred upgrade")
+ }
+}
+
+// TestTryAutoUpdate_HoldsBarrierAcrossRestart asserts the success path leaves
+// pauseClaims set: process exit is imminent and clearing the barrier would
+// open a window for a poller to claim a task that the imminent restart is
+// about to cancel.
+func TestTryAutoUpdate_HoldsBarrierAcrossRestart(t *testing.T) {
+ d, restartCalls := newAutoUpdateTestDaemon(t, "v0.1.13")
+ withStubRelease(t, &cli.GitHubRelease{TagName: "v0.1.14"}, nil)
+ d.runUpdateFn = func(string) (string, error) { return "upgraded", nil }
+
+ d.tryAutoUpdate(context.Background())
+
+ if restartCalls.Load() != 1 {
+ t.Fatalf("triggerRestart fired %d times, want 1", restartCalls.Load())
+ }
+ if !d.pauseClaims {
+ t.Fatalf("pauseClaims must remain set across the restart kick; got cleared")
+ }
+}
+
+// TestTryAutoUpdate_ReleasesBarrierOnUpgradeFailure asserts the failure path
+// clears pauseClaims so the daemon can keep claiming tasks normally and
+// retry the upgrade on the next tick.
+func TestTryAutoUpdate_ReleasesBarrierOnUpgradeFailure(t *testing.T) {
+ d, restartCalls := newAutoUpdateTestDaemon(t, "v0.1.13")
+ withStubRelease(t, &cli.GitHubRelease{TagName: "v0.1.14"}, nil)
+ d.runUpdateFn = func(string) (string, error) {
+ return "brew network error", errors.New("brew upgrade failed")
+ }
+
+ d.tryAutoUpdate(context.Background())
+
+ if restartCalls.Load() != 0 {
+ t.Fatalf("triggerRestart fired despite upgrade failure")
+ }
+ if d.pauseClaims {
+ t.Fatalf("pauseClaims must be cleared after a failed upgrade so pollers resume claiming")
+ }
+}
+
+// TestTryEnterClaim_RespectsBarrier asserts the poller-side helper returns
+// false while pauseClaims is held and that pairs of enter/exit balance the
+// counter so a later barrier set sees idle.
+func TestTryEnterClaim_RespectsBarrier(t *testing.T) {
+ d := &Daemon{}
+
+ if !d.tryEnterClaim() {
+ t.Fatal("tryEnterClaim should succeed when barrier is unset")
+ }
+ d.exitClaim()
+ if d.claimsInFlight != 0 {
+ t.Fatalf("claimsInFlight not balanced: %d", d.claimsInFlight)
+ }
+
+ if !d.trySetClaimBarrier() {
+ t.Fatal("trySetClaimBarrier should succeed when idle")
+ }
+ if d.tryEnterClaim() {
+ t.Fatal("tryEnterClaim must refuse while barrier is held")
+ }
+ d.releaseClaimBarrier()
+ if !d.tryEnterClaim() {
+ t.Fatal("tryEnterClaim should succeed after barrier release")
+ }
+ d.exitClaim()
+}
+
+func TestTryAutoUpdate_SkipsWhenFetchFails(t *testing.T) {
+ d, restartCalls := newAutoUpdateTestDaemon(t, "v0.1.13")
+ withStubRelease(t, nil, errors.New("network down"))
+
+ d.tryAutoUpdate(context.Background())
+
+ if restartCalls.Load() != 0 {
+ t.Fatalf("triggerRestart fired despite fetch failure")
+ }
+}
+
+func TestTryAutoUpdate_SkipsWhenNotNewer(t *testing.T) {
+ d, restartCalls := newAutoUpdateTestDaemon(t, "v0.1.13")
+ withStubRelease(t, &cli.GitHubRelease{TagName: "v0.1.13"}, nil)
+
+ d.tryAutoUpdate(context.Background())
+
+ if restartCalls.Load() != 0 {
+ t.Fatalf("triggerRestart fired even though latest == current")
+ }
+}
+
+func TestTryAutoUpdate_RunsUpgradeAndRestartsOnNewer(t *testing.T) {
+ d, restartCalls := newAutoUpdateTestDaemon(t, "v0.1.13")
+ withStubRelease(t, &cli.GitHubRelease{TagName: "v0.1.14"}, nil)
+
+ var upgradedTo string
+ d.runUpdateFn = func(target string) (string, error) {
+ upgradedTo = target
+ return "upgraded", nil
+ }
+
+ d.tryAutoUpdate(context.Background())
+
+ if upgradedTo != "v0.1.14" {
+ t.Fatalf("runUpdateFn called with %q, want v0.1.14", upgradedTo)
+ }
+ if restartCalls.Load() != 1 {
+ t.Fatalf("triggerRestart fired %d times, want 1", restartCalls.Load())
+ }
+ if !d.updating.Load() {
+ t.Fatalf("updating flag should remain set across the restart kick; got cleared")
+ }
+}
+
+func TestTryAutoUpdate_DoesNotRestartOnUpgradeFailure(t *testing.T) {
+ d, restartCalls := newAutoUpdateTestDaemon(t, "v0.1.13")
+ withStubRelease(t, &cli.GitHubRelease{TagName: "v0.1.14"}, nil)
+
+ d.runUpdateFn = func(string) (string, error) {
+ return "brew: network error", errors.New("brew upgrade failed")
+ }
+
+ d.tryAutoUpdate(context.Background())
+
+ if restartCalls.Load() != 0 {
+ t.Fatalf("triggerRestart fired despite upgrade failure")
+ }
+ if d.updating.Load() {
+ t.Fatalf("updating flag must be released after a failed upgrade so the next tick can retry")
+ }
+}
+
+func TestAutoUpdateLoop_EarlyExits(t *testing.T) {
+ tests := []struct {
+ name string
+ cfg Config
+ }{
+ {
+ name: "disabled by config",
+ cfg: Config{AutoUpdateEnabled: false, CLIVersion: "v0.1.13"},
+ },
+ {
+ name: "managed by desktop",
+ cfg: Config{AutoUpdateEnabled: true, CLIVersion: "v0.1.13", LaunchedBy: "desktop"},
+ },
+ {
+ name: "dev build",
+ cfg: Config{AutoUpdateEnabled: true, CLIVersion: "v0.1.13-235-gabcdef0"},
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ d := &Daemon{cfg: tt.cfg, logger: slog.Default()}
+ d.runUpdateFn = func(string) (string, error) {
+ t.Fatalf("runUpdateFn called from an early-exit code path")
+ return "", nil
+ }
+ withStubRelease(t, &cli.GitHubRelease{TagName: "v0.1.14"}, nil)
+
+ done := make(chan struct{})
+ go func() {
+ d.autoUpdateLoop(context.Background())
+ close(done)
+ }()
+ <-done
+ })
+ }
+}
diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.go
index 76813a9fb0..ba2479c2fe 100644
--- a/server/internal/daemon/config.go
+++ b/server/internal/daemon/config.go
@@ -28,6 +28,7 @@ const (
DefaultGCTTL = 24 * time.Hour // 1 day — AI-coding issues rarely stay open long
DefaultGCOrphanTTL = 72 * time.Hour // 3 days — orphans with no meta (crashes, pre-GC leftovers)
DefaultGCArtifactTTL = 12 * time.Hour // 12h — drop regenerable artifacts on completed but still-open issues
+ DefaultAutoUpdateCheckInterval = 6 * time.Hour // how often the daemon polls GitHub for a newer CLI release
)
// DefaultGCArtifactPatterns lists basename matches that the GC loop treats as
@@ -59,6 +60,8 @@ type Config struct {
GCOrphanTTL time.Duration // clean orphan dirs with no meta, or dirs whose issue gc-check returns 404, once they exceed this age (default: 72h). The 404 path uses the same TTL — a scoped-down token can't instantly wipe live workspaces.
GCArtifactTTL time.Duration // when a task has been completed for at least this long but its issue is still open, drop regenerable artifacts (default: 12h, set 0 to disable)
GCArtifactPatterns []string // basename patterns whose subtrees are removed during artifact cleanup (default: node_modules, .next, .turbo)
+ AutoUpdateEnabled bool // periodically check for a newer CLI release and self-update when idle (default: true)
+ AutoUpdateCheckInterval time.Duration // how often the auto-update loop polls for a new release (default: 6h)
PollInterval time.Duration
HeartbeatInterval time.Duration
AgentTimeout time.Duration
@@ -82,6 +85,11 @@ type Overrides struct {
RuntimeName string
Profile string // profile name (empty = default)
HealthPort int // health check port (0 = use default)
+ // DisableAutoUpdate, when true, forces the auto-update poller off. There
+ // is no symmetric "force on" override because the env/default already
+ // resolves to enabled; the flag exists so users can opt out from the CLI.
+ DisableAutoUpdate bool
+ AutoUpdateCheckInterval time.Duration // 0 = use env/default
}
// LoadConfig builds the daemon configuration from environment variables
@@ -326,6 +334,22 @@ func LoadConfig(overrides Overrides) (Config, error) {
}
gcArtifactPatterns := patternsFromEnv("MULTICA_GC_ARTIFACT_PATTERNS", DefaultGCArtifactPatterns)
+ // Auto-update config: env > defaults > CLI override.
+ autoUpdateEnabled := true
+ if v := strings.TrimSpace(os.Getenv("MULTICA_DAEMON_AUTO_UPDATE")); v == "false" || v == "0" {
+ autoUpdateEnabled = false
+ }
+ if overrides.DisableAutoUpdate {
+ autoUpdateEnabled = false
+ }
+ autoUpdateInterval, err := durationFromEnv("MULTICA_DAEMON_AUTO_UPDATE_INTERVAL", DefaultAutoUpdateCheckInterval)
+ if err != nil {
+ return Config{}, err
+ }
+ if overrides.AutoUpdateCheckInterval > 0 {
+ autoUpdateInterval = overrides.AutoUpdateCheckInterval
+ }
+
return Config{
ServerBaseURL: serverBaseURL,
DaemonID: daemonID,
@@ -342,6 +366,8 @@ func LoadConfig(overrides Overrides) (Config, error) {
GCOrphanTTL: gcOrphanTTL,
GCArtifactTTL: gcArtifactTTL,
GCArtifactPatterns: gcArtifactPatterns,
+ AutoUpdateEnabled: autoUpdateEnabled,
+ AutoUpdateCheckInterval: autoUpdateInterval,
HealthPort: healthPort,
MaxConcurrentTasks: maxConcurrentTasks,
PollInterval: pollInterval,
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index a81b5a8e9e..761189d59d 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -112,6 +112,22 @@ type Daemon struct {
updating atomic.Bool // prevents concurrent update attempts
activeTasks atomic.Int64 // number of tasks currently in handleTask; exposed via /health
+ // claimMu guards pauseClaims and claimsInFlight. It is held only for the
+ // microseconds it takes to make a decision; ClaimTask itself runs without
+ // the lock so a slow per-runtime claim cannot stall auto-update or any
+ // other poller.
+ //
+ // The pair is the auto-update path's barrier against the issue's
+ // requirement that "升级过程中如果有 task 进来,会延后升级而不是中断 task":
+ // runRuntimePoller refuses to call ClaimTask while pauseClaims is set, and
+ // tryAutoUpdate refuses to flip pauseClaims while any poller is mid-claim
+ // or any task is in handleTask. Together that closes the fetch-then-claim
+ // race where a new task slipping in during the release-metadata fetch
+ // would be cancelled by triggerRestart's root-ctx cancel.
+ claimMu sync.Mutex
+ pauseClaims bool // when true, runRuntimePoller skips ClaimTask
+ claimsInFlight int // pollers that have decided to claim but haven't yet handed the task off to handleTask
+
activeEnvRootsMu sync.Mutex
activeEnvRoots map[string]int // env root path -> reference count (handles reuse paths marked twice)
@@ -124,6 +140,10 @@ type Daemon struct {
runner taskRunner // executes agent tasks; set to d.runTask by New(), overridable in tests
cancelPollInterval time.Duration // how often handleTask polls for server-side cancellation; overridable in tests
+ // runUpdateFn executes the brew-or-download upgrade. Set to d.runUpdate by
+ // New() and overridable in tests so the auto-update poller can be exercised
+ // without touching the real network or the brew CLI.
+ runUpdateFn func(targetVersion string) (string, error)
}
// New creates a new Daemon instance.
@@ -150,6 +170,7 @@ func New(cfg Config, logger *slog.Logger) *Daemon {
cancelPollInterval: 5 * time.Second,
}
d.runner = taskRunnerFunc(d.runTask)
+ d.runUpdateFn = d.runUpdate
return d
}
@@ -596,6 +617,7 @@ func (d *Daemon) Run(ctx context.Context) error {
go d.taskWakeupLoop(ctx, taskWakeups)
go d.heartbeatLoop(ctx)
go d.gcLoop(ctx)
+ go d.autoUpdateLoop(ctx)
go d.serveHealth(ctx, healthLn, time.Now())
return d.pollLoop(ctx, taskWakeups)
}
@@ -1456,32 +1478,14 @@ func (d *Daemon) handleUpdate(ctx context.Context, runtimeID string, update *Pen
"status": "running",
})
- // Try Homebrew first, fall back to direct download.
- var output string
- if cli.IsBrewInstall() {
- d.logger.Info("updating CLI via Homebrew...")
- var err error
- output, err = cli.UpdateViaBrew()
- if err != nil {
- d.logger.Error("CLI update failed", "error", err, "output", output)
- d.reportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
- "status": "failed",
- "error": fmt.Sprintf("brew upgrade failed: %v", err),
- })
- return
- }
- } else {
- d.logger.Info("updating CLI via direct download...", "target_version", update.TargetVersion)
- var err error
- output, err = cli.UpdateViaDownload(update.TargetVersion)
- if err != nil {
- d.logger.Error("CLI update failed", "error", err)
- d.reportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
- "status": "failed",
- "error": fmt.Sprintf("download update failed: %v", err),
- })
- return
- }
+ output, err := d.runUpdateFn(update.TargetVersion)
+ if err != nil {
+ d.logger.Error("CLI update failed", "error", err, "output", output)
+ d.reportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
+ "status": "failed",
+ "error": err.Error(),
+ })
+ return
}
d.logger.Info("CLI update completed successfully", "output", output)
@@ -1494,6 +1498,29 @@ func (d *Daemon) handleUpdate(ctx context.Context, runtimeID string, update *Pen
d.triggerRestart()
}
+// runUpdate executes the brew-or-download upgrade against targetVersion and
+// returns the human-readable output (always populated, even on failure when
+// brew gives us a useful diagnostic). The caller is responsible for the
+// `updating` CAS guard and for reporting status back to the server / triggering
+// the restart — extracted so the server-triggered path (handleUpdate) and the
+// auto-update poller (autoUpdateLoop) share the exact same execution body.
+func (d *Daemon) runUpdate(targetVersion string) (string, error) {
+ if cli.IsBrewInstall() {
+ d.logger.Info("updating CLI via Homebrew...")
+ out, err := cli.UpdateViaBrew()
+ if err != nil {
+ return out, fmt.Errorf("brew upgrade failed: %w", err)
+ }
+ return out, nil
+ }
+ d.logger.Info("updating CLI via direct download...", "target_version", targetVersion)
+ out, err := cli.UpdateViaDownload(targetVersion)
+ if err != nil {
+ return out, fmt.Errorf("download update failed: %w", err)
+ }
+ return out, nil
+}
+
// updateReportBackoffs defines the retry schedule for delivering CLI update
// status back to the server. This mirrors localSkillReportBackoffs because
// both features have the same user-visible failure mode: the daemon completed
@@ -1550,6 +1577,55 @@ func (d *Daemon) reportUpdateResultWithRetry(ctx context.Context, runtimeID, upd
"runtime_id", runtimeID, "update_id", updateID, "error", lastErr)
}
+// tryEnterClaim records the intent to call ClaimTask. Returns true if the
+// caller may proceed, false if the auto-update barrier is in effect. Every
+// successful call MUST be paired with an exitClaim() on every exit path —
+// either right after a failed/empty claim, or via the handleTask goroutine's
+// defer once the task is handed off.
+func (d *Daemon) tryEnterClaim() bool {
+ d.claimMu.Lock()
+ defer d.claimMu.Unlock()
+ if d.pauseClaims {
+ return false
+ }
+ d.claimsInFlight++
+ return true
+}
+
+// exitClaim releases the in-flight claim recorded by tryEnterClaim.
+func (d *Daemon) exitClaim() {
+ d.claimMu.Lock()
+ defer d.claimMu.Unlock()
+ d.claimsInFlight--
+}
+
+// trySetClaimBarrier atomically pauses new ClaimTask calls if the daemon is
+// fully idle (no claims in flight, no tasks running). Returns true if the
+// caller now holds the barrier and must release it with releaseClaimBarrier
+// on every non-restart exit path; false if the daemon is busy and the caller
+// should defer to the next tick. Used by tryAutoUpdate to close the race
+// where a task slips in between the cheap pre-fetch idle check and the
+// actual upgrade kick-off.
+func (d *Daemon) trySetClaimBarrier() bool {
+ d.claimMu.Lock()
+ defer d.claimMu.Unlock()
+ if d.claimsInFlight > 0 || d.activeTasks.Load() > 0 {
+ return false
+ }
+ d.pauseClaims = true
+ return true
+}
+
+// releaseClaimBarrier clears the auto-update claim barrier so pollers may
+// resume claiming. Called on failure paths only — a successful upgrade leaves
+// the barrier set because triggerRestart is about to take the process down
+// and clearing it would open a window for new claims during shutdown.
+func (d *Daemon) releaseClaimBarrier() {
+ d.claimMu.Lock()
+ defer d.claimMu.Unlock()
+ d.pauseClaims = false
+}
+
// triggerRestart initiates a graceful daemon restart after a successful CLI update.
// For brew installs, it keeps the symlink path (e.g. /opt/homebrew/bin/multica)
// so the restarted daemon picks up the new Cellar version automatically.
@@ -1724,8 +1800,22 @@ func (d *Daemon) runRuntimePoller(
continue
}
+ // Refuse new claims while an auto-update is preparing to roll the
+ // process. The barrier is paired with a re-check of claimsInFlight +
+ // activeTasks inside tryAutoUpdate, so once we get past tryEnterClaim
+ // the auto-update path is guaranteed to defer until this poller has
+ // handed the task off (or given up).
+ if !d.tryEnterClaim() {
+ sem <- slot
+ if err := sleepWithContextOrWakeup(pollerCtx, d.cfg.PollInterval, wakeup); err != nil {
+ return
+ }
+ continue
+ }
+
task, err := d.client.ClaimTask(pollerCtx, rid)
if err != nil {
+ d.exitClaim()
sem <- slot
if pollerCtx.Err() == nil {
if isRuntimeNotFoundError(err) {
@@ -1745,6 +1835,7 @@ func (d *Daemon) runRuntimePoller(
}
if task == nil {
+ d.exitClaim()
sem <- slot
if err := sleepWithContextOrWakeup(pollerCtx, d.cfg.PollInterval, wakeup); err != nil {
return
@@ -1761,6 +1852,7 @@ func (d *Daemon) runRuntimePoller(
d.activeTasks.Add(1)
go func(t Task, slot int) {
defer taskWG.Done()
+ defer d.exitClaim()
defer d.activeTasks.Add(-1)
defer func() { sem <- slot }()
d.handleTask(parentCtx, t, slot)