Skip to content

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

Go

feat(runtimes): queue CLI updates while the machine is busy (MUL-9685) (#11034)

Multica Eve3b4511861888
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 455aa49687..c124ffbf59 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -417,6 +417,8 @@ import {
RuntimeUsageByHourListSchema,
RuntimeUsageListSchema,
RuntimeRateLimitsResponseSchema,
+ RuntimeUpdateSchema,
+ ActiveRuntimeUpdateResponseSchema,
SearchIssuesResponseSchema,
ProjectSchema,
ArchiveProjectResponseSchema,
@@ -680,6 +682,12 @@ function parseSearchIndexResponse<T>(raw: unknown, schema: ZodType, endpoint: st
return parsed;
}
+function parseRuntimeUpdate(raw: unknown, endpoint: string): RuntimeUpdate {
+ const parsed = parseWithFallback<RuntimeUpdate | null>(raw, RuntimeUpdateSchema, null, { endpoint });
+ if (parsed === null) throw new Error(`Malformed response from ${endpoint}`);
+ return parsed;
+}
+
export class ApiError extends Error {
readonly status: number;
readonly statusText: string;
@@ -3202,21 +3210,40 @@ export class ApiClient {
);
}
+ // queue_when_busy: a busy daemon holds the update and installs it once
+ // idle, instead of failing it; this UI can show and cancel the queue.
async initiateUpdate(
runtimeId: string,
targetVersion: string,
): Promise<RuntimeUpdate> {
- return this.fetch(`/api/runtimes/${runtimeId}/update`, {
+ const raw = await this.fetch<unknown>(`/api/runtimes/${runtimeId}/update`, {
method: "POST",
- body: JSON.stringify({ target_version: targetVersion }),
+ body: JSON.stringify({ target_version: targetVersion, queue_when_busy: true }),
});
+ return parseRuntimeUpdate(raw, "POST /api/runtimes/:id/update");
}
async getUpdateResult(
runtimeId: string,
updateId: string,
): Promise<RuntimeUpdate> {
- return this.fetch(`/api/runtimes/${runtimeId}/update/${updateId}`);
+ const raw = await this.fetch<unknown>(`/api/runtimes/${runtimeId}/update/${updateId}`);
+ return parseRuntimeUpdate(raw, "GET /api/runtimes/:id/update/:updateId");
+ }
+
+ /** The machine's unfinished update, started through any of its runtimes. */
+ async getActiveUpdate(runtimeId: string): Promise<RuntimeUpdate | null> {
+ const raw = await this.fetch<unknown>(`/api/runtimes/${runtimeId}/update`);
+ return parseWithFallback(raw, ActiveRuntimeUpdateResponseSchema, { update: null }, {
+ endpoint: "GET /api/runtimes/:id/update",
+ }).update;
+ }
+
+ async cancelUpdate(runtimeId: string, updateId: string): Promise<RuntimeUpdate> {
+ const raw = await this.fetch<unknown>(`/api/runtimes/${runtimeId}/update/${updateId}/cancel`, {
+ method: "POST",
+ });
+ return parseRuntimeUpdate(raw, "POST /api/runtimes/:id/update/:updateId/cancel");
}
// Both discovery endpoints feed a UI state machine (poll while
diff --git a/packages/core/api/runtime-update-schema.test.ts b/packages/core/api/runtime-update-schema.test.ts
new file mode 100644
index 0000000000..87a624922c
--- /dev/null
+++ b/packages/core/api/runtime-update-schema.test.ts
@@ -0,0 +1,35 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import { ActiveRuntimeUpdateResponseSchema, RuntimeUpdateSchema } from "./schemas";
+
+describe("RuntimeUpdateSchema", () => {
+ it("parses a queued update", () => {
+ const parsed = RuntimeUpdateSchema.parse({
+ id: "u1",
+ runtime_id: "r1",
+ status: "scheduled",
+ target_version: "v0.12.0",
+ active_tasks: 2,
+ cancellable: true,
+ created_at: "2026-11-20T00:00:00Z",
+ updated_at: "2026-11-20T00:00:00Z",
+ });
+ expect(parsed).toMatchObject({ status: "scheduled", active_tasks: 2, cancellable: true });
+ });
+
+ it("degrades unknown and missing fields instead of failing", () => {
+ const parsed = RuntimeUpdateSchema.parse({ id: "u1", status: "paused_by_future_server", active_tasks: "two" });
+ expect(parsed).toMatchObject({ status: "pending", cancellable: false, active_tasks: undefined, target_version: "" });
+ });
+
+ it("rejects a response without an id", () => {
+ expect(RuntimeUpdateSchema.safeParse({ status: "pending" }).success).toBe(false);
+ });
+});
+
+describe("ActiveRuntimeUpdateResponseSchema", () => {
+ it("falls back to no update when the payload is unusable", () => {
+ expect(ActiveRuntimeUpdateResponseSchema.parse({ update: null })).toEqual({ update: null });
+ expect(ActiveRuntimeUpdateResponseSchema.parse({ update: "nope" })).toEqual({ update: null });
+ });
+});
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index df1a8e18d3..b0ce9b6881 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -2364,6 +2364,26 @@ export const RuntimeRateLimitsResponseSchema = z.object({
rate_limits: RuntimeRateLimitsSchema.nullable().catch(null),
}).loose();
+export const RuntimeUpdateSchema = z.object({
+ id: z.string(),
+ runtime_id: z.string().default(""),
+ // An unknown future status keeps the card neutral and polling.
+ status: z
+ .enum(["pending", "scheduled", "running", "completed", "failed", "timeout", "cancelled", "expired"])
+ .catch("pending"),
+ target_version: z.string().default(""),
+ output: z.string().optional().catch(undefined),
+ error: z.string().optional().catch(undefined),
+ active_tasks: z.number().optional().catch(undefined),
+ cancellable: z.boolean().default(false).catch(false),
+ created_at: z.string().default(""),
+ updated_at: z.string().default(""),
+}).loose();
+
+export const ActiveRuntimeUpdateResponseSchema = z.object({
+ update: RuntimeUpdateSchema.nullable().catch(null),
+}).loose();
+
// Agent task responses. The base object stays loose so daemon/runtime fields
// can drift while task-list consumers still validate the fields they render.
diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.ts
index 3f8a56ccc8..0fa36cbea9 100644
--- a/packages/core/types/agent.ts
+++ b/packages/core/types/agent.ts
@@ -1247,10 +1247,15 @@ export interface DashboardFailureByAgent {
export type RuntimeUpdateStatus =
| "pending"
+ // The daemon is busy and installs once its last agent task finishes.
+ | "scheduled"
| "running"
| "completed"
| "failed"
- | "timeout";
+ | "timeout"
+ | "cancelled"
+ // The machine did not become idle within 24 hours.
+ | "expired";
export interface RuntimeUpdate {
id: string;
@@ -1259,6 +1264,10 @@ export interface RuntimeUpdate {
target_version: string;
output?: string;
error?: string;
+ /** Agent tasks the daemon is waiting for while `scheduled`. */
+ active_tasks?: number;
+ /** True until installation starts. */
+ cancellable: boolean;
created_at: string;
updated_at: string;
}
diff --git a/packages/views/locales/en/runtimes.json b/packages/views/locales/en/runtimes.json
index 142516a01d..09ebf45be7 100644
--- a/packages/views/locales/en/runtimes.json
+++ b/packages/views/locales/en/runtimes.json
@@ -343,10 +343,19 @@
"available": "available",
"action": "Update",
"retry": "Retry",
+ "cancel": "Cancel",
+ "cancel_failed": "Couldn't confirm the cancel, so the update may still run. Try again.",
+ "cancel_conflict": "Couldn't cancel: installation has already started.",
"unknown_error": "Unknown error",
"initiate_failed": "Failed to initiate update",
+ "scheduled_tasks": "{{running}} running",
+ "note_no_interrupt": "Running tasks won't be interrupted.",
+ "expired_note": "Expired after waiting 24 hours for the machine to go idle.",
+ "busy_note": "The machine was busy, so the update didn't start. Try again when it's idle.",
+ "another_update_note": "Another update is already queued or installing on this machine.",
"status": {
"pending": "Waiting for daemon...",
+ "scheduled": "Updates when idle",
"running": "Updating...",
"completed": "Update complete. Daemon is restarting...",
"failed": "Update failed",
diff --git a/packages/views/locales/es/runtimes.json b/packages/views/locales/es/runtimes.json
index 4be391a631..3a4f2a77e8 100644
--- a/packages/views/locales/es/runtimes.json
+++ b/packages/views/locales/es/runtimes.json
@@ -343,10 +343,19 @@
"available": "disponible",
"action": "Actualizar",
"retry": "Reintentar",
+ "cancel": "Cancelar",
+ "cancel_failed": "No se pudo confirmar la cancelación, así que la actualización aún podría ejecutarse. Inténtalo de nuevo.",
+ "cancel_conflict": "No se puede cancelar: la instalación ya ha comenzado.",
"unknown_error": "Error desconocido",
"initiate_failed": "No se ha podido iniciar la actualización",
+ "scheduled_tasks": "{{running}} en curso",
+ "note_no_interrupt": "Las tareas en curso no se interrumpirán.",
+ "expired_note": "Caducó tras esperar 24 horas a que la máquina quedara inactiva.",
+ "busy_note": "La máquina estaba ocupada, así que la actualización no empezó. Vuelve a intentarlo cuando esté inactiva.",
+ "another_update_note": "Ya hay otra actualización en cola o instalándose en esta máquina.",
"status": {
"pending": "Esperando al daemon...",
+ "scheduled": "Se actualizará en reposo",
"running": "Actualizando...",
"completed": "Actualización completa. El daemon se está reiniciando...",
"failed": "La actualización falló",
diff --git a/packages/views/locales/fr/runtimes.json b/packages/views/locales/fr/runtimes.json
index 5c3918456f..f2b7c0ad58 100644
--- a/packages/views/locales/fr/runtimes.json
+++ b/packages/views/locales/fr/runtimes.json
@@ -343,10 +343,19 @@
"available": "disponible",
"action": "Mettre à jour",
"retry": "Réessayer",
+ "cancel": "Annuler",
+ "cancel_failed": "Impossible de confirmer l’annulation : la mise à jour peut encore s’exécuter. Réessayez.",
+ "cancel_conflict": "Annulation impossible : l’installation a déjà commencé.",
"unknown_error": "Erreur inconnue",
"initiate_failed": "Échec du lancement de la mise à jour",
+ "scheduled_tasks": "{{running}} en cours",
+ "note_no_interrupt": "Les tâches en cours ne seront pas interrompues.",
+ "expired_note": "Expirée après 24 heures d'attente sans que la machine soit inactive.",
+ "busy_note": "La machine était occupée, la mise à jour n'a donc pas démarré. Réessayez quand elle sera inactive.",
+ "another_update_note": "Une autre mise à jour est déjà en file d'attente ou en cours d'installation sur cette machine.",
"status": {
"pending": "En attente du daemon...",
+ "scheduled": "Mise à jour à l'inactivité",
"running": "Mise à jour...",
"completed": "Mise à jour terminée. Le daemon redémarre...",
"failed": "Échec de la mise à jour",
diff --git a/packages/views/locales/ja/runtimes.json b/packages/views/locales/ja/runtimes.json
index edc015030d..e54d600352 100644
--- a/packages/views/locales/ja/runtimes.json
+++ b/packages/views/locales/ja/runtimes.json
@@ -332,10 +332,19 @@
"available": "利用可能",
"action": "更新",
"retry": "再試行",
+ "cancel": "キャンセル",
+ "cancel_failed": "取り消しを確認できませんでした。更新がこのまま実行される可能性があります。もう一度お試しください。",
+ "cancel_conflict": "取り消せません。インストールはすでに始まっています。",
"unknown_error": "不明なエラー",
"initiate_failed": "更新を開始できませんでした",
+ "scheduled_tasks": "{{running}} 件実行中",
+ "note_no_interrupt": "実行中のタスクは中断されません。",
+ "expired_note": "マシンがアイドルになるのを 24 時間待ったため、期限切れになりました。",
+ "busy_note": "マシンがタスクを実行中だったため、更新は開始されませんでした。アイドル時に再試行してください。",
+ "another_update_note": "このマシンでは別の更新がすでにキュー待ちまたはインストール中です。",
"status": {
"pending": "デーモンを待っています...",
+ "scheduled": "アイドル時に更新",
"running": "更新中...",
"completed": "更新が完了しました。デーモンを再起動しています...",
"failed": "更新に失敗しました",
diff --git a/packages/views/locales/ko/runtimes.json b/packages/views/locales/ko/runtimes.json
index c820391091..0b2b2da567 100644
--- a/packages/views/locales/ko/runtimes.json
+++ b/packages/views/locales/ko/runtimes.json
@@ -332,10 +332,19 @@
"available": "사용 가능",
"action": "업데이트",
"retry": "다시 시도",
+ "cancel": "취소",
+ "cancel_failed": "취소를 확인하지 못했습니다. 업데이트가 그대로 실행될 수 있습니다. 다시 시도하세요.",
+ "cancel_conflict": "취소할 수 없습니다. 이미 설치가 시작되었습니다.",
"unknown_error": "알 수 없는 오류",
"initiate_failed": "업데이트를 시작하지 못했습니다",
+ "scheduled_tasks": "{{running}}개 실행 중",
+ "note_no_interrupt": "실행 중인 작업은 중단되지 않습니다.",
+ "expired_note": "머신이 유휴 상태가 되기를 24시간 동안 기다려 만료되었습니다.",
+ "busy_note": "머신이 작업을 실행 중이어서 업데이트가 시작되지 않았습니다. 유휴 상태일 때 다시 시도하세요.",
+ "another_update_note": "이 머신에서 다른 업데이트가 이미 대기 중이거나 설치 중입니다.",
"status": {
"pending": "데몬 대기 중...",
+ "scheduled": "유휴 시 업데이트",
"running": "업데이트 중...",
"completed": "업데이트 완료. 데몬을 다시 시작하는 중...",
"failed": "업데이트 실패",
diff --git a/packages/views/locales/ru/runtimes.json b/packages/views/locales/ru/runtimes.json
index 7105d644fe..3e18e48597 100644
--- a/packages/views/locales/ru/runtimes.json
+++ b/packages/views/locales/ru/runtimes.json
@@ -361,10 +361,19 @@
"available": "доступна",
"action": "Обновить",
"retry": "Повторить",
+ "cancel": "Отмена",
+ "cancel_failed": "Не удалось подтвердить отмену, поэтому обновление всё ещё может запуститься. Попробуйте ещё раз.",
+ "cancel_conflict": "Отменить нельзя: установка уже началась.",
"unknown_error": "Неизвестная ошибка",
"initiate_failed": "Не удалось запустить обновление",
+ "scheduled_tasks": "Выполняется: {{running}}",
+ "note_no_interrupt": "Выполняющиеся задачи не будут прерваны.",
+ "expired_note": "Срок истёк: машина не освобождалась 24 часа.",
+ "busy_note": "Машина была занята, поэтому обновление не началось. Повторите попытку, когда она освободится.",
+ "another_update_note": "На этой машине уже стоит в очереди или устанавливается другое обновление.",
"status": {
"pending": "Ожидание демона...",
+ "scheduled": "Обновится при простое",
"running": "Обновление...",
"completed": "Обновление завершено. Демон перезапускается...",
"failed": "Обновление не удалось",
diff --git a/packages/views/locales/zh-Hans/runtimes.json b/packages/views/locales/zh-Hans/runtimes.json
index 9c08212600..98f008d301 100644
--- a/packages/views/locales/zh-Hans/runtimes.json
+++ b/packages/views/locales/zh-Hans/runtimes.json
@@ -332,10 +332,19 @@
"available": "可用",
"action": "更新",
"retry": "重试",
+ "cancel": "取消",
+ "cancel_failed": "未能确认取消,更新仍可能执行。请重试。",
+ "cancel_conflict": "无法取消:已经开始安装。",
"unknown_error": "未知错误",
"initiate_failed": "启动更新失败",
+ "scheduled_tasks": "{{running}} 个运行中",
+ "note_no_interrupt": "不会中断正在运行的任务。",
+ "expired_note": "等待机器空闲已超过 24 小时,本次排队已失效。",
+ "busy_note": "机器正在执行任务,本次没有开始更新。请在空闲时重试。",
+ "another_update_note": "这台机器上已有另一个更新在排队或安装中。",
"status": {
"pending": "等待守护进程...",
+ "scheduled": "空闲后更新",
"running": "更新中...",
"completed": "更新完成。守护进程正在重启...",
"failed": "更新失败",
diff --git a/packages/views/locales/zh-Hant/runtimes.json b/packages/views/locales/zh-Hant/runtimes.json
index 5d46eaa089..6642e929bb 100644
--- a/packages/views/locales/zh-Hant/runtimes.json
+++ b/packages/views/locales/zh-Hant/runtimes.json
@@ -332,10 +332,19 @@
"available": "可用",
"action": "更新",
"retry": "重試",
+ "cancel": "取消",
+ "cancel_failed": "未能確認取消,更新仍可能執行。請重試。",
+ "cancel_conflict": "無法取消:已經開始安裝。",
"unknown_error": "未知錯誤",
"initiate_failed": "啟動更新失敗",
+ "scheduled_tasks": "{{running}} 個執行中",
+ "note_no_interrupt": "不會中斷正在執行的任務。",
+ "expired_note": "等待機器閒置已超過 24 小時,本次排隊已失效。",
+ "busy_note": "機器正在執行任務,本次沒有開始更新。請在閒置時重試。",
+ "another_update_note": "這台機器上已有另一個更新在排隊或安裝中。",
"status": {
"pending": "等待守護程序...",
+ "scheduled": "閒置後更新",
"running": "更新中...",
"completed": "更新完成。守護程序正在重啟...",
"failed": "更新失敗",
diff --git a/packages/views/runtimes/components/update-section.test.tsx b/packages/views/runtimes/components/update-section.test.tsx
index 1b29c08c17..d3a57d2f79 100644
--- a/packages/views/runtimes/components/update-section.test.tsx
+++ b/packages/views/runtimes/components/update-section.test.tsx
@@ -1,7 +1,9 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { cleanup, render, screen } from "@testing-library/react";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { api, ApiError } from "@multica/core/api";
+import type { RuntimeUpdate } from "@multica/core/types";
import { I18nProvider } from "@multica/core/i18n/react";
import enCommon from "../../locales/en/common.json";
import enRuntimes from "../../locales/en/runtimes.json";
@@ -9,10 +11,13 @@ import { UpdateSection } from "./update-section";
const TEST_RESOURCES = { en: { common: enCommon, runtimes: enRuntimes } };
-vi.mock("@multica/core/api", () => ({
+vi.mock("@multica/core/api", async (importOriginal) => ({
+ ApiError: (await importOriginal<typeof import("@multica/core/api")>()).ApiError,
api: {
initiateUpdate: vi.fn(),
getUpdateResult: vi.fn(),
+ getActiveUpdate: vi.fn().mockResolvedValue(null),
+ cancelUpdate: vi.fn(),
},
}));
@@ -170,3 +175,157 @@ describe("UpdateSection non-release versions", () => {
expect(screen.queryByText("Local build")).not.toBeInTheDocument();
});
});
+
+describe("UpdateSection queued updates", () => {
+ let clock = Date.now() + 100 * 60 * 60 * 1000;
+
+ function update(overrides: Partial<RuntimeUpdate>): RuntimeUpdate {
+ return {
+ id: "update-1",
+ runtime_id: "runtime-1",
+ status: "scheduled",
+ target_version: "v0.5.0",
+ cancellable: true,
+ created_at: "",
+ updated_at: "",
+ ...overrides,
+ };
+ }
+
+ beforeEach(() => {
+ clock += 60 * 60 * 1000;
+ vi.spyOn(Date, "now").mockReturnValue(clock);
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({ ok: true, json: async () => ({ tag_name: "v0.5.0" }) }),
+ );
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.mocked(api.getActiveUpdate).mockResolvedValue(null);
+ });
+
+ it("shows a queued update from the server and cancels it", async () => {
+ vi.mocked(api.getActiveUpdate).mockResolvedValue(update({ active_tasks: 2 }));
+ vi.mocked(api.cancelUpdate).mockResolvedValue(update({ status: "cancelled", cancellable: false }));
+
+ renderSection({ runtimeId: "runtime-1", currentVersion: "v0.4.0" });
+
+ expect(await screen.findByText("Updates when idle")).toBeInTheDocument();
+ expect(screen.getByText(/2 running · Running tasks won't be interrupted\./)).toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Update" })).not.toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
+
+ expect(await screen.findByRole("button", { name: "Update" })).toBeInTheDocument();
+ expect(api.cancelUpdate).toHaveBeenCalledWith("runtime-1", "update-1");
+ expect(screen.queryByText("Updates when idle")).not.toBeInTheDocument();
+ });
+
+ it("says so when installation already started before the cancel", async () => {
+ vi.mocked(api.getActiveUpdate).mockResolvedValue(update({}));
+ vi.mocked(api.cancelUpdate).mockRejectedValue(new ApiError("already started", 409, "Conflict"));
+ vi.mocked(api.getUpdateResult).mockResolvedValue(update({ status: "running", cancellable: false }));
+
+ renderSection({ runtimeId: "runtime-1", currentVersion: "v0.4.0" });
+ fireEvent.click(await screen.findByRole("button", { name: "Cancel" }));
+
+ expect(await screen.findByText("Couldn't cancel: installation has already started.")).toBeInTheDocument();
+ await waitFor(() => expect(screen.getByText("Updating...")).toBeInTheDocument());
+ expect(screen.queryByRole("button", { name: "Cancel" })).not.toBeInTheDocument();
+ });
+
+ it("queues an update clicked while busy", async () => {
+ vi.mocked(api.initiateUpdate).mockResolvedValue(update({ status: "pending" }));
+
+ renderSection({ runtimeId: "runtime-1", currentVersion: "v0.4.0" });
+ fireEvent.click(await screen.findByRole("button", { name: "Update" }));
+
+ expect(await screen.findByText("Waiting for daemon...")).toBeInTheDocument();
+ expect(api.initiateUpdate).toHaveBeenCalledWith("runtime-1", "v0.5.0");
+ expect(screen.getByRole("button", { name: "Cancel" })).toBeInTheDocument();
+ });
+
+ it("shows a busy refusal from a daemon that cannot queue as a neutral note", async () => {
+ vi.mocked(api.getActiveUpdate).mockResolvedValue(
+ update({
+ status: "failed",
+ cancellable: false,
+ error: "runtime update deferred because agent work is starting or still active; retry when the machine is idle",
+ }),
+ );
+
+ renderSection({ runtimeId: "runtime-1", currentVersion: "v0.4.0" });
+
+ expect(await screen.findByText(/The machine was busy/)).toBeInTheDocument();
+ expect(screen.queryByText("Update failed")).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Update" })).toBeInTheDocument();
+ });
+
+ it("drops the previous machine's queue when switching to one without an update", async () => {
+ vi.mocked(api.getActiveUpdate).mockImplementation(async (runtimeId) =>
+ runtimeId === "runtime-1" ? update({}) : null,
+ );
+ const view = renderSection({ runtimeId: "runtime-1", currentVersion: "v0.4.0" });
+ expect(await screen.findByText("Updates when idle")).toBeInTheDocument();
+
+ view.rerender(
+ <I18nProvider locale="en" resources={TEST_RESOURCES}>
+ <UpdateSection runtimeId="runtime-2" currentVersion="v0.4.0" isOnline />
+ </I18nProvider>,
+ );
+
+ expect(await screen.findByRole("button", { name: "Update" })).toBeInTheDocument();
+ expect(screen.queryByText("Updates when idle")).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Cancel" })).not.toBeInTheDocument();
+ });
+
+ it("does not report a downgrade as done before the daemon runs the target", async () => {
+ vi.mocked(api.getActiveUpdate).mockResolvedValue(
+ update({ status: "running", target_version: "v0.4.0", cancellable: false }),
+ );
+
+ renderSection({ runtimeId: "runtime-1", currentVersion: "v0.4.1" });
+
+ expect(await screen.findByText("Updating...")).toBeInTheDocument();
+ expect(screen.queryByText(/Update complete/)).not.toBeInTheDocument();
+ });
+
+ it("shows the machine's existing queue when another tab already queued one", async () => {
+ vi.mocked(api.initiateUpdate).mockRejectedValue(new ApiError("in progress", 409, "Conflict"));
+ vi.mocked(api.getActiveUpdate).mockResolvedValueOnce(null).mockResolvedValueOnce(update({}));
+
+ renderSection({ runtimeId: "runtime-1", currentVersion: "v0.4.0" });
+ fireEvent.click(await screen.findByRole("button", { name: "Update" }));
+
+ expect(await screen.findByText("Updates when idle")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Cancel" })).toBeInTheDocument();
+ expect(screen.queryByText("Failed to initiate update")).not.toBeInTheDocument();
+ });
+
+ it("does not claim installation started when the update already ended", async () => {
+ vi.mocked(api.getActiveUpdate).mockResolvedValue(update({}));
+ vi.mocked(api.cancelUpdate).mockRejectedValue(new ApiError("not cancellable", 409, "Conflict"));
+ vi.mocked(api.getUpdateResult).mockResolvedValue(update({ status: "expired", cancellable: false }));
+
+ renderSection({ runtimeId: "runtime-1", currentVersion: "v0.4.0" });
+ fireEvent.click(await screen.findByRole("button", { name: "Cancel" }));
+
+ expect(
+ await screen.findByText("Expired after waiting 24 hours for the machine to go idle."),
+ ).toBeInTheDocument();
+ expect(screen.queryByText(/installation has already started/)).not.toBeInTheDocument();
+ });
+
+ it("shows an expired queue as a neutral note", async () => {
+ vi.mocked(api.getActiveUpdate).mockResolvedValue(update({ status: "expired", cancellable: false }));
+
+ renderSection({ runtimeId: "runtime-1", currentVersion: "v0.4.0" });
+
+ expect(
+ await screen.findByText("Expired after waiting 24 hours for the machine to go idle."),
+ ).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Update" })).toBeInTheDocument();
+ });
+});
diff --git a/packages/views/runtimes/components/update-section.tsx b/packages/views/runtimes/components/update-section.tsx
index c3a77cd934..945b9b417d 100644
--- a/packages/views/runtimes/components/update-section.tsx
+++ b/packages/views/runtimes/components/update-section.tsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useCallback, useRef } from "react";
+import { useState, useEffect } from "react";
import {
Loader2,
CheckCircle2,
@@ -6,10 +6,11 @@ import {
ArrowUpCircle,
Check,
Lock,
+ Clock,
} from "@multica/ui/icons";
import { Button } from "@multica/ui/components/ui/button";
-import { api } from "@multica/core/api";
-import type { RuntimeUpdateStatus } from "@multica/core/types";
+import { api, ApiError } from "@multica/core/api";
+import type { RuntimeUpdate, RuntimeUpdateStatus } from "@multica/core/types";
import { useT } from "../../i18n";
const GITHUB_RELEASES_URL =
@@ -80,17 +81,42 @@ function isNewer(latest: string, current: string): boolean {
return false;
}
-const statusConfig: Record<
- RuntimeUpdateStatus,
- { icon: typeof Loader2; color: string }
-> = {
+type ShownStatus = "pending" | "scheduled" | "running" | "completed" | "failed" | "timeout";
+
+const statusConfig: Record<ShownStatus, { icon: typeof Loader2; color: string }> = {
pending: { icon: Loader2, color: "text-muted-foreground" },
+ scheduled: { icon: Clock, color: "text-muted-foreground" },
running: { icon: Loader2, color: "text-info" },
completed: { icon: CheckCircle2, color: "text-success" },
failed: { icon: XCircle, color: "text-destructive" },
timeout: { icon: XCircle, color: "text-warning" },
};
+const UNFINISHED: ReadonlySet<RuntimeUpdateStatus> = new Set(["pending", "scheduled", "running"]);
+
+type Note = "expired" | "busy" | "another_update" | "cancel_failed" | "cancel_conflict" | "initiate_failed";
+
+/**
+ * A failure that is not the machine's fault — it was busy (a daemon that
+ * cannot queue) or already has an update — reads as a neutral note.
+ */
+function neutralFailure(update: RuntimeUpdate): Note | null {
+ if (update.status === "expired") return "expired";
+ if (update.status !== "failed") return null;
+ const error = update.error ?? "";
+ if (error.includes("agent work is starting or still active")) return "busy";
+ if (error.includes("already queued or in progress") || error.includes("already in progress")) {
+ return "another_update";
+ }
+ return null;
+}
+
+function sameReleaseVersion(a: string, b: string): boolean {
+ const pa = parseReleaseVersion(a);
+ const pb = parseReleaseVersion(b);
+ return !!pa && !!pb && pa.every((part, i) => part === pb[i]);
+}
+
interface UpdateSectionProps {
/** Null for a read-only viewer who cannot use a runtime as the command channel. */
runtimeId: string | null;
@@ -114,87 +140,107 @@ export function UpdateSection({
const { t } = useT("runtimes");
const isManaged = launchedBy === "desktop";
const [latestVersion, setLatestVersion] = useState<string | null>(null);
- const [status, setStatus] = useState<RuntimeUpdateStatus | null>(null);
- 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(() => {
- if (pollRef.current) {
- clearInterval(pollRef.current);
- pollRef.current = null;
- }
- }, []);
-
- useEffect(() => cleanup, [cleanup]);
+ // The machine's update as the server last reported it.
+ const [update, setUpdate] = useState<RuntimeUpdate | null>(null);
+ const [note, setNote] = useState<Note | null>(null);
+ const [submitting, setSubmitting] = useState(false);
+ const [cancelling, setCancelling] = useState(false);
// Fetch latest version on mount.
useEffect(() => {
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],
- );
+ // A reload, or another runtime of the same daemon, picks up the queue.
+ // Switching machines replaces whatever the previous one showed.
+ useEffect(() => {
+ setUpdate(null);
+ setNote(null);
+ if (!runtimeId) return;
+ let stale = false;
+ api
+ .getActiveUpdate(runtimeId)
+ .then((active) => {
+ // Keep an update this page started while the lookup was in flight.
+ if (!stale) setUpdate((prev) => active ?? prev);
+ })
+ .catch(() => {});
+ return () => {
+ stale = true;
+ };
+ }, [runtimeId]);
+
+ const updateId = update?.id ?? null;
+ const polling = !!update && UNFINISHED.has(update.status);
+ const queued = update?.status === "scheduled";
+ useEffect(() => {
+ if (!runtimeId || !updateId || !polling) return;
+ const timer = setInterval(
+ async () => {
+ try {
+ const next = await api.getUpdateResult(runtimeId, updateId);
+ setUpdate((prev) => (prev?.id === next.id ? next : prev));
+ } catch {
+ // ignore poll errors
+ }
+ },
+ queued ? 10_000 : 2_000,
+ );
+ return () => clearInterval(timer);
+ }, [runtimeId, updateId, polling, queued]);
+ // The daemon restarts right after installing, often before its report
+ // lands; the runtime reporting the target version is proof enough. Only an
+ // exact match counts: a CLI request may target an older version.
useEffect(() => {
- if (!updating || !targetVersion || !currentVersion) return;
- if (!isNewer(targetVersion, currentVersion)) {
- markCompleted(`Updated to ${targetVersion}`);
+ if (update?.status !== "running" || !currentVersion) return;
+ if (sameReleaseVersion(update.target_version, currentVersion)) {
+ setUpdate({ ...update, status: "completed", output: `Updated to ${update.target_version}` });
}
- }, [currentVersion, markCompleted, targetVersion, updating]);
+ }, [currentVersion, update]);
+
+ // Let the re-fetched runtime show the new version after a moment.
+ useEffect(() => {
+ if (update?.status !== "completed") return;
+ const timer = setTimeout(() => setUpdate(null), 5000);
+ return () => clearTimeout(timer);
+ }, [update?.status]);
const handleUpdate = async () => {
if (!latestVersion || !runtimeId) return;
- cleanup();
- setUpdating(true);
- setTargetVersion(latestVersion);
- setStatus("pending");
- setError("");
- setOutput("");
-
+ setSubmitting(true);
+ setNote(null);
try {
- const update = await api.initiateUpdate(runtimeId, latestVersion);
+ setUpdate(await api.initiateUpdate(runtimeId, latestVersion));
+ } catch (err) {
+ // 409: the machine already has an update (e.g. from another tab); show it.
+ const active =
+ err instanceof ApiError && err.status === 409
+ ? await api.getActiveUpdate(runtimeId).catch(() => null)
+ : null;
+ setUpdate(active);
+ if (!active) setNote("initiate_failed");
+ } finally {
+ setSubmitting(false);
+ }
+ };
- pollRef.current = setInterval(async () => {
- try {
- const result = await api.getUpdateResult(runtimeId, update.id);
- setStatus(result.status as RuntimeUpdateStatus);
-
- if (result.status === "completed") {
- markCompleted(
- result.output ?? `Updated to ${targetVersion ?? latestVersion}`,
- );
- } else if (
- result.status === "failed" ||
- result.status === "timeout"
- ) {
- setError(result.error ?? t(($) => $.update.unknown_error));
- setUpdating(false);
- setTargetVersion(null);
- cleanup();
- }
- } catch {
- // ignore poll errors
- }
- }, 2000);
- } catch {
- setStatus("failed");
- setError(t(($) => $.update.initiate_failed));
- setUpdating(false);
- setTargetVersion(null);
+ const handleCancel = async () => {
+ if (!runtimeId || !update) return;
+ setCancelling(true);
+ setNote(null);
+ try {
+ const cancelled = await api.cancelUpdate(runtimeId, update.id);
+ setUpdate(cancelled.status === "cancelled" ? null : cancelled);
+ } catch (err) {
+ const conflict = err instanceof ApiError && err.status === 409;
+ const latest = await api.getUpdateResult(runtimeId, update.id).catch(() => null);
+ if (latest) setUpdate(latest.status === "cancelled" ? null : latest);
+ // A 409 means it started or ended meanwhile; only a start needs saying.
+ if (!conflict) setNote("cancel_failed");
+ else if (latest?.status === "running") setNote("cancel_conflict");
+ } finally {
+ setCancelling(false);
}
};
@@ -210,6 +256,13 @@ export function UpdateSection({
const isLocalBuild =
!!currentVersion && parseReleaseVersion(currentVersion) === null;
+ // Cancelled, expired, and neutral failures leave the card idle with a note.
+ const neutral = update ? neutralFailure(update) : null;
+ const status: ShownStatus | null =
+ update && !neutral && update.status in statusConfig
+ ? (update.status as ShownStatus)
+ : null;
+ const shownNote = note ?? neutral;
const config = status ? statusConfig[status] : null;
const Icon = config?.icon;
const isActive = status === "pending" || status === "running";
@@ -276,7 +329,7 @@ export function UpdateSection({
variant="outline"
size="xs"
onClick={handleUpdate}
- disabled={updating}
+ disabled={submitting}
>
<ArrowUpCircle className="h-3 w-3" />
{t(($) => $.update.action)}
@@ -291,19 +344,39 @@ export function UpdateSection({
>
<Icon className={`h-3 w-3 ${isActive ? "animate-spin" : ""}`} />
{t(($) => $.update.status[status])}
+ {status === "scheduled" && update?.target_version && (
+ <span className="font-mono">→ {update.target_version}</span>
+ )}
</span>
)}
+
+ {update?.cancellable && UNFINISHED.has(update.status) && runtimeId && (
+ <Button variant="ghost" size="xs" onClick={handleCancel} disabled={cancelling}>
+ {t(($) => $.update.cancel)}
+ </Button>
+ )}
</div>
- {status === "completed" && output && (
+ {status === "scheduled" && (
+ <p className="text-caption text-muted-foreground">
+ {update?.active_tasks
+ ? `${t(($) => $.update.scheduled_tasks, { running: update.active_tasks })} · `
+ : ""}
+ {t(($) => $.update.note_no_interrupt)}
+ </p>
+ )}
+
+ {status === "completed" && update?.output && (
<div className="rounded-lg border bg-success/5 px-3 py-2">
- <p className="text-caption text-success">{output}</p>
+ <p className="text-caption text-success">{update.output}</p>
</div>
)}
- {(status === "failed" || status === "timeout") && error && (
+ {(status === "failed" || status === "timeout") && (
<div className="rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2">
- <p className="text-caption text-destructive">{error}</p>
+ <p className="text-caption text-destructive">
+ {update?.error || t(($) => $.update.unknown_error)}
+ </p>
{status === "failed" && (
<Button
variant="ghost"
@@ -316,6 +389,23 @@ export function UpdateSection({
)}
</div>
)}
+
+ {shownNote && (
+ <p
+ className={`text-caption ${shownNote === "initiate_failed" ? "text-destructive" : "text-muted-foreground"}`}
+ >
+ {
+ {
+ expired: t(($) => $.update.expired_note),
+ busy: t(($) => $.update.busy_note),
+ another_update: t(($) => $.update.another_update_note),
+ cancel_failed: t(($) => $.update.cancel_failed),
+ cancel_conflict: t(($) => $.update.cancel_conflict),
+ initiate_failed: t(($) => $.update.initiate_failed),
+ }[shownNote]
+ }
+ </p>
+ )}
</div>
);
}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index f03657376d..f850c86d53 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -2604,7 +2604,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/rate-limits", h.GetRuntimeRateLimits)
r.Get("/activity", h.GetRuntimeTaskActivity)
r.Post("/update", h.InitiateUpdate)
+ r.Get("/update", h.GetActiveUpdate)
r.Get("/update/{updateId}", h.GetUpdate)
+ r.Post("/update/{updateId}/cancel", h.CancelUpdate)
r.Post("/models", h.InitiateListModels)
r.Get("/models/{requestId}", h.GetModelListRequest)
r.Post("/local-skills", h.InitiateListLocalSkills)
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index 76e07b438d..1382d31b74 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -897,8 +897,9 @@ type (
func (c *Client) SendHeartbeat(ctx context.Context, runtimeID string) (*HeartbeatResponse, error) {
var resp HeartbeatResponse
if err := c.postJSON(ctx, "/api/daemon/heartbeat", map[string]any{
- "runtime_id": runtimeID,
- "supports_batch_import": true,
+ "runtime_id": runtimeID,
+ "supports_batch_import": true,
+ "supports_queued_update": true,
}, &resp); err != nil {
return nil, err
}
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 23ce9a465a..71974a5a87 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -672,6 +672,10 @@ type Daemon struct {
brewInstall bool // resolved once: was this binary installed via brew?
brewPrefix string // Homebrew prefix when brewInstall and it resolved; the stable path is derived per call by cli.StableExecutablePath
updating atomic.Bool // prevents concurrent update attempts
+ // queuedUpdate is a deferrable update held until the daemon is idle; see
+ // queued_update.go. Guarded by queuedUpdateMu.
+ queuedUpdateMu sync.Mutex
+ queuedUpdate *queuedServerUpdate
// activeTasks is the ownership-safe count of tasks currently in handleTask.
// It deliberately includes preparation and local-directory waiters because
// restart/update barriers must not kill any claimed task.
@@ -5176,6 +5180,10 @@ func (d *Daemon) handleUpdate(ctx context.Context, runtimeID string, update *Pen
})
return
}
+ if update.Deferrable {
+ d.handleQueuedUpdate(ctx, runtimeID, update)
+ return
+ }
switch d.tryBeginServerUpdate(ctx) {
case serverUpdateAlreadyRunning:
@@ -5193,6 +5201,16 @@ func (d *Daemon) handleUpdate(ctx context.Context, runtimeID string, update *Pen
})
return
}
+ d.logger.Info("CLI update requested", "runtime_id", runtimeID, "update_id", update.ID, "target_version", update.TargetVersion)
+ d.reportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
+ "status": "running",
+ })
+ d.runAcquiredServerUpdate(ctx, runtimeID, update.ID, update.TargetVersion)
+}
+
+// runAcquiredServerUpdate installs targetVersion and restarts. The caller has
+// won tryBeginServerUpdate and already reported "running".
+func (d *Daemon) runAcquiredServerUpdate(ctx context.Context, runtimeID, updateID, targetVersion string) {
restarting := false
defer func() {
if !restarting {
@@ -5201,17 +5219,10 @@ 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.reportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
- "status": "running",
- })
-
- output, err := d.runUpdateFn(update.TargetVersion)
+ output, err := d.runUpdateFn(targetVersion)
if err != nil {
d.logger.Error("CLI update failed", "error", err, "output", output)
- d.reportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
+ d.reportUpdateResult(ctx, runtimeID, updateID, map[string]any{
"status": "failed",
"error": err.Error(),
})
@@ -5219,9 +5230,9 @@ func (d *Daemon) handleUpdate(ctx context.Context, runtimeID string, update *Pen
}
d.logger.Info("CLI update completed successfully", "output", output)
- d.reportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
+ d.reportUpdateResult(ctx, runtimeID, updateID, map[string]any{
"status": "completed",
- "output": fmt.Sprintf("Updated to %s", update.TargetVersion),
+ "output": fmt.Sprintf("Updated to %s", targetVersion),
})
// Trigger daemon restart with the new binary.
@@ -5313,13 +5324,15 @@ func (d *Daemon) runUpdate(targetVersion string) (string, error) {
// 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 {
+func (d *Daemon) reportUpdateResult(ctx context.Context, runtimeID, updateID string, payload map[string]any) error {
+ return 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) {
+// reportUpdateResultWithRetry returns nil once a report is accepted, or the
+// last error.
+func (d *Daemon) reportUpdateResultWithRetry(ctx context.Context, runtimeID, updateID string, fn func(context.Context) error) error {
var lastErr error
for attempt, wait := range updateReportBackoffs {
if wait > 0 {
@@ -5328,7 +5341,7 @@ func (d *Daemon) reportUpdateResultWithRetry(ctx context.Context, runtimeID, upd
d.logger.Error("CLI update report cancelled",
"runtime_id", runtimeID, "update_id", updateID,
"attempt", attempt, "error", ctx.Err())
- return
+ return ctx.Err()
case <-time.After(wait):
}
}
@@ -5340,7 +5353,7 @@ func (d *Daemon) reportUpdateResultWithRetry(ctx context.Context, runtimeID, upd
"runtime_id", runtimeID, "update_id", updateID,
"attempt", attempt+1)
}
- return
+ return nil
}
lastErr = err
@@ -5349,7 +5362,7 @@ func (d *Daemon) reportUpdateResultWithRetry(ctx context.Context, runtimeID, upd
d.logger.Error("CLI update report rejected — not retrying",
"runtime_id", runtimeID, "update_id", updateID,
"status", reqErr.StatusCode, "error", err)
- return
+ return err
}
d.logger.Warn("CLI update report failed — will retry",
@@ -5358,6 +5371,7 @@ func (d *Daemon) reportUpdateResultWithRetry(ctx context.Context, runtimeID, upd
}
d.logger.Error("CLI update report exhausted retries",
"runtime_id", runtimeID, "update_id", updateID, "error", lastErr)
+ return lastErr
}
// tryEnterClaim records the intent to call ClaimTask. Returns true if the
@@ -5667,7 +5681,7 @@ func (d *Daemon) runBatchPoller(pollerCtx, parentCtx context.Context, sem chan i
}
go func(t Task, slot int) {
defer taskWG.Done()
- defer d.activeTasks.Add(-1)
+ defer d.finishActiveTask()
executionSlot := newTaskSlotLease(sem, slot, wakeup)
defer executionSlot.release()
d.handleTask(parentCtx, t, executionSlot)
diff --git a/server/internal/daemon/queued_update.go b/server/internal/daemon/queued_update.go
new file mode 100644
index 0000000000..f8fc97361f
--- /dev/null
+++ b/server/internal/daemon/queued_update.go
@@ -0,0 +1,152 @@
+package daemon
+
+import (
+ "context"
+ "errors"
+ "net/http"
+)
+
+// queuedServerUpdate is a deferrable update from the Runtimes page that
+// arrived while agent work was running. The daemon holds it — without pausing
+// claims — and starts it the moment its last task finishes.
+//
+// The daemon holds at most one, and refuses a different update while holding
+// or installing one. One daemon is one machine, so this is what keeps a
+// machine to a single update even when its runtimes span several workspaces.
+//
+// The server stays the source of truth: it re-offers a waiting update on every
+// heartbeat (so a restarted daemon picks it up again) and refuses the
+// "scheduled" / "running" reports with 409 once it was cancelled or expired.
+// The daemon installs only after the server accepted "running".
+type queuedServerUpdate struct {
+ runtimeID string
+ id string
+ targetVersion string
+ // reportedTasks is the task count last reported as "scheduled", or -1.
+ reportedTasks int64
+ // installing is set once the server accepted "running". The update stays
+ // held while it installs, so a re-offer that was already in flight is
+ // recognised as the same update rather than refused as a second one.
+ installing bool
+}
+
+const errAnotherUpdateQueued = "another runtime update is already queued or in progress on this machine"
+
+func (d *Daemon) handleQueuedUpdate(ctx context.Context, runtimeID string, update *PendingUpdate) {
+ d.queuedUpdateMu.Lock()
+ defer d.queuedUpdateMu.Unlock()
+
+ held := d.queuedUpdate
+ if held != nil && held.installing {
+ // A re-offer of the installing update is ignored, not refused.
+ if held.id != update.ID {
+ d.reportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
+ "status": "failed",
+ "error": errAnotherUpdateQueued,
+ })
+ }
+ return
+ }
+ if held != nil && held.id != update.ID {
+ // The held update may have been cancelled or expired since; a
+ // refused "scheduled" report says so and frees the slot.
+ if !isUpdateWithdrawn(d.reportQueuedUpdateWaiting(ctx, held)) {
+ d.reportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
+ "status": "failed",
+ "error": errAnotherUpdateQueued,
+ })
+ return
+ }
+ d.queuedUpdate, held = nil, nil
+ }
+ if held == nil {
+ if d.updating.Load() {
+ d.reportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
+ "status": "failed",
+ "error": errAnotherUpdateQueued,
+ })
+ return
+ }
+ d.queuedUpdate = &queuedServerUpdate{
+ runtimeID: runtimeID,
+ id: update.ID,
+ targetVersion: update.TargetVersion,
+ reportedTasks: -1,
+ }
+ }
+ d.tryQueuedUpdateLocked(ctx)
+}
+
+// finishActiveTask ends a task's activeTasks slot and, when the daemon just
+// became idle, starts a held update.
+func (d *Daemon) finishActiveTask() {
+ if d.activeTasks.Add(-1) == 0 {
+ go func() {
+ d.queuedUpdateMu.Lock()
+ defer d.queuedUpdateMu.Unlock()
+ d.tryQueuedUpdateLocked(d.recoveryContext())
+ }()
+ }
+}
+
+func (d *Daemon) tryQueuedUpdateLocked(ctx context.Context) {
+ held := d.queuedUpdate
+ if held == nil || held.installing {
+ return
+ }
+
+ switch d.tryBeginServerUpdate(ctx) {
+ case serverUpdateAlreadyRunning:
+ // Auto-update owns the machine; the next offer tries again.
+ return
+ case serverUpdateRuntimeBusy:
+ if active := d.activeTasks.Load(); active != held.reportedTasks {
+ d.logger.Info("update queued until the daemon is idle", "runtime_id", held.runtimeID, "update_id", held.id, "active_tasks", active)
+ err := d.reportQueuedUpdateWaiting(ctx, held)
+ switch {
+ case err == nil:
+ held.reportedTasks = active
+ case isUpdateWithdrawn(err):
+ d.queuedUpdate = nil
+ }
+ }
+ return
+ }
+
+ // Idle, with claims paused. Install only if the server still wants it.
+ err := d.reportUpdateResult(ctx, held.runtimeID, held.id, map[string]any{"status": "running"})
+ if err != nil {
+ d.releaseClaimBarrier()
+ d.updating.Store(false)
+ if isUpdateWithdrawn(err) {
+ d.logger.Info("queued update dropped: cancelled or expired", "runtime_id", held.runtimeID, "update_id", held.id)
+ d.queuedUpdate = nil
+ }
+ return
+ }
+ held.installing = true
+ d.logger.Info("CLI update requested", "runtime_id", held.runtimeID, "update_id", held.id, "target_version", held.targetVersion)
+ go func() {
+ d.runAcquiredServerUpdate(ctx, held.runtimeID, held.id, held.targetVersion)
+ // Reached on failure; a successful install restarts the daemon.
+ d.queuedUpdateMu.Lock()
+ if d.queuedUpdate == held {
+ d.queuedUpdate = nil
+ }
+ d.queuedUpdateMu.Unlock()
+ }()
+}
+
+func (d *Daemon) reportQueuedUpdateWaiting(ctx context.Context, held *queuedServerUpdate) error {
+ return d.reportUpdateResult(ctx, held.runtimeID, held.id, map[string]any{
+ "status": "scheduled",
+ "active_tasks": d.activeTasks.Load(),
+ })
+}
+
+// isUpdateWithdrawn reports the server refusing a held update: cancelled,
+// expired or finished (409), or gone (404).
+func isUpdateWithdrawn(err error) bool {
+ var reqErr *requestError
+ return errors.As(err, &reqErr) && (reqErr.StatusCode == http.StatusConflict || reqErr.StatusCode == http.StatusNotFound)
+}
diff --git a/server/internal/daemon/queued_update_test.go b/server/internal/daemon/queued_update_test.go
new file mode 100644
index 0000000000..7e82f9d516
--- /dev/null
+++ b/server/internal/daemon/queued_update_test.go
@@ -0,0 +1,210 @@
+package daemon
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+type updateReport struct {
+ updateID string
+ payload map[string]any
+}
+
+// queuedUpdateDaemon returns a daemon whose update reports are recorded and
+// answered by respond (nil answers 200).
+func queuedUpdateDaemon(t *testing.T, respond func(updateReport) int) (*Daemon, func() []updateReport) {
+ t.Helper()
+ withFastUpdateReportBackoffs(t)
+ var mu sync.Mutex
+ var reports []updateReport
+ d, _ := updateReportDaemon(t, func(w http.ResponseWriter, r *http.Request) {
+ var rep updateReport
+ parts := strings.Split(r.URL.Path, "/")
+ rep.updateID = parts[len(parts)-2]
+ if err := json.NewDecoder(r.Body).Decode(&rep.payload); err != nil {
+ t.Errorf("decode update report: %v", err)
+ }
+ mu.Lock()
+ reports = append(reports, rep)
+ mu.Unlock()
+ code := http.StatusOK
+ if respond != nil {
+ code = respond(rep)
+ }
+ w.WriteHeader(code)
+ })
+ d.runUpdateFn = func(string) (string, error) {
+ t.Fatal("runUpdateFn must not run")
+ return "", nil
+ }
+ return d, func() []updateReport {
+ mu.Lock()
+ defer mu.Unlock()
+ return append([]updateReport(nil), reports...)
+ }
+}
+
+func deferrable(id string) *PendingUpdate {
+ return &PendingUpdate{ID: id, TargetVersion: "v0.12.0", Deferrable: true}
+}
+
+func statuses(reports []updateReport) []string {
+ out := make([]string, len(reports))
+ for i, r := range reports {
+ out[i] = r.updateID + ":" + r.payload["status"].(string)
+ }
+ return out
+}
+
+func TestQueuedUpdate_HeldWhileBusyAndStartedWhenIdle(t *testing.T) {
+ d, reports := queuedUpdateDaemon(t, nil)
+ d.activeTasks.Store(2)
+
+ d.handleUpdate(context.Background(), "runtime-1", deferrable("update-1"))
+ // A re-offer with an unchanged task count reports nothing new.
+ d.handleUpdate(context.Background(), "runtime-1", deferrable("update-1"))
+
+ got := reports()
+ if len(got) != 1 || got[0].payload["status"] != "scheduled" || got[0].payload["active_tasks"] != float64(2) {
+ t.Fatalf("reports = %+v, want one scheduled report with 2 active tasks", got)
+ }
+ d.claimMu.Lock()
+ paused := d.pauseClaims
+ d.claimMu.Unlock()
+ if paused || d.updating.Load() {
+ t.Fatal("holding an update must not pause claims")
+ }
+
+ installed := make(chan string, 1)
+ d.runUpdateFn = func(target string) (string, error) {
+ installed <- target
+ return "", errors.New("stop before restart")
+ }
+ d.finishActiveTask()
+ d.finishActiveTask()
+
+ select {
+ case target := <-installed:
+ if target != "v0.12.0" {
+ t.Fatalf("installed %q", target)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("held update did not start once the daemon became idle")
+ }
+ waitFor(t, func() bool { return len(reports()) == 3 }, "install result reported")
+ if got := statuses(reports()); got[1] != "update-1:running" || got[2] != "update-1:failed" {
+ t.Fatalf("reports = %v", got)
+ }
+}
+
+func TestQueuedUpdate_RefusedStartIsNotInstalled(t *testing.T) {
+ d, reports := queuedUpdateDaemon(t, func(r updateReport) int {
+ if r.payload["status"] == "running" {
+ return http.StatusConflict // cancelled or expired meanwhile
+ }
+ return http.StatusOK
+ })
+ d.activeTasks.Store(1)
+ d.handleUpdate(context.Background(), "runtime-1", deferrable("update-1"))
+
+ d.activeTasks.Store(0)
+ d.handleUpdate(context.Background(), "runtime-1", deferrable("update-1"))
+
+ if got := statuses(reports()); len(got) != 2 || got[1] != "update-1:running" {
+ t.Fatalf("reports = %v", got)
+ }
+ if d.queuedUpdate != nil {
+ t.Fatal("a refused update must be dropped")
+ }
+ d.claimMu.Lock()
+ paused := d.pauseClaims
+ d.claimMu.Unlock()
+ if paused || d.updating.Load() {
+ t.Fatal("a refused start must release the claim barrier")
+ }
+}
+
+func TestQueuedUpdate_OneUpdatePerMachine(t *testing.T) {
+ var withdrawn atomic.Bool
+ d, reports := queuedUpdateDaemon(t, func(r updateReport) int {
+ if r.updateID == "update-1" && withdrawn.Load() {
+ return http.StatusConflict
+ }
+ return http.StatusOK
+ })
+ d.activeTasks.Store(1)
+ d.handleUpdate(context.Background(), "runtime-ws-a", deferrable("update-1"))
+
+ // Another workspace's runtime on the same daemon asks for a second update.
+ d.handleUpdate(context.Background(), "runtime-ws-b", deferrable("update-2"))
+ got := reports()
+ last := got[len(got)-1]
+ if last.updateID != "update-2" || last.payload["status"] != "failed" || last.payload["error"] != errAnotherUpdateQueued {
+ t.Fatalf("second update reports = %v, want it refused", statuses(got))
+ }
+ if d.queuedUpdate == nil || d.queuedUpdate.id != "update-1" {
+ t.Fatal("the held update must stay held")
+ }
+
+ // Once the held one is cancelled, the next one takes the slot.
+ withdrawn.Store(true)
+ d.handleUpdate(context.Background(), "runtime-ws-b", deferrable("update-3"))
+ if d.queuedUpdate == nil || d.queuedUpdate.id != "update-3" {
+ t.Fatalf("held = %+v, want update-3", d.queuedUpdate)
+ }
+}
+
+func TestQueuedUpdate_RefusedWhileInstalling(t *testing.T) {
+ d, reports := queuedUpdateDaemon(t, nil)
+ d.updating.Store(true)
+
+ d.handleUpdate(context.Background(), "runtime-1", deferrable("update-2"))
+
+ got := reports()
+ if len(got) != 1 || got[0].payload["status"] != "failed" || got[0].payload["error"] != errAnotherUpdateQueued {
+ t.Fatalf("reports = %v, want the update refused", statuses(got))
+ }
+ if d.queuedUpdate != nil {
+ t.Fatal("nothing should be held while another update installs")
+ }
+}
+
+// A re-offer computed before the server accepted "running" can arrive while
+// the update installs; it must not be reported as a failure of itself.
+func TestQueuedUpdate_ReofferWhileInstallingIsIgnored(t *testing.T) {
+ d, reports := queuedUpdateDaemon(t, nil)
+ release := make(chan struct{})
+ installed := make(chan struct{})
+ d.runUpdateFn = func(string) (string, error) {
+ close(installed)
+ <-release
+ return "", errors.New("stop before restart")
+ }
+
+ d.handleUpdate(context.Background(), "runtime-1", deferrable("update-1"))
+ <-installed
+ d.handleUpdate(context.Background(), "runtime-1", deferrable("update-1"))
+ d.handleUpdate(context.Background(), "runtime-2", deferrable("update-2"))
+ close(release)
+
+ waitFor(t, func() bool { return len(reports()) == 3 }, "install result reported")
+ got := statuses(reports())
+ want := []string{"update-1:running", "update-2:failed", "update-1:failed"}
+ for i := range want {
+ if got[i] != want[i] {
+ t.Fatalf("reports = %v, want %v", got, want)
+ }
+ }
+ waitFor(t, func() bool {
+ d.queuedUpdateMu.Lock()
+ defer d.queuedUpdateMu.Unlock()
+ return d.queuedUpdate == nil
+ }, "failed install releases the slot")
+}
diff --git a/server/internal/daemon/wakeup.go b/server/internal/daemon/wakeup.go
index b0c118cc3d..539df5bb32 100644
--- a/server/internal/daemon/wakeup.go
+++ b/server/internal/daemon/wakeup.go
@@ -315,7 +315,7 @@ func (d *Daemon) sendWSHeartbeats(ctx context.Context, runtimeIDs []string, writ
}
frame, err := json.Marshal(protocol.Message{
Type: protocol.EventDaemonHeartbeat,
- Payload: marshalRaw(protocol.DaemonHeartbeatRequestPayload{RuntimeID: rid, SupportsBatchImport: true}),
+ Payload: marshalRaw(protocol.DaemonHeartbeatRequestPayload{RuntimeID: rid, SupportsBatchImport: true, SupportsQueuedUpdate: true}),
})
if err != nil {
d.logger.Debug("ws heartbeat marshal failed", "error", err, "runtime_id", rid)
diff --git a/server/internal/daemonws/hub.go b/server/internal/daemonws/hub.go
index 53a696d5a1..92058a3ff1 100644
--- a/server/internal/daemonws/hub.go
+++ b/server/internal/daemonws/hub.go
@@ -294,7 +294,7 @@ func (h *Hub) forgetRuntimeGoneSeen(eventID string) {
// runtimeID is one of identity.RuntimeIDs (the connection's authenticated
// scope) and return the ack payload to send back. Returning an error skips
// the ack and is logged at debug level.
-type HeartbeatHandler func(ctx context.Context, identity ClientIdentity, runtimeID string, supportsBatchImport bool) (*protocol.DaemonHeartbeatAckPayload, error)
+type HeartbeatHandler func(ctx context.Context, identity ClientIdentity, runtimeID string, req protocol.DaemonHeartbeatRequestPayload) (*protocol.DaemonHeartbeatAckPayload, error)
// RPCHandler processes a generic daemon:rpc_request (MUL-4257). It dispatches
// on method (e.g. "tasks.claim"), scoping work to identity (DaemonID +
@@ -1117,7 +1117,7 @@ func (c *client) handleHeartbeatFrame(raw json.RawMessage) {
// that keeps the HTTP heartbeat from putting a per-call timeout on
// PopPending. The natural bound is the read pump's lifetime (the conn
// closes if the daemon goes away) plus Redis's own server-side limits.
- ack, err := handler(context.Background(), c.identity, payload.RuntimeID, payload.SupportsBatchImport)
+ ack, err := handler(context.Background(), c.identity, payload.RuntimeID, payload)
if err != nil {
slog.Warn("daemon websocket heartbeat handler failed",
"error", err,
diff --git a/server/internal/daemonws/hub_test.go b/server/internal/daemonws/hub_test.go
index 207650b6c7..111d6d5db2 100644
--- a/server/internal/daemonws/hub_test.go
+++ b/server/internal/daemonws/hub_test.go
@@ -455,7 +455,7 @@ func TestHeartbeatRoundTrip(t *testing.T) {
hub := NewHub()
var calls atomic.Int32
- hub.SetHeartbeatHandler(func(_ context.Context, identity ClientIdentity, runtimeID string, _ bool) (*protocol.DaemonHeartbeatAckPayload, error) {
+ hub.SetHeartbeatHandler(func(_ context.Context, identity ClientIdentity, runtimeID string, _ protocol.DaemonHeartbeatRequestPayload) (*protocol.DaemonHeartbeatAckPayload, error) {
calls.Add(1)
if identity.WorkspaceID != "ws-1" {
t.Errorf("identity workspace = %q, want ws-1", identity.WorkspaceID)
@@ -537,7 +537,7 @@ func TestHeartbeatHandlerCtxNotTimeBounded(t *testing.T) {
hub := NewHub()
const stall = 250 * time.Millisecond
- hub.SetHeartbeatHandler(func(ctx context.Context, _ ClientIdentity, runtimeID string, _ bool) (*protocol.DaemonHeartbeatAckPayload, error) {
+ hub.SetHeartbeatHandler(func(ctx context.Context, _ ClientIdentity, runtimeID string, _ protocol.DaemonHeartbeatRequestPayload) (*protocol.DaemonHeartbeatAckPayload, error) {
select {
case <-time.After(stall):
case <-ctx.Done():
@@ -598,7 +598,7 @@ func TestHeartbeatRejectsUnauthorizedRuntime(t *testing.T) {
hub := NewHub()
var called atomic.Bool
- hub.SetHeartbeatHandler(func(context.Context, ClientIdentity, string, bool) (*protocol.DaemonHeartbeatAckPayload, error) {
+ hub.SetHeartbeatHandler(func(context.Context, ClientIdentity, string, protocol.DaemonHeartbeatRequestPayload) (*protocol.DaemonHeartbeatAckPayload, error) {
called.Store(true)
return &protocol.DaemonHeartbeatAckPayload{Status: "ok"}, nil
})
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index c07a8426c9..507f8ed3ce 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -1441,10 +1441,7 @@ func (h *Handler) DaemonDeregister(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
-type DaemonHeartbeatRequest struct {
- RuntimeID string `json:"runtime_id"`
- SupportsBatchImport bool `json:"supports_batch_import,omitempty"`
-}
+type DaemonHeartbeatRequest = protocol.DaemonHeartbeatRequestPayload
// heartbeatHasPendingTimeout bounds the cheap HasPending probe on the
// heartbeat hot path. Probes are read-only (ZCARD in Redis) so a timeout is
@@ -1585,7 +1582,7 @@ func (h *Handler) DaemonHeartbeat(w http.ResponseWriter, r *http.Request) {
}
updateMs = time.Since(updateStart).Milliseconds()
- ack, m, err := h.processHeartbeat(r.Context(), runtimeID, req.SupportsBatchImport)
+ ack, m, err := h.processHeartbeat(r.Context(), runtimeID, req)
probeModelMs = m.ProbeModelMs
popModelMs = m.PopModelMs
probeSkillsMs = m.ProbeSkillsMs
@@ -1629,7 +1626,7 @@ func (h *Handler) DaemonHeartbeat(w http.ResponseWriter, r *http.Request) {
// captured each runtime's liveness state in a connection lease, so the hot
// path never reads agent_runtime. HTTP heartbeat remains the stateless lookup
// fallback for a daemon that stops receiving WebSocket acknowledgements.
-func (h *Handler) HandleDaemonWSHeartbeat(ctx context.Context, identity daemonws.ClientIdentity, runtimeID string, supportsBatchImport bool) (*protocol.DaemonHeartbeatAckPayload, error) {
+func (h *Handler) HandleDaemonWSHeartbeat(ctx context.Context, identity daemonws.ClientIdentity, runtimeID string, req protocol.DaemonHeartbeatRequestPayload) (*protocol.DaemonHeartbeatAckPayload, error) {
lease := identity.RuntimeLeases[runtimeID]
if lease == nil {
return nil, fmt.Errorf("runtime not in connection lease")
@@ -1649,7 +1646,7 @@ func (h *Handler) HandleDaemonWSHeartbeat(ctx context.Context, identity daemonws
}
return nil, err
}
- ack, _, err := h.processHeartbeat(ctx, runtimeID, supportsBatchImport)
+ ack, _, err := h.processHeartbeat(ctx, runtimeID, req)
return ack, err
}
@@ -1789,7 +1786,7 @@ type heartbeatMetrics struct {
// heartbeats using only the runtime ID. Each transport records liveness first:
// HTTP uses its stateless runtime row, while WebSocket uses the connection
// lease. Auth and request decoding also remain transport-specific.
-func (h *Handler) processHeartbeat(ctx context.Context, runtimeID string, supportsBatchImport bool) (*protocol.DaemonHeartbeatAckPayload, heartbeatMetrics, error) {
+func (h *Handler) processHeartbeat(ctx context.Context, runtimeID string, req protocol.DaemonHeartbeatRequestPayload) (*protocol.DaemonHeartbeatAckPayload, heartbeatMetrics, error) {
var m heartbeatMetrics
slog.Debug("daemon heartbeat", "runtime_id", runtimeID)
@@ -1805,13 +1802,14 @@ func (h *Handler) processHeartbeat(ctx context.Context, runtimeID string, suppor
cancelProbeUpdate()
switch {
case probeUpdateErr == nil && hasUpdate:
- pending, popUpdateErr := h.UpdateStore.PopPending(ctx, runtimeID)
+ pending, popUpdateErr := h.UpdateStore.PopPending(ctx, runtimeID, req.SupportsQueuedUpdate)
if popUpdateErr != nil {
slog.Warn("update PopPending failed", "error", popUpdateErr, "runtime_id", runtimeID)
} else if pending != nil {
ack.PendingUpdate = &protocol.DaemonHeartbeatPendingUpdate{
ID: pending.ID,
TargetVersion: pending.TargetVersion,
+ Deferrable: offerDeferrable(pending, req.SupportsQueuedUpdate),
}
}
case probeUpdateErr != nil:
@@ -1886,7 +1884,7 @@ func (h *Handler) processHeartbeat(ctx context.Context, runtimeID string, suppor
switch {
case probeErr == nil && hasImport:
popStart := time.Now()
- if supportsBatchImport {
+ if req.SupportsBatchImport {
pendingImports, popErr := h.LocalSkillImportStore.PopPendingBatch(ctx, runtimeID, maxLocalSkillImportBatch)
m.PopImportMs = time.Since(popStart).Milliseconds()
if popErr != nil {
diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.go
index e987b0c790..3466fd23f7 100644
--- a/server/internal/handler/daemon_test.go
+++ b/server/internal/handler/daemon_test.go
@@ -921,7 +921,7 @@ func TestHandleDaemonWSHeartbeat_RuntimeGoneReturnsAckNotError(t *testing.T) {
missingRuntime: daemonws.NewRuntimeLease(testWorkspaceID, "online", time.Now().Add(-2*runtimeHeartbeatDBFlushInterval), true),
},
},
- missingRuntime, false)
+ missingRuntime, protocol.DaemonHeartbeatRequestPayload{})
if err != nil {
t.Fatalf("HandleDaemonWSHeartbeat: unexpected error %v", err)
}
@@ -965,7 +965,7 @@ func TestHandleDaemonWSHeartbeat_AllowsAnyAuthorizedWorkspace(t *testing.T) {
runtimeID: daemonws.NewRuntimeLease(workspaceID, "online", time.Now(), true),
},
},
- runtimeID, false)
+ runtimeID, protocol.DaemonHeartbeatRequestPayload{})
if err != nil {
t.Fatalf("HandleDaemonWSHeartbeat: unexpected error %v", err)
}
diff --git a/server/internal/handler/runtime_lookup_metrics_test.go b/server/internal/handler/runtime_lookup_metrics_test.go
index 7b91af9191..5eb8b8c4ec 100644
--- a/server/internal/handler/runtime_lookup_metrics_test.go
+++ b/server/internal/handler/runtime_lookup_metrics_test.go
@@ -13,6 +13,7 @@ import (
"github.com/multica-ai/multica/server/internal/daemonws"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
"github.com/multica-ai/multica/server/internal/testutil"
+ "github.com/multica-ai/multica/server/pkg/protocol"
)
// TestAgentRuntimeLookupWSHotPathIsZeroRead drives 1,000 heartbeats through one
@@ -42,7 +43,7 @@ func TestAgentRuntimeLookupWSHotPathIsZeroRead(t *testing.T) {
before := lookupSnapshot(t, m)
for i := 0; i < 1000; i++ {
- if _, err := h.HandleDaemonWSHeartbeat(ctx, identity, runtimeID, false); err != nil {
+ if _, err := h.HandleDaemonWSHeartbeat(ctx, identity, runtimeID, protocol.DaemonHeartbeatRequestPayload{}); err != nil {
t.Fatalf("HandleDaemonWSHeartbeat %d: %v", i, err)
}
}
diff --git a/server/internal/handler/runtime_update.go b/server/internal/handler/runtime_update.go
index 7f14376c5d..b5a8cc46b3 100644
--- a/server/internal/handler/runtime_update.go
+++ b/server/internal/handler/runtime_update.go
@@ -12,6 +12,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/multica-ai/multica/server/internal/logger"
obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
)
// CLI update request store
@@ -19,44 +20,112 @@ import (
type UpdateStatus string
const (
- UpdatePending UpdateStatus = "pending"
+ UpdatePending UpdateStatus = "pending"
+ // UpdateScheduled: the daemon is busy and holds the request until its last
+ // agent task finishes.
+ UpdateScheduled UpdateStatus = "scheduled"
UpdateRunning UpdateStatus = "running"
UpdateCompleted UpdateStatus = "completed"
UpdateFailed UpdateStatus = "failed"
UpdateTimeout UpdateStatus = "timeout"
+ UpdateCancelled UpdateStatus = "cancelled"
+ // UpdateExpired: the machine never became idle within updateQueueTimeout.
+ UpdateExpired UpdateStatus = "expired"
)
// UpdateRequest represents a pending or completed CLI update request.
type UpdateRequest struct {
- ID string `json:"id"`
- RuntimeID string `json:"runtime_id"`
- InitiatorUserID string `json:"-"`
- Status UpdateStatus `json:"status"`
- TargetVersion string `json:"target_version"`
- Output string `json:"output,omitempty"`
- Error string `json:"error,omitempty"`
- CreatedAt time.Time `json:"created_at"`
- UpdatedAt time.Time `json:"updated_at"`
- RunStartedAt *time.Time `json:"-"`
+ ID string `json:"id"`
+ RuntimeID string `json:"runtime_id"`
+ InitiatorUserID string `json:"-"`
+ MachineKey string `json:"-"`
+ // QueueWhenBusy is set by clients that can show a queued update. Only
+ // such requests are held by a busy daemon; others keep failing fast.
+ QueueWhenBusy bool `json:"-"`
+ Status UpdateStatus `json:"status"`
+ TargetVersion string `json:"target_version"`
+ Output string `json:"output,omitempty"`
+ Error string `json:"error,omitempty"`
+ // ActiveTasks is the daemon's running task count while scheduled.
+ ActiveTasks *int `json:"active_tasks,omitempty"`
+ Cancellable bool `json:"cancellable"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
+ RunStartedAt *time.Time `json:"-"`
}
const (
updatePendingTimeout = 120 * time.Second
updateRunningTimeout = 150 * time.Second
+ updateQueueTimeout = 24 * time.Hour
updateStoreRetention = 5 * time.Minute
+ // updateWaitingRetention keeps a waiting record (and its machine slot)
+ // alive for as long as it can still be queued.
+ updateWaitingRetention = updateQueueTimeout + updateStoreRetention
)
+var (
+ errUpdateInProgress = &updateError{msg: "an update is already in progress or queued on this machine"}
+ errUpdateWithdrawn = &updateError{msg: "this update was cancelled, expired, or has already finished"}
+ errUpdateNotCancellable = &updateError{msg: "this update can no longer be cancelled"}
+)
+
+type updateError struct{ msg string }
+
+func (e *updateError) Error() string { return e.msg }
+
+// updateTransition changes a request in place, or returns an error and
+// leaves it untouched. Stores apply it atomically, so a cancel and a start
+// racing on the same request can never both succeed.
+type updateTransition func(req *UpdateRequest, now time.Time) error
+
type UpdateStore interface {
- Create(ctx context.Context, runtimeID, targetVersion, initiatorUserID string) (*UpdateRequest, error)
+ Create(ctx context.Context, runtimeID, machineKey, targetVersion, initiatorUserID string, queueWhenBusy bool) (*UpdateRequest, error)
Get(ctx context.Context, id string) (*UpdateRequest, error)
+ // GetActive returns the unfinished request holding the machine, if any.
+ GetActive(ctx context.Context, machineKey string) (*UpdateRequest, error)
HasPending(ctx context.Context, runtimeID string) (bool, error)
- PopPending(ctx context.Context, runtimeID string) (*UpdateRequest, error)
- Complete(ctx context.Context, id string, output string) error
- Fail(ctx context.Context, id string, errMsg string) error
+ // PopPending returns the request to offer on this runtime's heartbeat.
+ // When the daemon can hold it (offerDeferrable), the request stays
+ // waiting and is offered again on every heartbeat until the daemon starts
+ // it — so a restarted daemon picks it up again. Otherwise it is marked
+ // running and offered once, exactly as before queued updates existed.
+ PopPending(ctx context.Context, runtimeID string, daemonCanQueue bool) (*UpdateRequest, error)
+ Transition(ctx context.Context, id string, fn updateTransition) (*UpdateRequest, error)
+}
+
+// updateMachineKey identifies the daemon process behind a runtime. A daemon
+// registers one runtime per provider, so this is what one update applies to.
+// The daemon ID is client-reported, so it is scoped by workspace and owner.
+// The daemon itself refuses a second update across workspaces.
+func updateMachineKey(rt db.AgentRuntime) string {
+ if rt.DaemonID.Valid && rt.DaemonID.String != "" {
+ return uuidToString(rt.WorkspaceID) + ":" + uuidToString(rt.OwnerID) + ":" + rt.DaemonID.String
+ }
+ return "runtime:" + uuidToString(rt.ID)
}
func updateRequestTerminal(status UpdateStatus) bool {
- return status == UpdateCompleted || status == UpdateFailed || status == UpdateTimeout
+ switch status {
+ case UpdateCompleted, UpdateFailed, UpdateTimeout, UpdateCancelled, UpdateExpired:
+ return true
+ }
+ return false
+}
+
+func updateRequestWaiting(status UpdateStatus) bool {
+ return status == UpdatePending || status == UpdateScheduled
+}
+
+func offerDeferrable(req *UpdateRequest, daemonCanQueue bool) bool {
+ return req.QueueWhenBusy && daemonCanQueue
+}
+
+func updateRetention(req *UpdateRequest) time.Duration {
+ if updateRequestTerminal(req.Status) {
+ return updateStoreRetention
+ }
+ return updateWaitingRetention
}
func applyUpdateTimeout(req *UpdateRequest, now time.Time) bool {
@@ -68,6 +137,13 @@ func applyUpdateTimeout(req *UpdateRequest, now time.Time) bool {
req.UpdatedAt = now
return true
}
+ case UpdateScheduled:
+ if now.Sub(req.CreatedAt) > updateQueueTimeout {
+ req.Status = UpdateExpired
+ req.Error = "the machine did not become idle within 24 hours"
+ req.UpdatedAt = now
+ return true
+ }
case UpdateRunning:
if req.RunStartedAt != nil && now.Sub(*req.RunStartedAt) > updateRunningTimeout {
req.Status = UpdateTimeout
@@ -79,6 +155,76 @@ func applyUpdateTimeout(req *UpdateRequest, now time.Time) bool {
return false
}
+// startUpdate is the daemon's go-ahead: only a request that is still waiting
+// (not cancelled or expired) may start installing. A request that is already
+// running stays running — that is a daemon without queue support confirming
+// the offer it got.
+func startUpdate(req *UpdateRequest, now time.Time) error {
+ switch {
+ case req.Status == UpdateRunning:
+ return nil
+ case updateRequestWaiting(req.Status):
+ req.Status = UpdateRunning
+ req.RunStartedAt = &now
+ req.UpdatedAt = now
+ return nil
+ }
+ return errUpdateWithdrawn
+}
+
+func scheduleUpdate(activeTasks *int) updateTransition {
+ return func(req *UpdateRequest, now time.Time) error {
+ if !updateRequestWaiting(req.Status) {
+ return errUpdateWithdrawn
+ }
+ req.Status = UpdateScheduled
+ req.ActiveTasks = activeTasks
+ req.UpdatedAt = now
+ return nil
+ }
+}
+
+// updateCancellable: only requests from clients that chose to queue can be
+// cancelled — other clients (the CLI's --wait) do not know "cancelled".
+func updateCancellable(req *UpdateRequest) bool {
+ return req.QueueWhenBusy && updateRequestWaiting(req.Status)
+}
+
+// cancelUpdate is idempotent: cancelling a cancelled request succeeds, so two
+// tabs cancelling the same update both see it cancelled.
+func cancelUpdate(req *UpdateRequest, now time.Time) error {
+ if req.Status == UpdateCancelled {
+ return nil
+ }
+ if !updateCancellable(req) {
+ return errUpdateNotCancellable
+ }
+ req.Status = UpdateCancelled
+ req.UpdatedAt = now
+ return nil
+}
+
+func finishUpdate(status UpdateStatus, output, errMsg string) updateTransition {
+ return func(req *UpdateRequest, now time.Time) error {
+ if updateRequestTerminal(req.Status) {
+ return errUpdateWithdrawn
+ }
+ req.Status = status
+ req.Output = output
+ req.Error = errMsg
+ req.UpdatedAt = now
+ return nil
+ }
+}
+
+// ignoreWithdrawn turns a late terminal report into the no-op it always was.
+func ignoreWithdrawn(err error) error {
+ if errors.Is(err, errUpdateWithdrawn) {
+ return nil
+ }
+ return err
+}
+
// InMemoryUpdateStore is the single-node implementation. Multi-node deploys
// must use RedisUpdateStore so Web POST, daemon heartbeat, daemon report, and
// UI polling agree on the same request lifecycle.
@@ -93,20 +239,24 @@ func NewInMemoryUpdateStore() *InMemoryUpdateStore {
}
}
-func (s *InMemoryUpdateStore) Create(_ context.Context, runtimeID, targetVersion, initiatorUserID string) (*UpdateRequest, error) {
+func (s *InMemoryUpdateStore) Create(_ context.Context, runtimeID, machineKey, targetVersion, initiatorUserID string, queueWhenBusy bool) (*UpdateRequest, error) {
s.mu.Lock()
defer s.mu.Unlock()
- // Clean up old requests.
+ if machineKey == "" {
+ machineKey = "runtime:" + runtimeID
+ }
+ now := time.Now()
for id, req := range s.requests {
- if time.Since(req.CreatedAt) > updateStoreRetention {
- delete(s.requests, id)
+ applyUpdateTimeout(req, now)
+ if updateRequestTerminal(req.Status) {
+ if now.Sub(req.UpdatedAt) > updateStoreRetention {
+ delete(s.requests, id)
+ }
+ continue
}
- }
-
- // Reject if there is already a pending or running update for this runtime.
- for _, req := range s.requests {
- if req.RuntimeID == runtimeID && (req.Status == UpdatePending || req.Status == UpdateRunning) {
+ // One unfinished update per machine.
+ if req.MachineKey == machineKey {
return nil, errUpdateInProgress
}
}
@@ -115,21 +265,17 @@ func (s *InMemoryUpdateStore) Create(_ context.Context, runtimeID, targetVersion
ID: randomID(),
RuntimeID: runtimeID,
InitiatorUserID: initiatorUserID,
+ MachineKey: machineKey,
+ QueueWhenBusy: queueWhenBusy,
Status: UpdatePending,
TargetVersion: targetVersion,
- CreatedAt: time.Now(),
- UpdatedAt: time.Now(),
+ CreatedAt: now,
+ UpdatedAt: now,
}
s.requests[req.ID] = req
- return req, nil
+ return cloneUpdateRequest(req), nil
}
-var errUpdateInProgress = &updateError{msg: "an update is already in progress for this runtime"}
-
-type updateError struct{ msg string }
-
-func (e *updateError) Error() string { return e.msg }
-
func (s *InMemoryUpdateStore) Get(_ context.Context, id string) (*UpdateRequest, error) {
s.mu.Lock()
defer s.mu.Unlock()
@@ -139,73 +285,93 @@ func (s *InMemoryUpdateStore) Get(_ context.Context, id string) (*UpdateRequest,
return nil, nil
}
applyUpdateTimeout(req, time.Now())
- return req, nil
+ return cloneUpdateRequest(req), nil
}
-func (s *InMemoryUpdateStore) HasPending(_ context.Context, runtimeID string) (bool, error) {
+func (s *InMemoryUpdateStore) GetActive(_ context.Context, machineKey string) (*UpdateRequest, error) {
s.mu.Lock()
defer s.mu.Unlock()
now := time.Now()
for _, req := range s.requests {
applyUpdateTimeout(req, now)
- if req.RuntimeID == runtimeID && req.Status == UpdatePending {
- return true, nil
+ if req.MachineKey == machineKey && !updateRequestTerminal(req.Status) {
+ return cloneUpdateRequest(req), nil
}
}
- return false, nil
+ return nil, nil
}
-// PopPending returns and marks as running the pending update for a runtime.
-func (s *InMemoryUpdateStore) PopPending(_ context.Context, runtimeID string) (*UpdateRequest, error) {
+func (s *InMemoryUpdateStore) HasPending(_ context.Context, runtimeID string) (bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
+ return s.oldestWaitingLocked(runtimeID, time.Now()) != nil, nil
+}
+func (s *InMemoryUpdateStore) oldestWaitingLocked(runtimeID string, now time.Time) *UpdateRequest {
var oldest *UpdateRequest
- now := time.Now()
for _, req := range s.requests {
applyUpdateTimeout(req, now)
- if req.RuntimeID == runtimeID && req.Status == UpdatePending {
+ if req.RuntimeID == runtimeID && updateRequestWaiting(req.Status) {
if oldest == nil || req.CreatedAt.Before(oldest.CreatedAt) {
oldest = req
}
}
}
- if oldest != nil {
- oldest.Status = UpdateRunning
- startedAt := now
- oldest.RunStartedAt = &startedAt
- oldest.UpdatedAt = now
- }
- return oldest, nil
+ return oldest
}
-func (s *InMemoryUpdateStore) Complete(_ context.Context, id string, output string) error {
+func (s *InMemoryUpdateStore) PopPending(_ context.Context, runtimeID string, daemonCanQueue bool) (*UpdateRequest, error) {
s.mu.Lock()
defer s.mu.Unlock()
- if req, ok := s.requests[id]; ok {
- req.Status = UpdateCompleted
- req.Output = output
- req.UpdatedAt = time.Now()
+ now := time.Now()
+ req := s.oldestWaitingLocked(runtimeID, now)
+ if req == nil {
+ return nil, nil
}
- return nil
+ if !offerDeferrable(req, daemonCanQueue) {
+ _ = startUpdate(req, now)
+ }
+ return cloneUpdateRequest(req), nil
}
-func (s *InMemoryUpdateStore) Fail(_ context.Context, id string, errMsg string) error {
+func (s *InMemoryUpdateStore) Transition(_ context.Context, id string, fn updateTransition) (*UpdateRequest, error) {
s.mu.Lock()
defer s.mu.Unlock()
- if req, ok := s.requests[id]; ok {
- req.Status = UpdateFailed
- req.Error = errMsg
- req.UpdatedAt = time.Now()
+ req, ok := s.requests[id]
+ if !ok {
+ return nil, nil
}
- return nil
+ now := time.Now()
+ applyUpdateTimeout(req, now)
+ err := fn(req, now)
+ return cloneUpdateRequest(req), err
+}
+
+func (s *InMemoryUpdateStore) Complete(ctx context.Context, id string, output string) error {
+ _, err := s.Transition(ctx, id, finishUpdate(UpdateCompleted, output, ""))
+ return ignoreWithdrawn(err)
+}
+
+func (s *InMemoryUpdateStore) Fail(ctx context.Context, id string, errMsg string) error {
+ _, err := s.Transition(ctx, id, finishUpdate(UpdateFailed, "", errMsg))
+ return ignoreWithdrawn(err)
+}
+
+func cloneUpdateRequest(req *UpdateRequest) *UpdateRequest {
+ out := *req
+ return &out
}
// Handlers
+func writeUpdate(w http.ResponseWriter, update *UpdateRequest) {
+ update.Cancellable = updateCancellable(update)
+ writeJSON(w, http.StatusOK, update)
+}
+
// InitiateUpdate creates a new CLI update request (protected route, called by frontend).
func (h *Handler) InitiateUpdate(w http.ResponseWriter, r *http.Request) {
runtimeID := chi.URLParam(r, "runtimeId")
@@ -220,6 +386,7 @@ func (h *Handler) InitiateUpdate(w http.ResponseWriter, r *http.Request) {
var req struct {
TargetVersion string `json:"target_version"`
+ QueueWhenBusy bool `json:"queue_when_busy"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
@@ -233,8 +400,10 @@ func (h *Handler) InitiateUpdate(w http.ResponseWriter, r *http.Request) {
update, err := h.UpdateStore.Create(
r.Context(),
uuidToString(rt.ID),
+ updateMachineKey(rt),
req.TargetVersion,
uuidToString(member.UserID),
+ req.QueueWhenBusy,
)
if err != nil {
// Only the in-progress rejection is a conflict the caller can act on.
@@ -253,26 +422,59 @@ func (h *Handler) InitiateUpdate(w http.ResponseWriter, r *http.Request) {
return
}
- writeJSON(w, http.StatusOK, update)
+ writeUpdate(w, update)
}
-// GetUpdate returns the status of an update request (protected route, called by frontend).
-func (h *Handler) GetUpdate(w http.ResponseWriter, r *http.Request) {
+// GetActiveUpdate returns the unfinished update of this runtime's machine,
+// started through any of the machine's runtimes, so a reload or another
+// runtime of the same daemon shows the queue.
+func (h *Handler) GetActiveUpdate(w http.ResponseWriter, r *http.Request) {
runtimeID := chi.URLParam(r, "runtimeId")
rt, member, ok := h.requireRuntimeReadAccess(w, r, obsmetrics.RuntimeLookupSourceRuntimeUpdatePoll, runtimeID)
if !ok {
return
}
- updateID := chi.URLParam(r, "updateId")
+ if !canEditRuntime(member, rt) {
+ writeJSON(w, http.StatusOK, map[string]any{"update": nil})
+ return
+ }
- update, err := h.UpdateStore.Get(r.Context(), updateID)
+ update, err := h.UpdateStore.GetActive(r.Context(), updateMachineKey(rt))
if err != nil {
- slog.Warn("load update failed", append(logger.RequestAttrs(r), "error", err)...)
+ slog.Warn("load active update failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to load update")
return
}
- if update == nil || update.RuntimeID != uuidToString(rt.ID) {
+ if update != nil {
+ update.Cancellable = updateCancellable(update)
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"update": update})
+}
+
+// loadMachineUpdate loads an update that belongs to this runtime's machine.
+func (h *Handler) loadMachineUpdate(w http.ResponseWriter, r *http.Request, rt db.AgentRuntime) (*UpdateRequest, bool) {
+ update, err := h.UpdateStore.Get(r.Context(), chi.URLParam(r, "updateId"))
+ if err != nil {
+ slog.Warn("load update failed", append(logger.RequestAttrs(r), "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to load update")
+ return nil, false
+ }
+ if update == nil || (update.RuntimeID != uuidToString(rt.ID) && update.MachineKey != updateMachineKey(rt)) {
writeError(w, http.StatusNotFound, "update not found")
+ return nil, false
+ }
+ return update, true
+}
+
+// GetUpdate returns the status of an update request (protected route, called by frontend).
+func (h *Handler) GetUpdate(w http.ResponseWriter, r *http.Request) {
+ runtimeID := chi.URLParam(r, "runtimeId")
+ rt, member, ok := h.requireRuntimeReadAccess(w, r, obsmetrics.RuntimeLookupSourceRuntimeUpdatePoll, runtimeID)
+ if !ok {
+ return
+ }
+ update, ok := h.loadMachineUpdate(w, r, rt)
+ if !ok {
return
}
// Keep an in-flight poll alive if an admin is downgraded after starting
@@ -283,10 +485,46 @@ func (h *Handler) GetUpdate(w http.ResponseWriter, r *http.Request) {
return
}
- writeJSON(w, http.StatusOK, update)
+ writeUpdate(w, update)
+}
+
+// CancelUpdate withdraws an update that has not started installing yet.
+func (h *Handler) CancelUpdate(w http.ResponseWriter, r *http.Request) {
+ runtimeID := chi.URLParam(r, "runtimeId")
+ rt, member, ok := h.requireRuntimeReadAccess(w, r, obsmetrics.RuntimeLookupSourceRuntimeAPI, runtimeID)
+ if !ok {
+ return
+ }
+ if !canEditRuntime(member, rt) {
+ writeError(w, http.StatusForbidden, "only runtime owners and workspace admins can cancel updates")
+ return
+ }
+ existing, ok := h.loadMachineUpdate(w, r, rt)
+ if !ok {
+ return
+ }
+
+ update, err := h.UpdateStore.Transition(r.Context(), existing.ID, cancelUpdate)
+ switch {
+ case errors.Is(err, errUpdateNotCancellable):
+ writeError(w, http.StatusConflict, err.Error())
+ return
+ case err != nil:
+ slog.Error("UpdateStore cancel failed", "error", err, "update_id", existing.ID)
+ writeError(w, http.StatusInternalServerError, "failed to cancel the update")
+ return
+ case update == nil:
+ writeError(w, http.StatusNotFound, "update not found")
+ return
+ }
+ writeUpdate(w, update)
}
// ReportUpdateResult receives the update result from the daemon.
+//
+// "scheduled" (busy, holding the update) and "running" (about to install) are
+// answered with 409 once the request was cancelled, expired, or finished; a
+// daemon holding a queued update installs only after a 2xx to "running".
func (h *Handler) ReportUpdateResult(w http.ResponseWriter, r *http.Request) {
runtimeID := chi.URLParam(r, "runtimeId")
@@ -307,43 +545,48 @@ func (h *Handler) ReportUpdateResult(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusNotFound, "update not found")
return
}
- if updateRequestTerminal(existing.Status) {
- slog.Debug("ignoring stale update report", "runtime_id", runtimeID, "update_id", updateID, "status", existing.Status)
- writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
- return
- }
var req struct {
- Status string `json:"status"` // "running", "completed", or "failed"
- Output string `json:"output"`
- Error string `json:"error"`
+ Status string `json:"status"` // "scheduled", "running", "completed", or "failed"
+ Output string `json:"output"`
+ Error string `json:"error"`
+ ActiveTasks *int `json:"active_tasks"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
+ var fn updateTransition
switch req.Status {
case "completed":
- if err := h.UpdateStore.Complete(r.Context(), updateID, req.Output); err != nil {
- slog.Error("UpdateStore Complete failed", "error", err, "update_id", updateID)
- writeError(w, http.StatusInternalServerError, "failed to persist completion")
- return
- }
+ fn = finishUpdate(UpdateCompleted, req.Output, "")
case "failed":
- if err := h.UpdateStore.Fail(r.Context(), updateID, req.Error); err != nil {
- slog.Error("UpdateStore Fail failed", "error", err, "update_id", updateID)
- writeError(w, http.StatusInternalServerError, "failed to persist failure")
- return
- }
+ fn = finishUpdate(UpdateFailed, "", req.Error)
case "running":
- // No-op: status is already "running" from PopPending. This call is
- // just a progress signal from the daemon to confirm it received the
- // update command and is executing it.
+ fn = startUpdate
+ case "scheduled":
+ fn = scheduleUpdate(req.ActiveTasks)
default:
writeError(w, http.StatusBadRequest, "invalid status: "+req.Status)
return
}
+ updated, err := h.UpdateStore.Transition(r.Context(), updateID, fn)
+ switch {
+ case errors.Is(err, errUpdateWithdrawn) && (req.Status == "completed" || req.Status == "failed"):
+ slog.Debug("ignoring stale update report", "runtime_id", runtimeID, "update_id", updateID, "status", req.Status)
+ case errors.Is(err, errUpdateWithdrawn):
+ writeError(w, http.StatusConflict, err.Error())
+ return
+ case err != nil:
+ slog.Error("UpdateStore report failed", "error", err, "update_id", updateID, "status", req.Status)
+ writeError(w, http.StatusInternalServerError, "failed to persist update status")
+ return
+ case updated == nil:
+ writeError(w, http.StatusNotFound, "update not found")
+ return
+ }
+
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
diff --git a/server/internal/handler/runtime_update_authorization_test.go b/server/internal/handler/runtime_update_authorization_test.go
index 7d9d15266b..9170a4fe92 100644
--- a/server/internal/handler/runtime_update_authorization_test.go
+++ b/server/internal/handler/runtime_update_authorization_test.go
@@ -107,7 +107,7 @@ func TestGetUpdateRequiresRuntimeManager(t *testing.T) {
actorID = plainMemberID
}
- update, err := testHandler.UpdateStore.Create(context.Background(), runtimeID, "v9.9.9", runtimeOwnerID)
+ update, err := testHandler.UpdateStore.Create(context.Background(), runtimeID, "", "v9.9.9", runtimeOwnerID, false)
if err != nil {
t.Fatalf("create update request: %v", err)
}
diff --git a/server/internal/handler/runtime_update_error_classification_test.go b/server/internal/handler/runtime_update_error_classification_test.go
index 6b5548eee3..1bb66237f7 100644
--- a/server/internal/handler/runtime_update_error_classification_test.go
+++ b/server/internal/handler/runtime_update_error_classification_test.go
@@ -17,7 +17,7 @@ type failingUpdateStore struct {
createErr error
}
-func (s *failingUpdateStore) Create(context.Context, string, string, string) (*UpdateRequest, error) {
+func (s *failingUpdateStore) Create(context.Context, string, string, string, string, bool) (*UpdateRequest, error) {
return nil, s.createErr
}
diff --git a/server/internal/handler/runtime_update_queue_test.go b/server/internal/handler/runtime_update_queue_test.go
new file mode 100644
index 0000000000..c487bae3b8
--- /dev/null
+++ b/server/internal/handler/runtime_update_queue_test.go
@@ -0,0 +1,308 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// forEachUpdateStore runs fn against the in-memory store and, when
+// REDIS_TEST_URL is set, the Redis store.
+func forEachUpdateStore(t *testing.T, fn func(t *testing.T, store UpdateStore, age func(id string, by time.Duration))) {
+ t.Run("memory", func(t *testing.T) {
+ store := NewInMemoryUpdateStore()
+ fn(t, store, func(id string, by time.Duration) {
+ store.mu.Lock()
+ defer store.mu.Unlock()
+ store.requests[id].CreatedAt = store.requests[id].CreatedAt.Add(-by)
+ })
+ })
+ t.Run("redis", func(t *testing.T) {
+ rdb := newRedisTestClient(t)
+ store := NewRedisUpdateStore(rdb)
+ fn(t, store, func(id string, by time.Duration) {
+ req, err := store.Get(context.Background(), id)
+ if err != nil || req == nil {
+ t.Fatalf("get %s: %v", id, err)
+ }
+ req.CreatedAt = req.CreatedAt.Add(-by)
+ persistUpdateForTest(t, rdb, store, req)
+ })
+ })
+}
+
+func mustCreateUpdate(t *testing.T, store UpdateStore, runtimeID, machineKey string, queue bool) *UpdateRequest {
+ t.Helper()
+ req, err := store.Create(context.Background(), runtimeID, machineKey, "v0.12.0", "user-1", queue)
+ if err != nil {
+ t.Fatalf("create: %v", err)
+ }
+ return req
+}
+
+func TestUpdateQueue_OfferedUntilStarted(t *testing.T) {
+ forEachUpdateStore(t, func(t *testing.T, store UpdateStore, _ func(string, time.Duration)) {
+ ctx := context.Background()
+ req := mustCreateUpdate(t, store, "rt-1", "machine-1", true)
+
+ for i := 0; i < 2; i++ {
+ offered, err := store.PopPending(ctx, "rt-1", true)
+ if err != nil || offered == nil || offered.ID != req.ID || offered.Status != UpdatePending {
+ t.Fatalf("offer %d = %+v, %v; want the pending request again", i, offered, err)
+ }
+ }
+ tasks := 3
+ got, err := store.Transition(ctx, req.ID, scheduleUpdate(&tasks))
+ if err != nil || got.Status != UpdateScheduled || *got.ActiveTasks != 3 {
+ t.Fatalf("schedule = %+v, %v", got, err)
+ }
+ if offered, _ := store.PopPending(ctx, "rt-1", true); offered == nil || offered.ID != req.ID {
+ t.Fatalf("a scheduled request must still be offered (daemon restart), got %+v", offered)
+ }
+ if got, err := store.Transition(ctx, req.ID, startUpdate); err != nil || got.Status != UpdateRunning {
+ t.Fatalf("start = %+v, %v", got, err)
+ }
+ if offered, _ := store.PopPending(ctx, "rt-1", true); offered != nil {
+ t.Fatalf("a running request must not be offered again, got %+v", offered)
+ }
+ })
+}
+
+func TestUpdateQueue_DaemonWithoutQueueSupportRunsFromDelivery(t *testing.T) {
+ forEachUpdateStore(t, func(t *testing.T, store UpdateStore, _ func(string, time.Duration)) {
+ ctx := context.Background()
+ req := mustCreateUpdate(t, store, "rt-1", "machine-1", true)
+ offered, err := store.PopPending(ctx, "rt-1", false)
+ if err != nil || offered == nil || offered.Status != UpdateRunning {
+ t.Fatalf("offer = %+v, %v; want running", offered, err)
+ }
+ if _, err := store.Transition(ctx, req.ID, cancelUpdate); !errors.Is(err, errUpdateNotCancellable) {
+ t.Fatalf("cancel after delivery: %v, want errUpdateNotCancellable", err)
+ }
+ })
+}
+
+func TestUpdateQueue_CancelAndStartExclusive(t *testing.T) {
+ forEachUpdateStore(t, func(t *testing.T, store UpdateStore, _ func(string, time.Duration)) {
+ ctx := context.Background()
+
+ cancelled := mustCreateUpdate(t, store, "rt-1", "machine-1", true)
+ if _, err := store.Transition(ctx, cancelled.ID, cancelUpdate); err != nil {
+ t.Fatalf("cancel: %v", err)
+ }
+ if _, err := store.Transition(ctx, cancelled.ID, startUpdate); !errors.Is(err, errUpdateWithdrawn) {
+ t.Fatalf("start after cancel: %v, want errUpdateWithdrawn", err)
+ }
+ if _, err := store.Transition(ctx, cancelled.ID, scheduleUpdate(nil)); !errors.Is(err, errUpdateWithdrawn) {
+ t.Fatalf("schedule after cancel: %v, want errUpdateWithdrawn", err)
+ }
+
+ for round := 0; round < 20; round++ {
+ req := mustCreateUpdate(t, store, "rt-1", "machine-1", true)
+ var wg sync.WaitGroup
+ var cancelErr, startErr error
+ wg.Add(2)
+ go func() { defer wg.Done(); _, cancelErr = store.Transition(ctx, req.ID, cancelUpdate) }()
+ go func() { defer wg.Done(); _, startErr = store.Transition(ctx, req.ID, startUpdate) }()
+ wg.Wait()
+ if (cancelErr == nil) == (startErr == nil) {
+ t.Fatalf("round %d: cancel=%v start=%v, want exactly one to win", round, cancelErr, startErr)
+ }
+ final, _ := store.Get(ctx, req.ID)
+ if want := map[bool]UpdateStatus{true: UpdateCancelled, false: UpdateRunning}[cancelErr == nil]; final.Status != want {
+ t.Fatalf("round %d: stored %s, want %s", round, final.Status, want)
+ }
+ if final.Status == UpdateRunning {
+ _, _ = store.Transition(ctx, req.ID, finishUpdate(UpdateCompleted, "", ""))
+ }
+ }
+ })
+}
+
+func TestUpdateQueue_OneUnfinishedUpdatePerMachine(t *testing.T) {
+ forEachUpdateStore(t, func(t *testing.T, store UpdateStore, _ func(string, time.Duration)) {
+ ctx := context.Background()
+ first := mustCreateUpdate(t, store, "rt-claude", "machine-1", true)
+
+ if _, err := store.Create(ctx, "rt-codex", "machine-1", "v0.12.0", "user-1", true); !errors.Is(err, errUpdateInProgress) {
+ t.Fatalf("second runtime of the machine: %v, want errUpdateInProgress", err)
+ }
+ active, err := store.GetActive(ctx, "machine-1")
+ if err != nil || active == nil || active.ID != first.ID {
+ t.Fatalf("active = %+v, %v; want the first request", active, err)
+ }
+ mustCreateUpdate(t, store, "rt-other", "machine-2", true)
+
+ if _, err := store.Transition(ctx, first.ID, cancelUpdate); err != nil {
+ t.Fatalf("cancel: %v", err)
+ }
+ if active, _ := store.GetActive(ctx, "machine-1"); active != nil {
+ t.Fatalf("active after cancel = %+v, want none", active)
+ }
+ mustCreateUpdate(t, store, "rt-codex", "machine-1", true)
+ })
+}
+
+func TestUpdateQueue_OnlyQueuedRequestsAreCancellable(t *testing.T) {
+ forEachUpdateStore(t, func(t *testing.T, store UpdateStore, _ func(string, time.Duration)) {
+ ctx := context.Background()
+ // A CLI request does not opt into queueing; its --wait does not know "cancelled".
+ cli := mustCreateUpdate(t, store, "rt-1", "machine-1", false)
+ if _, err := store.Transition(ctx, cli.ID, cancelUpdate); !errors.Is(err, errUpdateNotCancellable) {
+ t.Fatalf("cancel CLI request: %v, want errUpdateNotCancellable", err)
+ }
+ if got, _ := store.Get(ctx, cli.ID); got.Status != UpdatePending || updateCancellable(got) {
+ t.Fatalf("CLI request = %+v, want pending and not cancellable", got)
+ }
+ })
+}
+
+func TestUpdateQueue_ConcurrentCreatesOnOneMachine(t *testing.T) {
+ forEachUpdateStore(t, func(t *testing.T, store UpdateStore, _ func(string, time.Duration)) {
+ const n = 16
+ var wg sync.WaitGroup
+ errs := make(chan error, n)
+ for i := 0; i < n; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ _, err := store.Create(context.Background(), fmt.Sprintf("rt-%d", i), "machine-1", "v0.12.0", "user-1", true)
+ errs <- err
+ }(i)
+ }
+ wg.Wait()
+ close(errs)
+ created := 0
+ for err := range errs {
+ switch {
+ case err == nil:
+ created++
+ case !errors.Is(err, errUpdateInProgress):
+ t.Fatalf("create: %v", err)
+ }
+ }
+ if created != 1 {
+ t.Fatalf("created %d requests on one machine, want 1", created)
+ }
+ })
+}
+
+func TestUpdateQueue_ExpiresAfter24Hours(t *testing.T) {
+ forEachUpdateStore(t, func(t *testing.T, store UpdateStore, age func(string, time.Duration)) {
+ ctx := context.Background()
+ req := mustCreateUpdate(t, store, "rt-1", "machine-1", true)
+ if _, err := store.Transition(ctx, req.ID, scheduleUpdate(nil)); err != nil {
+ t.Fatalf("schedule: %v", err)
+ }
+
+ age(req.ID, updateQueueTimeout-time.Minute)
+ if got, _ := store.Get(ctx, req.ID); got.Status != UpdateScheduled {
+ t.Fatalf("status before 24h = %s", got.Status)
+ }
+ age(req.ID, 2*time.Minute)
+ if got, _ := store.Get(ctx, req.ID); got.Status != UpdateExpired {
+ t.Fatalf("status after 24h = %s, want expired", got.Status)
+ }
+ if _, err := store.Transition(ctx, req.ID, startUpdate); !errors.Is(err, errUpdateWithdrawn) {
+ t.Fatalf("start after expiry: %v, want errUpdateWithdrawn", err)
+ }
+ if offered, _ := store.PopPending(ctx, "rt-1", true); offered != nil {
+ t.Fatalf("an expired request must not be offered, got %+v", offered)
+ }
+ mustCreateUpdate(t, store, "rt-1", "machine-1", true)
+ })
+}
+
+// TestQueuedUpdateThroughHandlers walks the HTTP flow on one machine with two
+// runtimes: queue, see it from the sibling runtime, refuse a second update,
+// cancel, and refuse the daemon's start afterwards.
+func TestQueuedUpdateThroughHandlers(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ original := testHandler.UpdateStore
+ testHandler.UpdateStore = NewInMemoryUpdateStore()
+ t.Cleanup(func() { testHandler.UpdateStore = original })
+
+ runtimes := make([]string, 2)
+ for i, provider := range []string{"queue_test_claude", "queue_test_codex"} {
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_runtime (workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, owner_id, last_seen_at)
+ VALUES ($1, 'queue-test-daemon', $2, 'local', $2, 'online', 'queue test', '{}'::jsonb, $3, now())
+ RETURNING id
+ `, testWorkspaceID, provider, testUserID).Scan(&runtimes[i]); err != nil {
+ t.Fatalf("create runtime: %v", err)
+ }
+ id := runtimes[i]
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, id) })
+ }
+ rtA, rtB := runtimes[0], runtimes[1]
+
+ call := func(fn http.HandlerFunc, method, path string, body any, params ...string) *httptest.ResponseRecorder {
+ w := httptest.NewRecorder()
+ fn(w, withURLParams(newRequest(method, path, body), params...))
+ return w
+ }
+
+ w := call(testHandler.InitiateUpdate, http.MethodPost, "/api/runtimes/"+rtA+"/update",
+ map[string]any{"target_version": "v0.12.0", "queue_when_busy": true}, "runtimeId", rtA)
+ var created UpdateRequest
+ if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &created) != nil || !created.Cancellable {
+ t.Fatalf("initiate: %d %s", w.Code, w.Body.String())
+ }
+
+ // The heartbeat offers it as deferrable to a daemon that can hold it.
+ ack, _, err := testHandler.processHeartbeat(ctx, rtA, protocol.DaemonHeartbeatRequestPayload{RuntimeID: rtA, SupportsQueuedUpdate: true})
+ if err != nil || ack.PendingUpdate == nil || ack.PendingUpdate.ID != created.ID || !ack.PendingUpdate.Deferrable {
+ t.Fatalf("heartbeat offer = %+v, %v", ack, err)
+ }
+ report := func(status string) int {
+ return call(testHandler.ReportUpdateResult, http.MethodPost, "/api/daemon/runtimes/"+rtA+"/update/"+created.ID+"/result",
+ map[string]any{"status": status, "active_tasks": 2}, "runtimeId", rtA, "updateId", created.ID).Code
+ }
+ if code := report("scheduled"); code != http.StatusOK {
+ t.Fatalf("scheduled report: %d", code)
+ }
+
+ // The sibling runtime of the same daemon sees the queued update.
+ w = call(testHandler.GetActiveUpdate, http.MethodGet, "/api/runtimes/"+rtB+"/update", nil, "runtimeId", rtB)
+ var active struct {
+ Update *UpdateRequest `json:"update"`
+ }
+ if json.Unmarshal(w.Body.Bytes(), &active) != nil || active.Update == nil || active.Update.ID != created.ID ||
+ active.Update.Status != UpdateScheduled || *active.Update.ActiveTasks != 2 {
+ t.Fatalf("active from sibling runtime: %d %s", w.Code, w.Body.String())
+ }
+ w = call(testHandler.InitiateUpdate, http.MethodPost, "/api/runtimes/"+rtB+"/update",
+ map[string]any{"target_version": "v0.12.0", "queue_when_busy": true}, "runtimeId", rtB)
+ if w.Code != http.StatusConflict {
+ t.Fatalf("second update on the machine: %d %s", w.Code, w.Body.String())
+ }
+
+ w = call(testHandler.CancelUpdate, http.MethodPost, "/api/runtimes/"+rtB+"/update/"+created.ID+"/cancel", nil,
+ "runtimeId", rtB, "updateId", created.ID)
+ if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"status":"cancelled"`) {
+ t.Fatalf("cancel: %d %s", w.Code, w.Body.String())
+ }
+ if code := report("running"); code != http.StatusConflict {
+ t.Fatalf("start after cancel: %d, want 409", code)
+ }
+ if code := report("completed"); code != http.StatusOK {
+ t.Fatalf("late terminal report: %d, want 200 (ignored)", code)
+ }
+ w = call(testHandler.CancelUpdate, http.MethodPost, "/api/runtimes/"+rtA+"/update/"+created.ID+"/cancel", nil,
+ "runtimeId", rtA, "updateId", created.ID)
+ if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `"status":"cancelled"`) {
+ t.Fatalf("second cancel (another tab): %d %s, want 200 cancelled", w.Code, w.Body.String())
+ }
+}
diff --git a/server/internal/handler/runtime_update_redis_store.go b/server/internal/handler/runtime_update_redis_store.go
index d6a630f55a..42ee0c6781 100644
--- a/server/internal/handler/runtime_update_redis_store.go
+++ b/server/internal/handler/runtime_update_redis_store.go
@@ -22,11 +22,12 @@ const (
updatePendingPrefix = "mul:" + runtimePendingRedisHashTag + ":update:pending:"
updateActivePrefix = "mul:" + runtimePendingRedisHashTag + ":update:active:"
updateRedisPopMaxRetries = 5
+ updateRedisCASMaxRetries = 10
)
func updateKey(id string) string { return updateKeyPrefix + id }
func updatePendingKey(runtimeID string) string { return updatePendingPrefix + runtimeID }
-func updateActiveKey(runtimeID string) string { return updateActivePrefix + runtimeID }
+func updateActiveKey(machineKey string) string { return updateActivePrefix + machineKey }
var deleteIfValueScript = redis.NewScript(`
if redis.call('GET', KEYS[1]) == ARGV[1] then
@@ -35,6 +36,31 @@ end
return 0
`)
+// createUpdateScript claims the machine slot and writes the request and its
+// pending-queue entry in one step, so a slot never points at a request that
+// is still being written. Lua rather than MULTI: some managed Redis
+// deployments deny MULTI.
+var createUpdateScript = redis.NewScript(`
+if not redis.call('SET', KEYS[1], ARGV[1], 'NX', 'EX', tonumber(ARGV[3])) then
+ return 0
+end
+redis.call('SET', KEYS[2], ARGV[2], 'EX', tonumber(ARGV[3]))
+redis.call('ZADD', KEYS[3], ARGV[4], ARGV[1])
+redis.call('EXPIRE', KEYS[3], tonumber(ARGV[3]))
+return 1
+`)
+
+// compareAndSetScript replaces KEYS[1] only if it still holds the bytes the
+// caller read. Every state change of an update record goes through it, so a
+// cancel and a start racing on one request cannot both win.
+var compareAndSetScript = redis.NewScript(`
+if redis.call('GET', KEYS[1]) ~= ARGV[1] then
+ return 0
+end
+redis.call('SET', KEYS[1], ARGV[2], 'EX', tonumber(ARGV[3]))
+return 1
+`)
+
type RedisUpdateStore struct {
rdb redis.UniversalClient
}
@@ -43,12 +69,17 @@ func NewRedisUpdateStore(rdb redis.UniversalClient) *RedisUpdateStore {
return &RedisUpdateStore{rdb: rdb}
}
-func (s *RedisUpdateStore) Create(ctx context.Context, runtimeID, targetVersion, initiatorUserID string) (*UpdateRequest, error) {
+func (s *RedisUpdateStore) Create(ctx context.Context, runtimeID, machineKey, targetVersion, initiatorUserID string, queueWhenBusy bool) (*UpdateRequest, error) {
+ if machineKey == "" {
+ machineKey = "runtime:" + runtimeID
+ }
now := time.Now()
req := &UpdateRequest{
ID: randomID(),
RuntimeID: runtimeID,
InitiatorUserID: initiatorUserID,
+ MachineKey: machineKey,
+ QueueWhenBusy: queueWhenBusy,
Status: UpdatePending,
TargetVersion: targetVersion,
CreatedAt: now,
@@ -59,79 +90,130 @@ func (s *RedisUpdateStore) Create(ctx context.Context, runtimeID, targetVersion,
return nil, err
}
- activeKey := updateActiveKey(runtimeID)
- ok, err := s.rdb.SetNX(ctx, activeKey, req.ID, updateStoreRetention).Result()
- if err != nil {
- return nil, fmt.Errorf("reserve active update: %w", err)
- }
- if !ok {
- return nil, errUpdateInProgress
- }
-
- // The active reservation above provides the concurrency guarantee this
- // write needs. Use a plain pipeline so managed Redis deployments that allow
- // SET/ZADD but deny MULTI can still create update requests. Exec failures
- // remain safe because the compensation below removes every partially
- // written key and releases the reservation.
- pipe := s.rdb.Pipeline()
- pipe.Set(ctx, updateKey(req.ID), data, updateStoreRetention)
- pipe.ZAdd(ctx, updatePendingKey(runtimeID), redis.Z{
- Score: float64(now.UnixNano()),
- Member: req.ID,
- })
- pipe.Expire(ctx, updatePendingKey(runtimeID), updateStoreRetention*2)
- if _, err := pipe.Exec(ctx); err != nil {
- _ = s.clearActiveIfMatches(ctx, runtimeID, req.ID)
- _ = s.rdb.Del(ctx, updateKey(req.ID)).Err()
- _ = s.rdb.ZRem(ctx, updatePendingKey(runtimeID), req.ID).Err()
- return nil, fmt.Errorf("persist update request: %w", err)
+ activeKey := updateActiveKey(machineKey)
+ for attempt := 0; attempt < 2; attempt++ {
+ created, err := createUpdateScript.Run(ctx, s.rdb,
+ []string{activeKey, updateKey(req.ID), updatePendingKey(runtimeID)},
+ req.ID, data, int(updateWaitingRetention.Seconds()), now.UnixNano(),
+ ).Int64()
+ if err != nil {
+ return nil, fmt.Errorf("persist update request: %w", err)
+ }
+ if created == 1 {
+ return req, nil
+ }
+ // Creation is atomic, so a slot whose request is finished or gone is
+ // stale (e.g. a lost slot release) and can be taken over.
+ holder, err := s.rdb.Get(ctx, activeKey).Result()
+ if errors.Is(err, redis.Nil) {
+ continue
+ }
+ if err != nil {
+ return nil, fmt.Errorf("reserve active update: %w", err)
+ }
+ existing, err := s.Get(ctx, holder)
+ if err != nil {
+ return nil, err
+ }
+ if existing != nil && !updateRequestTerminal(existing.Status) {
+ return nil, errUpdateInProgress
+ }
+ if err := s.clearActiveIfMatches(ctx, machineKey, holder); err != nil {
+ return nil, err
+ }
}
- return req, nil
+ return nil, errUpdateInProgress
}
+// Get loads a request, persisting a timeout transition if one is due.
func (s *RedisUpdateStore) Get(ctx context.Context, id string) (*UpdateRequest, error) {
- return s.loadRequest(ctx, id)
+ return s.Transition(ctx, id, nil)
}
-func (s *RedisUpdateStore) loadRequest(ctx context.Context, id string) (*UpdateRequest, error) {
- raw, err := s.rdb.Get(ctx, updateKey(id)).Bytes()
+func (s *RedisUpdateStore) GetActive(ctx context.Context, machineKey string) (*UpdateRequest, error) {
+ id, err := s.rdb.Get(ctx, updateActiveKey(machineKey)).Result()
if errors.Is(err, redis.Nil) {
return nil, nil
}
if err != nil {
- return nil, fmt.Errorf("get update request: %w", err)
+ return nil, fmt.Errorf("get active update: %w", err)
}
- req, err := s.unmarshalRequest(raw)
- if err != nil {
+ req, err := s.Get(ctx, id)
+ if err != nil || req == nil || updateRequestTerminal(req.Status) {
return nil, err
}
- if applyUpdateTimeout(req, time.Now()) {
- if err := s.persistRequest(ctx, req); err != nil {
+ return req, nil
+}
+
+// Transition applies fn (and any due timeout) to the stored request with a
+// compare-and-set, retrying when another writer got there first. A nil fn
+// only applies the timeout. Once the request is terminal its machine slot
+// and pending-queue entry are released.
+func (s *RedisUpdateStore) Transition(ctx context.Context, id string, fn updateTransition) (*UpdateRequest, error) {
+ for attempt := 0; attempt < updateRedisCASMaxRetries; attempt++ {
+ raw, err := s.rdb.Get(ctx, updateKey(id)).Bytes()
+ if errors.Is(err, redis.Nil) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, fmt.Errorf("get update request: %w", err)
+ }
+ req, err := s.unmarshalRequest(raw)
+ if err != nil {
return nil, err
}
- if err := s.clearActiveIfMatches(ctx, req.RuntimeID, req.ID); err != nil {
+ now := time.Now()
+ changed := applyUpdateTimeout(req, now)
+ var fnErr error
+ if fn != nil {
+ if fnErr = fn(req, now); fnErr == nil {
+ changed = true
+ }
+ }
+ if !changed {
+ return req, fnErr
+ }
+ data, err := s.marshalRequest(req)
+ if err != nil {
return nil, err
}
- s.rdb.ZRem(ctx, updatePendingKey(req.RuntimeID), req.ID)
+ swapped, err := compareAndSetScript.Run(ctx, s.rdb, []string{updateKey(id)},
+ raw, data, int(updateRetention(req).Seconds())).Int64()
+ if err != nil {
+ return nil, fmt.Errorf("persist update request: %w", err)
+ }
+ if swapped == 0 {
+ continue
+ }
+ if !updateRequestWaiting(req.Status) {
+ s.rdb.ZRem(ctx, updatePendingKey(req.RuntimeID), req.ID)
+ }
+ if updateRequestTerminal(req.Status) {
+ if err := s.clearActiveIfMatches(ctx, req.MachineKey, req.ID); err != nil {
+ return nil, err
+ }
+ }
+ return req, fnErr
}
- return req, nil
+ return nil, fmt.Errorf("update request %s: too much write contention", id)
}
-func (s *RedisUpdateStore) persistRequest(ctx context.Context, req *UpdateRequest) error {
- data, err := s.marshalRequest(req)
- if err != nil {
- return err
- }
- if err := s.rdb.Set(ctx, updateKey(req.ID), data, updateStoreRetention).Err(); err != nil {
- return fmt.Errorf("persist update request: %w", err)
- }
- return nil
+func (s *RedisUpdateStore) Complete(ctx context.Context, id string, output string) error {
+ _, err := s.Transition(ctx, id, finishUpdate(UpdateCompleted, output, ""))
+ return ignoreWithdrawn(err)
+}
+
+func (s *RedisUpdateStore) Fail(ctx context.Context, id string, errMsg string) error {
+ _, err := s.Transition(ctx, id, finishUpdate(UpdateFailed, "", errMsg))
+ return ignoreWithdrawn(err)
}
type redisUpdateEnvelope struct {
Public *UpdateRequest `json:"r"`
RunStartedAt *time.Time `json:"s,omitempty"`
InitiatorUserID string `json:"u,omitempty"`
+ MachineKey string `json:"m,omitempty"`
+ QueueWhenBusy bool `json:"q,omitempty"`
}
func (s *RedisUpdateStore) marshalRequest(req *UpdateRequest) ([]byte, error) {
@@ -139,6 +221,8 @@ func (s *RedisUpdateStore) marshalRequest(req *UpdateRequest) ([]byte, error) {
Public: req,
RunStartedAt: req.RunStartedAt,
InitiatorUserID: req.InitiatorUserID,
+ MachineKey: req.MachineKey,
+ QueueWhenBusy: req.QueueWhenBusy,
}
data, err := json.Marshal(env)
if err != nil {
@@ -157,6 +241,8 @@ func (s *RedisUpdateStore) unmarshalRequest(raw []byte) (*UpdateRequest, error)
}
env.Public.RunStartedAt = env.RunStartedAt
env.Public.InitiatorUserID = env.InitiatorUserID
+ env.Public.MachineKey = env.MachineKey
+ env.Public.QueueWhenBusy = env.QueueWhenBusy
return env.Public, nil
}
@@ -168,7 +254,7 @@ func (s *RedisUpdateStore) HasPending(ctx context.Context, runtimeID string) (bo
return cnt > 0, nil
}
-func (s *RedisUpdateStore) PopPending(ctx context.Context, runtimeID string) (*UpdateRequest, error) {
+func (s *RedisUpdateStore) PopPending(ctx context.Context, runtimeID string, daemonCanQueue bool) (*UpdateRequest, error) {
pendingKey := updatePendingKey(runtimeID)
for attempt := 0; attempt < updateRedisPopMaxRetries; attempt++ {
@@ -181,91 +267,43 @@ func (s *RedisUpdateStore) PopPending(ctx context.Context, runtimeID string) (*U
}
id := ids[0]
- req, err := s.loadRequest(ctx, id)
+ req, err := s.Get(ctx, id)
if err != nil {
return nil, err
}
- if req == nil {
+ if req == nil || !updateRequestWaiting(req.Status) {
s.rdb.ZRem(ctx, pendingKey, id)
continue
}
- if req.Status != UpdatePending {
- s.rdb.ZRem(ctx, pendingKey, id)
- continue
+ if offerDeferrable(req, daemonCanQueue) {
+ // Stays queued and is offered again on the next heartbeat.
+ return req, nil
}
- now := time.Now()
- req.Status = UpdateRunning
- req.RunStartedAt = &now
- req.UpdatedAt = now
- data, err := s.marshalRequest(req)
- if err != nil {
- return nil, err
+ // Offered once: running from delivery. The CAS loses to a concurrent
+ // cancel or to another heartbeat that already claimed it.
+ claimed, err := s.Transition(ctx, id, func(r *UpdateRequest, now time.Time) error {
+ if !updateRequestWaiting(r.Status) {
+ return errUpdateWithdrawn
+ }
+ return startUpdate(r, now)
+ })
+ if errors.Is(err, errUpdateWithdrawn) || claimed == nil {
+ continue
}
-
- result, err := claimPendingScript.Run(
- ctx, s.rdb,
- []string{pendingKey, updateKey(id)},
- id, data, int(updateStoreRetention.Seconds()),
- ).Int64()
if err != nil {
return nil, fmt.Errorf("claim pending update: %w", err)
}
- if result == 0 {
- continue
- }
- return req, nil
+ return claimed, nil
}
return nil, nil
}
-func (s *RedisUpdateStore) Complete(ctx context.Context, id string, output string) error {
- req, err := s.loadRequest(ctx, id)
- if err != nil {
- return err
- }
- if req == nil || updateRequestTerminal(req.Status) {
- return nil
- }
- req.Status = UpdateCompleted
- req.Output = output
- req.UpdatedAt = time.Now()
- if err := s.persistRequest(ctx, req); err != nil {
- return err
- }
- if err := s.clearActiveIfMatches(ctx, req.RuntimeID, req.ID); err != nil {
- return err
- }
- s.rdb.ZRem(ctx, updatePendingKey(req.RuntimeID), req.ID)
- return nil
-}
-
-func (s *RedisUpdateStore) Fail(ctx context.Context, id string, errMsg string) error {
- req, err := s.loadRequest(ctx, id)
- if err != nil {
- return err
- }
- if req == nil || updateRequestTerminal(req.Status) {
- return nil
- }
- req.Status = UpdateFailed
- req.Error = errMsg
- req.UpdatedAt = time.Now()
- if err := s.persistRequest(ctx, req); err != nil {
- return err
- }
- if err := s.clearActiveIfMatches(ctx, req.RuntimeID, req.ID); err != nil {
- return err
- }
- s.rdb.ZRem(ctx, updatePendingKey(req.RuntimeID), req.ID)
- return nil
-}
-
-func (s *RedisUpdateStore) clearActiveIfMatches(ctx context.Context, runtimeID, id string) error {
- if runtimeID == "" || id == "" {
+func (s *RedisUpdateStore) clearActiveIfMatches(ctx context.Context, machineKey, id string) error {
+ if machineKey == "" || id == "" {
return nil
}
- if err := deleteIfValueScript.Run(ctx, s.rdb, []string{updateActiveKey(runtimeID)}, id).Err(); err != nil {
+ if err := deleteIfValueScript.Run(ctx, s.rdb, []string{updateActiveKey(machineKey)}, id).Err(); err != nil {
return fmt.Errorf("clear active update: %w", err)
}
return nil
diff --git a/server/internal/handler/runtime_update_redis_store_test.go b/server/internal/handler/runtime_update_redis_store_test.go
index 3953fbae81..57653b50e5 100644
--- a/server/internal/handler/runtime_update_redis_store_test.go
+++ b/server/internal/handler/runtime_update_redis_store_test.go
@@ -5,6 +5,8 @@ import (
"sync"
"testing"
"time"
+
+ "github.com/redis/go-redis/v9"
)
func TestRedisUpdateStore_EnvelopePersistsRunStartedAt(t *testing.T) {
@@ -48,7 +50,7 @@ func TestRedisUpdateStore_CreateGetComplete(t *testing.T) {
ctx := context.Background()
store := NewRedisUpdateStore(rdb)
- req, err := store.Create(ctx, "runtime-1", "v1.2.3", "user-1")
+ req, err := store.Create(ctx, "runtime-1", "", "v1.2.3", "user-1", false)
if err != nil {
t.Fatalf("create: %v", err)
}
@@ -75,7 +77,7 @@ func TestRedisUpdateStore_CreateGetComplete(t *testing.T) {
t.Fatalf("completed request mismatch: %+v", got)
}
- if _, err := store.Create(ctx, "runtime-1", "v1.2.4", "user-1"); err != nil {
+ if _, err := store.Create(ctx, "runtime-1", "", "v1.2.4", "user-1", false); err != nil {
t.Fatalf("create after complete should be allowed: %v", err)
}
}
@@ -84,7 +86,7 @@ func TestRedisUpdateStore_CreateWithoutMultiPermission(t *testing.T) {
rdb := newRedisTestClientWithoutMulti(t)
ctx := context.Background()
store := NewRedisUpdateStore(rdb)
- req, err := store.Create(ctx, "runtime-no-multi", "v1.2.3", "user-1")
+ req, err := store.Create(ctx, "runtime-no-multi", "", "v1.2.3", "user-1", false)
if err != nil {
t.Fatalf("create without MULTI permission: %v", err)
}
@@ -115,12 +117,12 @@ func TestRedisUpdateStore_PopPendingAcrossInstances(t *testing.T) {
nodeA := NewRedisUpdateStore(rdb)
nodeB := NewRedisUpdateStore(rdb)
- req, err := nodeA.Create(ctx, "runtime-cross", "v1.2.3", "user-1")
+ req, err := nodeA.Create(ctx, "runtime-cross", "", "v1.2.3", "user-1", false)
if err != nil {
t.Fatalf("node A create: %v", err)
}
- popped, err := nodeB.PopPending(ctx, "runtime-cross")
+ popped, err := nodeB.PopPending(ctx, "runtime-cross", false)
if err != nil {
t.Fatalf("node B pop: %v", err)
}
@@ -134,7 +136,7 @@ func TestRedisUpdateStore_PopPendingAcrossInstances(t *testing.T) {
t.Fatal("RunStartedAt not set after pop")
}
- again, err := nodeB.PopPending(ctx, "runtime-cross")
+ again, err := nodeB.PopPending(ctx, "runtime-cross", false)
if err != nil {
t.Fatalf("node B second pop: %v", err)
}
@@ -152,11 +154,11 @@ func TestRedisUpdateStore_ReportAndPollAcrossInstances(t *testing.T) {
nodeC := NewRedisUpdateStore(rdb)
nodeD := NewRedisUpdateStore(rdb)
- req, err := nodeA.Create(ctx, "runtime-report", "v1.2.3", "user-1")
+ req, err := nodeA.Create(ctx, "runtime-report", "", "v1.2.3", "user-1", false)
if err != nil {
t.Fatalf("node A create: %v", err)
}
- if _, err := nodeB.PopPending(ctx, "runtime-report"); err != nil {
+ if _, err := nodeB.PopPending(ctx, "runtime-report", false); err != nil {
t.Fatalf("node B pop: %v", err)
}
if err := nodeC.Complete(ctx, req.ID, "updated to v1.2.3"); err != nil {
@@ -180,11 +182,11 @@ func TestRedisUpdateStore_FailAcrossInstances(t *testing.T) {
nodeB := NewRedisUpdateStore(rdb)
nodeC := NewRedisUpdateStore(rdb)
- req, err := nodeA.Create(ctx, "runtime-fail", "v1.2.3", "user-1")
+ req, err := nodeA.Create(ctx, "runtime-fail", "", "v1.2.3", "user-1", false)
if err != nil {
t.Fatalf("create: %v", err)
}
- if _, err := nodeB.PopPending(ctx, "runtime-fail"); err != nil {
+ if _, err := nodeB.PopPending(ctx, "runtime-fail", false); err != nil {
t.Fatalf("pop: %v", err)
}
if err := nodeC.Fail(ctx, req.ID, "download failed"); err != nil {
@@ -205,17 +207,17 @@ func TestRedisUpdateStore_RejectsConcurrentActive(t *testing.T) {
ctx := context.Background()
store := NewRedisUpdateStore(rdb)
- req, err := store.Create(ctx, "runtime-active", "v1.2.3", "user-1")
+ req, err := store.Create(ctx, "runtime-active", "", "v1.2.3", "user-1", false)
if err != nil {
t.Fatalf("create: %v", err)
}
- if _, err := store.Create(ctx, "runtime-active", "v1.2.4", "user-1"); err != errUpdateInProgress {
+ if _, err := store.Create(ctx, "runtime-active", "", "v1.2.4", "user-1", false); err != errUpdateInProgress {
t.Fatalf("second create error = %v, want errUpdateInProgress", err)
}
if err := store.Complete(ctx, req.ID, "done"); err != nil {
t.Fatalf("complete: %v", err)
}
- if _, err := store.Create(ctx, "runtime-active", "v1.2.4", "user-1"); err != nil {
+ if _, err := store.Create(ctx, "runtime-active", "", "v1.2.4", "user-1", false); err != nil {
t.Fatalf("create after terminal should succeed: %v", err)
}
}
@@ -225,11 +227,11 @@ func TestRedisUpdateStore_RunningTimeoutClearsActive(t *testing.T) {
ctx := context.Background()
store := NewRedisUpdateStore(rdb)
- req, err := store.Create(ctx, "runtime-timeout", "v1.2.3", "user-1")
+ req, err := store.Create(ctx, "runtime-timeout", "", "v1.2.3", "user-1", false)
if err != nil {
t.Fatalf("create: %v", err)
}
- popped, err := store.PopPending(ctx, "runtime-timeout")
+ popped, err := store.PopPending(ctx, "runtime-timeout", false)
if err != nil {
t.Fatalf("pop: %v", err)
}
@@ -239,9 +241,7 @@ func TestRedisUpdateStore_RunningTimeoutClearsActive(t *testing.T) {
aged := time.Now().Add(-(updateRunningTimeout + time.Second))
popped.RunStartedAt = &aged
- if err := store.persistRequest(ctx, popped); err != nil {
- t.Fatalf("persist aged request: %v", err)
- }
+ persistUpdateForTest(t, rdb, store, popped)
got, err := store.Get(ctx, req.ID)
if err != nil {
@@ -250,7 +250,7 @@ func TestRedisUpdateStore_RunningTimeoutClearsActive(t *testing.T) {
if got.Status != UpdateTimeout {
t.Fatalf("status = %s, want timeout", got.Status)
}
- if _, err := store.Create(ctx, "runtime-timeout", "v1.2.4", "user-1"); err != nil {
+ if _, err := store.Create(ctx, "runtime-timeout", "", "v1.2.4", "user-1", false); err != nil {
t.Fatalf("create after timeout should succeed: %v", err)
}
}
@@ -260,7 +260,7 @@ func TestRedisUpdateStore_PopPendingConcurrent(t *testing.T) {
ctx := context.Background()
store := NewRedisUpdateStore(rdb)
- req, err := store.Create(ctx, "runtime-race", "v1.2.3", "user-1")
+ req, err := store.Create(ctx, "runtime-race", "", "v1.2.3", "user-1", false)
if err != nil {
t.Fatalf("create: %v", err)
}
@@ -273,7 +273,7 @@ func TestRedisUpdateStore_PopPendingConcurrent(t *testing.T) {
wg.Add(1)
go func() {
defer wg.Done()
- popped, err := store.PopPending(ctx, "runtime-race")
+ popped, err := store.PopPending(ctx, "runtime-race", false)
if err != nil {
errs <- err
return
@@ -307,3 +307,15 @@ var (
_ UpdateStore = (*InMemoryUpdateStore)(nil)
_ UpdateStore = (*RedisUpdateStore)(nil)
)
+
+// persistUpdateForTest overwrites a stored request, e.g. to age it.
+func persistUpdateForTest(t *testing.T, rdb redis.UniversalClient, store *RedisUpdateStore, req *UpdateRequest) {
+ t.Helper()
+ data, err := store.marshalRequest(req)
+ if err != nil {
+ t.Fatalf("marshal: %v", err)
+ }
+ if err := rdb.Set(context.Background(), updateKey(req.ID), data, updateWaitingRetention).Err(); err != nil {
+ t.Fatalf("persist request: %v", err)
+ }
+}
diff --git a/server/internal/handler/runtime_update_test.go b/server/internal/handler/runtime_update_test.go
index 5d03c224b2..e17912bed5 100644
--- a/server/internal/handler/runtime_update_test.go
+++ b/server/internal/handler/runtime_update_test.go
@@ -14,7 +14,7 @@ func TestInMemoryUpdateStore_HasPending(t *testing.T) {
t.Fatalf("empty store should not report pending: has=%v err=%v", has, err)
}
- if _, err := store.Create(ctx, "rt-1", "v1.2.3", "user-1"); err != nil {
+ if _, err := store.Create(ctx, "rt-1", "", "v1.2.3", "user-1", false); err != nil {
t.Fatalf("create: %v", err)
}
if has, err := store.HasPending(ctx, "rt-1"); err != nil || !has {
@@ -24,7 +24,7 @@ func TestInMemoryUpdateStore_HasPending(t *testing.T) {
t.Fatalf("expected pending=false for unrelated runtime: has=%v err=%v", has, err)
}
- if _, err := store.PopPending(ctx, "rt-1"); err != nil {
+ if _, err := store.PopPending(ctx, "rt-1", false); err != nil {
t.Fatalf("pop: %v", err)
}
if has, err := store.HasPending(ctx, "rt-1"); err != nil || has {
@@ -36,7 +36,7 @@ func TestInMemoryUpdateStore_PopPendingIgnoresTerminalHistory(t *testing.T) {
ctx := context.Background()
store := NewInMemoryUpdateStore()
- first, err := store.Create(ctx, "rt-1", "v1.2.3", "user-1")
+ first, err := store.Create(ctx, "rt-1", "", "v1.2.3", "user-1", false)
if err != nil {
t.Fatalf("create first: %v", err)
}
@@ -44,12 +44,12 @@ func TestInMemoryUpdateStore_PopPendingIgnoresTerminalHistory(t *testing.T) {
t.Fatalf("fail first: %v", err)
}
time.Sleep(2 * time.Millisecond)
- second, err := store.Create(ctx, "rt-1", "v1.2.4", "user-1")
+ second, err := store.Create(ctx, "rt-1", "", "v1.2.4", "user-1", false)
if err != nil {
t.Fatalf("create second: %v", err)
}
- got, err := store.PopPending(ctx, "rt-1")
+ got, err := store.PopPending(ctx, "rt-1", false)
if err != nil {
t.Fatalf("pop: %v", err)
}
@@ -62,11 +62,11 @@ func TestInMemoryUpdateStore_RunningRequestTimesOut(t *testing.T) {
ctx := context.Background()
store := NewInMemoryUpdateStore()
- req, err := store.Create(ctx, "rt-timeout", "v1.2.3", "user-1")
+ req, err := store.Create(ctx, "rt-timeout", "", "v1.2.3", "user-1", false)
if err != nil {
t.Fatalf("create: %v", err)
}
- claimed, err := store.PopPending(ctx, "rt-timeout")
+ claimed, err := store.PopPending(ctx, "rt-timeout", false)
if err != nil {
t.Fatalf("pop: %v", err)
}
@@ -78,7 +78,7 @@ func TestInMemoryUpdateStore_RunningRequestTimesOut(t *testing.T) {
}
aged := time.Now().Add(-(updateRunningTimeout + time.Second))
- claimed.RunStartedAt = &aged
+ store.requests[req.ID].RunStartedAt = &aged
got, err := store.Get(ctx, req.ID)
if err != nil {
t.Fatalf("get: %v", err)
@@ -95,17 +95,17 @@ func TestInMemoryUpdateStore_RejectsConcurrentActiveUntilTerminal(t *testing.T)
ctx := context.Background()
store := NewInMemoryUpdateStore()
- req, err := store.Create(ctx, "rt-1", "v1.2.3", "user-1")
+ req, err := store.Create(ctx, "rt-1", "", "v1.2.3", "user-1", false)
if err != nil {
t.Fatalf("create: %v", err)
}
- if _, err := store.Create(ctx, "rt-1", "v1.2.4", "user-1"); err != errUpdateInProgress {
+ if _, err := store.Create(ctx, "rt-1", "", "v1.2.4", "user-1", false); err != errUpdateInProgress {
t.Fatalf("second create error = %v, want errUpdateInProgress", err)
}
if err := store.Complete(ctx, req.ID, "done"); err != nil {
t.Fatalf("complete: %v", err)
}
- if _, err := store.Create(ctx, "rt-1", "v1.2.4", "user-1"); err != nil {
+ if _, err := store.Create(ctx, "rt-1", "", "v1.2.4", "user-1", false); err != nil {
t.Fatalf("create after terminal should succeed: %v", err)
}
}
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index 8940635a87..ebb4eb22b5 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -462,6 +462,9 @@ type ChatSessionUpdatedPayload struct {
type DaemonHeartbeatRequestPayload struct {
RuntimeID string `json:"runtime_id"`
SupportsBatchImport bool `json:"supports_batch_import,omitempty"`
+ // SupportsQueuedUpdate: the daemon can hold a deferrable update while
+ // busy and install it once idle (see DaemonHeartbeatPendingUpdate).
+ SupportsQueuedUpdate bool `json:"supports_queued_update,omitempty"`
}
// DaemonHeartbeatAckPayload is the server's reply to DaemonHeartbeatRequestPayload.
@@ -501,6 +504,12 @@ const HeartbeatStatusRuntimeGone = "runtime_gone"
type DaemonHeartbeatPendingUpdate struct {
ID string `json:"id"`
TargetVersion string `json:"target_version"`
+ // Deferrable: a busy daemon should hold this update, report "scheduled",
+ // and install it once idle — only after the server accepts its "running"
+ // report, which it refuses once the update was cancelled or expired. The
+ // offer repeats on every heartbeat until then. Without it, the update
+ // is running from delivery and a busy daemon fails it.
+ Deferrable bool `json:"deferrable,omitempty"`
}
// DaemonHeartbeatPendingModelList describes a request for the daemon to