Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix: register uses token workspace instead of workspaces[0] (#39)
Gener7f9d739dd15a
diff --git a/src/cli/commands/register.ts b/src/cli/commands/register.tsindex d2e504baf..d8df7818f 100644--- a/src/cli/commands/register.ts+++ b/src/cli/commands/register.ts@@ -21,6 +21,7 @@ interface AgentListItem {interface ActivateResponse {daemon_id: string;+ workspace_id: string;runtimes: { id: string; provider: string }[];}@@ -108,8 +109,6 @@ export function registerCommand(): Command {process.exit(1);}- const ws = workspaces[0];-// Detect local runtimesconsole.log("Scanning for AI runtimes...");const runtimes = detectRuntimes();@@ -146,6 +145,9 @@ export function registerCommand(): Command {process.exit(1);}+ // Use the workspace_id from activate response to find the correct workspace+ const ws = workspaces.find((w) => w.id === activateResp.workspace_id) || workspaces[0];+// Fetch agents for this workspaceconst wsClient = new APIClient(serverUrl, token, ws.id);let agentIds: string[] = [];diff --git a/src/web/src/app/api/daemon/register/route.test.ts b/src/web/src/app/api/daemon/register/route.test.tsindex 138393de6..5496991f7 100644--- a/src/web/src/app/api/daemon/register/route.test.ts+++ b/src/web/src/app/api/daemon/register/route.test.ts@@ -136,6 +136,32 @@ describe("POST /api/daemon/register", () => {expect(mockBroadcastToUser).not.toHaveBeenCalled();});+ it("returns 403 when token workspace_id does not match body workspace_id", async () => {+ const POST = await loadRoute({ ...authCtx, workspaceId: "w_other" });++ const res = await POST(makeReq(validBody));+ const body = await res.json();++ expect(res.status).toBe(403);+ expect(body.error).toBe("workspace_id does not match token");+ expect(mockGetMember).not.toHaveBeenCalled();+ expect(mockUpsertMachine).not.toHaveBeenCalled();+ });++ it("allows register when token workspace_id matches body workspace_id", async () => {+ const POST = await loadRoute({ ...authCtx, workspaceId: "w1" });++ mockGetMember.mockResolvedValue({ userId: "u1", workspaceId: "w1" });+ mockUpsertMachine.mockResolvedValue(undefined);+ mockUpsertAgentRuntime.mockResolvedValue({ id: "r1", name: "claude" });+ mockBroadcastToUser.mockResolvedValue(undefined);++ const res = await POST(makeReq(validBody));++ expect(res.status).toBe(200);+ expect(mockUpsertMachine).toHaveBeenCalledTimes(1);+ });+it("does not fail the request if broadcast throws (fire-and-forget)", async () => {const POST = await loadRoute(authCtx);diff --git a/src/web/src/app/api/daemon/register/route.ts b/src/web/src/app/api/daemon/register/route.tsindex 6ad418875..d2dbf52c3 100644--- a/src/web/src/app/api/daemon/register/route.ts+++ b/src/web/src/app/api/daemon/register/route.ts@@ -17,6 +17,11 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {const { workspace_id: workspaceId, daemon_id: daemonId, device_name: deviceName, cli_version: cliVersion, runtimes } = body;+ // When authenticated with a machine token, enforce workspace match+ if (ctx.workspaceId && ctx.workspaceId !== workspaceId) {+ return writeJSON({ error: "workspace_id does not match token" }, 403);+ }+const membership = await queries.member.getMemberByUserAndWorkspace(db,ctx.userId,diff --git a/src/web/src/app/api/machine-tokens/activate/route.test.ts b/src/web/src/app/api/machine-tokens/activate/route.test.tsnew file mode 100644index 000000000..a8ca89a43--- /dev/null+++ b/src/web/src/app/api/machine-tokens/activate/route.test.ts@@ -0,0 +1,158 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { NextRequest } from "next/server";++const mockGetMachineTokenByToken = vi.fn();+const mockActivateMachineToken = vi.fn();+const mockUpsertMachine = vi.fn();+const mockUpsertAgentRuntime = vi.fn();+const mockBroadcastToUser = vi.fn();++function sharedMocks() {+ return {+ "@opennextjs/cloudflare": {+ getCloudflareContext: vi.fn(() => Promise.resolve({ env: { DB: {} } })),+ },+ "@alook/shared": async () => ({+ createDb: vi.fn(() => ({})),+ queries: {+ machineToken: {+ getMachineTokenByToken: (...a: any[]) => mockGetMachineTokenByToken(...a),+ activateMachineToken: (...a: any[]) => mockActivateMachineToken(...a),+ },+ machine: {+ upsertMachine: (...a: any[]) => mockUpsertMachine(...a),+ },+ runtime: {+ upsertAgentRuntime: (...a: any[]) => mockUpsertAgentRuntime(...a),+ },+ },+ ActivateTokenRequestSchema: (await import("@alook/shared"))+ .ActivateTokenRequestSchema,+ createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),+ }),+ "@/lib/broadcast": {+ broadcastToUser: (...a: any[]) => mockBroadcastToUser(...a),+ },+ "@/lib/api/responses": {+ runtimeToResponse: (rt: any) => ({ id: rt.id, name: rt.name, provider: rt.provider }),+ },+ };+}++function makeReq(body: unknown) {+ return new NextRequest("http://localhost/api/machine-tokens/activate", {+ method: "POST",+ body: JSON.stringify(body),+ headers: { "Content-Type": "application/json" },+ });+}++describe("POST /api/machine-tokens/activate", () => {+ beforeEach(() => vi.clearAllMocks());++ async function loadRoute() {+ vi.resetModules();++ const mocks = sharedMocks();++ vi.doMock("@opennextjs/cloudflare", () => mocks["@opennextjs/cloudflare"]);+ vi.doMock("@alook/shared", mocks["@alook/shared"]);+ vi.doMock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));+ vi.doMock("@/lib/broadcast", () => mocks["@/lib/broadcast"]);+ vi.doMock("@/lib/api/responses", () => mocks["@/lib/api/responses"]);+ vi.doMock("@/lib/middleware/helpers", async () => {+ return await vi.importActual<typeof import("@/lib/middleware/helpers")>(+ "@/lib/middleware/helpers"+ );+ });++ const { POST } = await import("./route");+ return POST;+ }++ const validBody = {+ token: "al_test123",+ hostname: "TestMachine.local",+ runtimes: [{ type: "claude", version: "2.1.0" }],+ };++ const pendingToken = {+ id: "mt_1",+ userId: "u1",+ workspaceId: "sp_correct_workspace",+ status: "pending",+ };++ it("returns workspace_id in the response", async () => {+ const POST = await loadRoute();++ mockGetMachineTokenByToken.mockResolvedValue(pendingToken);+ mockUpsertMachine.mockResolvedValue(undefined);+ mockUpsertAgentRuntime.mockResolvedValue({ id: "r1", name: "claude (TestMachine.local)", provider: "claude" });+ mockActivateMachineToken.mockResolvedValue(undefined);+ mockBroadcastToUser.mockResolvedValue(undefined);++ const res = await POST(makeReq(validBody));+ const body = await res.json();++ expect(res.status).toBe(200);+ expect(body.workspace_id).toBe("sp_correct_workspace");+ expect(body.daemon_id).toBe("TestMachine.local");+ expect(body.runtimes).toHaveLength(1);+ });++ it("returns 404 when token not found", async () => {+ const POST = await loadRoute();++ mockGetMachineTokenByToken.mockResolvedValue(null);++ const res = await POST(makeReq(validBody));+ const body = await res.json();++ expect(res.status).toBe(404);+ expect(body.error).toBe("token not found");+ expect(mockUpsertMachine).not.toHaveBeenCalled();+ });++ it("returns 409 when token already used", async () => {+ const POST = await loadRoute();++ mockGetMachineTokenByToken.mockResolvedValue({ ...pendingToken, status: "active" });++ const res = await POST(makeReq(validBody));+ const body = await res.json();++ expect(res.status).toBe(409);+ expect(body.error).toBe("token already used");+ expect(mockUpsertMachine).not.toHaveBeenCalled();+ });++ it("creates machine and runtime with token's workspace_id", async () => {+ const POST = await loadRoute();++ mockGetMachineTokenByToken.mockResolvedValue(pendingToken);+ mockUpsertMachine.mockResolvedValue(undefined);+ mockUpsertAgentRuntime.mockResolvedValue({ id: "r1", name: "claude (TestMachine.local)", provider: "claude" });+ mockActivateMachineToken.mockResolvedValue(undefined);+ mockBroadcastToUser.mockResolvedValue(undefined);++ await POST(makeReq(validBody));++ expect(mockUpsertMachine).toHaveBeenCalledWith(expect.anything(), {+ daemonId: "TestMachine.local",+ workspaceId: "sp_correct_workspace",+ deviceInfo: "TestMachine.local",+ lastSeenAt: null,+ });++ expect(mockUpsertAgentRuntime).toHaveBeenCalledWith(expect.anything(), {+ workspaceId: "sp_correct_workspace",+ daemonId: "TestMachine.local",+ name: "claude (TestMachine.local)",+ runtimeMode: "local",+ provider: "claude",+ deviceInfo: "TestMachine.local",+ metadata: { version: "2.1.0" },+ });+ });+});diff --git a/src/web/src/app/api/machine-tokens/activate/route.ts b/src/web/src/app/api/machine-tokens/activate/route.tsindex 7e50dc1b9..da3e6710b 100644--- a/src/web/src/app/api/machine-tokens/activate/route.ts+++ b/src/web/src/app/api/machine-tokens/activate/route.ts@@ -81,6 +81,7 @@ export async function POST(req: NextRequest) {return writeJSON({daemon_id: daemonId,+ workspace_id: mt.workspaceId,runtimes: results.map(runtimeToResponse),});}