Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add runtime rescan and redesign machine card (#32)

Genere08d81aed0c7
diff --git a/src/cli/daemon/client.test.ts b/src/cli/daemon/client.test.ts
index 7156fed0f..ce93fba1a 100644
--- a/src/cli/daemon/client.test.ts
+++ b/src/cli/daemon/client.test.ts
@@ -37,6 +37,16 @@ describe("PollResponseSchema validation", () => {
expect(parsed.tasks[0].agent?.name).toBe("bot");
});
+ it("parses response with pending_rescan", () => {
+ const parsed = PollResponseSchema.parse({ tasks: [], pending_rescan: true });
+ expect(parsed.pending_rescan).toBe(true);
+ });
+
+ it("parses response without pending_rescan (optional)", () => {
+ const parsed = PollResponseSchema.parse({ tasks: [] });
+ expect(parsed.pending_rescan).toBeUndefined();
+ });
+
it("parses empty tasks array", () => {
const parsed = PollResponseSchema.parse({ tasks: [] });
expect(parsed.tasks).toEqual([]);
@@ -199,6 +209,31 @@ describe("DaemonClient.poll() with mocked fetch", () => {
expect(result.evicted).toBe(false);
});
+ it("returns pending_rescan when present in response", async () => {
+ globalThis.fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ tasks: [], pending_rescan: true }),
+ });
+
+ const client = new DaemonClient("http://localhost:8080");
+ const result = await client.poll("tok", "d1", 1);
+ expect(result.tasks).toEqual([]);
+ expect(result.pending_rescan).toBe(true);
+ });
+
+ it("returns undefined pending_rescan when absent", async () => {
+ globalThis.fetch = vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ tasks: [] }),
+ });
+
+ const client = new DaemonClient("http://localhost:8080");
+ const result = await client.poll("tok", "d1", 1);
+ expect(result.pending_rescan).toBeUndefined();
+ });
+
it("returns evicted: true when server signals eviction", async () => {
globalThis.fetch = vi.fn().mockResolvedValue({
ok: true,
diff --git a/src/cli/daemon/client.ts b/src/cli/daemon/client.ts
index 535f43ef5..f2bdf50c7 100644
--- a/src/cli/daemon/client.ts
+++ b/src/cli/daemon/client.ts
@@ -80,7 +80,7 @@ export class DaemonClient {
daemonId: string,
maxTasks: number,
cliVersion?: string,
- ): Promise<{ tasks: TaskApi[]; evicted: boolean; pending_update?: { version: string } }> {
+ ): Promise<{ tasks: TaskApi[]; evicted: boolean; pending_update?: { version: string }; pending_rescan?: boolean }> {
const raw = await this.request<unknown>(
"POST",
"/api/daemon/tasks/poll",
@@ -92,6 +92,7 @@ export class DaemonClient {
tasks: resp.tasks,
evicted: resp.evicted ?? false,
pending_update: resp.pending_update,
+ pending_rescan: resp.pending_rescan,
};
}
diff --git a/src/cli/daemon/daemon.test.ts b/src/cli/daemon/daemon.test.ts
index 0f66be7c5..a1a448b11 100644
--- a/src/cli/daemon/daemon.test.ts
+++ b/src/cli/daemon/daemon.test.ts
@@ -1395,6 +1395,76 @@ describe("daemon restart via update", () => {
});
+describe("daemon rescan via poll", () => {
+ beforeEach(async () => {
+ signalHandlers.clear();
+ intervalTimers.length = 0;
+ clearedTimers.length = 0;
+ spawnedChildren.length = 0;
+ nextPid = 50000;
+ vi.clearAllMocks();
+ mockProcessExit.mockImplementation((() => {}) as any);
+ mockOpenSync.mockReturnValue(99);
+
+ const { createHealthServer } = await import("./health.js");
+ vi.mocked(createHealthServer).mockReturnValue({
+ setRuntimeCount: vi.fn(),
+ server: { close: vi.fn((cb?: () => void) => { if (cb) cb(); }) },
+ } as any);
+
+ mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });
+ mockClientInstance.deregister.mockResolvedValue(undefined as any);
+ });
+
+ afterEach(() => {
+ for (const t of intervalTimers) realClearInterval(t);
+ });
+
+ it("calls requestRestart when pending_rescan is true in poll response", async () => {
+ vi.mocked(loadCLIConfigForProfile).mockReturnValue({
+ server_url: "",
+ watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
+ });
+
+ mockClientInstance.poll.mockResolvedValue({
+ tasks: [],
+ evicted: false,
+ pending_rescan: true,
+ });
+
+ await startDaemon();
+ await new Promise((r) => setTimeout(r, 200));
+
+ // requestRestart triggers shutdown + spawn of new daemon
+ const spawnCalls = vi.mocked(spawn).mock.calls;
+ const restartCall = spawnCalls.find(
+ (call) => call[0] === process.execPath && (call[1] as string[]).includes("--foreground"),
+ );
+ expect(restartCall).toBeDefined();
+ });
+
+ it("does not restart when pending_rescan is absent", async () => {
+ vi.mocked(loadCLIConfigForProfile).mockReturnValue({
+ server_url: "",
+ watched_workspaces: [{ id: "ws1", name: "Test WS", token: "al_test_token" }],
+ });
+
+ mockClientInstance.poll.mockResolvedValue({
+ tasks: [],
+ evicted: false,
+ });
+
+ await startDaemon();
+ await new Promise((r) => setTimeout(r, 200));
+
+ const spawnCalls = vi.mocked(spawn).mock.calls;
+ const restartCall = spawnCalls.find(
+ (call) => call[0] === process.execPath && (call[1] as string[]).includes("--foreground"),
+ );
+ expect(restartCall).toBeUndefined();
+ });
+});
+
describe("daemon restart spawn", () => {
beforeEach(async () => {
signalHandlers.clear();
diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.ts
index 816bce50a..4636f19b7 100644
--- a/src/cli/daemon/daemon.ts
+++ b/src/cli/daemon/daemon.ts
@@ -395,7 +395,7 @@ export async function startDaemon(
}
try {
- const { tasks: apiTasks, evicted, pending_update } = await client.poll(
+ const { tasks: apiTasks, evicted, pending_update, pending_rescan } = await client.poll(
ws.token,
config.daemonId,
remaining,
@@ -411,6 +411,11 @@ export async function startDaemon(
handleCliUpdate(pending_update.version, () => requestRestart(), profile);
}
+ if (pending_rescan) {
+ log.info("Rescan requested — restarting daemon to re-detect runtimes");
+ requestRestart();
+ }
+
for (const apiTask of apiTasks) {
const task = fromApiTask(apiTask);
syncAgentId(task.agentId, ws.workspaceId);
diff --git a/src/cli/package.json b/src/cli/package.json
index 2972cd133..22552cd6d 100644
--- a/src/cli/package.json
+++ b/src/cli/package.json
@@ -41,7 +41,7 @@
"build": "bun build src/index.ts --outdir dist --target node --format esm --external citty --external commander --external postal-mime && bun build daemon/session-runner.ts --outdir dist --target node --format esm --external citty --external commander --external postal-mime && node scripts/prepare-dist.mjs",
"prepack": "pnpm run build",
"test": "vitest run",
- "typecheck": "tsc --noEmit"
+ "typecheck": "tsc --noEmit -p tsconfig.build.json"
},
"dependencies": {
"citty": "^0.2.2",
diff --git a/src/cli/tsconfig.build.json b/src/cli/tsconfig.build.json
new file mode 100644
index 000000000..0a104bc79
--- /dev/null
+++ b/src/cli/tsconfig.build.json
@@ -0,0 +1,8 @@
+{
+ "extends": "./tsconfig.json",
+ "compilerOptions": {
+ "types": ["bun"]
+ },
+ "include": ["src", "commands", "daemon", "lib"],
+ "exclude": ["**/__tests__", "**/*.test.ts"]
+}
diff --git a/src/cli/tsconfig.json b/src/cli/tsconfig.json
index 74166aeac..b3e4828ee 100644
--- a/src/cli/tsconfig.json
+++ b/src/cli/tsconfig.json
@@ -5,8 +5,7 @@
"moduleResolution": "bundler",
"strict": true,
"skipLibCheck": true,
- "types": ["bun"]
+ "types": ["bun", "vitest/globals"]
},
- "include": ["src", "commands", "daemon", "lib"],
- "exclude": ["**/__tests__", "**/*.test.ts"]
+ "include": ["src", "commands", "daemon", "lib", "**/*.test.ts", "**/__tests__/**/*.ts"]
}
diff --git a/src/shared/src/db/queries/machine.ts b/src/shared/src/db/queries/machine.ts
index 89e221395..b13ab4877 100644
--- a/src/shared/src/db/queries/machine.ts
+++ b/src/shared/src/db/queries/machine.ts
@@ -121,3 +121,31 @@ export async function clearPendingUpdateVersion(
.set({ pendingUpdateVersion: null, updatedAt: now })
.where(eq(machine.daemonId, daemonId));
}
+
+export async function setPendingRescan(
+ db: Database,
+ daemonId: string,
+ workspaceId: string,
+) {
+ const now = new Date().toISOString();
+ await db
+ .update(machine)
+ .set({ pendingRescan: true, updatedAt: now })
+ .where(
+ and(eq(machine.daemonId, daemonId), eq(machine.workspaceId, workspaceId)),
+ );
+}
+
+export async function clearPendingRescan(
+ db: Database,
+ daemonId: string,
+ workspaceId: string,
+) {
+ const now = new Date().toISOString();
+ await db
+ .update(machine)
+ .set({ pendingRescan: false, updatedAt: now })
+ .where(
+ and(eq(machine.daemonId, daemonId), eq(machine.workspaceId, workspaceId)),
+ );
+}
diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.ts
index 7d13ba44c..4a90bc9f2 100644
--- a/src/shared/src/db/schema.ts
+++ b/src/shared/src/db/schema.ts
@@ -170,6 +170,7 @@ export const machine = sqliteTable(
lastSeenAt: text("last_seen_at"),
createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),
pendingUpdateVersion: text("pending_update_version"),
+ pendingRescan: integer("pending_rescan", { mode: "boolean" }).default(false),
updatedAt: text("updated_at").notNull().$defaultFn(() => new Date().toISOString()),
},
(t) => [primaryKey({ columns: [t.workspaceId, t.daemonId] })]
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index cd2b071ba..0417d0d7a 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -104,6 +104,7 @@ export const PollResponseSchema = z.object({
tasks: z.array(TaskApiSchema),
evicted: z.boolean().optional(),
pending_update: z.object({ version: z.string() }).optional(),
+ pending_rescan: z.boolean().optional(),
});
export type PollResponse = z.infer<typeof PollResponseSchema>;
diff --git a/src/shared/src/types.ts b/src/shared/src/types.ts
index ba80a0318..e174846d6 100644
--- a/src/shared/src/types.ts
+++ b/src/shared/src/types.ts
@@ -48,6 +48,7 @@ export interface AgentRuntime {
device_info: string;
metadata: Record<string, unknown>;
pending_update_version?: string | null;
+ pending_rescan?: boolean;
last_seen_at: string | null;
created_at: string;
updated_at: string;
diff --git a/src/web/migrations/0011_machine_pending_rescan.sql b/src/web/migrations/0011_machine_pending_rescan.sql
new file mode 100644
index 000000000..007c22f57
--- /dev/null
+++ b/src/web/migrations/0011_machine_pending_rescan.sql
@@ -0,0 +1 @@
+ALTER TABLE machine ADD COLUMN pending_rescan integer DEFAULT 0;
diff --git a/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx b/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx
index ace0a9acd..4ca5e3ab8 100644
--- a/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx
+++ b/src/web/src/app/(app)/w/[slug]/runtimes/page.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useState, useRef, useEffect, useCallback } from "react";
+import { useState, useMemo, useRef, useEffect, useCallback } from "react";
import { useSearchParams, useRouter, usePathname } from "next/navigation";
import { useAgentContext } from "@/contexts/agent-context";
import { Button } from "@/components/ui/button";
@@ -9,7 +9,6 @@ import {
Card,
CardHeader,
CardTitle,
- CardAction,
CardContent,
} from "@/components/ui/card";
import {
@@ -29,8 +28,8 @@ 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";
+import { triggerRuntimeUpdate, triggerRuntimeRescan, fetchLatestCliVersion } from "@/lib/api";
+import { Loader2, RefreshCw } from "lucide-react";
function ConnectMachineSteps({
generatedToken,
@@ -140,12 +139,13 @@ export default function RuntimesPage() {
const router = useRouter();
const pathname = usePathname();
- const [sheetOpen, setSheetOpen] = useState(false);
+ const [sheetOpen, setSheetOpen] = useState(() => searchParams.has("connect"));
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 [rescanningDaemons, setRescanningDaemons] = useState<Set<string>>(new Set());
const [confirmOpen, setConfirmOpen] = useState(false);
const [confirmTitle, setConfirmTitle] = useState("");
@@ -159,10 +159,9 @@ export default function RuntimesPage() {
.catch(() => {});
}, []);
- // Auto-open "New machine" sheet when navigated with ?connect
+ // Clean up ?connect query param after initial open
useEffect(() => {
if (searchParams.has("connect")) {
- setSheetOpen(true);
router.replace(pathname, { scroll: false });
}
}, [searchParams, router, pathname]);
@@ -226,25 +225,50 @@ export default function RuntimesPage() {
}
};
- // Clear updatingDaemons when runtimes reload shows update completed
- useEffect(() => {
- if (updatingDaemons.size === 0) return;
- const stillUpdating = new Set<string>();
+ const handleRescan = async (runtimeId: string, daemonId: string) => {
+ setRescanningDaemons((prev) => new Set(prev).add(daemonId));
+ try {
+ await triggerRuntimeRescan(runtimeId, workspaceId);
+ toast.success("Rescan triggered — daemon will restart to detect runtimes");
+ } catch {
+ toast.error("Failed to trigger rescan");
+ setRescanningDaemons((prev) => {
+ const next = new Set(prev);
+ next.delete(daemonId);
+ return next;
+ });
+ }
+ };
+
+ // Derive effective optimistic sets: filter out entries whose server-side flag has cleared
+ const effectiveUpdatingDaemons = useMemo(() => {
+ if (updatingDaemons.size === 0) return updatingDaemons;
+ const still = new Set<string>();
for (const rt of runtimes) {
const key = rt.daemon_id || rt.id;
if (updatingDaemons.has(key) && rt.pending_update_version) {
- stillUpdating.add(key);
+ still.add(key);
}
}
- if (stillUpdating.size < updatingDaemons.size) {
- setUpdatingDaemons(stillUpdating);
+ return still;
+ }, [runtimes, updatingDaemons]);
+
+ const effectiveRescanningDaemons = useMemo(() => {
+ if (rescanningDaemons.size === 0) return rescanningDaemons;
+ const still = new Set<string>();
+ for (const rt of runtimes) {
+ const key = rt.daemon_id || rt.id;
+ if (rescanningDaemons.has(key) && rt.pending_rescan) {
+ still.add(key);
+ }
}
- }, [runtimes]); // eslint-disable-line react-hooks/exhaustive-deps
+ return still;
+ }, [runtimes, rescanningDaemons]);
// Group runtimes by machine
const machines = new Map<
string,
- { deviceInfo: string; name: string; status: string; lastSeenAt: string | null; pendingUpdateVersion: string | null; cliVersion: string | null; runtimes: Runtime[] }
+ { deviceInfo: string; name: string; status: string; lastSeenAt: string | null; pendingUpdateVersion: string | null; pendingRescan: boolean; cliVersion: string | null; runtimes: Runtime[] }
>();
for (const rt of runtimes) {
const key = rt.daemon_id || rt.id;
@@ -256,6 +280,7 @@ export default function RuntimesPage() {
status: rt.status,
lastSeenAt: rt.last_seen_at,
pendingUpdateVersion: rt.pending_update_version ?? null,
+ pendingRescan: !!rt.pending_rescan,
cliVersion: (meta?.cli_version as string) ?? null,
runtimes: [],
});
@@ -372,61 +397,84 @@ export default function RuntimesPage() {
{machine.status}
</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;
- })()}
- <Button
- variant="ghost"
- size="sm"
- className="text-xs text-muted-foreground h-6 px-2 hover:text-destructive opacity-0 group-hover:opacity-100 transition-opacity"
- onClick={() => {
- openConfirm(
- "Remove machine",
- `This will remove "${displayName}" and all its runtimes. Agents using these runtimes will be unlinked.`,
- async () => {
- await handleDeleteMachine(daemonId);
- }
- );
- }}
- >
- Remove
- </Button>
- </CardAction>
+ {machine.cliVersion && (
+ <span className="text-xs text-muted-foreground/60 shrink-0">v{machine.cliVersion}</span>
+ )}
</CardHeader>
<CardContent>
<div className="space-y-2.5">
- <div className="flex items-center gap-2 text-xs text-muted-foreground tabular-nums">
- <span>
+ <div className="flex items-center justify-between">
+ <span className="text-xs text-muted-foreground tabular-nums">
{machine.lastSeenAt ? new Date(
machine.lastSeenAt
).toLocaleString() : "Never seen"}
</span>
- {machine.cliVersion && (
- <span className="text-muted-foreground/60">v{machine.cliVersion}</span>
- )}
+ <div className="flex items-center gap-1">
+ {(() => {
+ const isUpdating = !!machine.pendingUpdateVersion || effectiveUpdatingDaemons.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;
+ })()}
+ {(() => {
+ const isRescanning = machine.pendingRescan || effectiveRescanningDaemons.has(daemonId);
+ if (machine.status !== "online") return null;
+ if (isRescanning) {
+ return (
+ <Button variant="ghost" size="sm" disabled className="text-xs h-6 px-2">
+ <RefreshCw className="size-3 animate-spin mr-1" />
+ Rescanning...
+ </Button>
+ );
+ }
+ return (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-xs h-6 px-2"
+ onClick={() => handleRescan(machine.runtimes[0].id, daemonId)}
+ >
+ <RefreshCw className="size-3 mr-1" />
+ Rescan
+ </Button>
+ );
+ })()}
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-xs text-muted-foreground h-6 px-2 hover:text-destructive opacity-0 group-hover:opacity-100 transition-opacity"
+ onClick={() => {
+ openConfirm(
+ "Remove machine",
+ `This will remove "${displayName}" and all its runtimes. Agents using these runtimes will be unlinked.`,
+ async () => {
+ await handleDeleteMachine(daemonId);
+ }
+ );
+ }}
+ >
+ Remove
+ </Button>
+ </div>
</div>
<div className="flex flex-wrap gap-1.5">
{machine.runtimes.map((runtime) => (
@@ -458,7 +506,7 @@ export default function RuntimesPage() {
}}
title="Click to copy"
>
- <span className="absolute inset-0 -translate-x-full animate-[shimmer_2.5s_infinite] bg-gradient-to-r from-transparent via-[var(--shimmer-peak)] to-transparent" />
+ <span className="absolute inset-0 -translate-x-full animate-[shimmer_2.5s_infinite] bg-linear-to-r from-transparent via-(--shimmer-peak) to-transparent" />
<span className="relative">{CLI_CMD} daemon start</span>
</div>
</div>
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 3a57ce4e2..d513c8b6b 100644
--- a/src/web/src/app/api/daemon/tasks/poll/route.ts
+++ b/src/web/src/app/api/daemon/tasks/poll/route.ts
@@ -146,5 +146,16 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {
}
}
- return writeJSON({ tasks, ...(pendingUpdate && { pending_update: pendingUpdate }) });
+ // 6. Pending rescan check
+ let pendingRescan: boolean | undefined;
+ if (machineRow?.pendingRescan) {
+ pendingRescan = true;
+ await queries.machine.clearPendingRescan(db, body.daemon_id, ctx.workspaceId);
+ }
+
+ return writeJSON({
+ tasks,
+ ...(pendingUpdate && { pending_update: pendingUpdate }),
+ ...(pendingRescan && { pending_rescan: pendingRescan }),
+ });
});
diff --git a/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.test.ts b/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.test.ts
new file mode 100644
index 000000000..132b8c15a
--- /dev/null
+++ b/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.test.ts
@@ -0,0 +1,118 @@
+import { describe, it, expect, vi, beforeEach } from "vitest";
+import { NextRequest } from "next/server";
+
+const mockGetAgentRuntimeForWorkspace = vi.fn();
+const mockSetPendingRescan = vi.fn();
+const mockGetMemberByUserAndWorkspace = vi.fn();
+
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
+}));
+
+vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));
+
+vi.mock("@alook/shared", () => ({
+ createDb: vi.fn(() => ({})),
+ queries: {
+ runtime: {
+ getAgentRuntimeForWorkspace: (...args: any[]) =>
+ mockGetAgentRuntimeForWorkspace(...args),
+ },
+ machine: {
+ setPendingRescan: (...args: any[]) =>
+ mockSetPendingRescan(...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() },
+}));
+
+import { POST } from "./route";
+
+function makeReq(runtimeId: string, workspaceId: string) {
+ const url = `http://localhost/api/runtimes/${runtimeId}/rescan?workspace_id=${workspaceId}`;
+ return new NextRequest(url, { method: "POST" });
+}
+
+describe("POST /api/runtimes/[runtimeId]/rescan", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "m1" });
+ });
+
+ it("returns 200 with pending_rescan: true", async () => {
+ mockGetAgentRuntimeForWorkspace.mockResolvedValue({
+ id: "rt1",
+ daemonId: "d1",
+ });
+ mockSetPendingRescan.mockResolvedValue(undefined);
+
+ const res = await POST(makeReq("rt1", "w1"));
+ const body = await res.json();
+
+ expect(res.status).toBe(200);
+ expect(body.pending_rescan).toBe(true);
+ expect(mockSetPendingRescan).toHaveBeenCalledWith({}, "d1", "w1");
+ });
+
+ it("returns 404 for non-existent runtime", async () => {
+ mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);
+
+ const res = await POST(makeReq("nonexistent", "w1"));
+ const body = await res.json();
+
+ expect(res.status).toBe(404);
+ expect(body.error).toContain("not found");
+ });
+
+ it("returns 404 for runtime in another workspace", async () => {
+ mockGetMemberByUserAndWorkspace.mockResolvedValue(null);
+
+ const res = await POST(makeReq("rt1", "w-other"));
+ const body = await res.json();
+
+ expect(res.status).toBe(404);
+ expect(body.error).toContain("workspace not found");
+ });
+
+ it("returns 400 when runtime id is missing from URL", async () => {
+ mockGetAgentRuntimeForWorkspace.mockResolvedValue(null);
+ const url = `http://localhost/api/runtimes//rescan?workspace_id=w1`;
+ const req = new NextRequest(url, { method: "POST" });
+
+ const res = await POST(req);
+ const body = await res.json();
+
+ expect(res.status).toBe(400);
+ expect(body.error).toContain("runtime id required");
+ });
+});
diff --git a/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.ts b/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.ts
new file mode 100644
index 000000000..a87e35193
--- /dev/null
+++ b/src/web/src/app/api/runtimes/[runtimeId]/rescan/route.ts
@@ -0,0 +1,29 @@
+import { NextRequest } from "next/server";
+import { getCloudflareContext } from "@opennextjs/cloudflare";
+import { queries } from "@alook/shared";
+import { getDb } from "@/lib/db"
+import { withAuth } from "@/lib/middleware/auth";
+import { withWorkspaceMember } from "@/lib/middleware/workspace";
+import { writeJSON, writeError } from "@/lib/middleware/helpers";
+
+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 = getDb((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.setPendingRescan(db, runtime.daemonId, ws.workspaceId);
+
+ return writeJSON({ pending_rescan: true });
+});
diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.ts
index e425fa032..31a8bad3d 100644
--- a/src/web/src/lib/api.ts
+++ b/src/web/src/lib/api.ts
@@ -140,6 +140,12 @@ export const triggerRuntimeUpdate = (runtimeId: string, workspaceId: string) =>
{ method: "POST" }
);
+export const triggerRuntimeRescan = (runtimeId: string, workspaceId: string) =>
+ apiFetch<{ pending_rescan: boolean }>(
+ `/api/runtimes/${runtimeId}/rescan${wsQuery(workspaceId)}`,
+ { method: "POST" }
+ );
+
export const fetchLatestCliVersion = () =>
apiFetch<{ version: string }>("/api/cli/latest-version");
diff --git a/src/web/src/lib/api/responses.test.ts b/src/web/src/lib/api/responses.test.ts
index 7f98e7419..9c0c871f8 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", "pending_update_version", "provider", "runtime_mode", "status",
+ "metadata", "name", "pending_rescan", "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.ts
index 28c130618..aeb517003 100644
--- a/src/web/src/lib/api/responses.ts
+++ b/src/web/src/lib/api/responses.ts
@@ -173,6 +173,7 @@ export function runtimeToResponse(rt: any) {
device_info: rt.deviceInfo,
metadata,
pending_update_version: rt.pendingUpdateVersion ?? null,
+ pending_rescan: !!rt.pendingRescan,
last_seen_at: formatTimestampNullable(machineLastSeenAt),
created_at: formatTimestamp(rt.createdAt),
updated_at: formatTimestamp(rt.updatedAt),