Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix: remove KV heartbeat, write D1 on every heartbeat for consistency

Gener96c33540b668
diff --git a/src/web/src/app/api/daemon/heartbeat/route.test.ts b/src/web/src/app/api/daemon/heartbeat/route.test.ts
index b6cc7a867..044b022db 100644
--- a/src/web/src/app/api/daemon/heartbeat/route.test.ts
+++ b/src/web/src/app/api/daemon/heartbeat/route.test.ts
@@ -2,20 +2,12 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
import { NextRequest } from "next/server";
const mockUpsertMachine = vi.fn();
+const mockGetMachineByDaemon = vi.fn();
const mockBroadcastToUser = vi.fn();
-const mockKvPut = vi.fn().mockResolvedValue(undefined);
-const mockKvGet = vi.fn().mockResolvedValue(null);
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({
- env: {
- DB: {},
- CACHE_KV: {
- put: (...args: unknown[]) => mockKvPut(...args),
- get: (...args: unknown[]) => mockKvGet(...args),
- delete: vi.fn().mockResolvedValue(undefined),
- },
- },
+ env: { DB: {} },
})),
}));
@@ -30,6 +22,7 @@ vi.mock("@alook/shared", async () => {
queries: {
machine: {
upsertMachine: (...args: unknown[]) => mockUpsertMachine(...args),
+ getMachineByDaemon: (...args: unknown[]) => mockGetMachineByDaemon(...args),
},
},
};
@@ -53,13 +46,6 @@ vi.mock("@/lib/logger", () => ({
log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() },
}));
-vi.mock("@/lib/cache", () => ({
- cacheKeys: {
- heartbeat: (wsId: string, daemonId: string) => `hb:${wsId}:${daemonId}`,
- },
- throttled: vi.fn((_key: string, _interval: number, fn: () => Promise<void>) => fn().then(() => true)),
-}));
-
import { POST } from "./route";
function postReq(body: unknown) {
@@ -73,6 +59,7 @@ function postReq(body: unknown) {
describe("POST /api/daemon/heartbeat", () => {
beforeEach(() => {
vi.clearAllMocks();
+ mockGetMachineByDaemon.mockResolvedValue(null);
mockUpsertMachine.mockResolvedValue({});
mockBroadcastToUser.mockResolvedValue(undefined);
});
@@ -95,17 +82,7 @@ describe("POST /api/daemon/heartbeat", () => {
expect(body).toEqual({ ok: true });
});
- it("writes KV heartbeat with 120s TTL", async () => {
- await POST(postReq({ daemon_id: "d1" }));
-
- expect(mockKvPut).toHaveBeenCalledWith(
- "hb:w1:d1",
- expect.any(String),
- { expirationTtl: 120 },
- );
- });
-
- it("upserts machine via throttled D1 write", async () => {
+ it("upserts machine in D1 on every heartbeat", async () => {
await POST(postReq({ daemon_id: "d1" }));
expect(mockUpsertMachine).toHaveBeenCalledWith({}, {
@@ -116,7 +93,7 @@ describe("POST /api/daemon/heartbeat", () => {
});
it("broadcasts runtime.status when daemon transitions from offline to online", async () => {
- mockKvGet.mockResolvedValue(null);
+ mockGetMachineByDaemon.mockResolvedValue(null);
await POST(postReq({ daemon_id: "d1" }));
expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", {
@@ -127,8 +104,18 @@ describe("POST /api/daemon/heartbeat", () => {
});
});
+ it("broadcasts when last_seen_at exceeds offline threshold", async () => {
+ mockGetMachineByDaemon.mockResolvedValue({ lastSeenAt: new Date(Date.now() - 30_000).toISOString() });
+ await POST(postReq({ daemon_id: "d1" }));
+
+ expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", expect.objectContaining({
+ type: "runtime.status",
+ status: "online",
+ }));
+ });
+
it("does not broadcast when daemon was already online", async () => {
- mockKvGet.mockResolvedValue("2026-05-20T10:00:00.000Z");
+ mockGetMachineByDaemon.mockResolvedValue({ lastSeenAt: new Date().toISOString() });
await POST(postReq({ daemon_id: "d1" }));
expect(mockBroadcastToUser).not.toHaveBeenCalled();
@@ -148,14 +135,12 @@ describe("POST /api/daemon/heartbeat", () => {
vi.resetModules();
vi.doMock("@opennextjs/cloudflare", () => ({
- getCloudflareContext: vi.fn(() => ({
- env: { DB: {}, CACHE_KV: { put: vi.fn(), get: vi.fn().mockResolvedValue(null) } },
- })),
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
}));
vi.doMock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
vi.doMock("@alook/shared", async () => {
const real = await vi.importActual<typeof import("@alook/shared")>("@alook/shared");
- return { ...real, queries: { machine: { upsertMachine: vi.fn() } } };
+ return { ...real, queries: { machine: { upsertMachine: vi.fn(), getMachineByDaemon: vi.fn() } } };
});
vi.doMock("@/lib/middleware/auth", () => ({
withAuth: vi.fn((handler: any) => async (req: any) => {
@@ -167,10 +152,6 @@ describe("POST /api/daemon/heartbeat", () => {
);
vi.doMock("@/lib/broadcast", () => ({ broadcastToUser: vi.fn() }));
vi.doMock("@/lib/logger", () => ({ log: { warn: vi.fn(), info: vi.fn(), error: vi.fn(), debug: vi.fn() } }));
- vi.doMock("@/lib/cache", () => ({
- cacheKeys: { heartbeat: (wsId: string, daemonId: string) => `hb:${wsId}:${daemonId}` },
- throttled: vi.fn((_k: string, _i: number, fn: () => Promise<void>) => fn().then(() => true)),
- }));
const { POST: POST2 } = await import("./route");
const res = await POST2(postReq({ daemon_id: "d1" }));
diff --git a/src/web/src/app/api/daemon/heartbeat/route.ts b/src/web/src/app/api/daemon/heartbeat/route.ts
index 5463195cf..f2e27607d 100644
--- a/src/web/src/app/api/daemon/heartbeat/route.ts
+++ b/src/web/src/app/api/daemon/heartbeat/route.ts
@@ -1,6 +1,6 @@
import { NextRequest } from "next/server";
import { getCloudflareContext } from "@opennextjs/cloudflare";
-import { queries, HeartbeatRequestSchema } from "@alook/shared";
+import { queries, HeartbeatRequestSchema, OFFLINE_THRESHOLD_MS } from "@alook/shared";
import { getDb } from "@/lib/db";
import { withAuth } from "@/lib/middleware/auth";
import { writeJSON, writeError, parseBody } from "@/lib/middleware/helpers";
@@ -9,7 +9,6 @@ import { log } from "@/lib/logger";
export const POST = withAuth(async (req: NextRequest, ctx) => {
const { env } = getCloudflareContext();
- const { cacheKeys, throttled } = await import("@/lib/cache");
const [body, err] = await parseBody(req, HeartbeatRequestSchema);
if (err) return err;
@@ -18,32 +17,18 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
return writeError("Forbidden: machine token required", 403);
}
- const D1_HEARTBEAT_THROTTLE_S = 15;
- const kv = (env as Env).CACHE_KV ?? null;
+ const db = getDb((env as Env).DB);
let wasOffline = false;
- if (kv) {
- const prev = await kv.get(cacheKeys.heartbeat(ctx.workspaceId, body.daemon_id));
- wasOffline = !prev;
- kv.put(
- cacheKeys.heartbeat(ctx.workspaceId, body.daemon_id),
- new Date().toISOString(),
- { expirationTtl: 120 },
- ).catch(() => {});
- }
-
try {
- const db = getDb((env as Env).DB);
- await throttled(
- `hb_d1:${ctx.workspaceId}:${body.daemon_id}`,
- D1_HEARTBEAT_THROTTLE_S,
- async () => {
- await queries.machine.upsertMachine(db, {
- daemonId: body.daemon_id,
- workspaceId: ctx.workspaceId!,
- deviceInfo: body.daemon_id,
- });
- },
- );
+ const existing = await queries.machine.getMachineByDaemon(db, body.daemon_id, ctx.workspaceId!);
+ if (!existing || !existing.lastSeenAt || Date.now() - new Date(existing.lastSeenAt).getTime() >= OFFLINE_THRESHOLD_MS) {
+ wasOffline = true;
+ }
+ await queries.machine.upsertMachine(db, {
+ daemonId: body.daemon_id,
+ workspaceId: ctx.workspaceId!,
+ deviceInfo: body.daemon_id,
+ });
} catch (e) {
log.warn("heartbeat: machine upsert failed", { daemonId: body.daemon_id, err: String(e) });
}
diff --git a/src/web/src/app/api/runtimes/route.ts b/src/web/src/app/api/runtimes/route.ts
index 3bcd56f4a..4a9234631 100644
--- a/src/web/src/app/api/runtimes/route.ts
+++ b/src/web/src/app/api/runtimes/route.ts
@@ -16,19 +16,5 @@ export const GET = withAuth(async (req, ctx) => {
const runtimes = await cached(cacheKeys.allRuntimes(ws.workspaceId), 120, () => queries.runtime.listAgentRuntimes(db, ws.workspaceId));
- // Overlay KV heartbeats for real-time online status (deduplicated by daemonId)
- const kv = (env as Env).CACHE_KV ?? null;
- if (kv) {
- const uniqueDaemonIds = [...new Set(runtimes.map((rt) => rt.daemonId).filter(Boolean))] as string[];
- const heartbeats = await Promise.all(
- uniqueDaemonIds.map((id) => kv.get(cacheKeys.heartbeat(ws.workspaceId, id)).catch(() => null))
- );
- const hbMap = new Map(uniqueDaemonIds.map((id, i) => [id, heartbeats[i]]));
- for (const rt of runtimes) {
- const hb = rt.daemonId ? hbMap.get(rt.daemonId) : null;
- if (hb) rt.machineLastSeenAt = hb;
- }
- }
-
return writeJSON(runtimes.map(runtimeToResponse));
});