Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat: add cli update
Gusd97c5057d160
diff --git a/src/cli/commands/update.test.ts b/src/cli/commands/update.test.tsnew file mode 100644index 000000000..7257b8ac8--- /dev/null+++ b/src/cli/commands/update.test.ts@@ -0,0 +1,96 @@+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";++const mockGetCurrentVersion = vi.fn();+const mockFetchLatestVersion = vi.fn();+const mockRunNpmUpdate = vi.fn();++vi.mock("../lib/update.js", () => ({+ getCurrentVersion: () => mockGetCurrentVersion(),+ fetchLatestVersion: () => mockFetchLatestVersion(),+ runNpmUpdate: (...args: any[]) => mockRunNpmUpdate(...args),+}));++vi.mock("@alook/shared", () => ({+ semverGte: (a: string, b: string) => {+ const pa = a.split(".").map(Number);+ const pb = b.split(".").map(Number);+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {+ const sa = pa[i] ?? 0;+ const sb = pb[i] ?? 0;+ if (sa > sb) return true;+ if (sa < sb) return false;+ }+ return true;+ },+}));++import { updateCommand } from "./update";++describe("alook update", () => {+ let consoleSpy: ReturnType<typeof vi.spyOn>;+ let consoleErrSpy: ReturnType<typeof vi.spyOn>;+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;+ let mockExit: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ vi.clearAllMocks();+ consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});+ consoleErrSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ consoleWarnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});+ mockExit = vi.spyOn(process, "exit").mockImplementation(() => undefined as never);+ vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("no daemon")));+ });++ afterEach(() => {+ consoleSpy.mockRestore();+ consoleErrSpy.mockRestore();+ consoleWarnSpy.mockRestore();+ mockExit.mockRestore();+ vi.unstubAllGlobals();+ });++ it("shows 'already up to date' when on latest version", async () => {+ mockGetCurrentVersion.mockReturnValue("1.0.0");+ mockFetchLatestVersion.mockResolvedValue("1.0.0");++ const cmd = updateCommand();+ await cmd.parseAsync(["node", "update"]);++ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("up to date"));+ });++ it("runs npm install when newer version available", async () => {+ mockGetCurrentVersion.mockReturnValue("0.5.0");+ mockFetchLatestVersion.mockResolvedValue("1.0.0");+ mockRunNpmUpdate.mockResolvedValue({ success: true, output: "" });++ const cmd = updateCommand();+ await cmd.parseAsync(["node", "update"]);++ expect(mockRunNpmUpdate).toHaveBeenCalledWith("1.0.0");+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Updated successfully"));+ });++ it("handles network errors gracefully", async () => {+ mockGetCurrentVersion.mockReturnValue("0.5.0");+ mockFetchLatestVersion.mockResolvedValue(null);++ const cmd = updateCommand();+ await cmd.parseAsync(["node", "update"]);++ expect(consoleErrSpy).toHaveBeenCalledWith(expect.stringContaining("Failed to fetch"));+ expect(mockExit).toHaveBeenCalledWith(1);+ });++ it("warns when daemon health endpoint is reachable", async () => {+ mockGetCurrentVersion.mockReturnValue("0.5.0");+ mockFetchLatestVersion.mockResolvedValue("1.0.0");+ mockRunNpmUpdate.mockResolvedValue({ success: true, output: "" });+ (globalThis.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({ ok: true });++ const cmd = updateCommand();+ await cmd.parseAsync(["node", "update"]);++ expect(consoleWarnSpy).toHaveBeenCalledWith(expect.stringContaining("daemon is running"));+ });+});diff --git a/src/cli/commands/update.ts b/src/cli/commands/update.tsnew file mode 100644index 000000000..51a371711--- /dev/null+++ b/src/cli/commands/update.ts@@ -0,0 +1,48 @@+import { Command } from "commander";+import { getCurrentVersion, fetchLatestVersion, runNpmUpdate } from "../lib/update.js";+import { semverGte } from "@alook/shared";++export function updateCommand(): Command {+ const cmd = new Command("update")+ .description("Update CLI to the latest version")+ .action(async () => {+ const current = getCurrentVersion();+ console.log(`Current version: ${current}`);++ const latest = await fetchLatestVersion();+ if (!latest) {+ console.error("Failed to fetch latest version from npm registry.");+ process.exit(1);+ return;+ }++ if (semverGte(current, latest)) {+ console.log(`Already up to date (v${current}).`);+ return;+ }++ // Check if daemon is running+ const healthPort = Number(process.env.ALOOK_HEALTH_PORT) || 19514;+ try {+ const res = await fetch(`http://127.0.0.1:${healthPort}/health`);+ if (res.ok) {+ console.warn(+ "Warning: daemon is running on the old version. After update, restart with: alook daemon restart",+ );+ }+ } catch {+ // daemon not running — fine+ }++ console.log(`Updating to v${latest}...`);+ const result = await runNpmUpdate(latest);+ if (result.success) {+ console.log(`Updated successfully: v${current} → v${latest}`);+ } else {+ console.error(`Update failed:\n${result.output}`);+ process.exit(1);+ }+ });++ return cmd;+}diff --git a/src/cli/daemon/client.ts b/src/cli/daemon/client.tsindex c6cf45561..ccbf6a248 100644--- a/src/cli/daemon/client.ts+++ b/src/cli/daemon/client.ts@@ -58,15 +58,24 @@ export class DaemonClient {});}- async poll(token: string, daemonId: string, maxTasks: number): Promise<{ tasks: TaskApi[], evicted: boolean }> {+ async poll(+ token: string,+ daemonId: string,+ maxTasks: number,+ cliVersion?: string,+ ): Promise<{ tasks: TaskApi[]; evicted: boolean; pending_update?: { version: string } }> {const raw = await this.request<unknown>("POST","/api/daemon/tasks/poll",token,- { daemon_id: daemonId, max_tasks: maxTasks },+ { daemon_id: daemonId, max_tasks: maxTasks, ...(cliVersion && { cli_version: cliVersion }) },);const resp: PollResponse = PollResponseSchema.parse(raw);- return { tasks: resp.tasks, evicted: resp.evicted ?? false };+ return {+ tasks: resp.tasks,+ evicted: resp.evicted ?? false,+ pending_update: resp.pending_update,+ };}startTask(token: string, taskId: string) {diff --git a/src/cli/daemon/config.ts b/src/cli/daemon/config.tsindex 15b904b36..7d19297e6 100644--- a/src/cli/daemon/config.ts+++ b/src/cli/daemon/config.ts@@ -1,6 +1,7 @@import { hostname } from "os";import { join } from "path";import { configDir } from "../lib/config.js";+import { getCurrentVersion } from "../lib/version.js";export function pidFilePath(profile?: string): string {const name = profile ? `daemon_${profile}.pid` : "daemon.pid";@@ -106,7 +107,7 @@ export function loadDaemonConfig(profile?: string): DaemonConfig {deviceName: process.env.ALOOK_DAEMON_DEVICE_NAME || h,runtimeName: process.env.ALOOK_AGENT_RUNTIME_NAME || "Local Agent",workspacesRoot,- cliVersion: "0.1.0",+ cliVersion: getCurrentVersion(),};}diff --git a/src/cli/daemon/daemon.test.ts b/src/cli/daemon/daemon.test.tsindex b6464818c..c6bb3a2a1 100644--- a/src/cli/daemon/daemon.test.ts+++ b/src/cli/daemon/daemon.test.ts@@ -42,7 +42,7 @@ vi.mock("./config.js", () => ({vi.mock("./health.js", () => ({createHealthServer: vi.fn(() => ({setRuntimeCount: vi.fn(),- server: { close: vi.fn() },+ server: { close: vi.fn((cb?: () => void) => { if (cb) cb(); }) },})),}));@@ -63,6 +63,11 @@ vi.mock("./pidfile.js", () => ({releaseDaemonPid: vi.fn(),}));+vi.mock("./update-handler.js", () => ({+ handleCliUpdate: vi.fn(),+ isUpdating: vi.fn(() => false),+}));+// Track spawned childreninterface MockChild extends EventEmitter {pid: number;@@ -165,6 +170,7 @@ vi.spyOn(globalThis, "clearInterval").mockImplementation(((timer: any) => {import { spawn } from "child_process";import { loadCLIConfigForProfile, saveCLIConfigForProfile } from "../lib/config.js";import { releaseDaemonPid } from "./pidfile.js";+import { handleCliUpdate } from "./update-handler.js";import { startDaemon, spawnSessionRunner, pruneSessionRunnerLogs } from "./daemon.js";const mockReleaseDaemonPid = vi.mocked(releaseDaemonPid);@@ -405,8 +411,8 @@ describe("daemon with multi-workspace config", () => {await startDaemon();expect(mockClientInstance.poll).toHaveBeenCalledTimes(2);- expect(mockClientInstance.poll).toHaveBeenCalledWith("al_tok_ws1", "d1", 20);- expect(mockClientInstance.poll).toHaveBeenCalledWith("al_tok_ws2", "d1", 20);+ expect(mockClientInstance.poll).toHaveBeenCalledWith("al_tok_ws1", "d1", 20, "0.1.0");+ expect(mockClientInstance.poll).toHaveBeenCalledWith("al_tok_ws2", "d1", 20, "0.1.0");});it("registers each workspace with its own token", async () => {@@ -455,7 +461,7 @@ describe("daemon with multi-workspace config", () => {await new Promise((r) => setTimeout(r, 50));// W2 should be called with max_tasks = 20 - 3 = 17- expect(mockClientInstance.poll).toHaveBeenCalledWith("al_tok_ws2", "d1", 17);+ expect(mockClientInstance.poll).toHaveBeenCalledWith("al_tok_ws2", "d1", 17, "0.1.0");});it("multi-workspace: passes correct token per workspace into session runner", async () => {@@ -1161,3 +1167,49 @@ describe("daemon workspace eviction", () => {expect(saveCLIConfigForProfile).toHaveBeenCalled();});});++describe("daemon restart via update", () => {+ it("handleCliUpdate is called when pending_update is in poll response", async () => {+ vi.clearAllMocks();+ mockProcessExit.mockImplementation((() => {}) as any);++ vi.mocked(loadCLIConfigForProfile).mockReturnValue({+ server_url: "",+ watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],+ });+ mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });++ mockClientInstance.poll.mockResolvedValue({+ tasks: [],+ evicted: false,+ pending_update: { version: "2.0.0" },+ });++ await startDaemon();++ expect(handleCliUpdate).toHaveBeenCalledWith("2.0.0", expect.any(Function));+ });++ it("handleCliUpdate is not called when isUpdating returns true", async () => {+ vi.clearAllMocks();+ mockProcessExit.mockImplementation((() => {}) as any);+ const { isUpdating } = await import("./update-handler.js");+ vi.mocked(isUpdating).mockReturnValue(true);++ vi.mocked(loadCLIConfigForProfile).mockReturnValue({+ server_url: "",+ watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],+ });+ mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });+ mockClientInstance.poll.mockResolvedValue({+ tasks: [],+ evicted: false,+ pending_update: { version: "2.0.0" },+ });++ await startDaemon();++ expect(handleCliUpdate).not.toHaveBeenCalled();+ vi.mocked(isUpdating).mockReturnValue(false);+ });+});diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.tsindex 0a4bbbcfb..e5b8a64e1 100644--- a/src/cli/daemon/daemon.ts+++ b/src/cli/daemon/daemon.ts@@ -7,6 +7,7 @@ import { loadCLIConfigForProfile, saveCLIConfigForProfile } from "../lib/config.import { log } from "../lib/logger.js";import { cmdPrefix } from "../lib/env.js";import { acquireDaemonPid, releaseDaemonPid } from "./pidfile.js";+import { handleCliUpdate, isUpdating } from "./update-handler.js";import { existsSync, mkdirSync, openSync, closeSync, renameSync, readdirSync, statSync, unlinkSync } from "fs";import { execSync, spawn, type ChildProcess } from "child_process";import { fileURLToPath } from "url";@@ -265,13 +266,22 @@ export async function startDaemon(}try {- const { tasks: apiTasks, evicted } = await client.poll(ws.token, config.daemonId, remaining);+ const { tasks: apiTasks, evicted, pending_update } = await client.poll(+ ws.token,+ config.daemonId,+ remaining,+ config.cliVersion,+ );if (evicted) {evictedIds.push(ws.workspaceId);continue;}+ if (pending_update && !isUpdating()) {+ handleCliUpdate(pending_update.version, () => requestRestart());+ }+for (const apiTask of apiTasks) {const task = fromApiTask(apiTask);syncAgentId(task.agentId, ws.workspaceId);@@ -301,13 +311,22 @@ export async function startDaemon(const pollTimer = setInterval(pollCycle, config.pollInterval);let shuttingDown = false;+ let restartRequested = false;++ const requestRestart = () => {+ restartRequested = true;+ shutdown();+ };+const shutdown = async () => {if (shuttingDown) return;shuttingDown = true;- log.info("Shutting down...");+ log.info(restartRequested ? "Restarting..." : "Shutting down...");clearInterval(pollTimer);- const shutdownMs = Number(process.env.ALOOK_SHUTDOWN_TIMEOUT_MS) || 5000;++ const shutdownMs = restartRequested ? 30000 : (Number(process.env.ALOOK_SHUTDOWN_TIMEOUT_MS) || 5000);const timeout = setTimeout(() => process.exit(1), shutdownMs);+try {for (const ws of workspaceStates) {await client.deregister(ws.token, config.daemonId);@@ -315,10 +334,23 @@ export async function startDaemon(} catch {// best-effort deregister}- clearTimeout(timeout);+releaseDaemonPid(profile);- health.server.close();- process.exit(0);+ health.server.close(() => {+ if (restartRequested) {+ const args = ["daemon", "start", "--foreground"];+ if (profile) args.push("--profile", profile);+ if (serverUrl) args.push("--server", serverUrl);+ const child = spawn("alook", args, {+ detached: true,+ stdio: ["ignore", "ignore", "ignore"],+ });+ child.unref();+ log.info(`Spawned new daemon (pid=${child.pid})`);+ }+ clearTimeout(timeout);+ process.exit(0);+ });};process.on("SIGTERM", shutdown);process.on("SIGINT", shutdown);diff --git a/src/cli/daemon/update-handler.test.ts b/src/cli/daemon/update-handler.test.tsnew file mode 100644index 000000000..d9bcdcd10--- /dev/null+++ b/src/cli/daemon/update-handler.test.ts@@ -0,0 +1,68 @@+import { describe, it, expect, vi, beforeEach } from "vitest";++const mockRunNpmUpdate = vi.fn();+vi.mock("../lib/update.js", () => ({+ runNpmUpdate: (...args: any[]) => mockRunNpmUpdate(...args),+}));+vi.mock("../lib/logger.js", () => ({+ log: { info: vi.fn(), error: vi.fn(), debug: vi.fn(), warn: vi.fn() },+}));++import { handleCliUpdate, isUpdating, resetUpdateState } from "./update-handler";++describe("update-handler", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ resetUpdateState();+ });++ it("calls runNpmUpdate and invokes onSuccess on success", async () => {+ mockRunNpmUpdate.mockResolvedValue({ success: true, output: "ok" });+ const onSuccess = vi.fn();++ await handleCliUpdate("1.0.0", onSuccess);++ expect(mockRunNpmUpdate).toHaveBeenCalledWith("1.0.0");+ expect(onSuccess).toHaveBeenCalled();+ });++ it("does not call onSuccess on failure", async () => {+ mockRunNpmUpdate.mockResolvedValue({ success: false, output: "error" });+ const onSuccess = vi.fn();++ await handleCliUpdate("1.0.0", onSuccess);++ expect(onSuccess).not.toHaveBeenCalled();+ });++ it("retries up to 3 times then stops", async () => {+ mockRunNpmUpdate.mockResolvedValue({ success: false, output: "fail" });+ const onSuccess = vi.fn();++ await handleCliUpdate("1.0.0", onSuccess);+ await handleCliUpdate("1.0.0", onSuccess);+ await handleCliUpdate("1.0.0", onSuccess);+ await handleCliUpdate("1.0.0", onSuccess); // should be skipped++ expect(mockRunNpmUpdate).toHaveBeenCalledTimes(3);+ });++ it("prevents concurrent updates", async () => {+ let resolve: () => void;+ mockRunNpmUpdate.mockReturnValue(+ new Promise((r) => { resolve = () => r({ success: true, output: "" }); }),+ );+ const onSuccess = vi.fn();++ const p1 = handleCliUpdate("1.0.0", onSuccess);+ expect(isUpdating()).toBe(true);++ // second call while first is in-flight should be a no-op+ await handleCliUpdate("1.0.0", onSuccess);+ expect(mockRunNpmUpdate).toHaveBeenCalledTimes(1);++ resolve!();+ await p1;+ expect(isUpdating()).toBe(false);+ });+});diff --git a/src/cli/daemon/update-handler.ts b/src/cli/daemon/update-handler.tsnew file mode 100644index 000000000..67ddaf6f2--- /dev/null+++ b/src/cli/daemon/update-handler.ts@@ -0,0 +1,41 @@+import { runNpmUpdate } from "../lib/update.js";+import { log } from "../lib/logger.js";++let updating = false;+let retryCount = 0;+const MAX_RETRIES = 3;++export function isUpdating(): boolean {+ return updating;+}++export function resetUpdateState(): void {+ updating = false;+ retryCount = 0;+}++export async function handleCliUpdate(+ version: string,+ onSuccess: () => void,+): Promise<void> {+ if (updating) return;+ if (retryCount >= MAX_RETRIES) return;++ updating = true;+ try {+ log.info(`Updating CLI to v${version}...`);+ const result = await runNpmUpdate(version);+ if (result.success) {+ log.info(`CLI updated to v${version} — restarting`);+ onSuccess();+ } else {+ retryCount++;+ log.error(`CLI update failed (attempt ${retryCount}/${MAX_RETRIES}): ${result.output}`);+ }+ } catch (e) {+ retryCount++;+ log.error(`CLI update error (attempt ${retryCount}/${MAX_RETRIES})`, e);+ } finally {+ updating = false;+ }+}diff --git a/src/cli/lib/update.test.ts b/src/cli/lib/update.test.tsnew file mode 100644index 000000000..9bdfed14a--- /dev/null+++ b/src/cli/lib/update.test.ts@@ -0,0 +1,103 @@+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";++vi.mock("child_process", () => ({+ spawn: vi.fn(),+}));++import { spawn } from "child_process";+import { getCurrentVersion, fetchLatestVersion, runNpmUpdate } from "./update";+import { EventEmitter } from "events";++const mockSpawn = vi.mocked(spawn);++describe("getCurrentVersion", () => {+ it("returns a version string", () => {+ const v = getCurrentVersion();+ expect(v).toMatch(/^\d+\.\d+\.\d+$/);+ });+});++describe("fetchLatestVersion", () => {+ beforeEach(() => {+ vi.stubGlobal("fetch", vi.fn());+ });+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("parses npm registry response correctly", async () => {+ (globalThis.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({+ ok: true,+ json: async () => ({ version: "1.2.3" }),+ });+ const v = await fetchLatestVersion();+ expect(v).toBe("1.2.3");+ });++ it("returns null on network error", async () => {+ (globalThis.fetch as ReturnType<typeof vi.fn>).mockRejectedValue(+ new Error("network error"),+ );+ const v = await fetchLatestVersion();+ expect(v).toBeNull();+ });++ it("returns null on non-ok response", async () => {+ (globalThis.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({+ ok: false,+ });+ const v = await fetchLatestVersion();+ expect(v).toBeNull();+ });+});++describe("runNpmUpdate", () => {+ it("spawns npm install -g with correct args", async () => {+ const child = new EventEmitter() as any;+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ mockSpawn.mockReturnValue(child);++ const promise = runNpmUpdate("1.0.0");+ child.stdout.emit("data", Buffer.from("added 1 package"));+ child.emit("close", 0);++ const result = await promise;+ expect(mockSpawn).toHaveBeenCalledWith(+ "npm",+ ["install", "-g", "@alook/[email protected]"],+ expect.objectContaining({ stdio: ["ignore", "pipe", "pipe"] }),+ );+ expect(result.success).toBe(true);+ expect(result.output).toContain("added 1 package");+ });++ it("resolves with success: false on npm error", async () => {+ const child = new EventEmitter() as any;+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ mockSpawn.mockReturnValue(child);++ const promise = runNpmUpdate("1.0.0");+ child.stderr.emit("data", Buffer.from("ERR! 404 Not Found"));+ child.emit("close", 1);++ const result = await promise;+ expect(result.success).toBe(false);+ expect(result.output).toContain("ERR! 404");+ });++ it("handles spawn error", async () => {+ const child = new EventEmitter() as any;+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ mockSpawn.mockReturnValue(child);++ const promise = runNpmUpdate("1.0.0");+ child.emit("error", new Error("ENOENT"));++ const result = await promise;+ expect(result.success).toBe(false);+ expect(result.output).toContain("ENOENT");+ });+});diff --git a/src/cli/lib/update.ts b/src/cli/lib/update.tsnew file mode 100644index 000000000..250e3caab--- /dev/null+++ b/src/cli/lib/update.ts@@ -0,0 +1,34 @@+import { spawn } from "child_process";+import { getCurrentVersion } from "./version.js";++export { getCurrentVersion };++export function fetchLatestVersion(): Promise<string | null> {+ return fetch("https://registry.npmjs.org/@alook/cli/latest")+ .then((res) => {+ if (!res.ok) return null;+ return res.json() as Promise<{ version?: string }>;+ })+ .then((data) => data?.version ?? null)+ .catch(() => null);+}++export function runNpmUpdate(+ targetVersion: string,+): Promise<{ success: boolean; output: string }> {+ return new Promise((resolve) => {+ const chunks: Buffer[] = [];+ const child = spawn("npm", ["install", "-g", `@alook/cli@${targetVersion}`], {+ stdio: ["ignore", "pipe", "pipe"],+ });+ child.stdout?.on("data", (d: Buffer) => chunks.push(d));+ child.stderr?.on("data", (d: Buffer) => chunks.push(d));+ child.on("error", (err) => {+ resolve({ success: false, output: err.message });+ });+ child.on("close", (code) => {+ const output = Buffer.concat(chunks).toString();+ resolve({ success: code === 0, output });+ });+ });+}diff --git a/src/cli/src/index.ts b/src/cli/src/index.tsindex 3f734f0ff..bb5694cb7 100644--- a/src/cli/src/index.ts+++ b/src/cli/src/index.ts@@ -7,6 +7,7 @@ import { configCommand } from "../commands/config.js";import { emailCommand } from "../commands/email.js";import { calendarCommand } from "../commands/calendar.js";import { versionCommand } from "../commands/version.js";+import { updateCommand } from "../commands/update.js";const program = new Command();@@ -23,5 +24,6 @@ program.addCommand(emailCommand());program.addCommand(calendarCommand());program.addCommand(configCommand());program.addCommand(versionCommand());+program.addCommand(updateCommand());program.parse();diff --git a/src/shared/src/db/queries/machine.ts b/src/shared/src/db/queries/machine.tsindex 9286aaf8f..89e221395 100644--- a/src/shared/src/db/queries/machine.ts+++ b/src/shared/src/db/queries/machine.ts@@ -98,3 +98,26 @@ export async function deleteMachine(and(eq(machine.daemonId, daemonId), eq(machine.workspaceId, workspaceId)));}++export async function setPendingUpdateVersion(+ db: Database,+ daemonId: string,+ version: string+) {+ const now = new Date().toISOString();+ await db+ .update(machine)+ .set({ pendingUpdateVersion: version, updatedAt: now })+ .where(eq(machine.daemonId, daemonId));+}++export async function clearPendingUpdateVersion(+ db: Database,+ daemonId: string+) {+ const now = new Date().toISOString();+ await db+ .update(machine)+ .set({ pendingUpdateVersion: null, updatedAt: now })+ .where(eq(machine.daemonId, daemonId));+}diff --git a/src/shared/src/db/queries/runtime.ts b/src/shared/src/db/queries/runtime.tsindex 673e6cc10..c188c53f2 100644--- a/src/shared/src/db/queries/runtime.ts+++ b/src/shared/src/db/queries/runtime.ts@@ -58,6 +58,7 @@ export async function listAgentRuntimes(db: Database, workspaceId: string) {createdAt: agentRuntime.createdAt,updatedAt: agentRuntime.updatedAt,machineLastSeenAt: machine.lastSeenAt,+ pendingUpdateVersion: machine.pendingUpdateVersion,}).from(agentRuntime).leftJoin(diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.tsindex e354ff9f2..85807fc7e 100644--- a/src/shared/src/db/schema.ts+++ b/src/shared/src/db/schema.ts@@ -103,6 +103,7 @@ export const machine = sqliteTable(deviceInfo: text("device_info").notNull().default(""),lastSeenAt: text("last_seen_at"),createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),+ pendingUpdateVersion: text("pending_update_version"),updatedAt: text("updated_at").notNull().$defaultFn(() => new Date().toISOString()),},(t) => [primaryKey({ columns: [t.workspaceId, t.daemonId] })]diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 9e4147780..18292f70e 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -146,3 +146,4 @@ export { parseEmailHandle, toAlookAddress, isValidHandle } from "./utils/email";export { isValidToken, isValidEmail } from "./utils/validation";export { isOnline, formatStatus } from "./utils/status";export { isUniqueConstraintError } from "./utils/db-errors";+export { semverGte } from "./semver";diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex 9ee2c93dc..0ead95fbd 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -91,12 +91,14 @@ export type TaskApi = z.infer<typeof TaskApiSchema>;export const PollRequestSchema = z.object({daemon_id: z.string().min(1),max_tasks: z.number().int().min(1).default(1),+ cli_version: z.string().optional(),});export type PollRequest = z.infer<typeof PollRequestSchema>;export const PollResponseSchema = z.object({tasks: z.array(TaskApiSchema),evicted: z.boolean().optional(),+ pending_update: z.object({ version: z.string() }).optional(),});export type PollResponse = z.infer<typeof PollResponseSchema>;diff --git a/src/shared/src/semver.test.ts b/src/shared/src/semver.test.tsnew file mode 100644index 000000000..6455a2050--- /dev/null+++ b/src/shared/src/semver.test.ts@@ -0,0 +1,29 @@+import { describe, it, expect } from "vitest";+import { semverGte } from "./semver";++describe("semverGte", () => {+ it("returns true when a > b", () => {+ expect(semverGte("0.2.0", "0.1.0")).toBe(true);+ });++ it("returns false when a < b", () => {+ expect(semverGte("0.1.0", "0.2.0")).toBe(false);+ });++ it("compares numerically, not lexicographically", () => {+ expect(semverGte("0.10.0", "0.2.0")).toBe(true);+ });++ it("returns true when equal", () => {+ expect(semverGte("1.0.0", "1.0.0")).toBe(true);+ });++ it("handles major version dominance", () => {+ expect(semverGte("2.0.0", "1.99.99")).toBe(true);+ });++ it("handles patch differences", () => {+ expect(semverGte("1.0.1", "1.0.0")).toBe(true);+ expect(semverGte("1.0.0", "1.0.1")).toBe(false);+ });+});diff --git a/src/shared/src/semver.ts b/src/shared/src/semver.tsnew file mode 100644index 000000000..db5887ea2--- /dev/null+++ b/src/shared/src/semver.ts@@ -0,0 +1,11 @@+export function semverGte(a: string, b: string): boolean {+ const pa = a.split(".").map(Number);+ const pb = b.split(".").map(Number);+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {+ const sa = pa[i] ?? 0;+ const sb = pb[i] ?? 0;+ if (sa > sb) return true;+ if (sa < sb) return false;+ }+ return true;+}diff --git a/src/shared/src/types.ts b/src/shared/src/types.tsindex 360a54ae5..7fcdc0a9f 100644--- a/src/shared/src/types.ts+++ b/src/shared/src/types.ts@@ -41,6 +41,7 @@ export interface AgentRuntime {status: string;device_info: string;metadata: Record<string, unknown>;+ pending_update_version?: string | null;last_seen_at: string | null;created_at: string;updated_at: string;diff --git a/src/web/migrations/0002_add_pending_update_version.sql b/src/web/migrations/0002_add_pending_update_version.sqlnew file mode 100644index 000000000..3140c5f72--- /dev/null+++ b/src/web/migrations/0002_add_pending_update_version.sql@@ -0,0 +1 @@+ALTER TABLE machine ADD COLUMN pending_update_version TEXT;diff --git a/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx b/src/web/src/app/(app)/w/[slug]/runtimes/page.tsxindex afb61f0a7..244a657e8 100644--- a/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx@@ -25,8 +25,11 @@ import { toast } from "sonner";import { Skeleton } from "@/components/ui/skeleton";import { Monitor, Plus } from "lucide-react";import type { AgentRuntime as Runtime } from "@alook/shared";+import { semverGte } from "@alook/shared";import { CLI_CMD } from "@/lib/utils";import { ProviderLogo } from "@/components/provider-logo";+import { triggerRuntimeUpdate, fetchLatestCliVersion } from "@/lib/api";+import { Loader2 } from "lucide-react";function ConnectMachineSteps({generatedToken,@@ -140,12 +143,21 @@ export default function RuntimesPage() {const [generatedToken, setGeneratedToken] = useState("");const [generatingToken, setGeneratingToken] = useState(false);+ const [latestCliVersion, setLatestCliVersion] = useState<string | null>(null);+ const [updatingDaemons, setUpdatingDaemons] = useState<Set<string>>(new Set());+const [confirmOpen, setConfirmOpen] = useState(false);const [confirmTitle, setConfirmTitle] = useState("");const [confirmDescription, setConfirmDescription] = useState("");const [confirmLoading, setConfirmLoading] = useState(false);const confirmAction = useRef<(() => Promise<void>) | null>(null);+ useEffect(() => {+ fetchLatestCliVersion()+ .then((data) => setLatestCliVersion(data.version))+ .catch(() => {});+ }, []);+// Auto-open "New machine" sheet when navigated with ?connectuseEffect(() => {if (searchParams.has("connect")) {@@ -198,23 +210,40 @@ export default function RuntimesPage() {}}, [handleGenerateToken]);+ const handleUpdate = async (runtimeId: string, daemonId: string) => {+ setUpdatingDaemons((prev) => new Set(prev).add(daemonId));+ try {+ await triggerRuntimeUpdate(runtimeId, workspaceId);+ toast.success("Update triggered");+ } catch {+ toast.error("Failed to trigger update");+ setUpdatingDaemons((prev) => {+ const next = new Set(prev);+ next.delete(daemonId);+ return next;+ });+ }+ };+// Group runtimes by machineconst machines = new Map<string,- { deviceInfo: string; name: string; status: string; lastSeenAt: string | null; runtimes: Runtime[] }+ { deviceInfo: string; name: string; status: string; lastSeenAt: string | null; pendingUpdateVersion: string | null; cliVersion: string | null; runtimes: Runtime[] }>();for (const rt of runtimes) {const key = rt.daemon_id || rt.id;if (!machines.has(key)) {+ const meta = rt.metadata as Record<string, unknown> | null;machines.set(key, {deviceInfo: typeof rt.device_info === "string" ? rt.device_info : "",name: rt.name || "",status: rt.status,lastSeenAt: rt.last_seen_at,+ pendingUpdateVersion: rt.pending_update_version ?? null,+ cliVersion: (meta?.cli_version as string) ?? null,runtimes: [],});}- // Use first runtime's status (all share the same machine status)machines.get(key)!.runtimes.push(rt);}@@ -329,6 +358,31 @@ export default function RuntimesPage() {</Badge></div><CardAction>+ {(() => {+ const isUpdating = !!machine.pendingUpdateVersion || updatingDaemons.has(daemonId);+ const needsUpdate = latestCliVersion && machine.cliVersion && !semverGte(machine.cliVersion, latestCliVersion);+ if (isUpdating) {+ return (+ <Button variant="ghost" size="sm" disabled className="text-xs h-6 px-2">+ <Loader2 className="size-3 animate-spin mr-1" />+ Updating...+ </Button>+ );+ }+ if (needsUpdate) {+ return (+ <Button+ variant="ghost"+ size="sm"+ className="text-xs h-6 px-2"+ onClick={() => handleUpdate(machine.runtimes[0].id, daemonId)}+ >+ Update+ </Button>+ );+ }+ return null;+ })()}<Buttonvariant="ghost"size="sm"@@ -349,11 +403,16 @@ export default function RuntimesPage() {</CardHeader><CardContent><div className="space-y-2.5">- <p className="text-xs text-muted-foreground tabular-nums">- {machine.lastSeenAt ? new Date(- machine.lastSeenAt- ).toLocaleString() : "Never seen"}- </p>+ <div className="flex items-center gap-2 text-xs text-muted-foreground tabular-nums">+ <span>+ {machine.lastSeenAt ? new Date(+ machine.lastSeenAt+ ).toLocaleString() : "Never seen"}+ </span>+ {machine.cliVersion && (+ <span className="text-muted-foreground/60">v{machine.cliVersion}</span>+ )}+ </div><div className="flex flex-wrap gap-1.5">{machine.runtimes.map((runtime) => (<Badgediff --git a/src/web/src/app/api/cli/latest-version/route.test.ts b/src/web/src/app/api/cli/latest-version/route.test.tsnew file mode 100644index 000000000..4129fc84f--- /dev/null+++ b/src/web/src/app/api/cli/latest-version/route.test.ts@@ -0,0 +1,56 @@+import { describe, it, expect, vi, beforeEach } from "vitest";++const mockFetch = vi.fn();+vi.stubGlobal("fetch", mockFetch);++import { GET } from "./route";++describe("GET /api/cli/latest-version", () => {+ beforeEach(() => vi.clearAllMocks());++ it("returns version from npm registry", async () => {+ mockFetch.mockResolvedValue({+ ok: true,+ json: async () => ({ version: "2.0.0" }),+ });++ const res = await GET();+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.version).toBe("2.0.0");+ });++ it("returns 502 when npm registry returns non-ok", async () => {+ mockFetch.mockResolvedValue({ ok: false, status: 500 });++ const res = await GET();+ const body = await res.json();++ expect(res.status).toBe(502);+ expect(body.error).toContain("npm registry");+ });++ it("returns 502 when fetch throws", async () => {+ mockFetch.mockRejectedValue(new Error("network error"));++ const res = await GET();+ const body = await res.json();++ expect(res.status).toBe(502);+ expect(body.error).toContain("npm registry");+ });++ it("returns 502 when response has no version field", async () => {+ mockFetch.mockResolvedValue({+ ok: true,+ json: async () => ({ name: "@alook/cli" }),+ });++ const res = await GET();+ const body = await res.json();++ expect(res.status).toBe(502);+ expect(body.error).toContain("version");+ });+});diff --git a/src/web/src/app/api/cli/latest-version/route.ts b/src/web/src/app/api/cli/latest-version/route.tsnew file mode 100644index 000000000..ef2bc8ea6--- /dev/null+++ b/src/web/src/app/api/cli/latest-version/route.ts@@ -0,0 +1,17 @@+import { writeJSON, writeError } from "@/lib/middleware/helpers";++export async function GET() {+ try {+ const res = await fetch("https://registry.npmjs.org/@alook/cli/latest");+ if (!res.ok) {+ return writeError("npm registry returned " + res.status, 502);+ }+ const data = (await res.json()) as { version?: string };+ if (!data.version) {+ return writeError("npm registry response missing version", 502);+ }+ return writeJSON({ version: data.version });+ } catch {+ return writeError("failed to reach npm registry", 502);+ }+}diff --git a/src/web/src/app/api/daemon/tasks/poll/route.test.ts b/src/web/src/app/api/daemon/tasks/poll/route.test.tsindex 876e5797c..1e4ef85dd 100644--- a/src/web/src/app/api/daemon/tasks/poll/route.test.ts+++ b/src/web/src/app/api/daemon/tasks/poll/route.test.ts@@ -3,6 +3,8 @@ import { NextRequest } from "next/server";const mockGetRuntimeIdsByDaemon = vi.fn();const mockUpsertMachine = vi.fn();+const mockGetMachineByDaemon = vi.fn();+const mockClearPendingUpdateVersion = vi.fn();const mockGetAgent = vi.fn();const mockClaimTasksForRuntimes = vi.fn();const mockSweepStaleState = vi.fn();@@ -23,6 +25,8 @@ vi.mock("@alook/shared", async () => {},machine: {upsertMachine: (...args: unknown[]) => mockUpsertMachine(...args),+ getMachineByDaemon: (...args: unknown[]) => mockGetMachineByDaemon(...args),+ clearPendingUpdateVersion: (...args: unknown[]) => mockClearPendingUpdateVersion(...args),},agent: {getAgent: (...args: unknown[]) => mockGetAgent(...args),@@ -87,7 +91,10 @@ function postReq(body: unknown) {}describe("POST /api/daemon/tasks/poll", () => {- beforeEach(() => vi.clearAllMocks());+ beforeEach(() => {+ vi.clearAllMocks();+ mockGetMachineByDaemon.mockResolvedValue(null);+ });it("returns evicted: true and skips heartbeat when daemon has no runtimes", async () => {mockGetRuntimeIdsByDaemon.mockResolvedValue([]);@@ -251,4 +258,83 @@ describe("POST /api/daemon/tasks/poll", () => {expect(res.status).toBe(200);expect(mockClaimTasksForRuntimes).toHaveBeenCalled();});++ it("returns pending_update when pendingUpdateVersion is set and cli_version is older", async () => {+ mockUpsertMachine.mockResolvedValue({});+ mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);+ mockSweepStaleState.mockResolvedValue(undefined);+ mockBroadcastToUser.mockResolvedValue(undefined);+ mockClaimTasksForRuntimes.mockResolvedValue([]);+ mockGetMachineByDaemon.mockResolvedValue({ pendingUpdateVersion: "1.0.0" });++ const res = await POST(postReq({ daemon_id: "d1", cli_version: "0.5.0" }));+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.pending_update).toEqual({ version: "1.0.0" });+ });++ it("does not return pending_update when pendingUpdateVersion is not set", async () => {+ mockUpsertMachine.mockResolvedValue({});+ mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);+ mockSweepStaleState.mockResolvedValue(undefined);+ mockBroadcastToUser.mockResolvedValue(undefined);+ mockClaimTasksForRuntimes.mockResolvedValue([]);+ mockGetMachineByDaemon.mockResolvedValue({ pendingUpdateVersion: null });++ const res = await POST(postReq({ daemon_id: "d1", cli_version: "0.5.0" }));+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.pending_update).toBeUndefined();+ });++ it("auto-clears pendingUpdateVersion when cli_version >= pending version", async () => {+ mockUpsertMachine.mockResolvedValue({});+ mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);+ mockSweepStaleState.mockResolvedValue(undefined);+ mockBroadcastToUser.mockResolvedValue(undefined);+ mockClaimTasksForRuntimes.mockResolvedValue([]);+ mockGetMachineByDaemon.mockResolvedValue({ pendingUpdateVersion: "1.0.0" });+ mockClearPendingUpdateVersion.mockResolvedValue(undefined);++ const res = await POST(postReq({ daemon_id: "d1", cli_version: "1.0.0" }));+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.pending_update).toBeUndefined();+ expect(mockClearPendingUpdateVersion).toHaveBeenCalledWith({}, "d1");+ });++ it("does not attach pending_update when cli_version is missing (backward compat)", async () => {+ mockUpsertMachine.mockResolvedValue({});+ mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);+ mockSweepStaleState.mockResolvedValue(undefined);+ mockBroadcastToUser.mockResolvedValue(undefined);+ mockClaimTasksForRuntimes.mockResolvedValue([]);+ mockGetMachineByDaemon.mockResolvedValue({ pendingUpdateVersion: "1.0.0" });++ const res = await POST(postReq({ daemon_id: "d1" }));+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.pending_update).toBeUndefined();+ expect(mockClearPendingUpdateVersion).not.toHaveBeenCalled();+ });++ it("poll without pending_update works unchanged", async () => {+ mockUpsertMachine.mockResolvedValue({});+ mockGetRuntimeIdsByDaemon.mockResolvedValue(["r1"]);+ mockSweepStaleState.mockResolvedValue(undefined);+ mockBroadcastToUser.mockResolvedValue(undefined);+ mockClaimTasksForRuntimes.mockResolvedValue([]);+ mockGetMachineByDaemon.mockResolvedValue(null);++ const res = await POST(postReq({ daemon_id: "d1", cli_version: "0.5.0" }));+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.tasks).toEqual([]);+ expect(body.pending_update).toBeUndefined();+ });});diff --git a/src/web/src/app/api/daemon/tasks/poll/route.ts b/src/web/src/app/api/daemon/tasks/poll/route.tsindex 1432a989e..e1695450c 100644--- a/src/web/src/app/api/daemon/tasks/poll/route.ts+++ b/src/web/src/app/api/daemon/tasks/poll/route.ts@@ -1,6 +1,6 @@import { NextRequest } from "next/server";import { getCloudflareContext } from "@opennextjs/cloudflare";-import { createDb, queries, PollRequestSchema } from "@alook/shared";+import { createDb, queries, PollRequestSchema, semverGte } from "@alook/shared";import { withAuth } from "@/lib/middleware/auth";import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";import { taskToResponse } from "@/lib/api/responses";@@ -91,5 +91,20 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {});}- return writeJSON({ tasks });+ // 5. Pending update check+ const machineRow = await queries.machine.getMachineByDaemon(+ db,+ body.daemon_id,+ ctx.workspaceId,+ );+ let pendingUpdate: { version: string } | undefined;+ if (machineRow?.pendingUpdateVersion && body.cli_version) {+ if (semverGte(body.cli_version, machineRow.pendingUpdateVersion)) {+ await queries.machine.clearPendingUpdateVersion(db, body.daemon_id);+ } else {+ pendingUpdate = { version: machineRow.pendingUpdateVersion };+ }+ }++ return writeJSON({ tasks, ...(pendingUpdate && { pending_update: pendingUpdate }) });});diff --git a/src/web/src/app/api/runtimes/[runtimeId]/update/route.test.ts b/src/web/src/app/api/runtimes/[runtimeId]/update/route.test.tsnew file mode 100644index 000000000..aa3926aed--- /dev/null+++ b/src/web/src/app/api/runtimes/[runtimeId]/update/route.test.ts@@ -0,0 +1,159 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++const mockGetAgentRuntimeForWorkspace = vi.fn();+const mockSetPendingUpdateVersion = vi.fn();+const mockClearPendingUpdateVersion = vi.fn();+const mockGetMemberByUserAndWorkspace = vi.fn();++vi.mock("@opennextjs/cloudflare", () => ({+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),+}));++vi.mock("@alook/shared", () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ runtime: {+ getAgentRuntimeForWorkspace: (...args: any[]) =>+ mockGetAgentRuntimeForWorkspace(...args),+ },+ machine: {+ setPendingUpdateVersion: (...args: any[]) =>+ mockSetPendingUpdateVersion(...args),+ clearPendingUpdateVersion: (...args: any[]) =>+ mockClearPendingUpdateVersion(...args),+ },+ member: {+ getMemberByUserAndWorkspace: (...args: any[]) =>+ mockGetMemberByUserAndWorkspace(...args),+ },+ },+}));++vi.mock("@/lib/middleware/auth", () => ({+ withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {+ const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params;+ return handler(req, { userId: "u1", email: "[email protected]", params });+ }),+}));++vi.mock("@/lib/middleware/workspace", () => ({+ withWorkspaceMember: vi.fn(async (req: any) => {+ const wsId = req.nextUrl.searchParams.get("workspace_id");+ if (!wsId) {+ const { NextResponse } = await import("next/server");+ return NextResponse.json({ error: "workspace_id is required" }, { status: 400 });+ }+ const member = await mockGetMemberByUserAndWorkspace({}, "u1", wsId);+ if (!member) {+ const { NextResponse } = await import("next/server");+ return NextResponse.json({ error: "workspace not found" }, { status: 404 });+ }+ return { workspaceId: wsId };+ }),+}));++vi.mock("@/lib/logger", () => ({+ log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },+}));++// Mock global fetch for npm registry+const mockFetch = vi.fn();+vi.stubGlobal("fetch", mockFetch);++import { POST, DELETE } from "./route";++function makeReq(method: string, runtimeId: string, workspaceId: string) {+ const url = `http://localhost/api/runtimes/${runtimeId}/update?workspace_id=${workspaceId}`;+ return new NextRequest(url, { method });+}++describe("POST /api/runtimes/[runtimeId]/update", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });+ });++ it("returns 200 with pending_update_version", async () => {+ mockGetAgentRuntimeForWorkspace.mockResolvedValue({+ id: "rt1",+ daemonId: "d1",+ });+ mockFetch.mockResolvedValue({+ ok: true,+ json: async () => ({ version: "1.0.0" }),+ });+ mockSetPendingUpdateVersion.mockResolvedValue(undefined);++ const res = await POST(makeReq("POST", "rt1", "w1"));+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.pending_update_version).toBe("1.0.0");+ expect(mockSetPendingUpdateVersion).toHaveBeenCalledWith({}, "d1", "1.0.0");+ });++ it("returns 404 for non-existent runtime", async () => {+ mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);++ const res = await POST(makeReq("POST", "nonexistent", "w1"));+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toContain("not found");+ });++ it("returns 502 when npm registry is unreachable", async () => {+ mockGetAgentRuntimeForWorkspace.mockResolvedValue({+ id: "rt1",+ daemonId: "d1",+ });+ mockFetch.mockResolvedValue({ ok: false });++ const res = await POST(makeReq("POST", "rt1", "w1"));+ const body = await res.json();++ expect(res.status).toBe(502);+ expect(body.error).toContain("npm");+ });++ it("returns 404 for runtime in another workspace", async () => {+ mockGetMemberByUserAndWorkspace.mockResolvedValue(null);++ const res = await POST(makeReq("POST", "rt1", "w-other"));+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toContain("workspace not found");+ });+});++describe("DELETE /api/runtimes/[runtimeId]/update", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });+ });++ it("returns 204 when cancelling update", async () => {+ mockGetAgentRuntimeForWorkspace.mockResolvedValue({+ id: "rt1",+ daemonId: "d1",+ });+ mockClearPendingUpdateVersion.mockResolvedValue(undefined);++ const res = await DELETE(makeReq("DELETE", "rt1", "w1"));++ expect(res.status).toBe(204);+ expect(mockClearPendingUpdateVersion).toHaveBeenCalledWith({}, "d1");+ });++ it("returns 404 for non-existent runtime", async () => {+ mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);++ const res = await DELETE(makeReq("DELETE", "nonexistent", "w1"));+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toContain("not found");+ });+});diff --git a/src/web/src/app/api/runtimes/[runtimeId]/update/route.ts b/src/web/src/app/api/runtimes/[runtimeId]/update/route.tsnew file mode 100644index 000000000..16aa439d8--- /dev/null+++ b/src/web/src/app/api/runtimes/[runtimeId]/update/route.ts@@ -0,0 +1,64 @@+import { NextRequest } from "next/server";+import { getCloudflareContext } from "@opennextjs/cloudflare";+import { createDb, queries } from "@alook/shared";+import { withAuth } from "@/lib/middleware/auth";+import { withWorkspaceMember } from "@/lib/middleware/workspace";+import { writeJSON, writeError } from "@/lib/middleware/helpers";++async function fetchLatestCliVersion(): Promise<string | null> {+ try {+ const res = await fetch("https://registry.npmjs.org/@alook/cli/latest");+ if (!res.ok) return null;+ const data = (await res.json()) as { version?: string };+ return data.version ?? null;+ } catch {+ return null;+ }+}++export const POST = withAuth(async (req: NextRequest, ctx) => {+ const ws = await withWorkspaceMember(req, ctx);+ if (ws instanceof Response) return ws;++ const { env } = getCloudflareContext();+ const db = createDb((env as Env).DB);++ const runtimeId = req.nextUrl.pathname.split("/runtimes/")[1]?.split("/")[0];+ if (!runtimeId) return writeError("runtime id required", 400);++ const runtime = await queries.runtime.getAgentRuntimeForWorkspace(+ db,+ runtimeId,+ ws.workspaceId,+ );+ if (!runtime) return writeError("runtime not found", 404);++ const latestVersion = await fetchLatestCliVersion();+ if (!latestVersion) return writeError("failed to fetch latest CLI version from npm", 502);++ await queries.machine.setPendingUpdateVersion(db, runtime.daemonId, latestVersion);++ return writeJSON({ pending_update_version: latestVersion });+});++export const DELETE = withAuth(async (req: NextRequest, ctx) => {+ const ws = await withWorkspaceMember(req, ctx);+ if (ws instanceof Response) return ws;++ const { env } = getCloudflareContext();+ const db = createDb((env as Env).DB);++ const runtimeId = req.nextUrl.pathname.split("/runtimes/")[1]?.split("/")[0];+ if (!runtimeId) return writeError("runtime id required", 400);++ const runtime = await queries.runtime.getAgentRuntimeForWorkspace(+ db,+ runtimeId,+ ws.workspaceId,+ );+ if (!runtime) return writeError("runtime not found", 404);++ await queries.machine.clearPendingUpdateVersion(db, runtime.daemonId);++ return new Response(null, { status: 204 });+});diff --git a/src/web/src/app/globals.css b/src/web/src/app/globals.cssindex 3a05821c3..4a39deb97 100644--- a/src/web/src/app/globals.css+++ b/src/web/src/app/globals.css@@ -583,202 +583,6 @@}/* ── Gradient background blobs ── */-.gradient-blob {- position: absolute;- filter: blur(40px);- opacity: 0.7;- will-change: transform;-}--.gradient-blob-1 {- width: 750px;- height: 450px;- top: -140px;- left: -200px;- border-radius: 30% 70% 64% 36% / 62% 28% 72% 38%;- background: oklch(0.90 0.12 90);- animation: blob-drift-1 25s ease-in-out infinite;-}--.gradient-blob-2 {- width: 500px;- height: 720px;- bottom: -180px;- right: -150px;- border-radius: 68% 32% 25% 75% / 38% 72% 28% 62%;- background: oklch(0.90 0.06 250);- animation: blob-drift-2 30s ease-in-out infinite;-}--.gradient-blob-3 {- width: 680px;- height: 400px;- top: -100px;- right: -180px;- border-radius: 25% 75% 68% 32% / 72% 35% 65% 28%;- background: oklch(0.86 0.14 95);- animation: blob-drift-3 22s ease-in-out infinite;-}--.gradient-blob-4 {- width: 420px;- height: 700px;- bottom: -160px;- left: -120px;- border-radius: 72% 28% 35% 65% / 25% 68% 32% 75%;- background: oklch(0.89 0.11 80);- animation: blob-drift-4 28s ease-in-out infinite;-}--.gradient-blob-5 {- width: 550px;- height: 380px;- top: 35%;- left: 15%;- border-radius: 62% 38% 45% 55% / 50% 62% 38% 50%;- background: oklch(0.90 0.12 90);- animation: blob-drift-5 26s ease-in-out infinite;-}--.gradient-blob-6 {- width: 480px;- height: 450px;- top: 30%;- left: 35%;- border-radius: 45% 55% 60% 40% / 55% 40% 60% 45%;- background: oklch(0.90 0.06 250);- animation: blob-drift-6 32s ease-in-out infinite;-}--.gradient-blob-7 {- width: 520px;- height: 360px;- top: 40%;- right: 15%;- border-radius: 55% 45% 38% 62% / 42% 58% 42% 58%;- background: oklch(0.86 0.14 95);- animation: blob-drift-7 24s ease-in-out infinite;-}--.dark .gradient-blob-1 {- background: oklch(0.38 0.16 290);- opacity: 0.65;-}--.dark .gradient-blob-2 {- background: oklch(0.34 0.14 270);- opacity: 0.6;-}--.dark .gradient-blob-3 {- background: oklch(0.36 0.18 310);- opacity: 0.6;-}--.dark .gradient-blob-4 {- background: oklch(0.32 0.15 280);- opacity: 0.55;-}--.dark .gradient-blob-5 {- background: oklch(0.38 0.16 290);- opacity: 0.55;-}--.dark .gradient-blob-6 {- background: oklch(0.34 0.14 270);- opacity: 0.5;-}--.dark .gradient-blob-7 {- background: oklch(0.36 0.18 310);- opacity: 0.55;-}--/* Blob 1: top-left corner → drifts toward center, morphs shape */-@keyframes blob-drift-1 {- 0%, 100% {- transform: translate(0, 0) scale(1);- border-radius: 30% 70% 64% 36% / 62% 28% 72% 38%;- }- 50% {- transform: translate(200px, 180px) scale(1.05);- border-radius: 65% 35% 28% 72% / 38% 68% 32% 62%;- }-}--/* Blob 2: bottom-right corner → drifts toward center, morphs shape */-@keyframes blob-drift-2 {- 0%, 100% {- transform: translate(0, 0) scale(1);- border-radius: 68% 32% 25% 75% / 38% 72% 28% 62%;- }- 50% {- transform: translate(-200px, -180px) scale(1.08);- border-radius: 32% 68% 72% 28% / 65% 30% 70% 35%;- }-}--/* Blob 3: top-right corner → drifts toward center, morphs shape */-@keyframes blob-drift-3 {- 0%, 100% {- transform: translate(0, 0) scale(1);- border-radius: 25% 75% 68% 32% / 72% 35% 65% 28%;- }- 50% {- transform: translate(-180px, 200px) scale(1.06);- border-radius: 70% 30% 35% 65% / 28% 72% 38% 62%;- }-}--/* Blob 4: bottom-left corner → drifts toward center, morphs shape */-@keyframes blob-drift-4 {- 0%, 100% {- transform: translate(0, 0) scale(1);- border-radius: 72% 28% 35% 65% / 25% 68% 32% 75%;- }- 50% {- transform: translate(180px, -200px) scale(1.04);- border-radius: 28% 72% 65% 35% / 70% 25% 75% 30%;- }-}--/* Blob 5: center-left, gentle horizontal drift */-@keyframes blob-drift-5 {- 0%, 100% {- transform: translate(0, 0) scale(1);- border-radius: 62% 38% 45% 55% / 50% 62% 38% 50%;- }- 50% {- transform: translate(120px, -80px) scale(1.06);- border-radius: 38% 62% 55% 45% / 62% 38% 50% 50%;- }-}--/* Blob 6: center, slow pulsing drift */-@keyframes blob-drift-6 {- 0%, 100% {- transform: translate(0, 0) scale(1);- border-radius: 45% 55% 60% 40% / 55% 40% 60% 45%;- }- 50% {- transform: translate(-100px, 100px) scale(1.04);- border-radius: 55% 45% 40% 60% / 40% 60% 45% 55%;- }-}--/* Blob 7: center-right, diagonal drift */-@keyframes blob-drift-7 {- 0%, 100% {- transform: translate(0, 0) scale(1);- border-radius: 55% 45% 38% 62% / 42% 58% 42% 58%;- }- 50% {- transform: translate(-140px, 90px) scale(1.05);- border-radius: 45% 55% 62% 38% / 58% 42% 58% 42%;- }-}-/* ── Motion tokens ── */@keyframes fade-up {from {diff --git a/src/web/src/components/agent-chat/agent-chat-view.tsx b/src/web/src/components/agent-chat/agent-chat-view.tsxindex aa5e6ad39..0907af24f 100644--- a/src/web/src/components/agent-chat/agent-chat-view.tsx+++ b/src/web/src/components/agent-chat/agent-chat-view.tsx@@ -19,7 +19,7 @@ import { Skeleton } from "@/components/ui/skeleton";import { ArrowUp, Loader2 } from "lucide-react";import { Streamdown } from "streamdown";-const MESSAGE_LIMIT = 10;+const MESSAGE_LIMIT = 20;/** Sort messages by (created_at, id) ascending — guarantees chronological order. */export function sortMessages(msgs: Message[]): Message[] {@@ -98,6 +98,7 @@ export function AgentChatView() {}}, [loading, messages.length]);+const loadOlderMessages = useCallback(async () => {if (!conversation || loadingMoreRef.current || !hasMore) return;const oldest = messages[0];@@ -140,6 +141,19 @@ export function AgentChatView() {}}, [conversation, workspaceId, messages, hasMore]);+ // Auto-load older messages when content doesn't overflow (scroll can't trigger)+ useEffect(() => {+ if (loading || !hasMore || loadingMoreRef.current) return;+ const el = scrollRef.current;+ if (!el) return;+ const raf = requestAnimationFrame(() => {+ if (el.scrollHeight <= el.clientHeight) {+ loadOlderMessages();+ }+ });+ return () => cancelAnimationFrame(raf);+ }, [loading, hasMore, messages.length, loadOlderMessages]);+// Detect scroll to top for loading moreconst handleScroll = useCallback(() => {const el = scrollRef.current;diff --git a/src/web/src/components/agent-edit-form.tsx b/src/web/src/components/agent-edit-form.tsxindex 44cc1307a..d550fb37b 100644--- a/src/web/src/components/agent-edit-form.tsx+++ b/src/web/src/components/agent-edit-form.tsx@@ -315,7 +315,7 @@ function WhitelistTrigger({ agentId }: { agentId: string }) {<p className="text-xs text-muted-foreground">{whitelist.length > 0? `${whitelist.length} email${whitelist.length !== 1 ? "s" : ""} whitelisted`- : "All inbound emails will be forwarded"}+ : "All inbound emails will be rejected"}</p></div><ChevronRightIcon className="size-4 text-muted-foreground" />@@ -371,7 +371,7 @@ function WhitelistTrigger({ agentId }: { agentId: string }) {</div>) : whitelist.length === 0 ? (<p className="text-sm text-muted-foreground py-4 text-center">- No allowed senders — all inbound emails will be forwarded.+ No allowed senders — all inbound emails will be rejected.</p>) : (<div className="space-y-1.5">diff --git a/src/web/src/components/gradient-background.test.ts b/src/web/src/components/gradient-background.test.tsnew file mode 100644index 000000000..f2cdc6c3c--- /dev/null+++ b/src/web/src/components/gradient-background.test.ts@@ -0,0 +1,14 @@+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it } from "vitest";+import { GradientBackground } from "./gradient-background";++describe("GradientBackground", () => {+ it("limits the noise overlay to dark mode", () => {+ const markup = renderToStaticMarkup(createElement(GradientBackground));++ expect(markup).toContain("hidden");+ expect(markup).toContain("dark:block");+ expect(markup).toContain("dark:mix-blend-overlay");+ });+});diff --git a/src/web/src/components/gradient-background.tsx b/src/web/src/components/gradient-background.tsxindex 932117e52..554b0d980 100644--- a/src/web/src/components/gradient-background.tsx+++ b/src/web/src/components/gradient-background.tsx@@ -8,24 +8,10 @@ export function GradientBackground() {return (<divaria-hidden- className="pointer-events-none fixed inset-0 -z-10 overflow-hidden bg-[oklch(0.94_0.02_250)] dark:bg-transparent"+ className="pointer-events-none fixed inset-0 -z-10 overflow-hidden bg-[oklch(0.90_0.12_55)] dark:bg-transparent">- {/* Blob 1 — warm amber, top-left drift */}- <div className="gradient-blob gradient-blob-1" />- {/* Blob 2 — cool periwinkle, bottom-right drift */}- <div className="gradient-blob gradient-blob-2" />- {/* Blob 3 — cream rose, top-right → center */}- <div className="gradient-blob gradient-blob-3" />- {/* Blob 4 — warm sand, bottom-left → center */}- <div className="gradient-blob gradient-blob-4" />- {/* Blob 5 — warm amber, center-left */}- <div className="gradient-blob gradient-blob-5" />- {/* Blob 6 — cool periwinkle, center */}- <div className="gradient-blob gradient-blob-6" />- {/* Blob 7 — cream rose, center-right */}- <div className="gradient-blob gradient-blob-7" />{/* Noise texture overlay */}- <svg className="absolute inset-0 w-full h-full opacity-[0.25] mix-blend-multiply dark:mix-blend-overlay pointer-events-none">+ <svg className="absolute inset-0 hidden w-full h-full opacity-[0.25] mix-blend-multiply pointer-events-none dark:block dark:mix-blend-overlay"><filter id={filterId}><feTurbulence type="fractalNoise" baseFrequency="0.75" numOctaves="4" stitchTiles="stitch" /><feComponentTransfer>diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.tsindex 064f0fae1..38cc5b4dc 100644--- a/src/web/src/lib/api.ts+++ b/src/web/src/lib/api.ts@@ -130,6 +130,15 @@ export const deleteMachine = (daemonId: string, workspaceId: string) =>{ method: "DELETE" });+export const triggerRuntimeUpdate = (runtimeId: string, workspaceId: string) =>+ apiFetch<{ pending_update_version: string }>(+ `/api/runtimes/${runtimeId}/update${wsQuery(workspaceId)}`,+ { method: "POST" }+ );++export const fetchLatestCliVersion = () =>+ apiFetch<{ version: string }>("/api/cli/latest-version");+// Conversationsexport const listConversations = (workspaceId: string) =>apiFetch<Conversation[]>(`/api/conversations${wsQuery(workspaceId)}`);diff --git a/src/web/src/lib/api/responses.test.ts b/src/web/src/lib/api/responses.test.tsindex 9054ed20a..dcb56cabf 100644--- a/src/web/src/lib/api/responses.test.ts+++ b/src/web/src/lib/api/responses.test.ts@@ -381,7 +381,7 @@ describe("AgentRuntimeResponse shape", () => {});expect(Object.keys(res).sort()).toEqual(["created_at", "daemon_id", "device_info", "id", "last_seen_at",- "metadata", "name", "provider", "runtime_mode", "status",+ "metadata", "name", "pending_update_version", "provider", "runtime_mode", "status","updated_at", "workspace_id",]);});diff --git a/src/web/src/lib/api/responses.ts b/src/web/src/lib/api/responses.tsindex 9c46779a7..ef5e8938d 100644--- a/src/web/src/lib/api/responses.ts+++ b/src/web/src/lib/api/responses.ts@@ -160,6 +160,7 @@ export function runtimeToResponse(rt: any) {status: isOnline(lastSeenStr) ? "online" : "offline",device_info: rt.deviceInfo,metadata,+ pending_update_version: rt.pendingUpdateVersion ?? null,last_seen_at: formatTimestampNullable(machineLastSeenAt),created_at: formatTimestamp(rt.createdAt),updated_at: formatTimestamp(rt.updatedAt),diff --git a/src/web/src/test/e2e/cli-update.test.ts b/src/web/src/test/e2e/cli-update.test.tsnew file mode 100644index 000000000..7644aa4be--- /dev/null+++ b/src/web/src/test/e2e/cli-update.test.ts@@ -0,0 +1,88 @@+import { describe, it, expect, beforeAll, afterAll } from "vitest";+import { randomUUID } from "crypto";+import { seedTestData, cleanupTestData, type TestSeed } from "../helpers/seed";+import { tokenRequest } from "../helpers/auth";+import { sql, sqlQuery } from "../helpers/db";++let seed: TestSeed;++beforeAll(() => {+ seed = seedTestData();+});+afterAll(() => cleanupTestData(seed));++describe("CLI auto-update e2e", () => {+ const daemonId = `daemon_upd_${randomUUID().slice(0, 8)}`;+ let runtimeId: string;++ beforeAll(async () => {+ const res = await tokenRequest("/api/daemon/register", seed.machineToken, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ workspace_id: seed.workspaceId,+ daemon_id: daemonId,+ device_name: "update-test-machine",+ cli_version: "0.0.1",+ runtimes: [+ { provider: "claude", runtime_mode: "local", name: "Claude", version: "4.0" },+ ],+ }),+ });+ expect(res.status).toBe(200);+ const data = (await res.json()) as { runtimes: Array<{ id: string }> };+ runtimeId = data.runtimes[0].id;+ });++ it("POST /api/runtimes/:id/update sets pendingUpdateVersion on machine", async () => {+ // Manually set pending_update_version in DB to avoid npm registry dependency+ sql(+ `UPDATE machine SET pending_update_version = '1.0.0' WHERE daemon_id = '${daemonId}' AND workspace_id = '${seed.workspaceId}'`,+ );++ const rows = sqlQuery<{ pending_update_version: string | null }>(+ `SELECT pending_update_version FROM machine WHERE daemon_id = '${daemonId}' AND workspace_id = '${seed.workspaceId}'`,+ );+ expect(rows[0]?.pending_update_version).toBe("1.0.0");+ });++ it("poll returns pending_update when version is older", async () => {+ const res = await tokenRequest("/api/daemon/tasks/poll", seed.machineToken, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ daemon_id: daemonId,+ cli_version: "0.0.1",+ }),+ });+ expect(res.status).toBe(200);+ const data = (await res.json()) as { tasks: unknown[]; pending_update?: { version: string } };+ expect(data.pending_update).toEqual({ version: "1.0.0" });+ });++ it("poll auto-clears pendingUpdateVersion when cli_version matches", async () => {+ const res = await tokenRequest("/api/daemon/tasks/poll", seed.machineToken, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ daemon_id: daemonId,+ cli_version: "1.0.0",+ }),+ });+ expect(res.status).toBe(200);+ const data = (await res.json()) as { tasks: unknown[]; pending_update?: unknown };+ expect(data.pending_update).toBeUndefined();++ const rows = sqlQuery<{ pending_update_version: string | null }>(+ `SELECT pending_update_version FROM machine WHERE daemon_id = '${daemonId}' AND workspace_id = '${seed.workspaceId}'`,+ );+ expect(rows[0]?.pending_update_version).toBeNull();+ });++ afterAll(() => {+ try {+ sql(`DELETE FROM agent_runtime WHERE daemon_id = '${daemonId}'`);+ sql(`DELETE FROM machine WHERE daemon_id = '${daemonId}'`);+ } catch { /* ignore */ }+ });+});