Skip to content

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

Go

fix: make CLI update completion status reliable (#2018)

Multica Evef85b7cce913c
diff --git a/packages/views/runtimes/components/update-section.tsx b/packages/views/runtimes/components/update-section.tsx
index df44a3b64c..c91cb5ddb9 100644
--- a/packages/views/runtimes/components/update-section.tsx
+++ b/packages/views/runtimes/components/update-section.tsx
@@ -99,6 +99,7 @@ export function UpdateSection({
const [error, setError] = useState("");
const [output, setOutput] = useState("");
const [updating, setUpdating] = useState(false);
+ const [targetVersion, setTargetVersion] = useState<string | null>(null);
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);
const cleanup = useCallback(() => {
@@ -115,10 +116,32 @@ export function UpdateSection({
fetchLatestVersion().then(setLatestVersion);
}, []);
+ const markCompleted = useCallback(
+ (message: string) => {
+ setStatus("completed");
+ setOutput(message);
+ setUpdating(false);
+ setTargetVersion(null);
+ cleanup();
+ // Auto-clear status after a few seconds so the UI refreshes to show the
+ // new version from the re-fetched runtime data.
+ setTimeout(() => setStatus(null), 5000);
+ },
+ [cleanup],
+ );
+
+ useEffect(() => {
+ if (!updating || !targetVersion || !currentVersion) return;
+ if (!isNewer(targetVersion, currentVersion)) {
+ markCompleted(`Updated to ${targetVersion}`);
+ }
+ }, [currentVersion, markCompleted, targetVersion, updating]);
+
const handleUpdate = async () => {
if (!latestVersion) return;
cleanup();
setUpdating(true);
+ setTargetVersion(latestVersion);
setStatus("pending");
setError("");
setOutput("");
@@ -132,18 +155,16 @@ export function UpdateSection({
setStatus(result.status as RuntimeUpdateStatus);
if (result.status === "completed") {
- setOutput(result.output ?? "");
- setUpdating(false);
- cleanup();
- // Auto-clear status after a few seconds so the UI
- // refreshes to show the new version from the re-fetched runtime data.
- setTimeout(() => setStatus(null), 5000);
+ markCompleted(
+ result.output ?? `Updated to ${targetVersion ?? latestVersion}`,
+ );
} else if (
result.status === "failed" ||
result.status === "timeout"
) {
setError(result.error ?? "Unknown error");
setUpdating(false);
+ setTargetVersion(null);
cleanup();
}
} catch {
@@ -154,6 +175,7 @@ export function UpdateSection({
setStatus("failed");
setError("Failed to initiate update");
setUpdating(false);
+ setTargetVersion(null);
}
};
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 6228773a6b..3d1b8e9d28 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -79,11 +79,11 @@ func New(cfg Config, logger *slog.Logger) *Daemon {
// server can split logs/metrics by client version (parallel to the CLI).
client.SetVersion(cfg.CLIVersion)
return &Daemon{
- cfg: cfg,
- client: client,
- repoCache: repocache.New(cacheRoot, logger),
- logger: logger,
- workspaces: make(map[string]*workspaceState),
+ cfg: cfg,
+ client: client,
+ repoCache: repocache.New(cacheRoot, logger),
+ logger: logger,
+ workspaces: make(map[string]*workspaceState),
runtimeIndex: make(map[string]Runtime),
runtimeSetCh: make(chan struct{}, 1),
agentVersions: make(map[string]string),
@@ -886,7 +886,7 @@ func (d *Daemon) handleUpdate(ctx context.Context, runtimeID string, update *Pen
// could brick the embedded binary mid-update. Refuse cleanly.
if d.cfg.LaunchedBy == "desktop" {
d.logger.Info("refusing CLI self-update: daemon is managed by Desktop", "runtime_id", runtimeID, "update_id", update.ID)
- d.client.ReportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
+ d.reportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
"status": "failed",
"error": "CLI is managed by Multica Desktop — update the Desktop app to upgrade the CLI",
})
@@ -903,7 +903,7 @@ func (d *Daemon) handleUpdate(ctx context.Context, runtimeID string, update *Pen
d.logger.Info("CLI update requested", "runtime_id", runtimeID, "update_id", update.ID, "target_version", update.TargetVersion)
// Report running status.
- d.client.ReportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
+ d.reportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
"status": "running",
})
@@ -915,7 +915,7 @@ func (d *Daemon) handleUpdate(ctx context.Context, runtimeID string, update *Pen
output, err = cli.UpdateViaBrew()
if err != nil {
d.logger.Error("CLI update failed", "error", err, "output", output)
- d.client.ReportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
+ d.reportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
"status": "failed",
"error": fmt.Sprintf("brew upgrade failed: %v", err),
})
@@ -927,7 +927,7 @@ func (d *Daemon) handleUpdate(ctx context.Context, runtimeID string, update *Pen
output, err = cli.UpdateViaDownload(update.TargetVersion)
if err != nil {
d.logger.Error("CLI update failed", "error", err)
- d.client.ReportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
+ d.reportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
"status": "failed",
"error": fmt.Sprintf("download update failed: %v", err),
})
@@ -936,7 +936,7 @@ func (d *Daemon) handleUpdate(ctx context.Context, runtimeID string, update *Pen
}
d.logger.Info("CLI update completed successfully", "output", output)
- d.client.ReportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
+ d.reportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
"status": "completed",
"output": fmt.Sprintf("Updated to %s", update.TargetVersion),
})
@@ -945,6 +945,62 @@ func (d *Daemon) handleUpdate(ctx context.Context, runtimeID string, update *Pen
d.triggerRestart()
}
+// 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
+// work locally, but a transient report failure leaves the UI waiting until the
+// server-side request times out.
+//
+// Overridable for tests to avoid real sleeps.
+var updateReportBackoffs = []time.Duration{0, 500 * time.Millisecond, 2 * time.Second, 4 * time.Second}
+
+func (d *Daemon) reportUpdateResult(ctx context.Context, runtimeID, updateID string, payload map[string]any) {
+ d.reportUpdateResultWithRetry(ctx, runtimeID, updateID, func(ctx context.Context) error {
+ return d.client.ReportUpdateResult(ctx, runtimeID, updateID, payload)
+ })
+}
+
+func (d *Daemon) reportUpdateResultWithRetry(ctx context.Context, runtimeID, updateID string, fn func(context.Context) error) {
+ var lastErr error
+ for attempt, wait := range updateReportBackoffs {
+ if wait > 0 {
+ select {
+ case <-ctx.Done():
+ d.logger.Error("CLI update report cancelled",
+ "runtime_id", runtimeID, "update_id", updateID,
+ "attempt", attempt, "error", ctx.Err())
+ return
+ case <-time.After(wait):
+ }
+ }
+
+ err := fn(ctx)
+ if err == nil {
+ if attempt > 0 {
+ d.logger.Info("CLI update report succeeded after retry",
+ "runtime_id", runtimeID, "update_id", updateID,
+ "attempt", attempt+1)
+ }
+ return
+ }
+ lastErr = err
+
+ var reqErr *requestError
+ if errors.As(err, &reqErr) && reqErr.StatusCode >= 400 && reqErr.StatusCode < 500 {
+ d.logger.Error("CLI update report rejected — not retrying",
+ "runtime_id", runtimeID, "update_id", updateID,
+ "status", reqErr.StatusCode, "error", err)
+ return
+ }
+
+ d.logger.Warn("CLI update report failed — will retry",
+ "runtime_id", runtimeID, "update_id", updateID,
+ "attempt", attempt+1, "error", err)
+ }
+ d.logger.Error("CLI update report exhausted retries",
+ "runtime_id", runtimeID, "update_id", updateID, "error", lastErr)
+}
+
// 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.
diff --git a/server/internal/daemon/update_report_test.go b/server/internal/daemon/update_report_test.go
new file mode 100644
index 0000000000..2ca3e28599
--- /dev/null
+++ b/server/internal/daemon/update_report_test.go
@@ -0,0 +1,120 @@
+package daemon
+
+import (
+ "context"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func withFastUpdateReportBackoffs(t *testing.T) {
+ t.Helper()
+ prev := updateReportBackoffs
+ updateReportBackoffs = []time.Duration{0, 0, 0, 0}
+ t.Cleanup(func() { updateReportBackoffs = prev })
+}
+
+func updateReportDaemon(t *testing.T, handler http.HandlerFunc) (*Daemon, *int32) {
+ t.Helper()
+ var calls int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ atomic.AddInt32(&calls, 1)
+ handler(w, r)
+ }))
+ t.Cleanup(srv.Close)
+ return &Daemon{
+ client: NewClient(srv.URL),
+ logger: slog.Default(),
+ }, &calls
+}
+
+func TestReportUpdateResult_RetriesOn500AndEventuallySucceeds(t *testing.T) {
+ withFastUpdateReportBackoffs(t)
+
+ var hits int32
+ d, calls := updateReportDaemon(t, func(w http.ResponseWriter, _ *http.Request) {
+ n := atomic.AddInt32(&hits, 1)
+ if n <= 2 {
+ http.Error(w, "{}", http.StatusInternalServerError)
+ return
+ }
+ w.WriteHeader(http.StatusOK)
+ w.Write([]byte(`{"status":"ok"}`))
+ })
+
+ d.reportUpdateResult(context.Background(), "rt-1", "upd-1", map[string]any{"status": "completed"})
+
+ if got := atomic.LoadInt32(calls); got != 3 {
+ t.Fatalf("expected 3 attempts (2 failures + 1 success), got %d", got)
+ }
+}
+
+func TestReportUpdateResult_DoesNotRetryOn4xx(t *testing.T) {
+ withFastUpdateReportBackoffs(t)
+
+ d, calls := updateReportDaemon(t, func(w http.ResponseWriter, _ *http.Request) {
+ http.Error(w, `{"error":"update not found"}`, http.StatusNotFound)
+ })
+
+ d.reportUpdateResult(context.Background(), "rt-1", "upd-1", map[string]any{"status": "completed"})
+
+ if got := atomic.LoadInt32(calls); got != 1 {
+ t.Fatalf("expected exactly 1 attempt (4xx is terminal), got %d", got)
+ }
+}
+
+func TestReportUpdateResult_GivesUpAfterAllAttemptsFail(t *testing.T) {
+ withFastUpdateReportBackoffs(t)
+
+ d, calls := updateReportDaemon(t, func(w http.ResponseWriter, _ *http.Request) {
+ http.Error(w, "{}", http.StatusInternalServerError)
+ })
+
+ d.reportUpdateResult(context.Background(), "rt-1", "upd-1", map[string]any{"status": "completed"})
+
+ if got := atomic.LoadInt32(calls); int(got) != len(updateReportBackoffs) {
+ t.Fatalf("expected %d attempts, got %d", len(updateReportBackoffs), got)
+ }
+}
+
+func TestReportUpdateResult_AbortsOnContextCancel(t *testing.T) {
+ prev := updateReportBackoffs
+ updateReportBackoffs = []time.Duration{0, 200 * time.Millisecond}
+ t.Cleanup(func() { updateReportBackoffs = prev })
+
+ d, calls := updateReportDaemon(t, func(w http.ResponseWriter, _ *http.Request) {
+ http.Error(w, "{}", http.StatusInternalServerError)
+ })
+
+ ctx, cancel := context.WithCancel(context.Background())
+ go func() {
+ time.Sleep(30 * time.Millisecond)
+ cancel()
+ }()
+ d.reportUpdateResult(ctx, "rt-1", "upd-1", map[string]any{"status": "completed"})
+
+ if got := atomic.LoadInt32(calls); got != 1 {
+ t.Fatalf("expected exactly 1 attempt before cancel, got %d", got)
+ }
+}
+
+func TestReportUpdateResult_SendsCorrectPath(t *testing.T) {
+ withFastUpdateReportBackoffs(t)
+
+ var path string
+ d, _ := updateReportDaemon(t, func(w http.ResponseWriter, r *http.Request) {
+ path = r.URL.Path
+ w.WriteHeader(http.StatusOK)
+ w.Write([]byte(`{"status":"ok"}`))
+ })
+
+ d.reportUpdateResult(context.Background(), "rt-a", "upd-a", map[string]any{"status": "completed"})
+
+ if !strings.HasSuffix(path, "/api/daemon/runtimes/rt-a/update/upd-a/result") {
+ t.Fatalf("update path = %q", path)
+ }
+}