Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): dismiss CLI-update dialog reliably after runtime updates (#405)

Gener80aa8c52d699
diff --git a/src/shared/src/db/queries/runtime.ts b/src/shared/src/db/queries/runtime.ts
index f55e7f91b..6d8a7dd59 100644
--- a/src/shared/src/db/queries/runtime.ts
+++ b/src/shared/src/db/queries/runtime.ts
@@ -203,6 +203,28 @@ export async function deleteRuntimesByDaemonId(
);
}
+export async function updateRuntimeCliVersionByDaemon(
+ db: Database,
+ daemonId: string,
+ workspaceId: string,
+ cliVersion: string
+) {
+ if (!cliVersion) return;
+ const metaJson = JSON.stringify({ cli_version: cliVersion });
+ await db
+ .update(agentRuntime)
+ .set({
+ metadata: sql`json_patch(coalesce(${agentRuntime.metadata}, '{}'), ${metaJson})`,
+ updatedAt: new Date().toISOString(),
+ })
+ .where(
+ and(
+ eq(agentRuntime.daemonId, daemonId),
+ eq(agentRuntime.workspaceId, workspaceId)
+ )
+ );
+}
+
export async function getRuntimeIdsByDaemon(
db: Database,
daemonId: string,
diff --git a/src/shared/test/queries/runtime.test.ts b/src/shared/test/queries/runtime.test.ts
index 4a7bf0fc3..711aae506 100644
--- a/src/shared/test/queries/runtime.test.ts
+++ b/src/shared/test/queries/runtime.test.ts
@@ -32,6 +32,37 @@ describe("runtime query module exports", () => {
});
});
+describe("updateRuntimeCliVersionByDaemon", () => {
+ function createUpdateMockDb() {
+ const chain: any = {};
+ chain.update = vi.fn(() => chain);
+ chain.set = vi.fn(() => chain);
+ chain.where = vi.fn(() => Promise.resolve(undefined));
+ return chain;
+ }
+
+ it("exports updateRuntimeCliVersionByDaemon", () => {
+ expect(typeof runtimeQueries.updateRuntimeCliVersionByDaemon).toBe("function");
+ });
+
+ it("no-ops without touching DB when cliVersion is empty", async () => {
+ const mockDb = createUpdateMockDb();
+ await runtimeQueries.updateRuntimeCliVersionByDaemon(mockDb, "d1", "ws1", "");
+ expect(mockDb.update).not.toHaveBeenCalled();
+ });
+
+ it("issues a scoped update patching cli_version into metadata", async () => {
+ const mockDb = createUpdateMockDb();
+ await runtimeQueries.updateRuntimeCliVersionByDaemon(mockDb, "d1", "ws1", "1.2.3");
+ expect(mockDb.update).toHaveBeenCalledOnce();
+ expect(mockDb.set).toHaveBeenCalledOnce();
+ expect(mockDb.where).toHaveBeenCalledOnce();
+ const setArg = mockDb.set.mock.calls[0][0];
+ expect(setArg).toHaveProperty("metadata");
+ expect(setArg).toHaveProperty("updatedAt");
+ });
+});
+
describe("getAgentRuntimesForWorkspace", () => {
it("returns empty array for empty ids without querying DB", async () => {
const result = await runtimeQueries.getAgentRuntimesForWorkspace(null as any, [], "ws1");
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.ts
index e70258469..1e8f1798b 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
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
const mockGetRuntimeIdsByDaemon = vi.fn();
+const mockUpdateRuntimeCliVersionByDaemon = vi.fn();
const mockUpsertMachine = vi.fn();
const mockGetMachineByDaemon = vi.fn();
const mockClearPendingUpdateVersion = vi.fn();
@@ -42,6 +43,7 @@ vi.mock("@alook/shared", async () => {
queries: {
runtime: {
getRuntimeIdsByDaemon: (...args: unknown[]) => mockGetRuntimeIdsByDaemon(...args),
+ updateRuntimeCliVersionByDaemon: (...args: unknown[]) => mockUpdateRuntimeCliVersionByDaemon(...args),
},
machine: {
upsertMachine: (...args: unknown[]) => mockUpsertMachine(...args),
@@ -319,6 +321,7 @@ describe("POST /api/daemon/tasks/poll", () => {
mockClaimTasksForRuntimes.mockResolvedValue([]);
mockGetMachineByDaemon.mockResolvedValue({ pendingUpdateVersion: "1.0.0" });
mockClearPendingUpdateVersion.mockResolvedValue(undefined);
+ mockUpdateRuntimeCliVersionByDaemon.mockResolvedValue(undefined);
const res = await POST(postReq({ daemon_id: "d1", cli_version: "1.0.0" }));
const body = await res.json();
@@ -326,6 +329,7 @@ describe("POST /api/daemon/tasks/poll", () => {
expect(res.status).toBe(200);
expect(body.pending_update).toBeUndefined();
expect(mockClearPendingUpdateVersion).toHaveBeenCalledWith({}, "d1", "w1");
+ expect(mockUpdateRuntimeCliVersionByDaemon).toHaveBeenCalledWith({}, "d1", "w1", "1.0.0");
expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", {
type: "runtime.status",
daemonId: "d1",
diff --git a/src/web/src/app/api/daemon/tasks/poll/route.ts b/src/web/src/app/api/daemon/tasks/poll/route.ts
index 96349810a..c287157a4 100644
--- a/src/web/src/app/api/daemon/tasks/poll/route.ts
+++ b/src/web/src/app/api/daemon/tasks/poll/route.ts
@@ -71,7 +71,10 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
try {
if (machineRow?.pendingUpdateVersion && body.cli_version) {
if (semverGte(body.cli_version, machineRow.pendingUpdateVersion)) {
- await queries.machine.clearPendingUpdateVersion(db, body.daemon_id, ctx.workspaceId);
+ await Promise.all([
+ queries.machine.clearPendingUpdateVersion(db, body.daemon_id, ctx.workspaceId),
+ queries.runtime.updateRuntimeCliVersionByDaemon(db, body.daemon_id, ctx.workspaceId, body.cli_version),
+ ]);
broadcastToUser(ctx.userId, {
type: "runtime.status",
daemonId: body.daemon_id,
diff --git a/src/web/src/contexts/agent-context.tsx b/src/web/src/contexts/agent-context.tsx
index 5d8a8b33a..367f68622 100644
--- a/src/web/src/contexts/agent-context.tsx
+++ b/src/web/src/contexts/agent-context.tsx
@@ -104,6 +104,8 @@ export function AgentProvider({
const reconnectSubscribersRef = useRef(new Set<() => void>());
const taskCountsMountedRef = useRef(true);
const isReloadingRuntimesRef = useRef(false);
+ const runtimesDirtyRef = useRef(false);
+ const runtimesRetryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const subscribeWs = useCallback((fn: WsSubscriber) => {
subscribersRef.current.add(fn);
@@ -183,18 +185,40 @@ export function AgentProvider({
}, [workspaceId]);
const reloadRuntimes = useCallback(async () => {
- if (isReloadingRuntimesRef.current) return;
+ if (isReloadingRuntimesRef.current) {
+ runtimesDirtyRef.current = true;
+ return;
+ }
isReloadingRuntimesRef.current = true;
try {
- const r = await listRuntimes(workspaceId);
- setRuntimes(r);
+ // Coalesce concurrent requests, but cap the passes so a storm of
+ // runtime.status frames can't hold the lock and re-fetch indefinitely.
+ let passes = 0;
+ do {
+ runtimesDirtyRef.current = false;
+ const r = await listRuntimes(workspaceId);
+ setRuntimes(r);
+ } while (runtimesDirtyRef.current && ++passes < 3);
} catch {
- // ignore — next tick will retry
+ // Fetch failed; the triggering event would otherwise be dropped until the
+ // 30s poll. Schedule a short retry so the event isn't lost.
+ if (!runtimesRetryTimerRef.current) {
+ runtimesRetryTimerRef.current = setTimeout(() => {
+ runtimesRetryTimerRef.current = null;
+ reloadRuntimesRef.current();
+ }, 2000);
+ }
} finally {
isReloadingRuntimesRef.current = false;
}
}, [workspaceId]);
+ const reloadRuntimesRef = useRef(reloadRuntimes);
+ useEffect(() => {
+ /* eslint-disable-next-line react-hooks/immutability -- latest-ref for the retry timer */
+ reloadRuntimesRef.current = reloadRuntimes;
+ }, [reloadRuntimes]);
+
useEffect(() => {
reload();
}, [reload]);
@@ -220,6 +244,7 @@ export function AgentProvider({
return () => {
clearInterval(intervalId);
if (jitterTimer) clearTimeout(jitterTimer);
+ if (runtimesRetryTimerRef.current) clearTimeout(runtimesRetryTimerRef.current);
document.removeEventListener("visibilitychange", handleVisibility);
};
}, [reloadRuntimes]);
@@ -241,7 +266,7 @@ export function AgentProvider({
reload();
break;
case "runtime.status":
- if (msg.workspaceId !== workspaceId) break;
+ if (msg.workspaceId && msg.workspaceId !== workspaceId) break;
reloadRuntimes();
break;
case "agent.created":
diff --git a/src/web/src/test/e2e/cli-update.test.ts b/src/web/src/test/e2e/cli-update.test.ts
index 15ae93437..790530a1f 100644
--- a/src/web/src/test/e2e/cli-update.test.ts
+++ b/src/web/src/test/e2e/cli-update.test.ts
@@ -69,6 +69,14 @@ describe("CLI auto-update e2e", () => {
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" });
+
+ // Version not satisfied → metadata cli_version must NOT be bumped
+ const metaRows = sqlQuery<{ cli_version: string | null }>(
+ `SELECT json_extract(metadata, '$.cli_version') AS cli_version FROM agent_runtime WHERE daemon_id = ? AND workspace_id = ?`, daemonId, seed.workspaceId
+ );
+ for (const r of metaRows) {
+ expect(r.cli_version).toBe("0.0.1");
+ }
});
it("poll auto-clears pendingUpdateVersion when cli_version matches", async () => {
@@ -93,6 +101,15 @@ describe("CLI auto-update e2e", () => {
`SELECT pending_update_version FROM machine WHERE daemon_id = ? AND workspace_id = ?`, daemonId2, seed.workspaceId
);
expect(rows[0]?.pending_update_version).toBeNull();
+
+ // Runtime metadata cli_version is written back so the version gate clears
+ const metaRows = sqlQuery<{ cli_version: string | null }>(
+ `SELECT json_extract(metadata, '$.cli_version') AS cli_version FROM agent_runtime WHERE daemon_id = ? AND workspace_id = ?`, daemonId2, seed.workspaceId
+ );
+ expect(metaRows.length).toBeGreaterThan(0);
+ for (const r of metaRows) {
+ expect(r.cli_version).toBe("1.0.0");
+ }
});
afterAll(() => {