Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix: cli status auth

Gusd5b70ee7b58a
diff --git a/src/cli/daemon/daemon.test.ts b/src/cli/daemon/daemon.test.ts
new file mode 100644
index 000000000..9b4408df4
--- /dev/null
+++ b/src/cli/daemon/daemon.test.ts
@@ -0,0 +1,151 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+
+// Mock all external dependencies before importing
+vi.mock("./client.js", () => ({
+ DaemonClient: vi.fn().mockImplementation(() => ({
+ register: vi.fn(async () => ({
+ runtimes: [{ id: "rt1" }],
+ })),
+ heartbeat: vi.fn(async () => {}),
+ deregister: vi.fn(async () => {}),
+ claimTask: vi.fn(async () => ({ task: null })),
+ })),
+}));
+
+vi.mock("./config.js", () => ({
+ loadDaemonConfig: vi.fn(() => ({
+ serverURL: "http://localhost:8080",
+ claudePath: "claude",
+ codexPath: "codex",
+ opencodePath: "opencode",
+ claudeModel: "",
+ codexModel: "",
+ opencodeModel: "",
+ pollInterval: 3000,
+ heartbeatInterval: 15000,
+ agentTimeout: 7200000,
+ maxConcurrentTasks: 20,
+ daemonId: "d1",
+ deviceName: "test-host",
+ runtimeName: "Local Agent",
+ workspacesRoot: "/tmp/ws",
+ keepEnvAfterTask: false,
+ cliVersion: "0.1.0",
+ })),
+}));
+
+vi.mock("./health.js", () => ({
+ createHealthServer: vi.fn(() => ({
+ setRuntimeCount: vi.fn(),
+ server: { close: vi.fn() },
+ })),
+}));
+
+vi.mock("./agent/index.js", () => ({
+ createBackend: vi.fn(),
+ detectVersion: vi.fn(async () => "1.0.0"),
+}));
+
+vi.mock("../lib/config.js", () => ({
+ loadCLIConfigForProfile: vi.fn(() => ({
+ token: "al_test_token",
+ server_url: null,
+ watched_workspaces: [{ id: "ws1", name: "Test WS" }],
+ })),
+}));
+
+vi.mock("child_process", () => ({
+ execSync: vi.fn(),
+}));
+
+vi.mock("fs", () => ({
+ mkdirSync: vi.fn(),
+}));
+
+// Capture signal handlers and prevent actual process.exit
+const signalHandlers = new Map<string, (...args: any[]) => any>();
+const originalOn = process.on.bind(process);
+const mockProcessExit = vi.spyOn(process, "exit").mockImplementation((() => {}) as any);
+
+vi.spyOn(process, "on").mockImplementation(((event: string, handler: any) => {
+ if (event === "SIGTERM" || event === "SIGINT") {
+ signalHandlers.set(event, handler);
+ return process;
+ }
+ return originalOn(event, handler);
+}) as any);
+
+// Track setInterval/clearInterval calls
+const realSetInterval = globalThis.setInterval;
+const realClearInterval = globalThis.clearInterval;
+const intervalTimers: NodeJS.Timeout[] = [];
+
+vi.spyOn(globalThis, "setInterval").mockImplementation(((fn: any, ms: any) => {
+ const timer = realSetInterval(() => {}, 999999) as NodeJS.Timeout; // dummy timer
+ intervalTimers.push(timer);
+ return timer;
+}) as any);
+
+const clearedTimers: NodeJS.Timeout[] = [];
+vi.spyOn(globalThis, "clearInterval").mockImplementation(((timer: any) => {
+ clearedTimers.push(timer);
+ realClearInterval(timer);
+}) as any);
+
+import { startDaemon } from "./daemon.js";
+
+describe("daemon shutdown", () => {
+ beforeEach(() => {
+ signalHandlers.clear();
+ intervalTimers.length = 0;
+ clearedTimers.length = 0;
+ vi.clearAllMocks();
+ // Re-apply exit mock after clearAllMocks
+ mockProcessExit.mockImplementation((() => {}) as any);
+ });
+
+ afterEach(() => {
+ // Clear any real timers
+ for (const t of intervalTimers) realClearInterval(t);
+ });
+
+ it("clears heartbeat and poll intervals before calling deregister", async () => {
+ await startDaemon();
+
+ // startDaemon should have created 2 intervals (heartbeat + poll)
+ expect(intervalTimers.length).toBe(2);
+ const heartbeatTimer = intervalTimers[0];
+ const pollTimer = intervalTimers[1];
+
+ // Get the deregister mock to check call ordering
+ const { DaemonClient } = await import("./client.js");
+ const clientInstance = vi.mocked(DaemonClient).mock.results[0].value;
+ const deregisterMock = clientInstance.deregister;
+
+ let deregisterCalledAt = -1;
+ let clearCalledCount = 0;
+ deregisterMock.mockImplementation(async () => {
+ deregisterCalledAt = clearCalledCount;
+ });
+
+ // Replace clearInterval to track ordering
+ const originalClearMock = vi.mocked(globalThis.clearInterval);
+ originalClearMock.mockImplementation(((timer: any) => {
+ clearCalledCount++;
+ clearedTimers.push(timer);
+ realClearInterval(timer);
+ }) as any);
+
+ // Trigger SIGTERM
+ const shutdownHandler = signalHandlers.get("SIGTERM");
+ expect(shutdownHandler).toBeDefined();
+ await shutdownHandler!();
+
+ // Both intervals should have been cleared
+ expect(clearedTimers).toContain(heartbeatTimer);
+ expect(clearedTimers).toContain(pollTimer);
+
+ // clearInterval should have been called before deregister
+ expect(deregisterCalledAt).toBe(2); // both clearInterval calls happened before deregister
+ });
+});
diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.ts
index 4c48b78ed..223f9572f 100644
--- a/src/cli/daemon/daemon.ts
+++ b/src/cli/daemon/daemon.ts
@@ -110,8 +110,13 @@ export async function startDaemon(
`Daemon started. ${allRuntimeIds.length} runtime(s) registered across ${workspaces.length} workspace(s).`,
);
+ let heartbeatTimer: NodeJS.Timeout;
+ let pollTimer: NodeJS.Timeout;
+
const shutdown = async () => {
console.log("Shutting down...");
+ clearInterval(heartbeatTimer);
+ clearInterval(pollTimer);
const timeout = setTimeout(() => process.exit(1), 5000);
try {
await client.deregister(allRuntimeIds);
@@ -125,7 +130,7 @@ export async function startDaemon(
process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);
- setInterval(async () => {
+ heartbeatTimer = setInterval(async () => {
for (const rid of allRuntimeIds) {
try {
await client.heartbeat(rid);
@@ -158,7 +163,7 @@ export async function startDaemon(
}
};
- setInterval(poll, config.pollInterval);
+ pollTimer = setInterval(poll, config.pollInterval);
await poll();
}
diff --git a/src/web/app/api/daemon/deregister/route.test.ts b/src/web/app/api/daemon/deregister/route.test.ts
new file mode 100644
index 000000000..cf4a011d2
--- /dev/null
+++ b/src/web/app/api/daemon/deregister/route.test.ts
@@ -0,0 +1,90 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+function makeReq(body: unknown) {
+ return new NextRequest("http://localhost/api/daemon/deregister", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+}
+
+function setupMocks(opts: { workspaceId?: string } = { workspaceId: "w1" }) {
+ vi.resetModules();
+
+ vi.doMock("@/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]", workspaceId: opts.workspaceId, params });
+ }),
+ }));
+ vi.doMock("@/lib/db", () => ({ db: {} }));
+ vi.doMock("@/lib/db/queries/runtime", () => ({
+ setAgentRuntimeOffline: vi.fn(async () => {}),
+ getAgentRuntimeForWorkspace: vi.fn(async () => ({ id: "rt1", workspaceId: "w1" })),
+ }));
+}
+
+describe("POST /api/daemon/deregister", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("sets owned runtimes offline", async () => {
+ setupMocks();
+ const { POST } = await import("./route");
+ const { setAgentRuntimeOffline } = await import("@/lib/db/queries/runtime");
+
+ const res = await POST(makeReq({ runtime_ids: ["rt1"] }));
+ expect(res.status).toBe(200);
+ expect(setAgentRuntimeOffline).toHaveBeenCalledWith({}, "rt1");
+ });
+
+ it("skips unowned runtimes — setAgentRuntimeOffline not called for that ID", async () => {
+ setupMocks();
+ const { getAgentRuntimeForWorkspace, setAgentRuntimeOffline } =
+ await import("@/lib/db/queries/runtime");
+ vi.mocked(getAgentRuntimeForWorkspace).mockImplementation(async (_db, id) => {
+ if (id === "rt1") return { id: "rt1", workspaceId: "w1" } as any;
+ return null;
+ });
+
+ const { POST } = await import("./route");
+ const res = await POST(makeReq({ runtime_ids: ["rt1", "rt2"] }));
+ expect(res.status).toBe(200);
+ expect(setAgentRuntimeOffline).toHaveBeenCalledTimes(1);
+ expect(setAgentRuntimeOffline).toHaveBeenCalledWith({}, "rt1");
+ });
+
+ it("returns 200 with empty runtime_ids (no-op)", async () => {
+ setupMocks();
+ const { POST } = await import("./route");
+ const { setAgentRuntimeOffline } = await import("@/lib/db/queries/runtime");
+
+ const res = await POST(makeReq({ runtime_ids: [] }));
+ expect(res.status).toBe(200);
+ expect(setAgentRuntimeOffline).not.toHaveBeenCalled();
+ });
+
+ it("returns 403 when called without workspaceId", async () => {
+ setupMocks({ workspaceId: undefined });
+ const { POST } = await import("./route");
+ const res = await POST(makeReq({ runtime_ids: ["rt1"] }));
+ expect(res.status).toBe(403);
+ });
+
+ it("continues processing remaining runtimes after DB error on one", async () => {
+ setupMocks();
+ const { getAgentRuntimeForWorkspace, setAgentRuntimeOffline } =
+ await import("@/lib/db/queries/runtime");
+ vi.mocked(getAgentRuntimeForWorkspace).mockResolvedValue({ id: "rt1", workspaceId: "w1" } as any);
+ vi.mocked(setAgentRuntimeOffline)
+ .mockRejectedValueOnce(new Error("db error"))
+ .mockResolvedValueOnce(undefined);
+
+ const { POST } = await import("./route");
+ const res = await POST(makeReq({ runtime_ids: ["rt1", "rt2"] }));
+ expect(res.status).toBe(200);
+ expect(setAgentRuntimeOffline).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/src/web/app/api/daemon/deregister/route.ts b/src/web/app/api/daemon/deregister/route.ts
index 8f29c69c3..7014fd929 100644
--- a/src/web/app/api/daemon/deregister/route.ts
+++ b/src/web/app/api/daemon/deregister/route.ts
@@ -1,15 +1,29 @@
import { NextRequest } from "next/server";
import { db } from "@/lib/db";
-import { setAgentRuntimeOffline } from "@/lib/db/queries/runtime";
+import {
+ setAgentRuntimeOffline,
+ getAgentRuntimeForWorkspace,
+} from "@/lib/db/queries/runtime";
import { withAuth } from "@/lib/middleware/auth";
-import { writeJSON, parseBody } from "@/lib/middleware/helpers";
+import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";
import { DeregisterRequestSchema } from "@alook/shared";
-export const POST = withAuth(async (req: NextRequest) => {
+export const POST = withAuth(async (req: NextRequest, ctx) => {
const [body, err] = await parseBody(req, DeregisterRequestSchema);
if (err) return err;
+ if (!ctx.workspaceId) {
+ return writeError("Forbidden: machine token required", 403);
+ }
+
for (const id of body.runtime_ids) {
+ const runtime = await getAgentRuntimeForWorkspace(
+ db,
+ id,
+ ctx.workspaceId
+ );
+ if (!runtime) continue;
+
try {
await setAgentRuntimeOffline(db, id);
} catch (e) {
diff --git a/src/web/app/api/daemon/heartbeat/route.test.ts b/src/web/app/api/daemon/heartbeat/route.test.ts
index 24625ee33..cb12cee63 100644
--- a/src/web/app/api/daemon/heartbeat/route.test.ts
+++ b/src/web/app/api/daemon/heartbeat/route.test.ts
@@ -1,64 +1,140 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
-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/db", () => ({ db: {} }));
-vi.mock("@/lib/db/queries/runtime");
-vi.mock("@/lib/db/queries/task");
-vi.mock("@/lib/services/task");
-
-import {
- updateAgentRuntimeHeartbeat,
- markStaleRuntimesOffline,
-} from "@/lib/db/queries/runtime";
-import { failStaleDispatchedTasks } from "@/lib/db/queries/task";
-
-const mockHeartbeat = vi.mocked(updateAgentRuntimeHeartbeat);
-const mockMarkStale = vi.mocked(markStaleRuntimesOffline);
-const mockFailStale = vi.mocked(failStaleDispatchedTasks);
-
-beforeEach(() => {
- vi.clearAllMocks();
- mockHeartbeat.mockResolvedValue({ id: "rt1" } as any);
- mockFailStale.mockResolvedValue([]);
-});
+function makeReq(body: unknown) {
+ return new NextRequest("http://localhost/api/daemon/heartbeat", {
+ method: "POST",
+ body: JSON.stringify(body),
+ });
+}
+
+function setupMocks(opts: { workspaceId?: string } = { workspaceId: "w1" }) {
+ vi.resetModules();
+
+ vi.doMock("@/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]", workspaceId: opts.workspaceId, params });
+ }),
+ }));
+ vi.doMock("@/lib/db", () => ({ db: {} }));
+ vi.doMock("@/lib/db/queries/runtime", () => ({
+ updateAgentRuntimeHeartbeat: vi.fn(async () => ({ id: "rt1" })),
+ getAgentRuntimeForWorkspace: vi.fn(async () => ({ id: "rt1", workspaceId: "w1" })),
+ markStaleRuntimesOffline: vi.fn(async () => {}),
+ }));
+ vi.doMock("@/lib/db/queries/task", () => ({
+ failStaleDispatchedTasks: vi.fn(async () => []),
+ }));
+ vi.doMock("@/lib/services/task", () => ({
+ TaskService: vi.fn().mockImplementation(() => ({
+ reconcileAgentStatus: vi.fn(),
+ })),
+ }));
+}
describe("POST /api/daemon/heartbeat", () => {
- it("updates heartbeat and marks stale runtimes offline", async () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("succeeds for runtime in caller's workspace", async () => {
+ setupMocks();
const { POST } = await import("./route");
- const res = await POST(
- new NextRequest("http://localhost/api/daemon/heartbeat", {
- method: "POST",
- body: JSON.stringify({ runtime_id: "rt1" }),
- }),
- );
+ const { getAgentRuntimeForWorkspace, updateAgentRuntimeHeartbeat } =
+ await import("@/lib/db/queries/runtime");
+
+ const res = await POST(makeReq({ runtime_id: "rt1" }));
expect(res.status).toBe(200);
- expect(mockHeartbeat).toHaveBeenCalledWith({}, "rt1");
- expect(mockMarkStale).toHaveBeenCalledOnce();
+ expect(getAgentRuntimeForWorkspace).toHaveBeenCalledWith({}, "rt1", "w1");
+ expect(updateAgentRuntimeHeartbeat).toHaveBeenCalledWith({}, "rt1");
+ });
+
+ it("returns 404 when runtime not in caller's workspace", async () => {
+ setupMocks();
+ const { getAgentRuntimeForWorkspace } = await import("@/lib/db/queries/runtime");
+ vi.mocked(getAgentRuntimeForWorkspace).mockResolvedValue(null);
+
+ const { POST } = await import("./route");
+ const res = await POST(makeReq({ runtime_id: "rt-other" }));
+ expect(res.status).toBe(404);
+ });
+
+ it("returns 404 when runtime ID doesn't exist at all", async () => {
+ setupMocks();
+ const { getAgentRuntimeForWorkspace } = await import("@/lib/db/queries/runtime");
+ vi.mocked(getAgentRuntimeForWorkspace).mockResolvedValue(null);
+
+ const { POST } = await import("./route");
+ const res = await POST(makeReq({ runtime_id: "nonexistent" }));
+ expect(res.status).toBe(404);
+ });
+
+ it("returns 403 when called without workspaceId (JWT auth)", async () => {
+ setupMocks({ workspaceId: undefined });
+ const { POST } = await import("./route");
+ const res = await POST(makeReq({ runtime_id: "rt1" }));
+ expect(res.status).toBe(403);
+ });
+
+ it("does NOT call updateAgentRuntimeHeartbeat, markStaleRuntimesOffline, or failStaleDispatchedTasks when ownership fails", async () => {
+ setupMocks();
+ const { getAgentRuntimeForWorkspace, updateAgentRuntimeHeartbeat, markStaleRuntimesOffline } =
+ await import("@/lib/db/queries/runtime");
+ const { failStaleDispatchedTasks } = await import("@/lib/db/queries/task");
+ vi.mocked(getAgentRuntimeForWorkspace).mockResolvedValue(null);
+
+ const { POST } = await import("./route");
+ await POST(makeReq({ runtime_id: "rt-other" }));
+ expect(updateAgentRuntimeHeartbeat).not.toHaveBeenCalled();
+ expect(markStaleRuntimesOffline).not.toHaveBeenCalled();
+ expect(failStaleDispatchedTasks).not.toHaveBeenCalled();
+ });
+
+ it("calls markStaleRuntimesOffline with (db, workspaceId)", async () => {
+ setupMocks();
+ const { POST } = await import("./route");
+ const { markStaleRuntimesOffline } = await import("@/lib/db/queries/runtime");
+
+ await POST(makeReq({ runtime_id: "rt1" }));
+ expect(markStaleRuntimesOffline).toHaveBeenCalledWith({}, "w1");
});
- it("calls markStaleRuntimesOffline after updating heartbeat", async () => {
+ it("calls updateAgentRuntimeHeartbeat before markStaleRuntimesOffline", async () => {
+ setupMocks();
+ const { updateAgentRuntimeHeartbeat, markStaleRuntimesOffline } =
+ await import("@/lib/db/queries/runtime");
+
const callOrder: string[] = [];
- mockHeartbeat.mockImplementation(async () => {
+ vi.mocked(updateAgentRuntimeHeartbeat).mockImplementation(async () => {
callOrder.push("heartbeat");
return { id: "rt1" } as any;
});
- mockMarkStale.mockImplementation(async () => {
+ vi.mocked(markStaleRuntimesOffline).mockImplementation(async () => {
callOrder.push("markStale");
});
const { POST } = await import("./route");
- await POST(
- new NextRequest("http://localhost/api/daemon/heartbeat", {
- method: "POST",
- body: JSON.stringify({ runtime_id: "rt1" }),
- }),
- );
+ await POST(makeReq({ runtime_id: "rt1" }));
expect(callOrder).toEqual(["heartbeat", "markStale"]);
});
+
+ it("calls failStaleDispatchedTasks and reconcileAgentStatus on happy path", async () => {
+ setupMocks();
+ const { failStaleDispatchedTasks } = await import("@/lib/db/queries/task");
+ const { TaskService } = await import("@/lib/services/task");
+
+ const mockReconcile = vi.fn();
+ vi.mocked(TaskService).mockImplementation(() => ({ reconcileAgentStatus: mockReconcile }) as any);
+ vi.mocked(failStaleDispatchedTasks).mockResolvedValue([
+ { agentId: "a1" } as any,
+ { agentId: "a2" } as any,
+ ]);
+
+ const { POST } = await import("./route");
+ await POST(makeReq({ runtime_id: "rt1" }));
+ expect(failStaleDispatchedTasks).toHaveBeenCalled();
+ expect(mockReconcile).toHaveBeenCalledWith("a1");
+ expect(mockReconcile).toHaveBeenCalledWith("a2");
+ });
});
diff --git a/src/web/app/api/daemon/heartbeat/route.ts b/src/web/app/api/daemon/heartbeat/route.ts
index 4a699311d..89c7353fc 100644
--- a/src/web/app/api/daemon/heartbeat/route.ts
+++ b/src/web/app/api/daemon/heartbeat/route.ts
@@ -2,22 +2,36 @@ import { NextRequest } from "next/server";
import { db } from "@/lib/db";
import {
updateAgentRuntimeHeartbeat,
+ getAgentRuntimeForWorkspace,
markStaleRuntimesOffline,
} from "@/lib/db/queries/runtime";
import { failStaleDispatchedTasks } from "@/lib/db/queries/task";
import { withAuth } from "@/lib/middleware/auth";
-import { writeJSON, parseBody } from "@/lib/middleware/helpers";
+import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";
import { HeartbeatRequestSchema } from "@alook/shared";
import { TaskService } from "@/lib/services/task";
-export const POST = withAuth(async (req: NextRequest) => {
+export const POST = withAuth(async (req: NextRequest, ctx) => {
const [body, err] = await parseBody(req, HeartbeatRequestSchema);
if (err) return err;
+ if (!ctx.workspaceId) {
+ return writeError("Forbidden: machine token required", 403);
+ }
+
+ const runtime = await getAgentRuntimeForWorkspace(
+ db,
+ body.runtime_id,
+ ctx.workspaceId
+ );
+ if (!runtime) {
+ return writeError("Runtime not found", 404);
+ }
+
await updateAgentRuntimeHeartbeat(db, body.runtime_id);
- // Mark runtimes that haven't sent a heartbeat in >2 minutes as offline
- await markStaleRuntimesOffline(db);
+ // Mark runtimes that haven't sent a heartbeat in >45s as offline
+ await markStaleRuntimesOffline(db, ctx.workspaceId);
// Fail tasks stuck in "dispatched" for >20s (daemon likely crashed)
const stale = await failStaleDispatchedTasks(db);
diff --git a/src/web/app/api/daemon/routes.test.ts b/src/web/app/api/daemon/routes.test.ts
index 06dfcd67e..c91111d24 100644
--- a/src/web/app/api/daemon/routes.test.ts
+++ b/src/web/app/api/daemon/routes.test.ts
@@ -16,7 +16,7 @@ vi.mock("@/lib/middleware/auth", () => ({
? await context.params
: context.params
: undefined;
- return handler(req, { userId: "u1", email: "[email protected]", params });
+ return handler(req, { userId: "u1", email: "[email protected]", workspaceId: "w1", params });
};
},
}));
@@ -32,6 +32,8 @@ vi.mock("@/lib/db/queries/runtime", () => ({
})),
setAgentRuntimeOffline: vi.fn(async () => {}),
updateAgentRuntimeHeartbeat: vi.fn(async () => {}),
+ getAgentRuntimeForWorkspace: vi.fn(async () => ({ id: "rt1" })),
+ markStaleRuntimesOffline: vi.fn(async () => {}),
}));
vi.mock("@/lib/db/queries/task", () => ({
failStaleDispatchedTasks: vi.fn(async () => []),
diff --git a/src/web/app/api/runtimes/route.test.ts b/src/web/app/api/runtimes/route.test.ts
index 1c89b8264..04482ca92 100644
--- a/src/web/app/api/runtimes/route.test.ts
+++ b/src/web/app/api/runtimes/route.test.ts
@@ -43,6 +43,6 @@ describe("GET /api/runtimes", () => {
await GET(
new NextRequest("http://localhost/api/runtimes?workspace_id=w1"),
);
- expect(mockMarkStale).toHaveBeenCalledOnce();
+ expect(mockMarkStale).toHaveBeenCalledWith({}, "w1");
});
});
diff --git a/src/web/app/api/runtimes/route.ts b/src/web/app/api/runtimes/route.ts
index 8b8481ea4..de7917c81 100644
--- a/src/web/app/api/runtimes/route.ts
+++ b/src/web/app/api/runtimes/route.ts
@@ -12,8 +12,8 @@ export const GET = withAuth(async (req, ctx) => {
const ws = await withWorkspaceMember(req, ctx);
if (ws instanceof Response) return ws;
- // Mark runtimes that haven't sent a heartbeat in >2 minutes as offline
- await markStaleRuntimesOffline(db);
+ // Mark runtimes that haven't sent a heartbeat in >45s as offline
+ await markStaleRuntimesOffline(db, ws.workspaceId);
const runtimes = await listAgentRuntimes(db, ws.workspaceId);
return writeJSON(runtimes.map(runtimeToResponse));
diff --git a/src/web/lib/db/queries/runtime.ts b/src/web/lib/db/queries/runtime.ts
index d0c99cc30..a9ad970d5 100644
--- a/src/web/lib/db/queries/runtime.ts
+++ b/src/web/lib/db/queries/runtime.ts
@@ -137,14 +137,21 @@ export async function deleteRuntimesByDaemonId(
);
}
-export async function markStaleRuntimesOffline(db: Database) {
+export async function markStaleRuntimesOffline(
+ db: Database,
+ workspaceId: string
+) {
await db
.update(agentRuntime)
.set({ status: "offline", updatedAt: sql`now()` })
.where(
and(
+ eq(agentRuntime.workspaceId, workspaceId),
eq(agentRuntime.status, "online"),
- sql`${agentRuntime.lastSeenAt} < now() - interval '2 minutes'`
+ or(
+ sql`${agentRuntime.lastSeenAt} < now() - interval '45 seconds'`,
+ sql`${agentRuntime.lastSeenAt} IS NULL`
+ )
)
);
}