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: workspace creation regressions in onboarding flow (#144)
Generc9daa651230e
diff --git a/src/cli/commands/register.test.ts b/src/cli/commands/register.test.tsnew file mode 100644index 000000000..06fd316a0--- /dev/null+++ b/src/cli/commands/register.test.ts@@ -0,0 +1,221 @@+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";++const mockLoadCLIConfigForProfile = vi.fn();+const mockSaveCLIConfigForProfile = vi.fn();+const mockReadDaemonPid = vi.fn();+const mockIsProcessAlive = vi.fn();++vi.mock("../lib/config.js", () => ({+ loadCLIConfigForProfile: (...args: any[]) => mockLoadCLIConfigForProfile(...args),+ saveCLIConfigForProfile: (...args: any[]) => mockSaveCLIConfigForProfile(...args),+}));++vi.mock("../daemon/pidfile.js", () => ({+ readDaemonPid: (...args: any[]) => mockReadDaemonPid(...args),+ isProcessAlive: (...args: any[]) => mockIsProcessAlive(...args),+}));++vi.mock("../lib/env.js", () => ({+ cmdPrefix: () => "alook",+ isDev: () => false,+}));++vi.mock("child_process", () => ({+ execSync: vi.fn((cmd: string) => {+ if (cmd.includes("which claude")) return "/usr/bin/claude";+ if (cmd.includes("claude --version")) return "4.0.0";+ throw new Error("not found");+ }),+}));++import { registerCommand } from "./register";++describe("alook register", () => {+ let consoleSpy: ReturnType<typeof vi.spyOn>;+ let consoleErrSpy: ReturnType<typeof vi.spyOn>;+ let mockExit: ReturnType<typeof vi.spyOn>;+ let mockKill: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ vi.clearAllMocks();+ consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});+ consoleErrSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ mockExit = vi.spyOn(process, "exit").mockImplementation(() => undefined as never);+ mockKill = vi.spyOn(process, "kill").mockImplementation(() => true);+ });++ afterEach(() => {+ consoleSpy.mockRestore();+ consoleErrSpy.mockRestore();+ mockExit.mockRestore();+ mockKill.mockRestore();+ vi.unstubAllGlobals();+ });++ function mockFetch(responses: Record<string, { status: number; body: unknown }>) {+ vi.stubGlobal("fetch", vi.fn(async (url: string | URL | Request) => {+ const urlStr = typeof url === "string" ? url : url instanceof URL ? url.toString() : url.url;+ for (const [pattern, resp] of Object.entries(responses)) {+ if (urlStr.includes(pattern)) {+ return {+ ok: resp.status >= 200 && resp.status < 300,+ status: resp.status,+ json: async () => resp.body,+ text: async () => JSON.stringify(resp.body),+ };+ }+ }+ return { ok: false, status: 404, text: async () => "not found" };+ }));+ }++ it("stores workspace_id from activate response in config", async () => {+ mockLoadCLIConfigForProfile.mockReturnValue({+ server_url: "http://localhost:3000",+ watched_workspaces: [],+ });+ mockReadDaemonPid.mockReturnValue(null);++ mockFetch({+ "/api/me": { status: 200, body: { id: "u1", email: "[email protected]" } },+ "/api/machine-tokens/activate": {+ status: 200,+ body: { daemon_id: "host1", workspace_id: "sp_new123", runtimes: [{ id: "r1", provider: "claude" }] },+ },+ "/api/workspaces": { status: 200, body: [{ id: "sp_new123", name: "New WS" }] },+ "/api/agents": { status: 200, body: [] },+ });++ const cmd = registerCommand();+ await cmd.parseAsync(["node", "register", "--token", "al_testtoken123", "--server", "http://localhost:3000"]);++ expect(mockSaveCLIConfigForProfile).toHaveBeenCalledWith(+ undefined,+ expect.objectContaining({+ watched_workspaces: [+ { id: "sp_new123", name: "New WS", token: "al_testtoken123", agent_ids: [] },+ ],+ }),+ );+ });++ it("appends new workspace to existing config (does not replace)", async () => {+ mockLoadCLIConfigForProfile.mockReturnValue({+ server_url: "http://localhost:3000",+ watched_workspaces: [+ { id: "sp_existing", name: "Existing", token: "al_old", agent_ids: ["ag_1"] },+ ],+ });+ mockReadDaemonPid.mockReturnValue(null);++ mockFetch({+ "/api/me": { status: 200, body: { id: "u1", email: "[email protected]" } },+ "/api/machine-tokens/activate": {+ status: 200,+ body: { daemon_id: "host1", workspace_id: "sp_second", runtimes: [{ id: "r1", provider: "claude" }] },+ },+ "/api/workspaces": {+ status: 200,+ body: [+ { id: "sp_existing", name: "Existing" },+ { id: "sp_second", name: "Second WS" },+ ],+ },+ "/api/agents": { status: 200, body: [{ id: "ag_new" }] },+ });++ const cmd = registerCommand();+ await cmd.parseAsync(["node", "register", "--token", "al_newtoken", "--server", "http://localhost:3000"]);++ expect(mockSaveCLIConfigForProfile).toHaveBeenCalledWith(+ undefined,+ expect.objectContaining({+ watched_workspaces: [+ { id: "sp_existing", name: "Existing", token: "al_old", agent_ids: ["ag_1"] },+ { id: "sp_second", name: "Second WS", token: "al_newtoken", agent_ids: ["ag_new"] },+ ],+ }),+ );+ });++ it("updates workspace in-place when same workspace_id already exists", async () => {+ mockLoadCLIConfigForProfile.mockReturnValue({+ server_url: "http://localhost:3000",+ watched_workspaces: [+ { id: "sp_same", name: "Old Name", token: "al_old", agent_ids: [] },+ ],+ });+ mockReadDaemonPid.mockReturnValue(null);++ mockFetch({+ "/api/me": { status: 200, body: { id: "u1", email: "[email protected]" } },+ "/api/machine-tokens/activate": {+ status: 200,+ body: { daemon_id: "host1", workspace_id: "sp_same", runtimes: [{ id: "r1", provider: "claude" }] },+ },+ "/api/workspaces": { status: 200, body: [{ id: "sp_same", name: "Updated Name" }] },+ "/api/agents": { status: 200, body: [{ id: "ag_x" }] },+ });++ const cmd = registerCommand();+ await cmd.parseAsync(["node", "register", "--token", "al_renewed", "--server", "http://localhost:3000"]);++ expect(mockSaveCLIConfigForProfile).toHaveBeenCalledWith(+ undefined,+ expect.objectContaining({+ watched_workspaces: [+ { id: "sp_same", name: "Updated Name", token: "al_renewed", agent_ids: ["ag_x"] },+ ],+ }),+ );+ });++ it("sends SIGHUP when daemon is running", async () => {+ mockLoadCLIConfigForProfile.mockReturnValue({+ server_url: "http://localhost:3000",+ watched_workspaces: [],+ });+ mockReadDaemonPid.mockReturnValue(12345);+ mockIsProcessAlive.mockReturnValue(true);++ mockFetch({+ "/api/me": { status: 200, body: { id: "u1", email: "[email protected]" } },+ "/api/machine-tokens/activate": {+ status: 200,+ body: { daemon_id: "host1", workspace_id: "sp_1", runtimes: [{ id: "r1", provider: "claude" }] },+ },+ "/api/workspaces": { status: 200, body: [{ id: "sp_1", name: "WS" }] },+ "/api/agents": { status: 200, body: [] },+ });++ const cmd = registerCommand();+ await cmd.parseAsync(["node", "register", "--token", "al_test", "--server", "http://localhost:3000"]);++ expect(mockKill).toHaveBeenCalledWith(12345, "SIGHUP");+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Daemon (pid 12345) notified"));+ });++ it("does not send SIGHUP when daemon is not running", async () => {+ mockLoadCLIConfigForProfile.mockReturnValue({+ server_url: "http://localhost:3000",+ watched_workspaces: [],+ });+ mockReadDaemonPid.mockReturnValue(null);++ mockFetch({+ "/api/me": { status: 200, body: { id: "u1", email: "[email protected]" } },+ "/api/machine-tokens/activate": {+ status: 200,+ body: { daemon_id: "host1", workspace_id: "sp_1", runtimes: [{ id: "r1", provider: "claude" }] },+ },+ "/api/workspaces": { status: 200, body: [{ id: "sp_1", name: "WS" }] },+ "/api/agents": { status: 200, body: [] },+ });++ const cmd = registerCommand();+ await cmd.parseAsync(["node", "register", "--token", "al_test", "--server", "http://localhost:3000"]);++ expect(mockKill).not.toHaveBeenCalled();+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("daemon start"));+ });+});diff --git a/src/cli/lib/config.test.ts b/src/cli/lib/config.test.tsindex c81113a8b..8374cebab 100644--- a/src/cli/lib/config.test.ts+++ b/src/cli/lib/config.test.ts@@ -188,4 +188,64 @@ describe("saveCLIConfigForProfile", () => {expect(written.server_url).toBe("http://root.example.com");expect(written.watched_workspaces).toEqual([{ id: "w1", name: "WS", token: "ws-token" }]);});++ it("preserves multiple watched_workspaces when saving", () => {+ mockedReadFileSync.mockReturnValue(JSON.stringify({}));++ const profileCfg = {+ server_url: "http://example.com",+ watched_workspaces: [+ { id: "w1", name: "First", token: "t1" },+ { id: "w2", name: "Second", token: "t2" },+ { id: "w3", name: "Third", token: "t3" },+ ],+ };+ saveCLIConfigForProfile(undefined, profileCfg);++ const written = JSON.parse(+ mockedWriteFileSync.mock.calls[0][1] as string,+ );+ expect(written.watched_workspaces).toHaveLength(3);+ expect(written.watched_workspaces[0].id).toBe("w1");+ expect(written.watched_workspaces[1].id).toBe("w2");+ expect(written.watched_workspaces[2].id).toBe("w3");+ });+});++describe("loadCLIConfigForProfile — multiple workspaces", () => {+ it("returns all watched_workspaces from root config", () => {+ const cfg = {+ server_url: "http://example.com",+ watched_workspaces: [+ { id: "w1", name: "WS1", token: "t1" },+ { id: "w2", name: "WS2", token: "t2" },+ ],+ };+ mockedReadFileSync.mockReturnValue(JSON.stringify(cfg));++ const result = loadCLIConfigForProfile();+ expect(result.watched_workspaces).toHaveLength(2);+ expect(result.watched_workspaces[0].id).toBe("w1");+ expect(result.watched_workspaces[1].id).toBe("w2");+ });++ it("returns all watched_workspaces from profile config", () => {+ const cfg = {+ profiles: {+ prod: {+ server_url: "https://prod.example.com",+ watched_workspaces: [+ { id: "wp1", name: "Prod WS 1", token: "tp1" },+ { id: "wp2", name: "Prod WS 2", token: "tp2" },+ { id: "wp3", name: "Prod WS 3", token: "tp3" },+ ],+ },+ },+ };+ mockedReadFileSync.mockReturnValue(JSON.stringify(cfg));++ const result = loadCLIConfigForProfile("prod");+ expect(result.watched_workspaces).toHaveLength(3);+ expect(result.watched_workspaces.map((w: any) => w.id)).toEqual(["wp1", "wp2", "wp3"]);+ });});diff --git a/src/web/src/app/(app)/studio/new/client.tsx b/src/web/src/app/(app)/studio/new/client.tsxindex 36d4611f8..6af841f4d 100644--- a/src/web/src/app/(app)/studio/new/client.tsx+++ b/src/web/src/app/(app)/studio/new/client.tsx@@ -20,7 +20,7 @@ import {import type { AgentRuntime as Runtime } from "@alook/shared";import type { WsMessage } from "@alook/shared";-import { listRuntimes, createMachineToken } from "@/lib/api";+import { listRuntimes, createMachineToken, createWorkspace } from "@/lib/api";import { useUserWs } from "@/lib/use-user-ws";import type { TemplatePreset } from "@/lib/templates";@@ -208,14 +208,20 @@ export function StudioOnboardingClient({const handleGenerateToken = useCallback(async () => {setGeneratingToken(true);try {- const res = await createMachineToken("cli", workspaceId || undefined);+ let wsId = workspaceIdRef.current;+ if (!wsId && isNewWorkspace) {+ const ws = await createWorkspace("Personal");+ wsId = ws.id;+ setWorkspaceId(wsId);+ }+ const res = await createMachineToken("cli", wsId || undefined);setGeneratedToken(res.token);} catch {toast.error("Failed to generate token");} finally {setGeneratingToken(false);}- }, [workspaceId]);+ }, [isNewWorkspace]);const handleAssignRuntime = (memberIndex: number, runtimeId: string) => {setMembers((prev) =>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.tsindex 2f8477f09..9a4e2a312 100644--- a/src/web/src/app/api/machine-tokens/activate/route.test.ts+++ b/src/web/src/app/api/machine-tokens/activate/route.test.ts@@ -6,6 +6,9 @@ const mockActivateMachineToken = vi.fn();const mockUpsertMachine = vi.fn();const mockUpsertAgentRuntime = vi.fn();const mockBroadcastToUser = vi.fn();+const mockListWorkspaces = vi.fn();+const mockCreateWorkspace = vi.fn();+const mockCreateMember = vi.fn();function sharedMocks() {return {@@ -25,9 +28,17 @@ function sharedMocks() {runtime: {upsertAgentRuntime: (...a: any[]) => mockUpsertAgentRuntime(...a),},+ workspace: {+ listWorkspaces: (...a: any[]) => mockListWorkspaces(...a),+ createWorkspace: (...a: any[]) => mockCreateWorkspace(...a),+ },+ member: {+ createMember: (...a: any[]) => mockCreateMember(...a),+ },},ActivateTokenRequestSchema: (await import("@alook/shared")).ActivateTokenRequestSchema,+ generateWorkspaceSlug: () => "studio-test1234",createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),}),"@/lib/broadcast": {@@ -154,4 +165,34 @@ describe("POST /api/machine-tokens/activate", () => {metadata: { version: "2.1.0" },});});++ it("creates a new workspace when token has no workspace_id and user already has workspaces", async () => {+ const POST = await loadRoute();++ const tokenNoWs = { id: "mt_2", userId: "u1", workspaceId: null, status: "pending" };+ mockGetMachineTokenByToken.mockResolvedValue(tokenNoWs);+ mockCreateWorkspace.mockResolvedValue({ id: "sp_new_ws" });+ mockCreateMember.mockResolvedValue(undefined);+ mockUpsertMachine.mockResolvedValue(undefined);+ mockUpsertAgentRuntime.mockResolvedValue({ id: "r1", 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_new_ws");+ expect(mockCreateWorkspace).toHaveBeenCalledWith(expect.anything(), {+ name: "Personal",+ slug: "studio-test1234",+ });+ expect(mockCreateMember).toHaveBeenCalledWith(expect.anything(), {+ workspaceId: "sp_new_ws",+ userId: "u1",+ role: "owner",+ });+ // Should NOT reuse existing workspaces+ expect(mockListWorkspaces).not.toHaveBeenCalled();+ });});diff --git a/src/web/src/app/api/machine-tokens/activate/route.ts b/src/web/src/app/api/machine-tokens/activate/route.tsindex cb79c977c..33c3c86ab 100644--- a/src/web/src/app/api/machine-tokens/activate/route.ts+++ b/src/web/src/app/api/machine-tokens/activate/route.ts@@ -35,24 +35,21 @@ export async function POST(req: NextRequest) {return writeJSON({ error: "token already used" }, 409);}- // Resolve workspace: use token's workspace, find existing, or create new+ // Resolve workspace: use token's workspace or create new+ // Never reuse an existing workspace — if the token has no workspace_id,+ // the user explicitly triggered "New workspace" or is a first-time user.let workspaceId = mt.workspaceId;if (!workspaceId) {- const existing = await queries.workspace.listWorkspaces(db, mt.userId);- if (existing.length > 0) {- workspaceId = existing[0].id;- } else {- const ws = await queries.workspace.createWorkspace(db, {- name: "Personal",- slug: generateWorkspaceSlug(),- });- await queries.member.createMember(db, {- workspaceId: ws.id,- userId: mt.userId,- role: "owner",- });- workspaceId = ws.id;- }+ const ws = await queries.workspace.createWorkspace(db, {+ name: "Personal",+ slug: generateWorkspaceSlug(),+ });+ await queries.member.createMember(db, {+ workspaceId: ws.id,+ userId: mt.userId,+ role: "owner",+ });+ workspaceId = ws.id;}// Use hostname as daemonId — must match what the daemon uses (os.hostname())@@ -87,21 +84,19 @@ export async function POST(req: NextRequest) {invalidate(cacheKeys.allRuntimes(workspaceId)),]);- // Notify the web UI- try {- await broadcastToUser(mt.userId, {- type: "runtime.registered",- daemonId,- hostname,- workspaceId,- });- } catch (err) {+ // Notify the web UI (fire-and-forget to avoid blocking the response)+ broadcastToUser(mt.userId, {+ type: "runtime.registered",+ daemonId,+ hostname,+ workspaceId,+ }).catch((err) => {log.warn("broadcast after activation failed", {userId: mt.userId,daemonId,err: err instanceof Error ? err.message : String(err),});- }+ });return writeJSON({daemon_id: daemonId,diff --git a/src/web/src/components/connect-machine-steps.tsx b/src/web/src/components/connect-machine-steps.tsxindex 146b5c38f..74805ea75 100644--- a/src/web/src/components/connect-machine-steps.tsx+++ b/src/web/src/components/connect-machine-steps.tsx@@ -108,8 +108,9 @@ export function ConnectMachineSteps({className={`space-y-2 transition-opacity duration-300 ${!registered ? "opacity-40 pointer-events-none" : ""}`}><p className="text-sm font-medium flex items-center gap-2">- <StepIndicator step={2} completed={false} />+ <StepIndicator step={2} completed={registered} />Start the daemon+ {registered && <span className="text-xs text-emerald-500 font-normal">Done</span>}</p><p className="text-xs text-muted-foreground pl-7">The daemon connects your local agents to Alook.diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.tsindex ff594509c..f18661fe9 100644--- a/src/web/src/lib/api.ts+++ b/src/web/src/lib/api.ts@@ -127,10 +127,10 @@ export const getMe = () => apiFetch<User>("/api/me");// Workspacesexport const listWorkspaces = () => apiFetch<Workspace[]>("/api/workspaces");-export const createWorkspace = (name: string) =>+export const createWorkspace = (name: string, slug?: string) =>apiFetch<Workspace>("/api/workspaces", {method: "POST",- body: JSON.stringify({ name }),+ body: JSON.stringify({ name, slug: slug || name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "workspace" }),});// Helper to build query strings with workspace_iddiff --git a/src/web/src/test/e2e/daemon-lifecycle.test.ts b/src/web/src/test/e2e/daemon-lifecycle.test.tsindex b8ef76278..bbbfb789e 100644--- a/src/web/src/test/e2e/daemon-lifecycle.test.ts+++ b/src/web/src/test/e2e/daemon-lifecycle.test.ts@@ -15,7 +15,7 @@ describe("daemon lifecycle", () => {const daemonId = `daemon_e2e_${randomUUID().slice(0, 8)}`let registeredRuntimeId: string- it("POST /api/daemon/register creates runtimes", async () => {+ it("POST /api/daemon/register creates runtimes and returns workspace_id", async () => {const res = await tokenRequest("/api/daemon/register", seed.machineToken, {method: "POST",headers: { "Content-Type": "application/json" },@@ -34,12 +34,21 @@ describe("daemon lifecycle", () => {}),})expect(res.status).toBe(200)- const data = await res.json() as { runtimes: Array<{ id: string }> }+ const data = await res.json() as { runtimes: Array<{ id: string }>; workspaceId: string }expect(data.runtimes).toHaveLength(1)expect(data.runtimes[0].id).toBeTruthy()+ expect(data.workspaceId).toBe(seed.workspaceId)registeredRuntimeId = data.runtimes[0].id})+ it("POST /api/daemon/register sets machine last_seen_at (online)", async () => {+ const rows = sqlQuery<{ last_seen_at: string | null }>(+ `SELECT last_seen_at FROM machine WHERE daemon_id = '${daemonId}' AND workspace_id = '${seed.workspaceId}'`+ )+ expect(rows).toHaveLength(1)+ expect(rows[0]?.last_seen_at).toBeTruthy()+ })+it("POST /api/daemon/register is idempotent (upserts)", async () => {const res = await tokenRequest("/api/daemon/register", seed.machineToken, {method: "POST",diff --git a/src/web/src/test/e2e/machine-token.test.ts b/src/web/src/test/e2e/machine-token.test.tsindex 0b01b3ddf..3a6dab696 100644--- a/src/web/src/test/e2e/machine-token.test.ts+++ b/src/web/src/test/e2e/machine-token.test.ts@@ -1,6 +1,9 @@import { describe, it, expect, beforeAll, afterAll } from "vitest"+import { randomUUID } from "crypto"import { seedTestData, cleanupTestData, type TestSeed } from "../helpers/seed"import { sessionRequest, tokenRequest } from "../helpers/auth"+import { sql, sqlQuery, sqlBatch } from "../helpers/db"+import { fetchWithRetry } from "../helpers/fetch"let seed: TestSeed@@ -81,3 +84,98 @@ describe("machine tokens", () => {expect(verifyRes.status).toBe(401)})})++describe("machine token activation", () => {+ const createdWorkspaceIds: string[] = []++ afterAll(() => {+ for (const wsId of createdWorkspaceIds) {+ try {+ sqlBatch([+ `DELETE FROM agent_runtime WHERE workspace_id = '${wsId}'`,+ `DELETE FROM machine WHERE workspace_id = '${wsId}'`,+ `DELETE FROM machine_token WHERE workspace_id = '${wsId}'`,+ `DELETE FROM member WHERE workspace_id = '${wsId}'`,+ `DELETE FROM workspace WHERE id = '${wsId}'`,+ ])+ } catch { /* ignore */ }+ }+ })++ it("activation without workspace_id creates a new workspace (never reuses)", async () => {+ // Create a pending token WITHOUT workspace_id+ const tokenId = `mt_${randomUUID().replace(/-/g, "").slice(0, 21)}`+ const rawToken = `al_${randomUUID().replace(/-/g, "")}`+ const now = new Date().toISOString()+ sql(`INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, created_at) VALUES ('${tokenId}', '${seed.userId}', NULL, '${rawToken}', 'no-ws-token', 'pending', '${now}')`)++ // Activate+ const APP_URL = process.env.APP_URL ?? "http://localhost:3000"+ const res = await fetchWithRetry(`${APP_URL}/api/machine-tokens/activate`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ token: rawToken,+ hostname: "e2e-no-ws-machine",+ runtimes: [{ type: "claude", version: "4.0" }],+ }),+ })+ expect(res.status).toBe(200)+ const data = await res.json() as { workspace_id: string; daemon_id: string; runtimes: unknown[] }++ // workspace_id should be NEW (not the seed workspace)+ expect(data.workspace_id).toBeTruthy()+ expect(data.workspace_id).not.toBe(seed.workspaceId)+ createdWorkspaceIds.push(data.workspace_id)++ // Verify workspace exists in DB and user is owner+ const wsRows = sqlQuery<{ id: string; name: string }>(+ `SELECT id, name FROM workspace WHERE id = '${data.workspace_id}'`+ )+ expect(wsRows).toHaveLength(1)+ expect(wsRows[0]!.name).toBe("Personal")++ const memberRows = sqlQuery<{ user_id: string; role: string }>(+ `SELECT user_id, role FROM member WHERE workspace_id = '${data.workspace_id}' AND user_id = '${seed.userId}'`+ )+ expect(memberRows).toHaveLength(1)+ expect(memberRows[0]!.role).toBe("owner")+ })++ it("activation with workspace_id uses that workspace (does not create new)", async () => {+ // Create a pending token WITH workspace_id+ const tokenId = `mt_${randomUUID().replace(/-/g, "").slice(0, 21)}`+ const rawToken = `al_${randomUUID().replace(/-/g, "")}`+ const now = new Date().toISOString()+ sql(`INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, created_at) VALUES ('${tokenId}', '${seed.userId}', '${seed.workspaceId}', '${rawToken}', 'with-ws-token', 'pending', '${now}')`)++ // Count workspaces before+ const beforeRows = sqlQuery<{ cnt: number }>(+ `SELECT COUNT(*) as cnt FROM workspace WHERE id IN (SELECT workspace_id FROM member WHERE user_id = '${seed.userId}')`+ )+ const countBefore = beforeRows[0]!.cnt++ // Activate+ const APP_URL = process.env.APP_URL ?? "http://localhost:3000"+ const res = await fetchWithRetry(`${APP_URL}/api/machine-tokens/activate`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ token: rawToken,+ hostname: "e2e-with-ws-machine",+ runtimes: [{ type: "claude", version: "4.0" }],+ }),+ })+ expect(res.status).toBe(200)+ const data = await res.json() as { workspace_id: string }++ // Should use the specified workspace+ expect(data.workspace_id).toBe(seed.workspaceId)++ // No new workspace should be created+ const afterRows = sqlQuery<{ cnt: number }>(+ `SELECT COUNT(*) as cnt FROM workspace WHERE id IN (SELECT workspace_id FROM member WHERE user_id = '${seed.userId}')`+ )+ expect(afterRows[0]!.cnt).toBe(countBefore)+ })+})diff --git a/src/web/src/test/e2e/workspace.test.ts b/src/web/src/test/e2e/workspace.test.tsindex fd66a113b..7efdf8824 100644--- a/src/web/src/test/e2e/workspace.test.ts+++ b/src/web/src/test/e2e/workspace.test.ts@@ -1,7 +1,7 @@import { describe, it, expect, beforeAll, afterAll } from "vitest"import { randomUUID } from "crypto"import { signUp, signIn, sessionRequest } from "../helpers/auth"-import { sql } from "../helpers/db"+import { sql, sqlQuery, sqlBatch } from "../helpers/db"const testEmail = `e2e_ws_${randomUUID().slice(0, 8)}@test.local`const testPassword = "TestPassword123!"@@ -78,3 +78,94 @@ describe("workspace", () => {expect(res.status).toBe(400)})})++describe("workspace isolation", () => {+ const slugA = `e2e-iso-a-${randomUUID().slice(0, 8)}`+ const slugB = `e2e-iso-b-${randomUUID().slice(0, 8)}`+ let workspaceIdA: string+ let workspaceIdB: string+ const daemonId = `daemon_iso_${randomUUID().slice(0, 8)}`++ it("creates two separate workspaces", async () => {+ // Create workspace A+ const resA = await sessionRequest("/api/workspaces", cookie, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name: "Workspace A", slug: slugA }),+ })+ expect(resA.status).toBe(201)+ const dataA = await resA.json() as Record<string, unknown>+ workspaceIdA = dataA.id as string++ // Create workspace B+ const resB = await sessionRequest("/api/workspaces", cookie, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name: "Workspace B", slug: slugB }),+ })+ expect(resB.status).toBe(201)+ const dataB = await resB.json() as Record<string, unknown>+ workspaceIdB = dataB.id as string++ expect(workspaceIdA).not.toBe(workspaceIdB)+ })++ it("registering daemon to workspace A does not affect workspace B", async () => {+ // Create machine token for workspace A+ const tokenId = `mt_iso_${randomUUID().replace(/-/g, "").slice(0, 16)}`+ const rawToken = `al_${randomUUID().replace(/-/g, "")}`+ const now = new Date().toISOString()+ sql(`INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, created_at) VALUES ('${tokenId}', (SELECT id FROM "user" WHERE email = '${testEmail}'), '${workspaceIdA}', '${rawToken}', 'iso-token', 'active', '${now}')`)++ // Register daemon to workspace A+ const APP_URL = process.env.APP_URL ?? "http://localhost:3000"+ const res = await fetch(`${APP_URL}/api/daemon/register`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${rawToken}`,+ },+ body: JSON.stringify({+ workspace_id: workspaceIdA,+ daemon_id: daemonId,+ device_name: "iso-machine",+ cli_version: "0.1.0",+ runtimes: [{ provider: "claude", runtime_mode: "local", version: "4.0" }],+ }),+ })+ expect(res.status).toBe(200)+ const data = await res.json() as { runtimes: Array<{ id: string }>; workspaceId: string }+ expect(data.workspaceId).toBe(workspaceIdA)+ expect(data.runtimes).toHaveLength(1)++ // Workspace A should have the runtime+ const runtimesA = sqlQuery<{ id: string }>(+ `SELECT id FROM agent_runtime WHERE workspace_id = '${workspaceIdA}' AND daemon_id = '${daemonId}'`+ )+ expect(runtimesA.length).toBeGreaterThan(0)++ // Workspace B should have NO runtimes+ const runtimesB = sqlQuery<{ id: string }>(+ `SELECT id FROM agent_runtime WHERE workspace_id = '${workspaceIdB}' AND daemon_id = '${daemonId}'`+ )+ expect(runtimesB).toHaveLength(0)++ // Workspace B should have NO machine entry for this daemon+ const machinesB = sqlQuery<{ daemon_id: string }>(+ `SELECT daemon_id FROM machine WHERE workspace_id = '${workspaceIdB}' AND daemon_id = '${daemonId}'`+ )+ expect(machinesB).toHaveLength(0)+ })++ afterAll(() => {+ try {+ sqlBatch([+ `DELETE FROM agent_runtime WHERE daemon_id = '${daemonId}'`,+ `DELETE FROM machine WHERE daemon_id = '${daemonId}'`,+ `DELETE FROM machine_token WHERE workspace_id IN ('${workspaceIdA}', '${workspaceIdB}')`,+ `DELETE FROM member WHERE workspace_id IN ('${workspaceIdA}', '${workspaceIdB}')`,+ `DELETE FROM workspace WHERE id IN ('${workspaceIdA}', '${workspaceIdB}')`,+ ])+ } catch { /* ignore */ }+ })+})diff --git a/src/web/src/test/helpers/fetch.ts b/src/web/src/test/helpers/fetch.tsindex 9674df1ba..7c5e3acfe 100644--- a/src/web/src/test/helpers/fetch.ts+++ b/src/web/src/test/helpers/fetch.ts@@ -8,6 +8,7 @@ export function isRetryableError(err: unknown): boolean {const cause = (err as Error & { cause?: Error }).causeif (cause && (cause as NodeJS.ErrnoException).code === "ECONNRESET") return true+ if (cause && cause.message?.includes("other side closed")) return trueif (err instanceof TypeError && err.message.includes("fetch failed")) return true