import test from "node:test"; import assert from "node:assert/strict"; import os from "node:os"; import path from "node:path"; import { mkdtemp, rm } from "node:fs/promises"; import { NextRequest } from "next/server"; let runtimeRoot = ""; let postClaim: (typeof import("../src/app/api/v1/master-agent/tasks/claim/route.ts"))["POST"]; let queueMasterAgentTask: (typeof import("../src/lib/boss-data.ts"))["queueMasterAgentTask"]; async function setup() { if (runtimeRoot) return; runtimeRoot = await mkdtemp(path.join(os.tmpdir(), "boss-master-task-claim-route-")); process.env.BOSS_RUNTIME_ROOT = runtimeRoot; process.env.BOSS_STATE_FILE = path.join(runtimeRoot, "boss-state.json"); const [route, data] = await Promise.all([ import("../src/app/api/v1/master-agent/tasks/claim/route.ts"), import("../src/lib/boss-data.ts"), ]); postClaim = route.POST; queueMasterAgentTask = data.queueMasterAgentTask; } test.beforeEach(async () => { await setup(); await rm(runtimeRoot, { recursive: true, force: true }); }); test.after(async () => { if (runtimeRoot) { await rm(runtimeRoot, { recursive: true, force: true }); } }); test("master task claim waits for a matching queued task event before returning", async () => { const claimStartedAt = Date.now(); const claim = postClaim( new NextRequest("http://127.0.0.1:3000/api/v1/master-agent/tasks/claim", { method: "POST", headers: { "content-type": "application/json", "x-boss-device-token": "boss-mac-studio-token", }, body: JSON.stringify({ deviceId: "mac-studio", waitMs: 1_000, }), }), ); setTimeout(() => { void queueMasterAgentTask({ projectId: "master-agent", requestMessageId: "msg-long-poll", requestText: "打开 Finder", executionPrompt: "打开 Finder", requestedBy: "Boss 超级管理员", requestedByAccount: "krisolo", deviceId: "mac-studio", taskType: "desktop_control", }); }, 20); const response = await claim; const payload = (await response.json()) as { ok: boolean; task?: { taskId: string; taskType: string; status: string } | null; }; assert.equal(response.status, 200); assert.equal(payload.ok, true); assert.equal(payload.task?.taskType, "desktop_control"); assert.equal(payload.task?.status, "running"); assert.ok(Date.now() - claimStartedAt < 500); });