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
refactor: simplify onboarding — 2-state token, one-step register (#316)
Gener918061be2619
diff --git a/src/cli/commands/login.test.ts b/src/cli/commands/login.test.tsindex 32a569082..96338201a 100644--- a/src/cli/commands/login.test.ts+++ b/src/cli/commands/login.test.ts@@ -131,7 +131,7 @@ describe("alook login", () => {const cmd = loginCommand();await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));- // syncWorkspacesToConfig is called first (stores session token + synced workspaces)+ // syncWorkspacesToConfig stores session token + synced workspacesexpect(mockSaveCLIConfigForProfile).toHaveBeenCalledWith(undefined,expect.objectContaining({@@ -142,12 +142,12 @@ describe("alook login", () => {]),}),);- // activateAndSave adds the machine token entry+ // activateAndSave updates the workspace entry with the tokenexpect(mockSaveCLIConfigForProfile).toHaveBeenCalledWith(undefined,expect.objectContaining({watched_workspaces: expect.arrayContaining([- expect.objectContaining({ token: "al_machine_tok", status: "registered" }),+ expect.objectContaining({ id: "sp_ws1", token: "al_machine_tok", status: "active" }),]),}),);@@ -396,7 +396,12 @@ describe("alook login", () => {{ id: "sp_ws2", name: "Personal" },] },{ url: "/api/machine-tokens", status: 201, body: { token: "al_mt" } },- { url: "/api/machine-tokens/activate", status: 200, body: { daemon_id: "h1", token_status: "registered" } },+ { url: "/api/machine-tokens/activate", status: 200, body: { daemon_id: "h1", workspace_id: "sp_ws1", runtimes: [{ id: "r1", provider: "claude" }] } },+ { url: "/api/workspaces", status: 200, body: [+ { id: "sp_ws1", name: "Work" },+ { id: "sp_ws2", name: "Personal" },+ ] },+ { url: "/api/agents", status: 200, body: [] },]);const cmd = loginCommand();diff --git a/src/cli/commands/login.ts b/src/cli/commands/login.tsindex 76f7f1616..77ed75275 100644--- a/src/cli/commands/login.ts+++ b/src/cli/commands/login.ts@@ -74,7 +74,7 @@ function syncWorkspacesToConfig(}for (const w of watched) {- if (w.id && !serverIds.has(w.id) && w.status !== "registered") {+ if (w.id && !serverIds.has(w.id)) {w.status = "deleted";}}@@ -163,15 +163,24 @@ async function pollAndActivate(opts: {}syncWorkspacesToConfig(serverWorkspaces, profile, sessionToken);- const existingWorkspaceId = serverWorkspaces.length > 0 ? serverWorkspaces[0].id : "";+ let workspaceId = serverWorkspaces.length > 0 ? serverWorkspaces[0].id : "";- const mtUrl = existingWorkspaceId- ? `/api/machine-tokens?workspace_id=${existingWorkspaceId}`- : "/api/machine-tokens";+ if (!workspaceId) {+ try {+ const newWs = await client.postJSON<{ id: string; name: string }>("/api/workspaces", {+ name: "Personal",+ slug: email.split("@")[0]?.toLowerCase().replace(/[^a-z0-9-]/g, "-").slice(0, 48) || "personal",+ });+ workspaceId = newWs.id;+ } catch (err) {+ console.error(`Error: failed to create workspace: ${err instanceof Error ? err.message : err}`);+ process.exit(1);+ }+ }let machineToken: string;try {- const mtResp = await client.postJSON<{ token: string }>(mtUrl);+ const mtResp = await client.postJSON<{ token: string }>(`/api/machine-tokens?workspace_id=${workspaceId}`);machineToken = mtResp.token;} catch {process.exit(1);@@ -182,8 +191,8 @@ async function pollAndActivate(opts: {if (email) {console.log(`\nLogged in as ${email}`);}- console.log(`Machine: ${result.daemonId} (status: ${result.tokenStatus})`);- console.log(`Workspace binding will happen when you launch a company.`);+ console.log(`Workspace: ${result.workspaceName} (${result.workspaceId})`);+ console.log(`Runtimes: ${result.runtimeProviders.join(", ")}`);}// Background polling entry point — invoked as a detached child process in non-TTY modediff --git a/src/cli/commands/register.test.ts b/src/cli/commands/register.test.tsindex 7de5aa9cc..7c3a7cc73 100644--- a/src/cli/commands/register.test.ts+++ b/src/cli/commands/register.test.ts@@ -31,6 +31,7 @@ vi.mock("child_process", () => ({if (cmd.includes("claude --version")) return "4.0.0";throw new Error("not found");}),+ spawn: vi.fn(() => ({ unref: vi.fn() })),}));import { registerCommand } from "./register";@@ -74,7 +75,13 @@ describe("alook register", () => {}));}- it("stores token as registered entry in watched_workspaces", async () => {+ const activateResponse = {+ daemon_id: "host1",+ workspace_id: "ws_1",+ runtimes: [{ id: "rt_1", provider: "claude" }],+ };++ it("activates token and saves workspace to config", async () => {mockLoadCLIConfigForProfile.mockReturnValue({server_url: "http://localhost:3000",watched_workspaces: [],@@ -83,10 +90,9 @@ describe("alook register", () => {mockFetch({"/api/me": { status: 200, body: { id: "u1", email: "[email protected]" } },- "/api/machine-tokens/activate": {- status: 200,- body: { daemon_id: "host1", token_status: "registered" },- },+ "/api/machine-tokens/activate": { status: 200, body: activateResponse },+ "/api/workspaces": { status: 200, body: [{ id: "ws_1", name: "Personal" }] },+ "/api/agents": { status: 200, body: [] },});const cmd = registerCommand();@@ -97,27 +103,26 @@ describe("alook register", () => {expect.objectContaining({server_url: "http://localhost:3000",watched_workspaces: [- { id: null, name: null, token: "al_testtoken123", status: "registered", agent_ids: [] },+ { id: "ws_1", name: "Personal", token: "al_testtoken123", status: "active", agent_ids: [] },],}),);});- it("preserves existing watched_workspaces and appends registered entry", async () => {+ it("preserves existing watched_workspaces and updates matching entry", async () => {mockLoadCLIConfigForProfile.mockReturnValue({server_url: "http://localhost:3000",watched_workspaces: [- { id: "sp_existing", name: "Existing", token: "al_old", status: "active", agent_ids: ["ag_1"] },+ { id: "ws_1", name: "Existing", token: "al_old", status: "active", 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", token_status: "registered" },- },+ "/api/machine-tokens/activate": { status: 200, body: activateResponse },+ "/api/workspaces": { status: 200, body: [{ id: "ws_1", name: "Personal" }] },+ "/api/agents": { status: 200, body: [{ id: "ag_1" }] },});const cmd = registerCommand();@@ -127,8 +132,7 @@ describe("alook register", () => {undefined,expect.objectContaining({watched_workspaces: [- { id: "sp_existing", name: "Existing", token: "al_old", status: "active", agent_ids: ["ag_1"] },- { id: null, name: null, token: "al_newtoken", status: "registered", agent_ids: [] },+ { id: "ws_1", name: "Personal", token: "al_newtoken", status: "active", agent_ids: ["ag_1"] },],}),);@@ -144,10 +148,9 @@ describe("alook register", () => {mockFetch({"/api/me": { status: 200, body: { id: "u1", email: "[email protected]" } },- "/api/machine-tokens/activate": {- status: 200,- body: { daemon_id: "host1", token_status: "registered" },- },+ "/api/machine-tokens/activate": { status: 200, body: activateResponse },+ "/api/workspaces": { status: 200, body: [{ id: "ws_1", name: "Personal" }] },+ "/api/agents": { status: 200, body: [] },});const cmd = registerCommand();@@ -157,7 +160,7 @@ describe("alook register", () => {expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Daemon (pid 12345) notified"));});- it("does not send SIGHUP when daemon is not running", async () => {+ it("auto-starts daemon when not running", async () => {mockLoadCLIConfigForProfile.mockReturnValue({server_url: "http://localhost:3000",watched_workspaces: [],@@ -166,16 +169,15 @@ describe("alook register", () => {mockFetch({"/api/me": { status: 200, body: { id: "u1", email: "[email protected]" } },- "/api/machine-tokens/activate": {- status: 200,- body: { daemon_id: "host1", token_status: "registered" },- },+ "/api/machine-tokens/activate": { status: 200, body: activateResponse },+ "/api/workspaces": { status: 200, body: [{ id: "ws_1", name: "Personal" }] },+ "/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"));+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Starting daemon"));});});diff --git a/src/cli/commands/register.ts b/src/cli/commands/register.tsindex 260723433..1aa43abe8 100644--- a/src/cli/commands/register.ts+++ b/src/cli/commands/register.ts@@ -53,8 +53,8 @@ export function registerCommand(): Command {const result = await activateAndSave({ token, serverUrl, profile });console.log(`\nRegistered as ${me.email}`);- console.log(`Machine: ${result.daemonId} (status: ${result.tokenStatus})`);- console.log(`Workspace binding will happen when you launch a company.`);+ console.log(`Workspace: ${result.workspaceName} (${result.workspaceId})`);+ console.log(`Runtimes: ${result.runtimeProviders.join(", ")}`);});return cmd;diff --git a/src/cli/commands/workspace.test.ts b/src/cli/commands/workspace.test.tsindex d959ace3f..53412ff17 100644--- a/src/cli/commands/workspace.test.ts+++ b/src/cli/commands/workspace.test.ts@@ -343,7 +343,7 @@ describe("workspace init — self-resolve (no workspaceId)", () => {});mockedLoadConfig.mockReturnValue({server_url: "http://localhost:3000",- watched_workspaces: [{ id: null, name: null, token: "test-token", status: "registered" }],+ watched_workspaces: [{ id: "sp_ws1", name: "Existing", token: "test-token", status: "active" }],});});@@ -375,10 +375,9 @@ describe("workspace init — self-resolve (no workspaceId)", () => {getJSONMock.mockResolvedValueOnce([{ id: "sp_ws1", name: "Existing WS" }]) // GET /api/workspaces.mockResolvedValueOnce([]) // GET /api/agents?workspace_id=sp_ws1 (empty!)- .mockResolvedValueOnce([{ id: "rt1", machineLastSeenAt: new Date().toISOString() }]); // GET /api/runtimes (after bind-workspace polling)+ .mockResolvedValueOnce([{ id: "rt1", machineLastSeenAt: new Date().toISOString() }]); // GET /api/runtimespostJSONMock- .mockResolvedValueOnce({}) // POST /api/machine-tokens/bind-workspace.mockResolvedValueOnce({ // POST /api/studiosstudio: { name: "My WS" },workspace: { id: "sp_ws1", name: "My WS", slug: "my-ws" },@@ -388,7 +387,6 @@ describe("workspace init — self-resolve (no workspaceId)", () => {await runInit(["--json-file", jsonPath]);expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Workspace initialized"));- expect(postJSONMock).toHaveBeenCalledWith("/api/machine-tokens/bind-workspace", { workspace_id: "sp_ws1" });});it("creates new workspace when all existing ones have agents", async () => {@@ -404,7 +402,6 @@ describe("workspace init — self-resolve (no workspaceId)", () => {postJSONMock.mockResolvedValueOnce({ id: "sp_new", name: "Fresh WS" }) // POST /api/workspaces- .mockResolvedValueOnce({}) // POST /api/machine-tokens/bind-workspace.mockResolvedValueOnce({ // POST /api/studiosstudio: { name: "Fresh WS" },workspace: { id: "sp_new", name: "Fresh WS", slug: "fresh-ws" },@@ -428,7 +425,6 @@ describe("workspace init — self-resolve (no workspaceId)", () => {postJSONMock.mockResolvedValueOnce({ id: "sp_personal", name: "Personal" }) // POST /api/workspaces- .mockResolvedValueOnce({}) // POST /api/machine-tokens/bind-workspace.mockResolvedValueOnce({ // POST /api/studiosstudio: { name: "Personal" },workspace: { id: "sp_personal", name: "Personal", slug: "personal" },diff --git a/src/cli/commands/workspace.ts b/src/cli/commands/workspace.tsindex 9c89a4463..5278a58e2 100644--- a/src/cli/commands/workspace.ts+++ b/src/cli/commands/workspace.ts@@ -105,24 +105,12 @@ export function workspaceCommand(): Command {}// Self-resolve workspace if not available from config/env+ const parentOpts = getRootOpts(command) as { profile?: string };let targetWorkspaceId = resolvedWorkspaceId;if (!targetWorkspaceId) {const resolved = await resolveWorkspaceId(client, opts.name || config.name);targetWorkspaceId = resolved.workspaceId;- // If machine token is in "registered" status, bind it to this workspace- const parentOpts = getRootOpts(command) as { profile?: string };- const cfg = loadCLIConfigForProfile(parentOpts.profile);- const registeredWs = cfg.watched_workspaces?.find((w) => w.status === "registered" && !w.id);- if (registeredWs) {- try {- await client.postJSON("/api/machine-tokens/bind-workspace", { workspace_id: targetWorkspaceId });- console.log("Machine token bound to workspace. Waiting for runtime registration...");- } catch (err) {- console.warn(`Warning: bind-workspace failed: ${err instanceof Error ? err.message : err}`);- }- }-// Poll for runtime to appearlet runtimes: RuntimeResponse[] = [];const wsClient = new APIClient(serverUrl, token, targetWorkspaceId);diff --git a/src/cli/daemon/client.test.ts b/src/cli/daemon/client.test.tsindex b69ca0d82..adaf79b3b 100644--- a/src/cli/daemon/client.test.ts+++ b/src/cli/daemon/client.test.ts@@ -480,87 +480,6 @@ describe("DaemonClient.sweep() with mocked fetch", () => {});// ----------------------------------------------------------------------------// DaemonClient.checkStandby() tests-// -----------------------------------------------------------------------------describe("DaemonClient.checkStandby() with mocked fetch", () => {- const originalFetch = globalThis.fetch;-- afterEach(() => {- globalThis.fetch = originalFetch;- });-- it("returns standby: true when no workspace bound", async () => {- globalThis.fetch = vi.fn().mockResolvedValue({- ok: true,- status: 200,- json: () => Promise.resolve({ runtimes: [], standby: true }),- }) as unknown as typeof fetch;-- const client = new DaemonClient("http://localhost:8080");- const resp = await client.checkStandby("tok", {- daemon_id: "d1",- device_name: "mac",- cli_version: "1.0",- workspaces_root: "/tmp",- runtimes: [{ type: "claude" }],- });-- expect(resp.standby).toBe(true);- expect(resp.runtimes).toEqual([]);- });-- it("returns workspace data when token has been bound", async () => {- globalThis.fetch = vi.fn().mockResolvedValue({- ok: true,- status: 200,- json: () => Promise.resolve({- runtimes: [{ id: "rt1" }],- workspaceId: "sp_ws1",- }),- }) as unknown as typeof fetch;-- const client = new DaemonClient("http://localhost:8080");- const resp = await client.checkStandby("tok", {- daemon_id: "d1",- device_name: "mac",- cli_version: "1.0",- workspaces_root: "/tmp",- runtimes: [{ type: "claude" }],- });-- expect(resp.standby).toBeUndefined();- expect(resp.runtimes).toHaveLength(1);- expect(resp.workspaceId).toBe("sp_ws1");- });-- it("calls /api/daemon/register endpoint", async () => {- globalThis.fetch = vi.fn().mockResolvedValue({- ok: true,- status: 200,- json: () => Promise.resolve({ runtimes: [], standby: true }),- }) as unknown as typeof fetch;-- const client = new DaemonClient("http://localhost:8080");- await client.checkStandby("my_token", {- daemon_id: "d1",- device_name: "mac",- cli_version: "1.0",- workspaces_root: "/tmp",- runtimes: [{ type: "claude" }],- });-- expect(globalThis.fetch).toHaveBeenCalledWith(- "http://localhost:8080/api/daemon/register",- expect.objectContaining({- method: "POST",- headers: expect.objectContaining({- Authorization: "Bearer my_token",- }),- }),- );- });-});// ---------------------------------------------------------------------------// DaemonClient removed methodsdiff --git a/src/cli/daemon/client.ts b/src/cli/daemon/client.tsindex bc36db4d8..c21062599 100644--- a/src/cli/daemon/client.ts+++ b/src/cli/daemon/client.ts@@ -216,16 +216,4 @@ export class DaemonClient {);}- async checkStandby(- token: string,- body: RegisterDaemonRequest,- ): Promise<RegisterResponse & { standby?: boolean; workspaceId?: string }> {- return this.request(- "POST",- "/api/daemon/register",- token,- body,- );- }-}diff --git a/src/cli/daemon/daemon.test.ts b/src/cli/daemon/daemon.test.tsindex d9338e8b6..1bcc5912e 100644--- a/src/cli/daemon/daemon.test.ts+++ b/src/cli/daemon/daemon.test.ts@@ -1118,7 +1118,7 @@ describe("daemon startup failures release pidfile", () => {for (const t of intervalTimers) realClearInterval(t);});- it("starts in standby mode when no workspaces are configured", async () => {+ it("exits when no workspaces are configured", async () => {vi.mocked(loadCLIConfigForProfile).mockReturnValue({server_url: "",watched_workspaces: [],@@ -1126,7 +1126,7 @@ describe("daemon startup failures release pidfile", () => {await startDaemon();- expect(mockProcessExit).not.toHaveBeenCalled();+ expect(mockProcessExit).toHaveBeenCalledWith(1);});it("registers an exit handler that releases the pidfile", async () => {@@ -2502,7 +2502,7 @@ describe("daemon SIGHUP reload", () => {for (const t of intervalTimers) realClearInterval(t);});- it("starts in standby mode when no workspaces configured (no exit)", async () => {+ it("exits when no workspaces are configured", async () => {vi.mocked(loadCLIConfigForProfile).mockReturnValue({server_url: "",watched_workspaces: [],@@ -2510,21 +2510,22 @@ describe("daemon SIGHUP reload", () => {await startDaemon();- expect(mockProcessExit).not.toHaveBeenCalled();+ expect(mockProcessExit).toHaveBeenCalledWith(1);});- it("after SIGHUP, WS client is created when workspaceStates goes from 0 to 1+", async () => {- // Start with no workspaces+ it("after SIGHUP, new workspace is registered", async () => {let configCallCount = 0;vi.mocked(loadCLIConfigForProfile).mockImplementation(() => {configCallCount++;if (configCallCount === 1) {- return { server_url: "", watched_workspaces: [] };+ return { server_url: "", watched_workspaces: [{ id: "ws1", name: "WS1", token: "al_tok1" }] };}- // After SIGHUP, config has a workspacereturn {server_url: "",- watched_workspaces: [{ id: "ws1", name: "New WS", token: "al_new_token" }],+ watched_workspaces: [+ { id: "ws1", name: "WS1", token: "al_tok1" },+ { id: "ws2", name: "WS2", token: "al_tok2" },+ ],};});@@ -2532,62 +2533,15 @@ describe("daemon SIGHUP reload", () => {mockClientInstance.poll.mockResolvedValue({ tasks: [], evicted: false });await startDaemon();-- // Daemon started in standby — no WS client initially- expect(capturedWsOnMessage).toBeNull();expect(mockProcessExit).not.toHaveBeenCalled();- // Trigger SIGHUPconst sighupHandler = signalHandlers.get("SIGHUP");expect(sighupHandler).toBeDefined();await sighupHandler!();- // After SIGHUP, the workspace should have been registeredexpect(mockClientInstance.register).toHaveBeenCalledWith(- "al_new_token",- expect.objectContaining({ workspace_id: "ws1" }),+ "al_tok2",+ expect.objectContaining({ workspace_id: "ws2" }),);-- // WS client should now be initialized (capturedWsOnMessage set by MockDaemonWsClient constructor)- expect(capturedWsOnMessage).not.toBeNull();- });-- it("hadWorkspaces flag prevents shutdown when all evicted if daemon started empty", async () => {- // Start with no workspaces — hadWorkspaces is initially false- let configCallCount = 0;- vi.mocked(loadCLIConfigForProfile).mockImplementation(() => {- configCallCount++;- if (configCallCount === 1) {- return { server_url: "", watched_workspaces: [] };- }- return {- server_url: "",- watched_workspaces: [{ id: "ws1", name: "New WS", token: "al_new_token" }],- };- });-- mockClientInstance.register.mockResolvedValue({ runtimes: [{ id: "rt1" }] });-- // First poll returns nothing, subsequent polls will evict ws1- let pollCall = 0;- mockClientInstance.poll.mockImplementation((async () => {- pollCall++;- if (pollCall <= 1) return { tasks: [], evicted: false };- return { tasks: [], evicted: true };- }) as any);-- await startDaemon();- expect(mockProcessExit).not.toHaveBeenCalled();-- // Trigger SIGHUP to add a workspace — this sets hadWorkspaces = true- const sighupHandler = signalHandlers.get("SIGHUP");- await sighupHandler!();-- expect(mockClientInstance.register).toHaveBeenCalled();-- // After SIGHUP added workspace, hadWorkspaces is true.- // If all workspaces get evicted now, daemon should shut down- // (because hadWorkspaces is true — it started empty but got workspaces via SIGHUP)- // This verifies the hadWorkspaces = true assignment in the SIGHUP handler});});diff --git a/src/cli/daemon/daemon.ts b/src/cli/daemon/daemon.tsindex 5c64645c6..85b1bfab0 100644--- a/src/cli/daemon/daemon.ts+++ b/src/cli/daemon/daemon.ts@@ -252,14 +252,12 @@ export async function startDaemon(const cliConfig = loadCLIConfigForProfile(profile);const allEntries = cliConfig.watched_workspaces || [];- const workspaces = allEntries.filter((ws): ws is typeof ws & { id: string; name: string } => ws.status !== "registered" && !!ws.id);- const registeredEntries = allEntries.filter((ws) => ws.status === "registered" && !ws.id);- const standbyToken = registeredEntries[0]?.token ?? null;-- if (workspaces.length === 0 && standbyToken) {- log.info("No workspaces configured — daemon starting in standby mode with machine token. Awaiting workspace binding.");- } else if (workspaces.length === 0) {- log.info("No workspaces configured — daemon starting in standby mode. Register a workspace to begin.");+ const workspaces = allEntries.filter((ws): ws is typeof ws & { id: string; name: string } => ws.status !== "deleted" && !!ws.id);++ if (workspaces.length === 0) {+ log.error("No workspaces configured. Register a workspace first.");+ process.exit(1);+ return;}// Validate: each active workspace must have its own token@@ -302,7 +300,7 @@ export async function startDaemon(const workspaceStates: WorkspaceState[] = [];const runtimeIndex = new Map<string, RuntimeData>();- let hadWorkspaces = workspaces.length > 0;+ const hadWorkspaces = true;for (const ws of workspaces) {const runtimes = providers.map((p) => ({@@ -407,59 +405,6 @@ export async function startDaemon(log.info(`Workspace ${workspaceId} deleted server-side — removed from config`);}- async function handleWorkspaceAdded(workspaceId: string, workspaceName: string, token: string): Promise<void> {- if (workspaceStates.some((ws) => ws.workspaceId === workspaceId)) {- log.info(`Workspace ${workspaceId} already registered — ignoring workspace_added`);- return;- }-- log.info(`Workspace ${workspaceId} bound — registering...`);- const runtimes = providers.map((p) => ({ type: p.type, version: p.version }));- try {- const resp = await client.register(token, {- workspace_id: workspaceId,- daemon_id: config.daemonId,- device_name: config.deviceName,- cli_version: config.cliVersion,- workspaces_root: config.workspacesRoot,- runtimes,- });- const runtimeIds = resp.runtimes.map((r: { id: string }) => r.id);- workspaceStates.push({ workspaceId, token, runtimeIds });- for (let i = 0; i < runtimeIds.length; i++) {- runtimeIndex.set(runtimeIds[i], {- id: runtimeIds[i],- workspaceId,- provider: providers[i].type,- });- }- hadWorkspaces = true;- health.setRuntimeCount(- workspaceStates.reduce((sum, w) => sum + w.runtimeIds.length, 0),- );-- try {- const cfg = loadCLIConfigForProfile(profile);- const watched = cfg.watched_workspaces || [];- // Find the registered entry with this token and promote it to active- const registeredIdx = watched.findIndex((w) => w.token === token && w.status === "registered" && !w.id);- if (registeredIdx !== -1) {- watched[registeredIdx] = { id: workspaceId, name: workspaceName, token, status: "active", agent_ids: [] };- } else if (!watched.some((w) => w.id === workspaceId)) {- watched.push({ id: workspaceId, name: workspaceName, token, status: "active" });- }- cfg.watched_workspaces = watched;- saveCLIConfigForProfile(profile, cfg);- } catch {- // Best-effort config write- }-- log.info(`Workspace ${workspaceId} added via WS push — ${runtimeIds.length} runtime(s)`);- } catch (e) {- log.error(`Failed to register workspace ${workspaceId} from WS push`, e);- }- }-// Staggered per-workspace pollingconst pollCycle = async () => {let remaining = config.maxConcurrentTasks - activeTasks.size;@@ -680,14 +625,10 @@ export async function startDaemon(break;}- case "daemon.workspace_added": {- handleWorkspaceAdded(msg.workspaceId, msg.workspaceName, msg.token);- break;- }}}- const wsToken = firstToken || standbyToken;+ const wsToken = firstToken;let wsClient = wsToken? new DaemonWsClient({@@ -696,56 +637,18 @@ export async function startDaemon(machineToken: wsToken,onMessage: handleWsPush,onConnected: () => {- if (workspaceStates.length > 0) {- log.info("WS connected — switching to low-frequency poll");- updatePollInterval(config.wsPollInterval);- } else {- log.info("WS connected in standby mode — awaiting workspace binding");- }+ log.info("WS connected — switching to low-frequency poll");+ updatePollInterval(config.wsPollInterval);},onDisconnected: () => {- if (workspaceStates.length > 0) {- log.info("WS disconnected — reverting to high-frequency poll");- updatePollInterval(config.pollInterval);- }+ log.info("WS disconnected — reverting to high-frequency poll");+ updatePollInterval(config.pollInterval);},}): null;wsClient?.connect();- // --- Standby poll fallback: if WS push is lost, periodically check for workspace bindings ---- const STANDBY_POLL_MS = 30_000;- let standbyPollTimer: ReturnType<typeof setInterval> | null = null;-- if (standbyToken && workspaceStates.length === 0) {- const standbyPollTick = async () => {- if (workspaceStates.length > 0) {- if (standbyPollTimer) { clearInterval(standbyPollTimer); standbyPollTimer = null; }- return;- }- try {- const runtimes = providers.map((p) => ({ type: p.type, version: p.version }));- const resp = await client.checkStandby(standbyToken, {- daemon_id: config.daemonId,- device_name: config.deviceName,- cli_version: config.cliVersion,- workspaces_root: config.workspacesRoot,- runtimes,- });- if (!resp.standby && resp.runtimes.length > 0 && resp.workspaceId) {- log.info(`Standby poll: workspace ${resp.workspaceId} discovered via fallback`);- await handleWorkspaceAdded(resp.workspaceId, "", standbyToken);- if (standbyPollTimer) { clearInterval(standbyPollTimer); standbyPollTimer = null; }- }- } catch (e) {- log.debug("standby poll failed", { err: e instanceof Error ? e.message : String(e) });- }- };- standbyPollTick();- standbyPollTimer = setInterval(standbyPollTick, STANDBY_POLL_MS);- }-// --- Sweep timer: triggers server-side sweep + local reconciliation ---const sweepTick = async () => {for (const ws of workspaceStates) {@@ -788,7 +691,6 @@ export async function startDaemon(clearInterval(pollTimer);clearInterval(heartbeatTimer);clearInterval(sweepTimer);- if (standbyPollTimer) clearInterval(standbyPollTimer);stopSkillScanner();wsClient?.close();@@ -841,7 +743,7 @@ export async function startDaemon(try {const freshConfig = loadCLIConfigForProfile(profile);const freshWorkspaces = (freshConfig.watched_workspaces || [])- .filter((ws): ws is typeof ws & { id: string } => ws.status !== "registered" && !!ws.id);+ .filter((ws): ws is typeof ws & { id: string } => ws.status !== "deleted" && !!ws.id);const existingIds = new Set(workspaceStates.map((ws) => ws.workspaceId));const newWorkspaces = freshWorkspaces.filter(@@ -876,7 +778,6 @@ export async function startDaemon(}if (newWorkspaces.length > 0) {- hadWorkspaces = true;health.setRuntimeCount(workspaceStates.reduce((sum, w) => sum + w.runtimeIds.length, 0),);diff --git a/src/cli/lib/activate.ts b/src/cli/lib/activate.tsindex d431603be..f1c7a0fb7 100644--- a/src/cli/lib/activate.ts+++ b/src/cli/lib/activate.ts@@ -1,17 +1,35 @@import { hostname } from "os";+import { spawn } from "child_process";+import { openSync, closeSync, mkdirSync } from "fs";+import { dirname } from "path";+import { APIClient } from "./client.js";import { loadCLIConfigForProfile, saveCLIConfigForProfile } from "./config.js";import { cmdPrefix, isDev } from "./env.js";import { readDaemonPid, isProcessAlive } from "../daemon/pidfile.js";+import { daemonLogFilePath } from "../daemon/config.js";+import { startDaemon } from "../daemon/daemon.js";+import { resolveLoginShellEnv } from "./shell-env.js";import { detectRuntimes } from "./runtimes.js";interface ActivateResponse {daemon_id: string;- token_status: string;+ workspace_id: string;+ runtimes: { id: string; provider: string }[];+}++interface Workspace {+ id: string;+ name: string;+}++interface AgentListItem {+ id: string;}export interface ActivateResult {- daemonId: string;- tokenStatus: string;+ workspaceId: string;+ workspaceName: string;+ runtimeProviders: string[];}export async function activateAndSave(opts: {@@ -53,11 +71,41 @@ export async function activateAndSave(opts: {process.exit(1);}- const existing = loadCLIConfigForProfile(profile);+ const client = new APIClient(serverUrl, token);++ let workspaces: Workspace[];+ try {+ workspaces = await client.getJSON<Workspace[]>("/api/workspaces");+ } catch (err) {+ console.error(+ `Error: failed to fetch workspaces: ${err instanceof Error ? err.message : err}`,+ );+ process.exit(1);+ }++ if (!workspaces.length) {+ console.error("Error: no workspaces found for this user");+ process.exit(1);+ }+ const ws = workspaces.find((w) => w.id === activateResp.workspace_id) || workspaces[0];++ const wsClient = new APIClient(serverUrl, token, ws.id);+ let agentIds: string[] = [];+ try {+ const agents = await wsClient.getJSON<AgentListItem[]>(`/api/agents?workspace_id=${ws.id}`);+ agentIds = agents.map((a) => a.id);+ } catch {+ // Non-fatal+ }++ const existing = loadCLIConfigForProfile(profile);const watched = existing.watched_workspaces || [];- if (!watched.some((w) => w.token === token)) {- watched.push({ id: null, name: null, token, status: "registered", agent_ids: [] });+ const idx = watched.findIndex((w) => w.id === ws.id);+ if (idx >= 0) {+ watched[idx] = { id: ws.id, name: ws.name, token, status: "active", agent_ids: agentIds };+ } else {+ watched.push({ id: ws.id, name: ws.name, token, status: "active", agent_ids: agentIds });}saveCLIConfigForProfile(profile, {@@ -69,20 +117,42 @@ export async function activateAndSave(opts: {if (daemonPid && isProcessAlive(daemonPid)) {try {process.kill(daemonPid, "SIGHUP");- console.log(`\nDaemon (pid ${daemonPid}) notified — machine registered, awaiting workspace binding.`);+ console.log(`\nDaemon (pid ${daemonPid}) notified — workspace will be active shortly.`);} catch {- console.log(`\nDaemon is running but could not be notified. Restart it to pick up the new token.`);+ console.log(`\nDaemon is running but could not be notified. Restart it to pick up the new workspace.`);}+ } else if (isDev() && process.stdout.isTTY) {+ console.log("\nStarting daemon in foreground...");+ await startDaemon(profile, serverUrl);} else {- const startCmd = isDev()- ? `${cmdPrefix()} daemon start --foreground`- : `${cmdPrefix()} daemon start`;- console.log();- console.log(`Run '${startCmd}' to start the daemon.`);+ console.log("\nStarting daemon...");+ try {+ const entry = process.argv[1];+ const args = [entry];+ if (profile) args.push("--profile", profile);+ args.push("daemon", "start", "--foreground");++ const logPath = daemonLogFilePath();+ mkdirSync(dirname(logPath), { recursive: true, mode: 0o700 });+ const logFd = openSync(logPath, "a", 0o600);++ const child = spawn(process.execPath, args, {+ detached: true,+ stdio: ["ignore", logFd, logFd],+ env: resolveLoginShellEnv(),+ });+ child.unref();+ closeSync(logFd);+ console.log("Daemon started in background.");+ console.log(`Logs: ${logPath}`);+ } catch {+ console.log(`Failed to auto-start daemon. Run '${cmdPrefix()} daemon start' manually.`);+ }}return {- daemonId: activateResp.daemon_id,- tokenStatus: activateResp.token_status,+ workspaceId: ws.id,+ workspaceName: ws.name,+ runtimeProviders: activateResp.runtimes.map((r) => r.provider),};}diff --git a/src/cli/lib/config.test.ts b/src/cli/lib/config.test.tsindex 73ebf6f9a..6bf0c4a3a 100644--- a/src/cli/lib/config.test.ts+++ b/src/cli/lib/config.test.ts@@ -121,24 +121,15 @@ describe("loadCLIConfigForProfile", () => {});});- it("migrates legacy machine_token into watched_workspaces as registered item", () => {+ it("assigns deleted status to entries without id and no status", () => {const cfg = {server_url: "http://example.com",- watched_workspaces: [{ id: "w1", name: "WS1", token: "t1" }],- machine_token: "al_legacy_token",+ watched_workspaces: [{ id: null, name: null, token: "t1" }],};mockedReadFileSync.mockReturnValue(JSON.stringify(cfg));const result = loadCLIConfigForProfile();- expect(result.watched_workspaces).toHaveLength(2);- expect(result.watched_workspaces[0]).toMatchObject({ id: "w1", status: "active" });- expect(result.watched_workspaces[1]).toMatchObject({- id: null,- name: null,- token: "al_legacy_token",- status: "registered",- agent_ids: [],- });+ expect(result.watched_workspaces[0]).toMatchObject({ status: "deleted" });});it("does not duplicate if machine_token already in watched_workspaces", () => {diff --git a/src/cli/lib/config.ts b/src/cli/lib/config.tsindex ef706543d..953202f34 100644--- a/src/cli/lib/config.ts+++ b/src/cli/lib/config.ts@@ -6,7 +6,7 @@ interface WatchedWorkspace {id: string | null;name: string | null;token: string;- status?: "registered" | "active" | "deleted";+ status?: "active" | "deleted";agent_ids?: string[];}@@ -54,15 +54,9 @@ export function loadCLIConfigForProfile(profile?: string): ProfileConfig {watched_workspaces: cfg.watched_workspaces || [],};- // Migration: move legacy machine_token into watched_workspaces as a registered item- const legacy = (cfg as Record<string, unknown>).machine_token as string | undefined;- if (legacy && !result.watched_workspaces.some((w) => w.token === legacy)) {- result.watched_workspaces.push({ id: null, name: null, token: legacy, status: "registered", agent_ids: [] });- }-// Default status for old entries without itfor (const ws of result.watched_workspaces) {- if (!ws.status) ws.status = ws.id ? "active" : "registered";+ if (!ws.status) ws.status = ws.id ? "active" : "deleted";}return result;diff --git a/src/shared/src/db/queries/machine-token.ts b/src/shared/src/db/queries/machine-token.tsindex 6c03b6525..a2e295e15 100644--- a/src/shared/src/db/queries/machine-token.ts+++ b/src/shared/src/db/queries/machine-token.ts@@ -1,4 +1,4 @@-import { eq, and, desc, asc, isNull } from "drizzle-orm";+import { eq, and, desc, isNull } from "drizzle-orm";import { machineToken, user } from "../schema";import type { Database } from "../index";@@ -66,35 +66,17 @@ export async function getPendingMachineToken(return rows[0] ?? null;}-export async function registerMachineToken(+export async function activateMachineToken(db: Database,id: string,hostname: string,- runtimesJson: string,) {await db.update(machineToken)- .set({ status: "registered", hostname, runtimesJson, lastUsedAt: null })+ .set({ status: "active", hostname }).where(eq(machineToken.id, id));}-export async function activateMachineToken(db: Database, id: string, workspaceId?: string) {- await db- .update(machineToken)- .set({ status: "active", ...(workspaceId ? { workspaceId } : {}) })- .where(eq(machineToken.id, id));-}--export async function getRegisteredTokenForUser(db: Database, userId: string) {- const rows = await db- .select()- .from(machineToken)- .where(and(eq(machineToken.userId, userId), eq(machineToken.status, "registered")))- .orderBy(asc(machineToken.createdAt))- .limit(1);- return rows[0] ?? null;-}-export async function getLatestTokenForUser(db: Database, userId: string) {const rows = await db.select({@@ -104,7 +86,6 @@ export async function getLatestTokenForUser(db: Database, userId: string) {workspaceId: machineToken.workspaceId,hostname: machineToken.hostname,lastUsedAt: machineToken.lastUsedAt,- runtimesJson: machineToken.runtimesJson,}).from(machineToken).where(eq(machineToken.userId, userId))diff --git a/src/shared/src/db/queries/workspace.ts b/src/shared/src/db/queries/workspace.tsindex 79d7eb77a..296416003 100644--- a/src/shared/src/db/queries/workspace.ts+++ b/src/shared/src/db/queries/workspace.ts@@ -8,6 +8,7 @@ export async function getWorkspace(db: Database, id: string, userId: string) {id: workspace.id,name: workspace.name,slug: workspace.slug,+ onboarded: workspace.onboarded,createdAt: workspace.createdAt,updatedAt: workspace.updatedAt,})@@ -28,6 +29,7 @@ export async function listWorkspaces(db: Database, userId: string) {id: workspace.id,name: workspace.name,slug: workspace.slug,+ onboarded: workspace.onboarded,createdAt: workspace.createdAt,updatedAt: workspace.updatedAt,})@@ -57,6 +59,13 @@ export async function updateWorkspace(db: Database, id: string, data: { name?: sreturn rows[0] ?? null;}+export async function markOnboarded(db: Database, id: string) {+ await db+ .update(workspace)+ .set({ onboarded: 1, updatedAt: new Date().toISOString() })+ .where(eq(workspace.id, id));+}+export async function deleteWorkspace(db: Database, id: string) {const rows = await db.delete(workspace).where(eq(workspace.id, id)).returning();return rows[0] ?? null;diff --git a/src/shared/src/db/schema.ts b/src/shared/src/db/schema.tsindex 3b0eeeac1..32f0eaa1e 100644--- a/src/shared/src/db/schema.ts+++ b/src/shared/src/db/schema.ts@@ -77,6 +77,7 @@ export const workspace = sqliteTable("workspace", {id: text("id").primaryKey().$defaultFn(() => "sp_" + nanoid()),name: text("name").notNull(),slug: text("slug").unique().notNull(),+ onboarded: integer("onboarded").notNull().default(0),createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),updatedAt: text("updated_at").notNull().$defaultFn(() => new Date().toISOString()),});diff --git a/src/shared/src/index.ts b/src/shared/src/index.tsindex 49df0b9b2..f42344aad 100644--- a/src/shared/src/index.ts+++ b/src/shared/src/index.ts@@ -119,7 +119,6 @@ export {DaemonRuntimeItemSchema,ActivateTokenRuntimeSchema,ActivateTokenRequestSchema,- BindWorkspaceRequestSchema,RegisterDaemonRequestSchema,DeregisterRequestSchema,CompleteTaskRequestSchema,diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.tsindex 6ab120349..17e9c0007 100644--- a/src/shared/src/schemas.ts+++ b/src/shared/src/schemas.ts@@ -175,7 +175,6 @@ export const DaemonPushMessageSchema = z.discriminatedUnion("type", [z.object({ type: z.literal("daemon.update"), version: z.string() }),z.object({ type: z.literal("daemon.rescan") }),z.object({ type: z.literal("daemon.kill"), workspaceId: z.string(), agentId: z.string().min(1), taskId: z.string(), targetTaskId: z.string() }),- z.object({ type: z.literal("daemon.workspace_added"), workspaceId: z.string(), workspaceName: z.string(), token: z.string() }),]);export type DaemonPushMessageType = z.infer<typeof DaemonPushMessageSchema>;@@ -225,10 +224,6 @@ export const RegisterDaemonRequestSchema = z.object({});export type RegisterDaemonRequest = z.infer<typeof RegisterDaemonRequestSchema>;-export const BindWorkspaceRequestSchema = z.object({- workspace_id: z.string().min(1),-});-export type BindWorkspaceRequest = z.infer<typeof BindWorkspaceRequestSchema>;export const DeregisterRequestSchema = z.object({daemon_id: z.string().min(1),@@ -689,7 +684,7 @@ export type UpdateMemberRequest = z.infer<typeof UpdateMemberRequestSchema>;export const CreateWorkspaceRequestSchema = z.object({name: z.string().min(1, "name is required"),- slug: z.string().min(1, "slug is required"),+ slug: z.string().optional().default(""),});export type CreateWorkspaceRequest = z.infer<typeof CreateWorkspaceRequestSchemadiff --git a/src/shared/src/types.ts b/src/shared/src/types.tsindex 48f89daab..42efca3f9 100644--- a/src/shared/src/types.ts+++ b/src/shared/src/types.ts@@ -15,6 +15,7 @@ export interface Workspace {id: string;name: string;slug: string;+ onboarded: boolean;created_at: string;updated_at: string;}@@ -281,9 +282,8 @@ export interface MeetingSession {/** WebSocket event types — single source of truth for the WS protocol. */export type WsMessage =- | { type: "machine.registered"; daemonId: string; hostname: string }| { type: "runtime.registered"; daemonId: string; hostname: string; workspaceId: string }- | { type: "runtime.status"; daemonId: string; workspaceId?: string; status: string; standby?: boolean }+ | { type: "runtime.status"; daemonId: string; workspaceId?: string; status: string }| { type: "runtime.deleted"; daemonId: string }| { type: "task.created"; conversationId: string; task: TaskApi }| { type: "task.updated"; taskId: string; agentId: string; status: string }@@ -315,4 +315,3 @@ export type DaemonPushMessage =| { type: "daemon.update"; version: string }| { type: "daemon.rescan" }| { type: "daemon.kill"; workspaceId: string; agentId: string; taskId: string; targetTaskId: string }- | { type: "daemon.workspace_added"; workspaceId: string; workspaceName: string; token: string }diff --git a/src/shared/test/queries/machine-token.test.ts b/src/shared/test/queries/machine-token.test.tsindex 75764d240..f92c79437 100644--- a/src/shared/test/queries/machine-token.test.ts+++ b/src/shared/test/queries/machine-token.test.ts@@ -18,9 +18,7 @@ describe("machine-token exports", () => {it("exports createMachineToken", () => { expect(typeof mt.createMachineToken).toBe("function"); });it("exports getMachineTokenByToken", () => { expect(typeof mt.getMachineTokenByToken).toBe("function"); });it("exports getPendingMachineToken", () => { expect(typeof mt.getPendingMachineToken).toBe("function"); });- it("exports registerMachineToken", () => { expect(typeof mt.registerMachineToken).toBe("function"); });it("exports activateMachineToken", () => { expect(typeof mt.activateMachineToken).toBe("function"); });- it("exports getRegisteredTokenForUser", () => { expect(typeof mt.getRegisteredTokenForUser).toBe("function"); });it("exports getLatestTokenForUser", () => { expect(typeof mt.getLatestTokenForUser).toBe("function"); });it("exports listMachineTokens", () => { expect(typeof mt.listMachineTokens).toBe("function"); });it("exports deleteMachineToken", () => { expect(typeof mt.deleteMachineToken).toBe("function"); });@@ -75,56 +73,19 @@ describe("getPendingMachineToken", () => {});});-describe("registerMachineToken", () => {- it("sets registered status with hostname and runtimes", async () => {+describe("activateMachineToken", () => {+ it("sets active status with hostname", async () => {const chain: any = {};chain.update = vi.fn(() => chain); chain.set = vi.fn(() => chain);chain.where = vi.fn(() => Promise.resolve());- await mt.registerMachineToken(chain, "mt_1", "host.local", '[{"type":"claude"}]');+ await mt.activateMachineToken(chain, "mt_1", "host.local");expect(chain.set).toHaveBeenCalledWith(expect.objectContaining({- status: "registered",+ status: "active",hostname: "host.local",- runtimesJson: '[{"type":"claude"}]',}));});});-describe("activateMachineToken", () => {- it("sets active", async () => {- const chain: any = {};- chain.update = vi.fn(() => chain); chain.set = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve());- await mt.activateMachineToken(chain, "mt_1");- expect(chain.set).toHaveBeenCalledWith(expect.objectContaining({ status: "active" }));- });- it("sets workspaceId when provided", async () => {- const chain: any = {};- chain.update = vi.fn(() => chain); chain.set = vi.fn(() => chain);- chain.where = vi.fn(() => Promise.resolve());- await mt.activateMachineToken(chain, "mt_1", "ws_1");- expect(chain.set).toHaveBeenCalledWith(expect.objectContaining({ workspaceId: "ws_1" }));- });-});--describe("getRegisteredTokenForUser", () => {- it("returns null when none", async () => {- const chain: any = {};- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => chain); chain.orderBy = vi.fn(() => chain);- chain.limit = vi.fn(() => Promise.resolve([]));- expect(await mt.getRegisteredTokenForUser(chain, "u")).toBeNull();- });- it("returns registered token ordered by createdAt ASC", async () => {- const t = { id: "mt_1", status: "registered" };- const chain: any = {};- chain.select = vi.fn(() => chain); chain.from = vi.fn(() => chain);- chain.where = vi.fn(() => chain); chain.orderBy = vi.fn(() => chain);- chain.limit = vi.fn(() => Promise.resolve([t]));- expect(await mt.getRegisteredTokenForUser(chain, "u")).toEqual(t);- expect(chain.orderBy).toHaveBeenCalled();- });-});-describe("getLatestTokenForUser", () => {it("returns null when no tokens exist", async () => {const chain: any = {};diff --git a/src/web/migrations/0041_workspace_onboarded.sql b/src/web/migrations/0041_workspace_onboarded.sqlnew file mode 100644index 000000000..06b8f27e3--- /dev/null+++ b/src/web/migrations/0041_workspace_onboarded.sql@@ -0,0 +1,4 @@+ALTER TABLE workspace ADD COLUMN onboarded INTEGER NOT NULL DEFAULT 0;++-- Mark existing workspaces as onboarded (they were created before this feature)+UPDATE workspace SET onboarded = 1;diff --git a/src/web/src/app/(app)/studio/new/client.tsx b/src/web/src/app/(app)/studio/new/client.tsxindex be938ae60..e636bb18c 100644--- a/src/web/src/app/(app)/studio/new/client.tsx+++ b/src/web/src/app/(app)/studio/new/client.tsx@@ -1,17 +1,15 @@"use client";-import { useState, useCallback, useEffect, useRef } from "react";+import { useState, useCallback, useEffect } from "react";import { useRouter } from "next/navigation";import { Button } from "@/components/ui/button";-import { Input } from "@/components/ui/input";-import { Loader2, CheckCircle2, XCircle, LogOut, ArrowLeft, LayoutGrid } from "lucide-react";+import { Loader2, CheckCircle2, LogOut, ArrowLeft, LayoutGrid } from "lucide-react";import { toast } from "sonner";import { signOut } from "@/lib/auth-client";import { clearAllCache } from "@/lib/chat-cache";import { trackWorkspaceCreated, trackOnboardingCompleted, trackAgentCreated } from "@/lib/analytics";import { PublicLayout } from "@/components/public-layout";-import { ConnectMachineSteps } from "@/components/connect-machine-steps";import { ScenarioPicker } from "@/components/studio-onboarding/scenario-picker";import { TeamPreview, type TeamMember } from "@/components/studio-onboarding/team-preview";import {@@ -23,46 +21,32 @@ import {import type { AgentRuntime as Runtime } from "@alook/shared";import type { WsMessage } from "@alook/shared";import { isTauri, isDesktop, tauriInvoke } from "@alook/shared";-import { listRuntimes, createMachineToken, getMachineTokenStatus } from "@/lib/api";+import { listRuntimes, createMachineToken } from "@/lib/api";import { useUserWs } from "@/lib/use-user-ws";+import { ConnectMachineSteps } from "@/components/connect-machine-steps";import type { TemplatePreset } from "@/lib/templates";export function StudioOnboardingClient({- workspaceId: initialWorkspaceId,+ workspaceId,workspaceSlug,workspaceName,initialTemplate,}: {- workspaceId: string | null;+ workspaceId: string;workspaceSlug: string;workspaceName: string;initialTemplate?: TemplatePreset;}) {const router = useRouter();- const isNewWorkspace = !initialWorkspaceId;- const [workspaceId, setWorkspaceId] = useState<string | null>(initialWorkspaceId);- const workspaceIdRef = useRef(workspaceId);- useEffect(() => { workspaceIdRef.current = workspaceId; }, [workspaceId]);const [runtimes, setRuntimes] = useState<Runtime[]>([]);- const runtimesRef = useRef(runtimes);- useEffect(() => { runtimesRef.current = runtimes; }, [runtimes]);- const wsSendRef = useRef<(msg: object) => void>(() => {});- const [loadingRuntimes, setLoadingRuntimes] = useState(!!initialWorkspaceId);+ const [loadingRuntimes, setLoadingRuntimes] = useState(true);const [scenarioId, setScenarioId] = useState<ScenarioId | null>(initialTemplate ? initialTemplate.baseScenario : null,);- const [studioName, setStudioName] = useState(- isNewWorkspace ? "" : (workspaceName === "Personal" ? "" : workspaceName),- );- const [nameAvailable, setNameAvailable] = useState<boolean | null>(null);- const [nameLocked, setNameLocked] = useState(false);- const [checkingName, setCheckingName] = useState(false);const [members, setMembers] = useState<TeamMember[]>([]);const [creating, setCreating] = useState(false);- const creatingRef = useRef(false);- // Connect machine stateconst [generatedToken, setGeneratedToken] = useState("");const [generatingToken, setGeneratingToken] = useState(false);const [machineRegistered, setMachineRegistered] = useState(false);@@ -70,203 +54,67 @@ export function StudioOnboardingClient({const isTauriDesktop = isTauri() && isDesktop();const onlineRuntimes = runtimes.filter((r) => r.status === "online");- // Desktop: runtimes are local, show all regardless of daemon status- const availableRuntimes = isTauriDesktop ? runtimes : onlineRuntimes;const hasOnlineRuntime = onlineRuntimes.length > 0;- const onlineMachineCount = new Set(onlineRuntimes.map((r) => r.daemon_id).filter(Boolean)).size;- // Fetch runtimes on mount (only if workspace exists)useEffect(() => {- if (!workspaceId) return;listRuntimes(workspaceId)- .then(setRuntimes)+ .then((rts) => {+ setRuntimes(rts);+ if (rts.some((r) => r.status === "online")) {+ setMachineRegistered(true);+ setDaemonOnline(true);+ }+ }).catch(() => {}).finally(() => setLoadingRuntimes(false));}, [workspaceId]);- // Recover token state on mount (handles page refresh after register)- useEffect(() => {- const doDesktopRegister = async (token: string) => {- const result = await tauriInvoke<{ success: boolean; message: string }>("register_cli", { token });- if (!result.success) {- toast.error(result.message || "Auto-registration failed — please check CLI installation");- return;- }- setMachineRegistered(true);- const fresh = await getMachineTokenStatus();- if (fresh.runtimes?.length) {- setRuntimes(fresh.runtimes.map((rt) => ({- id: rt.id,- workspace_id: "",- daemon_id: fresh.hostname || null,- runtime_mode: "local",- provider: rt.type,- status: fresh.daemon_online ? "online" as const : "offline" as const,- device_info: fresh.hostname || "",- metadata: { version: rt.version },- last_seen_at: null,- created_at: "",- updated_at: "",- })));- if (fresh.daemon_online) setDaemonOnline(true);- }- };-- getMachineTokenStatus()- .then(async (data) => {- if (isTauriDesktop) {- // Desktop token logic:- // - registered: already registered, use runtimesJson directly- // - pending: reuse token, auto-register- // - active (bound to workspace): create new token + auto-register- // - null: create new token + auto-register- if (data.status === "registered") {- setMachineRegistered(true);- if (data.daemon_online) setDaemonOnline(true);- if (data.runtimes?.length) {- setRuntimes(data.runtimes.map((rt) => ({- id: rt.id,- workspace_id: "",- daemon_id: data.hostname || null,- runtime_mode: "local",- provider: rt.type,- status: rt.status,- device_info: data.hostname || "",- metadata: { version: rt.version },- last_seen_at: null,- created_at: "",- updated_at: "",- })));- }- } else if (data.status === "pending" && data.token) {- try {- await doDesktopRegister(data.token);- } catch {- toast.error("Failed to auto-register CLI — please check that Claude or Codex is installed");- }- } else {- // active (bound to another workspace) or null — create new token + register- try {- const { token } = await createMachineToken("cli");- await doDesktopRegister(token);- } catch {- toast.error("Failed to auto-register CLI — please check that Claude or Codex is installed");- }- }- } else {- // Web (non-desktop) token recovery- if (data.status === "registered" || data.status === "active") {- if (isNewWorkspace && data.workspace_id) return;- setMachineRegistered(true);- if (data.daemon_online) setDaemonOnline(true);- if (data.runtimes?.length) {- setRuntimes(data.runtimes.map((rt) => ({- id: rt.id,- workspace_id: "",- daemon_id: data.hostname || null,- runtime_mode: "local",- provider: rt.type,- status: rt.status,- device_info: data.hostname || "",- metadata: { version: rt.version },- last_seen_at: null,- created_at: "",- updated_at: "",- })));- }- }- }- })- .catch(() => {});- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);-- // WebSocket for runtime registration eventsconst handleWsMessage = useCallback((msg: WsMessage) => {- if (creatingRef.current) return;- const currentWsId = workspaceIdRef.current;- if (msg.type === "machine.registered") {- setMachineRegistered(true);- if (runtimesRef.current.length === 0) {- getMachineTokenStatus().then(data => {- if (data.runtimes?.length) {- setRuntimes(data.runtimes.map(rt => ({- id: rt.id,- workspace_id: "",- daemon_id: data.hostname || null,- runtime_mode: "local",- provider: rt.type,- status: data.daemon_online ? "online" as const : "offline" as const,- device_info: data.hostname || "",- metadata: { version: rt.version },- last_seen_at: null,- created_at: "",- updated_at: "",- })));- }- if (data.daemon_online) setDaemonOnline(true);- }).catch(() => {});- }- wsSendRef.current({ type: "check_daemon_status" });- } else if (msg.type === "runtime.registered") {+ if (msg.type === "runtime.registered" && msg.workspaceId === workspaceId) {setMachineRegistered(true);- const eventWsId = msg.workspaceId;- if (eventWsId && !currentWsId && !isNewWorkspace) {- setWorkspaceId(eventWsId);- listRuntimes(eventWsId).then(setRuntimes).catch(() => {});- } else if (currentWsId) {- listRuntimes(currentWsId).then(setRuntimes).catch(() => {});- }- } else if (msg.type === "runtime.status" && msg.status === "online") {setDaemonOnline(true);- const wsId = workspaceIdRef.current;- if (runtimesRef.current.length === 0) {- if (wsId) {- listRuntimes(wsId).then(setRuntimes).catch(() => {});+ listRuntimes(workspaceId).then(setRuntimes).catch(() => {});+ } else if (msg.type === "runtime.status" && msg.workspaceId === workspaceId) {+ setMachineRegistered(true);+ if (msg.status === "online") setDaemonOnline(true);+ else setDaemonOnline(false);+ }+ }, [workspaceId]);++ useUserWs(handleWsMessage);++ const handleGenerateToken = useCallback(async () => {+ setGeneratingToken(true);+ try {+ const res = await createMachineToken("cli", workspaceId);+ setGeneratedToken(res.token);+ if (isTauriDesktop) {+ const result = await tauriInvoke<{ success: boolean; message: string }>("register_cli", { token: res.token });+ if (result.success) {+ setMachineRegistered(true);+ setDaemonOnline(true);+ listRuntimes(workspaceId).then(setRuntimes).catch(() => {});} else {- getMachineTokenStatus().then(data => {- if (data.runtimes?.length) {- setRuntimes(data.runtimes.map(rt => ({- id: rt.id,- workspace_id: "",- daemon_id: data.hostname || null,- runtime_mode: "local",- provider: rt.type,- status: "online" as const,- device_info: data.hostname || "",- metadata: { version: rt.version },- last_seen_at: null,- created_at: "",- updated_at: "",- })));- }- }).catch(() => {});+ toast.error(result.message || "Auto-registration failed");}- } else if (wsId) {- listRuntimes(wsId).then(setRuntimes).catch(() => {});- } else {- setRuntimes(prev => prev.map(r => ({ ...r, status: "online" })));}- } else if (msg.type === "runtime.status" && msg.status === "offline") {- setDaemonOnline(false);- setRuntimes(prev => prev.map(r => ({ ...r, status: "offline" })));+ } catch {+ toast.error("Failed to generate token");+ } finally {+ setGeneratingToken(false);}- }, [isNewWorkspace]);-- const { send: wsSend } = useUserWs(handleWsMessage);- useEffect(() => { wsSendRef.current = wsSend; }, [wsSend]);+ }, [workspaceId, isTauriDesktop]);- // Auto-assign first available runtime when runtimes load/changeuseEffect(() => {- const firstAvailable = availableRuntimes[0]?.id;- if (!firstAvailable) return;+ const firstOnline = onlineRuntimes[0]?.id;+ if (!firstOnline) return;setMembers((prev) => {if (prev.length === 0) return prev;const needsUpdate = prev.some((m) => !m.runtimeId);if (!needsUpdate) return prev;- return prev.map((m) => m.runtimeId ? m : { ...m, runtimeId: firstAvailable });+ return prev.map((m) => m.runtimeId ? m : { ...m, runtimeId: firstOnline });});- }, [availableRuntimes]);+ }, [onlineRuntimes]);const resolveHandles = useCallback(async (memberNames: string[]) => {try {@@ -282,12 +130,11 @@ export function StudioOnboardingClient({}}, []);- // Initialize from template when runtimes are loadeduseEffect(() => {if (!initialTemplate || loadingRuntimes) return;if (members.length > 0) return;const generated = shuffleMembers(initialTemplate.members.length);- const defaultRuntimeId = availableRuntimes[0]?.id || "";+ const defaultRuntimeId = onlineRuntimes[0]?.id || "";const newMembers = initialTemplate.members.map((m, i) => ({name: generated[i].name,role: m.role,@@ -315,7 +162,7 @@ export function StudioOnboardingClient({setScenarioId(id);const preset = SCENARIO_PRESETS.find((s) => s.id === id)!;const generated = shuffleMembers(preset.members.length);- const defaultRuntimeId = availableRuntimes[0]?.id || "";+ const defaultRuntimeId = onlineRuntimes[0]?.id || "";const newMembers = preset.members.map((m, i) => ({name: generated[i].name,role: m.role,@@ -348,49 +195,6 @@ export function StudioOnboardingClient({}};- const handleCheckName = async () => {- if (!studioName.trim()) return;- setCheckingName(true);- setNameAvailable(null);- try {- const url = workspaceId- ? `/api/studios/check-name?name=${encodeURIComponent(studioName.trim())}&workspace_id=${workspaceId}`- : `/api/studios/check-name?name=${encodeURIComponent(studioName.trim())}`;- const res = await fetch(url);- if (!res.ok) {- const err = (await res.json().catch(() => ({}))) as { error?: string };- toast.error(err.error || "Invalid company name");- setNameAvailable(false);- return;- }- const data = (await res.json()) as { available: boolean };- setNameAvailable(data.available);- if (data.available) setNameLocked(true);- } catch {- setNameAvailable(null);- toast.error("Failed to check name availability");- } finally {- setCheckingName(false);- }- };-- const handleUnlockName = () => {- setNameLocked(false);- setNameAvailable(null);- };-- const handleGenerateToken = useCallback(async () => {- setGeneratingToken(true);- try {- const res = await createMachineToken("cli", workspaceIdRef.current || undefined);- setGeneratedToken(res.token);- } catch {- toast.error("Failed to generate token");- } finally {- setGeneratingToken(false);- }- }, []);-const handleAssignRuntime = (memberIndex: number, runtimeId: string) => {setMembers((prev) =>prev.map((m, i) => (i === memberIndex ? { ...m, runtimeId } : m)),@@ -399,92 +203,17 @@ export function StudioOnboardingClient({const handleCreate = async () => {setCreating(true);- creatingRef.current = true;try {- let resolvedWorkspaceId = workspaceId;-- if (!resolvedWorkspaceId) {- // Create workspace + bind machine token- const wsRes = await fetch("/api/workspaces", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- name: studioName.trim() || "Personal",- slug: (studioName.trim() || "personal").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""),- }),- });- if (!wsRes.ok) {- const err = (await wsRes.json().catch(() => ({}))) as { error?: string };- throw new Error(err.error || "Failed to create workspace");- }- const wsData = (await wsRes.json()) as { id: string; slug: string };- resolvedWorkspaceId = wsData.id;- setWorkspaceId(resolvedWorkspaceId);-- // Bind workspace to machine token- const bindRes = await fetch("/api/machine-tokens/bind-workspace", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ workspace_id: resolvedWorkspaceId }),- });- if (!bindRes.ok) {- // Cleanup orphaned workspace- await fetch(`/api/workspaces/${resolvedWorkspaceId}`, { method: "DELETE" }).catch(() => {});- setWorkspaceId(null);- const err = (await bindRes.json().catch(() => ({}))) as { error?: string };- throw new Error(err.error || "Failed to bind workspace");- }- }-- if (!resolvedWorkspaceId) {- toast.error("Please connect a computer first");- creatingRef.current = false;- setCreating(false);- return;- }-- // Wait for real runtimes and resolve temp IDs to actual runtime IDs.- // After bind-workspace, the daemon registers runtimes — poll until available.- let resolvedMembers = members;- const needsRuntimeResolution = members.some((m) => !m.runtimeId || m.runtimeId.startsWith("temp_"));- if (needsRuntimeResolution) {- let attempts = 0;- let freshRuntimes: Runtime[] = [];- while (attempts < 10) {- freshRuntimes = await listRuntimes(resolvedWorkspaceId);- if (freshRuntimes.some((r) => r.status === "online")) break;- await new Promise((r) => setTimeout(r, 1000));- attempts++;- }- const onlineFresh = freshRuntimes.filter((r) => r.status === "online");- if (onlineFresh.length > 0) {- resolvedMembers = members.map((m) => {- if (!m.runtimeId || m.runtimeId.startsWith("temp_")) {- const tempProvider = runtimes.find((r) => r.id === m.runtimeId)?.provider;- const match = onlineFresh.find((r) => r.provider === tempProvider) || onlineFresh[0];- return { ...m, runtimeId: match.id };- }- return m;- });- }- if (resolvedMembers.some((m) => !m.runtimeId || m.runtimeId.startsWith("temp_"))) {- toast.error("Waiting for runtime — please ensure the daemon is running");- creatingRef.current = false;- setCreating(false);- return;- }- }-const res = await fetch("/api/studios", {method: "POST",headers: {"Content-Type": "application/json",- "X-Workspace-ID": resolvedWorkspaceId,+ "X-Workspace-ID": workspaceId,},body: JSON.stringify({- name: studioName.trim() || undefined,+ name: undefined,scenario: scenarioId,- members: resolvedMembers.map((m) => ({+ members: members.map((m) => ({name: m.name,role: m.role,runtime_id: m.runtimeId,@@ -503,41 +232,32 @@ export function StudioOnboardingClient({}const data = (await res.json()) as { workspace: { slug: string }; leader_agent_id: string };- if (!initialWorkspaceId) {- trackWorkspaceCreated("onboarding");- }+ await fetch(`/api/workspaces/${workspaceId}/onboarded`, { method: "POST" }).catch(() => {});+ trackWorkspaceCreated("onboarding");trackOnboardingCompleted({template_used: scenarioId ?? undefined,- agent_count: resolvedMembers.length,+ agent_count: members.length,});- for (let i = 0; i < resolvedMembers.length; i++) {+ for (let i = 0; i < members.length; i++) {trackAgentCreated({is_first_agent: i === 0,- has_email: !!resolvedMembers[i].emailHandle,+ has_email: !!members[i].emailHandle,});}toast.success("Company created!");router.push(`/w/${data.workspace.slug}/agents/${data.leader_agent_id}`);} catch (e) {toast.error(e instanceof Error ? e.message : "Failed to create company");- creatingRef.current = false;setCreating(false);}};- const nameValid =- isNewWorkspace- ? studioName.trim() && nameAvailable === true- : nameAvailable !== false;-const canCreate =scenarioId &&members.length > 0 &&- (isTauriDesktop || isNewWorkspace || members.every((m) => m.runtimeId)) &&- nameValid &&- (hasOnlineRuntime || (machineRegistered && daemonOnline && runtimes.length > 0) || (isTauriDesktop && runtimes.length > 0));+ members.every((m) => m.runtimeId) &&+ (hasOnlineRuntime || (machineRegistered && daemonOnline) || isTauriDesktop);- // Page 1: Scenario selectionif (!scenarioId) {return (<PublicLayout@@ -578,28 +298,25 @@ export function StudioOnboardingClient({</p></div>- <ScenarioPicker selected={scenarioId} onSelect={handleScenarioSelect} onBrowseTemplates={() => router.push(workspaceId ? `/templates?workspace_id=${workspaceId}` : "/templates")} />+ <ScenarioPicker selected={scenarioId} onSelect={handleScenarioSelect} onBrowseTemplates={() => router.push(`/templates?workspace_id=${workspaceId}`)} />- {workspaceId && (- <div className="flex justify-center pt-2">- <button- type="button"- onClick={() => {- document.cookie = `skip_init=${workspaceId};path=/;max-age=86400`;- router.push(`/w/${workspaceSlug}/home`);- }}- className="text-xs text-muted-foreground hover:text-foreground transition-colors"- >- Skip for now- </button>- </div>- )}+ <div className="flex justify-center pt-2">+ <button+ type="button"+ onClick={async () => {+ await fetch(`/api/workspaces/${workspaceId}/onboarded`, { method: "POST" }).catch(() => {});+ router.push(`/w/${workspaceSlug}/home`);+ }}+ className="text-xs text-muted-foreground hover:text-foreground transition-colors"+ >+ Skip for now+ </button>+ </div></div></PublicLayout>);}- // Page 2: Build your companyreturn (<PublicLayoutleftSlot={@@ -638,7 +355,6 @@ export function StudioOnboardingClient({}><div className="mx-auto w-full max-w-3xl space-y-10 px-6 py-14">- {/* Header */}<div className="text-center"><h1className="text-2xl font-semibold tracking-tight"@@ -648,76 +364,16 @@ export function StudioOnboardingClient({</h1></div>- {/* Loading */}{loadingRuntimes ? (<div className="flex justify-center py-8"><Loader2 className="size-5 animate-spin text-muted-foreground" /></div>) : (<>- {/* Company Name */}- <div className="space-y-2">- <h2 className="text-base font-semibold tracking-tight">Company name</h2>- <div className="flex gap-2">- <Input- value={studioName}- onChange={(e) => {- setStudioName(e.target.value);- setNameAvailable(null);- }}- placeholder="e.g. Atlas Lab"- className="text-sm"- disabled={nameLocked}- />- {nameLocked ? (- <Button- variant="outline"- size="sm"- onClick={handleUnlockName}- className="shrink-0"- >- Edit- </Button>- ) : (- <Button- variant="outline"- size="sm"- onClick={handleCheckName}- disabled={!studioName.trim() || checkingName}- className="shrink-0"- >- {checkingName ? <Loader2 className="size-3 animate-spin" /> : "Check"}- </Button>- )}- </div>- <div className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground">- <span className="flex items-center gap-1.5">- {nameAvailable === true && (- <>- <span className="text-emerald-600 flex items-center gap-0.5">- <CheckCircle2 className="size-3" /> Available- </span>- <span>·</span>- </>- )}- {!isNewWorkspace ? (- <span>Optional — you can always rename later.</span>- ) : (- <span>Required — pick a name for your company.</span>- )}- </span>- {nameAvailable === false && (- <span className="text-red-500 flex items-center gap-1 ml-auto">- <XCircle className="size-3" /> Name is taken, try another- </span>- )}- </div>- </div>-{/* Team Preview */}<TeamPreviewmembers={members}- runtimes={availableRuntimes as Runtime[]}+ runtimes={onlineRuntimes as Runtime[]}onShuffle={handleShuffle}onAssignRuntime={handleAssignRuntime}/>@@ -726,9 +382,9 @@ export function StudioOnboardingClient({{!isTauriDesktop && (<div className="space-y-3"><h2 className="text-base font-semibold tracking-tight">Connect a computer</h2>- {(hasOnlineRuntime || (machineRegistered && daemonOnline && runtimes.length > 0)) ? (+ {(hasOnlineRuntime || (machineRegistered && daemonOnline)) ? (<p className="text-xs text-emerald-600 flex items-center gap-1">- <CheckCircle2 className="size-3" /> {onlineMachineCount || 1} computer{(onlineMachineCount || 1) > 1 ? "s" : ""} connected+ <CheckCircle2 className="size-3" /> Computer connected</p>) : (<>@@ -761,10 +417,6 @@ export function StudioOnboardingClient({<Loader2 className="size-4 animate-spin mr-2" />Launching...</>- ) : isNewWorkspace && nameAvailable === false ? (- "Name unavailable"- ) : isNewWorkspace && nameAvailable !== true ? (- "Check company name first") : ("Launch company")}diff --git a/src/web/src/app/(app)/studio/new/page.tsx b/src/web/src/app/(app)/studio/new/page.tsxindex 493b79c9b..89b089b30 100644--- a/src/web/src/app/(app)/studio/new/page.tsx+++ b/src/web/src/app/(app)/studio/new/page.tsx@@ -20,28 +20,26 @@ export default async function StudioNewPage({const initialTemplate = templateId ? getTemplateById(templateId) : undefined;const workspaceId = params.workspace_id ?? null;- let workspaceName = "";- let workspaceSlug = "";- if (workspaceId) {- const membership = await queries.member.getMemberByUserAndWorkspace(- db,- session.user.id,- workspaceId,- );- if (!membership) redirect("/workspaces");-- const workspace = await queries.workspace.getWorkspace(db, workspaceId, session.user.id);- if (!workspace) redirect("/workspaces");- workspaceName = workspace.name;- workspaceSlug = workspace.slug;+ if (!workspaceId) {+ redirect("/workspaces");}+ const membership = await queries.member.getMemberByUserAndWorkspace(+ db,+ session.user.id,+ workspaceId,+ );+ if (!membership) redirect("/workspaces");++ const workspace = await queries.workspace.getWorkspace(db, workspaceId, session.user.id);+ if (!workspace) redirect("/workspaces");+return (<StudioOnboardingClientworkspaceId={workspaceId}- workspaceSlug={workspaceSlug}- workspaceName={workspaceName}+ workspaceSlug={workspace.slug}+ workspaceName={workspace.name}initialTemplate={initialTemplate}/>);diff --git a/src/web/src/app/(app)/w/[slug]/home/page.tsx b/src/web/src/app/(app)/w/[slug]/home/page.tsxindex 0752ff323..2819999b6 100644--- a/src/web/src/app/(app)/w/[slug]/home/page.tsx+++ b/src/web/src/app/(app)/w/[slug]/home/page.tsx@@ -49,8 +49,10 @@ import {createAgentLink,updateAgentLink,deleteAgentLink,+ createMachineToken,} from "@/lib/api";import { toast } from "sonner";+import { cliCmd } from "@/lib/utils";import { ApiError } from "@/lib/errors";import { trackAgentLinkCreated, trackCanvasLayoutChanged } from "@/lib/analytics";import { AgentNode, type AgentNodeData } from "@/components/canvas/agent-node";@@ -640,9 +642,54 @@ function MobileAgentList({ onAgentClick }: { onAgentClick?: (agent: Agent) => vo);}+function ConnectComputerCard({ workspaceId }: { workspaceId: string }) {+ const [token, setToken] = useState("");+ const [loading, setLoading] = useState(true);++ useEffect(() => {+ createMachineToken("cli", workspaceId)+ .then((res) => setToken(res.token))+ .catch(() => toast.error("Failed to generate token"))+ .finally(() => setLoading(false));+ }, [workspaceId]);++ const command = `${cliCmd()} register --token ${token}`;++ const copy = () => {+ navigator.clipboard.writeText(command);+ toast.success("Copied to clipboard");+ };++ return (+ <div className="rounded-xl bg-muted/40 p-5 space-y-3">+ <h3 className="text-sm font-semibold">Connect a computer</h3>+ <p className="text-xs text-muted-foreground">+ Run this command in your terminal to link your machine.+ </p>+ {loading ? (+ <div className="rounded-md bg-muted p-2.5 font-mono text-xs text-muted-foreground animate-pulse">+ Generating token...+ </div>+ ) : (+ <>+ <div+ className="rounded-md bg-muted p-2.5 font-mono text-xs text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors break-all"+ onClick={copy}+ >+ {command}+ </div>+ <Button size="sm" onClick={copy} className="w-full">+ Copy Command+ </Button>+ </>+ )}+ </div>+ );+}+export default function HomePage() {const router = useRouter();- const { agents, loading } = useAgentContext();+ const { agents, runtimes, loading } = useAgentContext();const { workspaceId } = useWorkspace();const isMobile = useIsMobile();const { openAgentChat } = useAgentChatSheet();@@ -659,18 +706,26 @@ export default function HomePage() {);}+ const onlineRuntimes = runtimes.filter((r) => r.status === "online");+ const hasComputer = onlineRuntimes.length > 0;+if (agents.length === 0) {return (<div className="flex flex-1 items-center justify-center">- <div className="text-center animate-[fade-up_400ms_ease-out_both]">- <p className="text-muted-foreground text-sm">Build your AI company</p>- <Button- size="sm"- className="mt-4 glow-border"- onClick={() => router.push(`/studio/new?workspace_id=${workspaceId}`)}- >- Get Started- </Button>+ <div className="w-full max-w-sm space-y-6 animate-[fade-up_400ms_ease-out_both]">+ {!hasComputer && (+ <ConnectComputerCard workspaceId={workspaceId} />+ )}+ <div className="text-center">+ <p className="text-muted-foreground text-sm">Build your AI company</p>+ <Button+ size="sm"+ className="mt-4 glow-border"+ onClick={() => router.push(`/studio/new?workspace_id=${workspaceId}`)}+ >+ Get Started+ </Button>+ </div></div></div>);diff --git a/src/web/src/app/(app)/w/[slug]/layout.tsx b/src/web/src/app/(app)/w/[slug]/layout.tsxindex ea58a691e..b1094b012 100644--- a/src/web/src/app/(app)/w/[slug]/layout.tsx+++ b/src/web/src/app/(app)/w/[slug]/layout.tsx@@ -1,4 +1,3 @@-import { headers } from "next/headers"import { redirect } from "next/navigation"import { getCloudflareContext } from "@opennextjs/cloudflare"import { queries } from "@alook/shared"@@ -35,19 +34,8 @@ export default async function WorkspaceLayout({)if (!membership) redirect("/workspaces")- const agents = await queries.agent.listAgents(db, ws.id)- if (agents.length === 0) {- const hdrs = await headers()- const cookieHeader = hdrs.get("cookie") || ""- const cookies = Object.fromEntries(- cookieHeader.split(";").map((c) => {- const [k, ...v] = c.trim().split("=")- return [k, v.join("=")]- })- )- if (!cookies["skip_init"] || cookies["skip_init"] !== ws.id) {- redirect(`/studio/new?workspace_id=${ws.id}`)- }+ if (!ws.onboarded) {+ redirect(`/studio/new?workspace_id=${ws.id}`)}return (diff --git a/src/web/src/app/(app)/workspaces/client.tsx b/src/web/src/app/(app)/workspaces/client.tsxindex e6da4e742..55092ffcb 100644--- a/src/web/src/app/(app)/workspaces/client.tsx+++ b/src/web/src/app/(app)/workspaces/client.tsx@@ -1,13 +1,15 @@"use client"+import { useState } from "react"import { useRouter } from "next/navigation"import { Button } from "@/components/ui/button"import { Card, CardContent } from "@/components/ui/card"import { GradientBackground } from "@/components/gradient-background"import { Logo } from "@/components/logo"-import { Plus, ArrowRight, LogOut } from "lucide-react"+import { Plus, ArrowRight, LogOut, Loader2 } from "lucide-react"import { signOut } from "@/lib/auth-client"import { clearAllCache } from "@/lib/chat-cache"+import { toast } from "sonner"interface WorkspaceItem {id: string@@ -17,12 +19,31 @@ interface WorkspaceItem {export function WorkspaceListClient({workspaces,- emptyWorkspaceId,}: {workspaces: WorkspaceItem[]- emptyWorkspaceId?: string | null}) {const router = useRouter()+ const [creating, setCreating] = useState(false)++ const handleNewWorkspace = async () => {+ setCreating(true)+ try {+ const res = await fetch("/api/workspaces", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name: "Personal", slug: "" }),+ })+ if (!res.ok) {+ const err = (await res.json().catch(() => ({}))) as { error?: string }+ throw new Error(err.error || "Failed to create workspace")+ }+ const data = (await res.json()) as { id: string; slug: string }+ router.push(`/studio/new?workspace_id=${data.id}`)+ } catch (e) {+ toast.error(e instanceof Error ? e.message : "Failed to create workspace")+ setCreating(false)+ }+ }return (<div className="relative flex min-h-dvh flex-col items-center justify-center p-6">@@ -71,10 +92,14 @@ export function WorkspaceListClient({<Buttonvariant="outline"className="w-full"- onClick={() => router.push(emptyWorkspaceId ? `/studio/new?workspace_id=${emptyWorkspaceId}` : "/studio/new")}+ onClick={handleNewWorkspace}+ disabled={creating}>- <Plus className="size-4" />- New workspace+ {creating ? (+ <><Loader2 className="size-4 animate-spin" /> Creating...</>+ ) : (+ <><Plus className="size-4" /> New workspace</>+ )}</Button></div></div>diff --git a/src/web/src/app/(app)/workspaces/page.tsx b/src/web/src/app/(app)/workspaces/page.tsxindex 7e52d5b79..4bc15afde 100644--- a/src/web/src/app/(app)/workspaces/page.tsx+++ b/src/web/src/app/(app)/workspaces/page.tsx@@ -1,6 +1,6 @@import { redirect } from "next/navigation"import { getCloudflareContext } from "@opennextjs/cloudflare"-import { queries } from "@alook/shared"+import { queries, generateWorkspaceSlug } from "@alook/shared"import { getDb } from "@/lib/db"import { requireSession } from "@/lib/session"import { WorkspaceListClient } from "./client"@@ -16,30 +16,26 @@ export default async function WorkspacesPage({const workspaces = await queries.workspace.listWorkspaces(db, session.user.id)- // New users with no workspaces → redirect to /studio/new to start the flowif (workspaces.length === 0) {- redirect("/studio/new")+ const ws = await queries.workspace.createWorkspace(db, {+ name: "Personal",+ slug: generateWorkspaceSlug(),+ })+ await queries.member.createMember(db, {+ workspaceId: ws.id,+ userId: session.user.id,+ role: "owner",+ })+ redirect(`/studio/new?workspace_id=${ws.id}`)}- // Auto-redirect to single workspace only on post-login flowconst params = await searchParamsif (workspaces.length === 1 && params.auto !== undefined) {- const agents = await queries.agent.listAgents(db, workspaces[0].id)- if (agents.length === 0) {+ if (!workspaces[0].onboarded) {redirect(`/studio/new?workspace_id=${workspaces[0].id}`)}redirect(`/w/${workspaces[0].slug}/home`)}- // Find most recent workspace with 0 agents to reuse for "New workspace"- let emptyWorkspaceId: string | null = null- for (const ws of workspaces) {- const agents = await queries.agent.listAgents(db, ws.id)- if (agents.length === 0) {- emptyWorkspaceId = ws.id- break- }- }-- return <WorkspaceListClient workspaces={workspaces} emptyWorkspaceId={emptyWorkspaceId} />+ return <WorkspaceListClient workspaces={workspaces} />}diff --git a/src/web/src/app/(auth)/sign-in/page.tsx b/src/web/src/app/(auth)/sign-in/page.tsxindex c08fdb56e..fa2e65fb8 100644--- a/src/web/src/app/(auth)/sign-in/page.tsx+++ b/src/web/src/app/(auth)/sign-in/page.tsx@@ -23,13 +23,9 @@ import { SiGithub, SiGoogle } from "@icons-pack/react-simple-icons"import Image from "next/image"import { GradientBackground } from "@/components/gradient-background"import { Logo } from "@/components/logo"-import { resolveMode, DEV_PASSWORD } from "@alook/shared"+import { DEV_PASSWORD } from "@alook/shared"-const mode = resolveMode({- nodeEnv: process.env.NODE_ENV,- hostname: typeof window !== "undefined" ? window.location.hostname : undefined,-})-const isProd = mode !== "dev" && mode !== "app"+const isProd = process.env.NODE_ENV === "production"const DEFAULT_POST_LOGIN = "/workspaces?auto"diff --git a/src/web/src/app/api/daemon/register/route.test.ts b/src/web/src/app/api/daemon/register/route.test.tsindex 53e0b7cb9..42288d082 100644--- a/src/web/src/app/api/daemon/register/route.test.ts+++ b/src/web/src/app/api/daemon/register/route.test.ts@@ -284,28 +284,21 @@ describe("POST /api/daemon/register", () => {expect(mockGetMachineByDaemon).not.toHaveBeenCalled();});- it("returns standby when no workspace_id is provided or resolved", async () => {+ it("returns 400 when no workspace_id is provided or resolved", async () => {const POST = await loadRoute(authCtx);- mockBroadcastToUser.mockResolvedValue(undefined);- const standbyBody = {+ const body = {daemon_id: "d1",device_name: "MyMachine",cli_version: "0.0.2",runtimes: [{ type: "claude", version: "1.0", runtime_mode: "local" }],};- const res = await POST(makeReq(standbyBody));- const body = await res.json();+ const res = await POST(makeReq(body));+ const json = await res.json();- expect(res.status).toBe(200);- expect(body.standby).toBe(true);- expect(body.runtimes).toEqual([]);+ expect(res.status).toBe(400);+ expect(json.error).toBe("workspace_id is required");expect(mockUpsertMachine).not.toHaveBeenCalled();- expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", expect.objectContaining({- type: "runtime.status",- status: "online",- standby: true,- }));});it("uses auth context workspaceId when body workspace_id is missing", async () => {diff --git a/src/web/src/app/api/daemon/register/route.ts b/src/web/src/app/api/daemon/register/route.tsindex a769783ed..fe9425a22 100644--- a/src/web/src/app/api/daemon/register/route.ts+++ b/src/web/src/app/api/daemon/register/route.ts@@ -26,13 +26,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {}if (!workspaceId) {- broadcastToUser(ctx.userId, {- type: "runtime.status",- daemonId,- status: "online",- standby: true,- }).catch(() => {});- return writeJSON({ runtimes: [], standby: true });+ return writeJSON({ error: "workspace_id is required" }, 400);}// When authenticated with a machine token, enforce workspace matchdiff --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 34bea2ef6..a41f17846 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@@ -2,7 +2,9 @@ import { describe, it, expect, vi, beforeEach } from "vitest";import { NextRequest } from "next/server";const mockGetMachineTokenByToken = vi.fn();-const mockRegisterMachineToken = vi.fn();+const mockActivateMachineToken = vi.fn();+const mockUpsertMachine = vi.fn();+const mockUpsertAgentRuntime = vi.fn();const mockBroadcastToUser = vi.fn();function sharedMocks() {@@ -15,7 +17,13 @@ function sharedMocks() {queries: {machineToken: {getMachineTokenByToken: (...a: any[]) => mockGetMachineTokenByToken(...a),- registerMachineToken: (...a: any[]) => mockRegisterMachineToken(...a),+ activateMachineToken: (...a: any[]) => mockActivateMachineToken(...a),+ },+ machine: {+ upsertMachine: (...a: any[]) => mockUpsertMachine(...a),+ },+ runtime: {+ upsertAgentRuntime: (...a: any[]) => mockUpsertAgentRuntime(...a),},},ActivateTokenRequestSchema: (await import("@alook/shared"))@@ -50,13 +58,20 @@ describe("POST /api/machine-tokens/activate", () => {vi.doMock("@/lib/broadcast", () => mocks["@/lib/broadcast"]);vi.doMock("@/lib/cache", () => ({invalidate: vi.fn(() => Promise.resolve()),- cacheKeys: { machineToken: (t: string) => `mt:${t}` },+ cacheKeys: {+ machineToken: (t: string) => `mt:${t}`,+ runtimeIds: () => "ri:",+ allRuntimes: () => "ar:",+ },}));vi.doMock("@/lib/middleware/helpers", async () => {return await vi.importActual<typeof import("@/lib/middleware/helpers")>("@/lib/middleware/helpers");});+ vi.doMock("@/lib/api/responses", () => ({+ runtimeToResponse: (r: any) => ({ id: r.id, provider: r.provider }),+ }));const { POST } = await import("./route");return POST;@@ -71,15 +86,17 @@ describe("POST /api/machine-tokens/activate", () => {const pendingToken = {id: "mt_1",userId: "u1",- workspaceId: null,+ workspaceId: "ws_1",status: "pending",};- it("transitions token to registered status", async () => {+ it("creates machine + runtime rows and activates token", async () => {const POST = await loadRoute();mockGetMachineTokenByToken.mockResolvedValue(pendingToken);- mockRegisterMachineToken.mockResolvedValue(undefined);+ mockUpsertMachine.mockResolvedValue(undefined);+ mockUpsertAgentRuntime.mockResolvedValue({ id: "rt_1", provider: "claude" });+ mockActivateMachineToken.mockResolvedValue(undefined);mockBroadcastToUser.mockResolvedValue(undefined);const res = await POST(makeReq(validBody));@@ -87,41 +104,48 @@ describe("POST /api/machine-tokens/activate", () => {expect(res.status).toBe(200);expect(body.daemon_id).toBe("TestMachine.local");- expect(body.token_status).toBe("registered");- expect(body.workspace_id).toBeUndefined();- expect(body.runtimes).toBeUndefined();- });+ expect(body.workspace_id).toBe("ws_1");+ expect(body.runtimes).toHaveLength(1);- it("stores hostname and runtimes on the token", async () => {- const POST = await loadRoute();-- mockGetMachineTokenByToken.mockResolvedValue(pendingToken);- mockRegisterMachineToken.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);+ expect(mockUpsertMachine).toHaveBeenCalledWith(expect.anything(), {+ daemonId: "TestMachine.local",+ workspaceId: "ws_1",+ deviceInfo: "TestMachine.local",+ lastSeenAt: null,+ });- await POST(makeReq(validBody));+ expect(mockUpsertAgentRuntime).toHaveBeenCalledWith(expect.anything(), {+ workspaceId: "ws_1",+ daemonId: "TestMachine.local",+ runtimeMode: "local",+ provider: "claude",+ deviceInfo: "TestMachine.local",+ metadata: { version: "2.1.0" },+ });- expect(mockRegisterMachineToken).toHaveBeenCalledWith(+ expect(mockActivateMachineToken).toHaveBeenCalledWith(expect.anything(),"mt_1","TestMachine.local",- JSON.stringify([{ type: "claude", version: "2.1.0" }]),);});- it("broadcasts machine.registered event", async () => {+ it("broadcasts runtime.registered event", async () => {const POST = await loadRoute();mockGetMachineTokenByToken.mockResolvedValue(pendingToken);- mockRegisterMachineToken.mockResolvedValue(undefined);+ mockUpsertMachine.mockResolvedValue(undefined);+ mockUpsertAgentRuntime.mockResolvedValue({ id: "rt_1", provider: "claude" });+ mockActivateMachineToken.mockResolvedValue(undefined);mockBroadcastToUser.mockResolvedValue(undefined);await POST(makeReq(validBody));expect(mockBroadcastToUser).toHaveBeenCalledWith("u1", {- type: "machine.registered",+ type: "runtime.registered",daemonId: "TestMachine.local",hostname: "TestMachine.local",+ workspaceId: "ws_1",});});@@ -135,7 +159,6 @@ describe("POST /api/machine-tokens/activate", () => {expect(res.status).toBe(404);expect(body.error).toBe("token not found");- expect(mockRegisterMachineToken).not.toHaveBeenCalled();});it("returns 409 when token already used", async () => {@@ -148,19 +171,17 @@ describe("POST /api/machine-tokens/activate", () => {expect(res.status).toBe(409);expect(body.error).toBe("token already used");- expect(mockRegisterMachineToken).not.toHaveBeenCalled();});- it("does not create workspace or machine rows", async () => {+ it("returns 422 when token has no workspace_id", async () => {const POST = await loadRoute();- mockGetMachineTokenByToken.mockResolvedValue(pendingToken);- mockRegisterMachineToken.mockResolvedValue(undefined);- mockBroadcastToUser.mockResolvedValue(undefined);+ mockGetMachineTokenByToken.mockResolvedValue({ ...pendingToken, workspaceId: null });- await POST(makeReq(validBody));+ const res = await POST(makeReq(validBody));+ const body = await res.json();- // Only registerMachineToken should be called — no workspace/machine/runtime creation- expect(mockRegisterMachineToken).toHaveBeenCalledTimes(1);+ expect(res.status).toBe(422);+ expect(body.error).toContain("no workspace_id");});});diff --git a/src/web/src/app/api/machine-tokens/activate/route.ts b/src/web/src/app/api/machine-tokens/activate/route.tsindex 8b697d8ad..c0fd98bc4 100644--- a/src/web/src/app/api/machine-tokens/activate/route.ts+++ b/src/web/src/app/api/machine-tokens/activate/route.ts@@ -3,6 +3,7 @@ import { getCloudflareContext } from "@opennextjs/cloudflare";import { queries, ActivateTokenRequestSchema, createLogger } from "@alook/shared";import { getDb } from "@/lib/db"import { writeJSON } from "@/lib/middleware/helpers";+import { runtimeToResponse } from "@/lib/api/responses";import { broadcastToUser } from "@/lib/broadcast";import { invalidate, cacheKeys } from "@/lib/cache";@@ -34,28 +35,57 @@ export async function POST(req: NextRequest) {return writeJSON({ error: "token already used" }, 409);}- await queries.machineToken.registerMachineToken(- db,- mt.id,- hostname,- JSON.stringify(runtimes),- );+ const workspaceId = mt.workspaceId;+ if (!workspaceId) {+ return writeJSON({ error: "token has no workspace_id — create workspace first" }, 422);+ }++ const daemonId = hostname;++ await queries.machine.upsertMachine(db, {+ daemonId,+ workspaceId,+ deviceInfo: hostname,+ lastSeenAt: null,+ });++ const results = [];+ for (const rt of runtimes) {+ const result = await queries.runtime.upsertAgentRuntime(db, {+ workspaceId,+ daemonId,+ runtimeMode: "local",+ provider: rt.type,+ deviceInfo: hostname,+ metadata: { version: rt.version || "" },+ });+ results.push({ ...result, machineLastSeenAt: null });+ }++ await queries.machineToken.activateMachineToken(db, mt.id, hostname);- await invalidate(cacheKeys.machineToken(token));+ await Promise.all([+ invalidate(cacheKeys.machineToken(token)),+ invalidate(cacheKeys.runtimeIds(workspaceId, daemonId)),+ invalidate(cacheKeys.allRuntimes(workspaceId)),+ ]);broadcastToUser(mt.userId, {- type: "machine.registered",- daemonId: hostname,+ type: "runtime.registered",+ daemonId,hostname,+ workspaceId,}).catch((err) => {- log.warn("broadcast after registration failed", {+ log.warn("broadcast after activation failed", {userId: mt.userId,+ daemonId,err: err instanceof Error ? err.message : String(err),});});return writeJSON({- daemon_id: hostname,- token_status: "registered",+ daemon_id: daemonId,+ workspace_id: workspaceId,+ runtimes: results.map(runtimeToResponse),});}diff --git a/src/web/src/app/api/machine-tokens/bind-workspace/route.test.ts b/src/web/src/app/api/machine-tokens/bind-workspace/route.test.tsdeleted file mode 100644index 99261dfd8..000000000--- a/src/web/src/app/api/machine-tokens/bind-workspace/route.test.ts+++ /dev/null@@ -1,329 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { NextRequest } from "next/server";--const mockGetRegisteredTokenForUser = vi.fn();-const mockGetLatestTokenForUser = vi.fn();-const mockActivateMachineToken = vi.fn();-const mockGetMemberByUserAndWorkspace = vi.fn();-const mockUpsertMachine = vi.fn();-const mockUpsertAgentRuntime = vi.fn();-const mockBroadcastToUser = vi.fn();-const mockBroadcastToDaemon = vi.fn();-const mockInvalidate = vi.fn(() => Promise.resolve());--function sharedMocks() {- return {- "@opennextjs/cloudflare": {- getCloudflareContext: vi.fn(() => Promise.resolve({ env: { DB: {} } })),- },- "@alook/shared": async () => ({- createDb: vi.fn(() => ({})),- queries: {- machineToken: {- getRegisteredTokenForUser: (...a: any[]) => mockGetRegisteredTokenForUser(...a),- getLatestTokenForUser: (...a: any[]) => mockGetLatestTokenForUser(...a),- activateMachineToken: (...a: any[]) => mockActivateMachineToken(...a),- },- member: {- getMemberByUserAndWorkspace: (...a: any[]) => mockGetMemberByUserAndWorkspace(...a),- },- machine: {- upsertMachine: (...a: any[]) => mockUpsertMachine(...a),- },- runtime: {- upsertAgentRuntime: (...a: any[]) => mockUpsertAgentRuntime(...a),- },- workspace: {- getWorkspace: vi.fn(() => Promise.resolve({ id: "sp_ws1", name: "Test Workspace" })),- },- },- BindWorkspaceRequestSchema: (await import("@alook/shared")).BindWorkspaceRequestSchema,- createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }),- }),- "@/lib/broadcast": {- broadcastToUser: (...a: any[]) => mockBroadcastToUser(...a),- broadcastToDaemon: (...a: any[]) => mockBroadcastToDaemon(...a),- },- "@/lib/cache": {- invalidate: (...a: any[]) => mockInvalidate(...a),- cacheKeys: {- machineToken: (t: string) => `mt:${t}`,- runtimeIds: (w: string, d: string) => `rt:${w}:${d}`,- allRuntimes: (w: string) => `runtimes:${w}`,- },- },- "@/lib/api/responses": {- runtimeToResponse: (rt: any) => ({ id: rt.id, provider: rt.provider }),- },- };-}--function makeReq(body: unknown, userId = "u1") {- const req = new NextRequest("http://localhost/api/machine-tokens/bind-workspace", {- method: "POST",- body: JSON.stringify(body),- headers: { "Content-Type": "application/json" },- });- // Auth context is injected by withAuth — we mock it via the module- return { req, userId };-}--describe("POST /api/machine-tokens/bind-workspace", () => {- 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(() => ({})),- withD1Retry: (fn: () => any) => fn(),- }));- vi.doMock("@/lib/broadcast", () => mocks["@/lib/broadcast"]);- vi.doMock("@/lib/cache", () => mocks["@/lib/cache"]);- 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"- );- });- vi.doMock("@/lib/middleware/auth", () => ({- withAuth: (handler: any) => (req: any) => handler(req, { userId: "u1", email: "[email protected]" }),- }));-- const { POST } = await import("./route");- return POST;- }-- const registeredToken = {- id: "mt_1",- userId: "u1",- token: "al_test123",- hostname: "TestMachine.local",- runtimesJson: JSON.stringify([{ type: "claude", version: "2.1.0" }]),- status: "registered",- };-- it("binds workspace and creates machine/runtime rows", async () => {- const POST = await loadRoute();-- mockGetRegisteredTokenForUser.mockResolvedValue(registeredToken);- mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "mem_1" });- mockActivateMachineToken.mockResolvedValue(undefined);- mockUpsertMachine.mockResolvedValue(undefined);- mockUpsertAgentRuntime.mockResolvedValue({ id: "r1", provider: "claude" });- mockBroadcastToUser.mockResolvedValue(undefined);- mockBroadcastToDaemon.mockResolvedValue({ sent: 1 });-- const req = new NextRequest("http://localhost/api/machine-tokens/bind-workspace", {- method: "POST",- body: JSON.stringify({ workspace_id: "sp_ws1" }),- headers: { "Content-Type": "application/json" },- });-- const res = await POST(req);- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.workspace_id).toBe("sp_ws1");- expect(body.runtimes).toHaveLength(1);-- expect(mockActivateMachineToken).toHaveBeenCalledWith(- expect.anything(),- "mt_1",- "sp_ws1",- );-- expect(mockUpsertMachine).toHaveBeenCalledWith(expect.anything(), {- daemonId: "TestMachine.local",- workspaceId: "sp_ws1",- deviceInfo: "TestMachine.local",- lastSeenAt: null,- });-- expect(mockBroadcastToDaemon).toHaveBeenCalledWith("TestMachine.local", {- type: "daemon.workspace_added",- workspaceId: "sp_ws1",- workspaceName: "Test Workspace",- token: "al_test123",- });- });-- it("returns 404 when no registered token", async () => {- const POST = await loadRoute();-- mockGetRegisteredTokenForUser.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/machine-tokens/bind-workspace", {- method: "POST",- body: JSON.stringify({ workspace_id: "sp_ws1" }),- headers: { "Content-Type": "application/json" },- });-- const res = await POST(req);- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("no registered token found");- });-- it("returns 403 when user is not workspace member", async () => {- const POST = await loadRoute();-- mockGetRegisteredTokenForUser.mockResolvedValue(registeredToken);- mockGetMemberByUserAndWorkspace.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/machine-tokens/bind-workspace", {- method: "POST",- body: JSON.stringify({ workspace_id: "sp_ws1" }),- headers: { "Content-Type": "application/json" },- });-- const res = await POST(req);- const body = await res.json();-- expect(res.status).toBe(403);- expect(body.error).toBe("not a member of this workspace");- });-- it("returns 409 when token exists but status is not registered (pending)", async () => {- const POST = await loadRoute();-- mockGetRegisteredTokenForUser.mockResolvedValue(null);- mockGetLatestTokenForUser.mockResolvedValue({ id: "mt_1", status: "pending" });-- const req = new NextRequest("http://localhost/api/machine-tokens/bind-workspace", {- method: "POST",- body: JSON.stringify({ workspace_id: "sp_ws1" }),- headers: { "Content-Type": "application/json" },- });-- const res = await POST(req);- const body = await res.json();-- expect(res.status).toBe(409);- expect(body.error).toContain("pending");- expect(body.error).toContain("expected \"registered\"");- });-- it("returns 409 when token exists but status is active", async () => {- const POST = await loadRoute();-- mockGetRegisteredTokenForUser.mockResolvedValue(null);- mockGetLatestTokenForUser.mockResolvedValue({ id: "mt_1", status: "active" });-- const req = new NextRequest("http://localhost/api/machine-tokens/bind-workspace", {- method: "POST",- body: JSON.stringify({ workspace_id: "sp_ws1" }),- headers: { "Content-Type": "application/json" },- });-- const res = await POST(req);- const body = await res.json();-- expect(res.status).toBe(409);- expect(body.error).toContain("active");- expect(body.error).toContain("expected \"registered\"");- });-- it("returns 404 when no tokens exist at all", async () => {- const POST = await loadRoute();-- mockGetRegisteredTokenForUser.mockResolvedValue(null);- mockGetLatestTokenForUser.mockResolvedValue(null);-- const req = new NextRequest("http://localhost/api/machine-tokens/bind-workspace", {- method: "POST",- body: JSON.stringify({ workspace_id: "sp_ws1" }),- headers: { "Content-Type": "application/json" },- });-- const res = await POST(req);- const body = await res.json();-- expect(res.status).toBe(404);- expect(body.error).toBe("no registered token found");- });-- it("returns 400 for invalid request body", async () => {- const POST = await loadRoute();-- const req = new NextRequest("http://localhost/api/machine-tokens/bind-workspace", {- method: "POST",- body: "not json",- headers: { "Content-Type": "application/json" },- });-- const res = await POST(req);- expect(res.status).toBe(400);- });-- it("returns 400 for missing workspace_id", async () => {- const POST = await loadRoute();-- const req = new NextRequest("http://localhost/api/machine-tokens/bind-workspace", {- method: "POST",- body: JSON.stringify({}),- headers: { "Content-Type": "application/json" },- });-- const res = await POST(req);- expect(res.status).toBe(400);- });-- it("succeeds even when broadcast throws (fire-and-forget)", async () => {- const POST = await loadRoute();-- mockGetRegisteredTokenForUser.mockResolvedValue(registeredToken);- mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "mem_1" });- mockActivateMachineToken.mockResolvedValue(undefined);- mockUpsertMachine.mockResolvedValue(undefined);- mockUpsertAgentRuntime.mockResolvedValue({ id: "r1", provider: "claude" });- mockBroadcastToUser.mockRejectedValue(new Error("ws down"));- mockBroadcastToDaemon.mockRejectedValue(new Error("ws down"));-- const req = new NextRequest("http://localhost/api/machine-tokens/bind-workspace", {- method: "POST",- body: JSON.stringify({ workspace_id: "sp_ws1" }),- headers: { "Content-Type": "application/json" },- });-- const res = await POST(req);- expect(res.status).toBe(200);- });-- it("binds the earliest registered token when multiple exist", async () => {- const POST = await loadRoute();-- const earliestToken = {- ...registeredToken,- id: "mt_earliest",- createdAt: "2025-01-01T00:00:00Z",- };- mockGetRegisteredTokenForUser.mockResolvedValue(earliestToken);- mockGetMemberByUserAndWorkspace.mockResolvedValue({ id: "mem_1" });- mockActivateMachineToken.mockResolvedValue(undefined);- mockUpsertMachine.mockResolvedValue(undefined);- mockUpsertAgentRuntime.mockResolvedValue({ id: "r1", provider: "claude" });- mockBroadcastToUser.mockResolvedValue(undefined);- mockBroadcastToDaemon.mockResolvedValue({ sent: 1 });-- const req = new NextRequest("http://localhost/api/machine-tokens/bind-workspace", {- method: "POST",- body: JSON.stringify({ workspace_id: "sp_ws1" }),- headers: { "Content-Type": "application/json" },- });-- const res = await POST(req);- expect(res.status).toBe(200);-- expect(mockActivateMachineToken).toHaveBeenCalledWith(- expect.anything(),- "mt_earliest",- "sp_ws1",- );- });-});diff --git a/src/web/src/app/api/machine-tokens/bind-workspace/route.ts b/src/web/src/app/api/machine-tokens/bind-workspace/route.tsdeleted file mode 100644index dc66611f3..000000000--- a/src/web/src/app/api/machine-tokens/bind-workspace/route.ts+++ /dev/null@@ -1,130 +0,0 @@-import { NextRequest } from "next/server";-import { getCloudflareContext } from "@opennextjs/cloudflare";-import { queries, createLogger, BindWorkspaceRequestSchema } from "@alook/shared";-import { getDb, withD1Retry } from "@/lib/db";-import { withAuth } from "@/lib/middleware/auth";-import { writeJSON } from "@/lib/middleware/helpers";-import { runtimeToResponse } from "@/lib/api/responses";-import { broadcastToUser, broadcastToDaemon } from "@/lib/broadcast";-import { invalidate, cacheKeys } from "@/lib/cache";--const log = createLogger({ service: "machine-tokens/bind-workspace" });--export const POST = withAuth(async (req: NextRequest, ctx) => {- let raw: unknown;- try {- raw = await req.json();- } catch {- return writeJSON({ error: "invalid request body" }, 400);- }-- const parsed = BindWorkspaceRequestSchema.safeParse(raw);- if (!parsed.success) {- return writeJSON({ error: "invalid payload", details: parsed.error.flatten() }, 400);- }-- const { workspace_id: workspaceId } = parsed.data;-- const { env } = await getCloudflareContext({ async: true });- const db = getDb((env as Env).DB);-- const token = await withD1Retry(() =>- queries.machineToken.getRegisteredTokenForUser(db, ctx.userId)- );- if (!token) {- const latest = await withD1Retry(() =>- queries.machineToken.getLatestTokenForUser(db, ctx.userId)- );- if (latest) {- return writeJSON(- { error: `token exists but status is "${latest.status}", expected "registered"` },- 409,- );- }- return writeJSON({ error: "no registered token found" }, 404);- }-- const membership = await withD1Retry(() =>- queries.member.getMemberByUserAndWorkspace(db, ctx.userId, workspaceId)- );- if (!membership) {- return writeJSON({ error: "not a member of this workspace" }, 403);- }-- await withD1Retry(() =>- queries.machineToken.activateMachineToken(db, token.id, workspaceId)- );-- const hostname = token.hostname || "unknown";- const daemonId = hostname;-- await withD1Retry(() =>- queries.machine.upsertMachine(db, {- daemonId,- workspaceId,- deviceInfo: hostname,- lastSeenAt: null,- })- );-- let runtimesData: Array<{ type: string; version?: string }> = [];- try {- runtimesData = token.runtimesJson ? JSON.parse(token.runtimesJson) : [];- } catch {- return writeJSON({ error: "corrupt runtimes data on token" }, 422);- }-- const results = [];- for (const rt of runtimesData) {- const result = await withD1Retry(() =>- queries.runtime.upsertAgentRuntime(db, {- workspaceId,- daemonId,- runtimeMode: "local",- provider: rt.type,- deviceInfo: hostname,- metadata: { version: rt.version || "" },- })- );- results.push({ ...result, machineLastSeenAt: null });- }-- await Promise.all([- invalidate(cacheKeys.machineToken(token.token)),- invalidate(cacheKeys.runtimeIds(workspaceId, daemonId)),- invalidate(cacheKeys.allRuntimes(workspaceId)),- ]);-- broadcastToUser(ctx.userId, {- type: "runtime.registered",- daemonId,- hostname,- workspaceId,- }).catch((err) => {- log.warn("broadcast after bind failed", {- userId: ctx.userId,- err: err instanceof Error ? err.message : String(err),- });- });-- const ws = await withD1Retry(() =>- queries.workspace.getWorkspace(db, workspaceId, ctx.userId)- );-- broadcastToDaemon(daemonId, {- type: "daemon.workspace_added",- workspaceId,- workspaceName: ws?.name || "Personal",- token: token.token,- }).catch((err) => {- log.warn("daemon push after bind failed", {- daemonId,- err: err instanceof Error ? err.message : String(err),- });- });-- return writeJSON({- workspace_id: workspaceId,- runtimes: results.map(runtimeToResponse),- });-});diff --git a/src/web/src/app/api/machine-tokens/route.test.ts b/src/web/src/app/api/machine-tokens/route.test.tsindex 5f264b0bb..48fef684c 100644--- a/src/web/src/app/api/machine-tokens/route.test.ts+++ b/src/web/src/app/api/machine-tokens/route.test.ts@@ -103,29 +103,8 @@ describe("POST /api/machine-tokens", () => {expect(mockGenerateMachineToken).not.toHaveBeenCalled();});- it("returns existing registered token if one exists (no pending)", async () => {- mockGetPendingMachineToken.mockResolvedValue(null);- const registered = { id: "mt0", token: "al_registered", name: "default", lastUsedAt: null, createdAt: "2025-01-01T00:00:00Z" };- mockGetRegisteredTokenForUser.mockResolvedValue(registered);-- const res = await POST(- new NextRequest("http://localhost/api/machine-tokens", {- method: "POST",- body: JSON.stringify({}),- headers: { "Content-Type": "application/json" },- })- );- const body = await res.json();-- expect(res.status).toBe(200);- expect(body.token).toBe("al_registered");- expect(mockCreateMachineToken).not.toHaveBeenCalled();- expect(mockGenerateMachineToken).not.toHaveBeenCalled();- });-it("creates pending token when none exists and returns 201", async () => {mockGetPendingMachineToken.mockResolvedValue(null);- mockGetRegisteredTokenForUser.mockResolvedValue(null);const mt = { id: "mt1", name: "my-token", lastUsedAt: null, createdAt: "2025-01-01T00:00:00Z" };mockCreateMachineToken.mockResolvedValue(mt);diff --git a/src/web/src/app/api/machine-tokens/route.ts b/src/web/src/app/api/machine-tokens/route.tsindex 0baeed2ed..cd501383e 100644--- a/src/web/src/app/api/machine-tokens/route.ts+++ b/src/web/src/app/api/machine-tokens/route.ts@@ -37,11 +37,6 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeJSON({ token: pending.token, ...machineTokenToResponse(pending) });}- const registered = await queries.machineToken.getRegisteredTokenForUser(db, ctx.userId);- if (registered) {- return writeJSON({ token: registered.token, ...machineTokenToResponse(registered) });- }-let name = "default";try {const body = (await req.json()) as { name?: string };diff --git a/src/web/src/app/api/machine-tokens/status/route.test.ts b/src/web/src/app/api/machine-tokens/status/route.test.tsindex d33697e52..be8f3a44c 100644--- a/src/web/src/app/api/machine-tokens/status/route.test.ts+++ b/src/web/src/app/api/machine-tokens/status/route.test.ts@@ -126,11 +126,10 @@ describe("GET /api/machine-tokens/status", () => {expect(body.daemon_online).toBe(false);});- it("does NOT return runtimes when token is already bound to a workspace", async () => {+ it("returns active status with workspace_id and hostname", async () => {mockGetLatestTokenForUser.mockResolvedValue({id: "mt_1", status: "active", workspaceId: "sp_ws1", hostname: "MacBook.local",lastUsedAt: new Date(Date.now() - 30_000).toISOString(),- runtimesJson: '[{"type":"claude","version":"4.0"}]',});const req = new NextRequest("http://localhost/api/machine-tokens/status");@@ -140,14 +139,14 @@ describe("GET /api/machine-tokens/status", () => {expect(res.status).toBe(200);expect(body.status).toBe("active");expect(body.workspace_id).toBe("sp_ws1");- expect(body.runtimes).toBeUndefined();+ expect(body.hostname).toBe("MacBook.local");+ expect(body.daemon_online).toBe(true);});- it("returns runtimes when token is NOT bound to a workspace", async () => {+ it("returns pending status with token value", async () => {mockGetLatestTokenForUser.mockResolvedValue({- id: "mt_1", status: "registered", workspaceId: null, hostname: "MacBook.local",- lastUsedAt: new Date(Date.now() - 30_000).toISOString(),- runtimesJson: '[{"type":"claude","version":"4.0"}]',+ id: "mt_1", status: "pending", workspaceId: "sp_ws1", hostname: null,+ lastUsedAt: null, token: "al_secret_pending",});const req = new NextRequest("http://localhost/api/machine-tokens/status");@@ -155,11 +154,9 @@ describe("GET /api/machine-tokens/status", () => {const body = await res.json();expect(res.status).toBe(200);- expect(body.status).toBe("registered");- expect(body.workspace_id).toBeUndefined();- expect(body.runtimes).toBeDefined();- expect(body.runtimes).toHaveLength(1);- expect(body.runtimes[0].type).toBe("claude");+ expect(body.status).toBe("pending");+ expect(body.token).toBe("al_secret_pending");+ expect(body.daemon_online).toBe(false);});});diff --git a/src/web/src/app/api/machine-tokens/status/route.ts b/src/web/src/app/api/machine-tokens/status/route.tsindex 3a3d605e7..8904c8cd1 100644--- a/src/web/src/app/api/machine-tokens/status/route.ts+++ b/src/web/src/app/api/machine-tokens/status/route.ts@@ -19,25 +19,11 @@ export const GET = withAuth(async (_req, ctx) => {? Date.now() - new Date(token.lastUsedAt).getTime() < DAEMON_ONLINE_THRESHOLD_MS: false;- let runtimes: Array<{ id: string; type: string; version: string; status: string }> | undefined;- if (token.runtimesJson && !token.workspaceId) {- try {- const parsed = JSON.parse(token.runtimesJson) as Array<{ type: string; version?: string }>;- runtimes = parsed.map((rt, i) => ({- id: `temp_${rt.type}_${i}`,- type: rt.type,- version: rt.version || "",- status: daemonOnline ? "online" : "offline",- }));- } catch {}- }-return writeJSON({status: token.status,token: token.status === "pending" ? token.token : undefined,workspace_id: token.workspaceId || undefined,hostname: token.hostname || undefined,daemon_online: daemonOnline,- runtimes,});});diff --git a/src/web/src/app/api/workspaces/[id]/onboarded/route.ts b/src/web/src/app/api/workspaces/[id]/onboarded/route.tsnew file mode 100644index 000000000..311b9daef--- /dev/null+++ b/src/web/src/app/api/workspaces/[id]/onboarded/route.ts@@ -0,0 +1,21 @@+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 { writeJSON } from "@/lib/middleware/helpers";++export const POST = withAuth(async (req: NextRequest, ctx) => {+ const { env } = await getCloudflareContext({ async: true });+ const db = getDb((env as Env).DB);++ const id = req.nextUrl.pathname.split("/").at(-2)!;++ const membership = await queries.member.getMemberByUserAndWorkspace(db, ctx.userId, id);+ if (!membership) {+ return writeJSON({ error: "not a member" }, 403);+ }++ await queries.workspace.markOnboarded(db, id);+ return writeJSON({ ok: true });+});diff --git a/src/web/src/app/api/workspaces/route.test.ts b/src/web/src/app/api/workspaces/route.test.tsindex 1ef335ffa..3122fd662 100644--- a/src/web/src/app/api/workspaces/route.test.ts+++ b/src/web/src/app/api/workspaces/route.test.ts@@ -110,7 +110,10 @@ describe("POST /api/workspaces", () => {expect(body.details).toContainEqual(expect.stringContaining("name"));});- it("returns 400 for missing slug", async () => {+ it("auto-generates slug when not provided", async () => {+ mockCreateWorkspace.mockResolvedValue({ id: "sp_1", name: "Test", slug: "auto-slug", onboarded: 0, createdAt: "2025-01-01T00:00:00Z", updatedAt: "2025-01-01T00:00:00Z" });+ mockCreateMember.mockResolvedValue({});+const req = new NextRequest("http://localhost/api/workspaces", {method: "POST",body: JSON.stringify({ name: "Test" }),@@ -118,10 +121,7 @@ describe("POST /api/workspaces", () => {});const res = await POST(req, {} as any);- expect(res.status).toBe(400);- const body = await res.json();- expect(body.error).toBe("validation error");- expect(body.details).toContainEqual(expect.stringContaining("slug"));+ expect(res.status).toBe(201);});it("retries with suffixed slug on duplicate and returns 201", async () => {diff --git a/src/web/src/app/api/workspaces/route.ts b/src/web/src/app/api/workspaces/route.tsindex 25fbde389..5fd48dcf7 100644--- a/src/web/src/app/api/workspaces/route.ts+++ b/src/web/src/app/api/workspaces/route.ts@@ -1,6 +1,6 @@import { NextRequest } from "next/server";import { getCloudflareContext } from "@opennextjs/cloudflare"-import { queries, isUniqueConstraintError, CreateWorkspaceRequestSchema } from "@alook/shared"+import { queries, isUniqueConstraintError, generateWorkspaceSlug, CreateWorkspaceRequestSchema } from "@alook/shared"import { getDb } from "@/lib/db"import { nanoid } from "nanoid"import { withAuth } from "@/lib/middleware/auth";@@ -23,7 +23,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {if (valErr) return valErr;const name = body.name.trim();- const slug = body.slug.toLowerCase().trim();+ const slug = body.slug?.trim() ? body.slug.toLowerCase().trim() : generateWorkspaceSlug();const suffixLengths = [4, 4, 4, 8, 8, 8, 16, 16, 16];let candidateSlug = slug;diff --git a/src/web/src/components/connect-machine-steps.tsx b/src/web/src/components/connect-machine-steps.tsxindex dcf876889..6d68e3b09 100644--- a/src/web/src/components/connect-machine-steps.tsx+++ b/src/web/src/components/connect-machine-steps.tsx@@ -5,24 +5,9 @@ import { Button } from "@/components/ui/button";import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";import { Check, Play, Loader2 } from "lucide-react";import { toast } from "sonner";-import { cliCmd, daemonStartCmd, getAppMode } from "@/lib/utils";+import { cliCmd, getAppMode } from "@/lib/utils";import { isTauri, tauriInvoke } from "@alook/shared";-function StepIndicator({ step, completed }: { step: number; completed: boolean }) {- if (completed) {- return (- <span className="flex items-center justify-center size-5 rounded-full bg-emerald-500 text-white transition-all duration-300">- <Check className="size-3" strokeWidth={3} />- </span>- );- }- return (- <span className="flex items-center justify-center size-5 rounded-full bg-foreground text-background text-xs font-semibold">- {step}- </span>- );-}-export function ConnectMachineSteps({generatedToken,generatingToken,@@ -39,9 +24,11 @@ export function ConnectMachineSteps({const hasTriggered = useRef(false);const mode = getAppMode();const isDesktopApp = mode === "desktop";- const [executing, setExecuting] = useState<"register" | "daemon" | null>(null);+ const [executing, setExecuting] = useState(false);const [cliPrefix, setCliPrefix] = useState<string | null>(null);+ const connected = registered && daemonOnline;+useEffect(() => {if (isDesktopApp && isTauri()) {tauriInvoke<{ command: string; is_dev: boolean }>("get_cli_info")@@ -57,184 +44,89 @@ export function ConnectMachineSteps({}}, [generatedToken, generatingToken, onGenerateToken]);+ const command = `${cliCmd()} register --token ${generatedToken}`;+const copyRegister = () => {- navigator.clipboard.writeText(`${cliCmd()} register --token ${generatedToken}`);+ navigator.clipboard.writeText(command);toast.success("Copied to clipboard");};const executeRegister = async () => {if (!isTauri()) return;- setExecuting("register");+ setExecuting(true);try {const result = await tauriInvoke<{ success: boolean; message: string }>("register_cli", { token: generatedToken });if (result.success) {- toast.success("CLI registered successfully");+ toast.success("Registered successfully");} else {toast.error(result.message || "Registration failed");}} catch {toast.error("Failed to execute registration");} finally {- setExecuting(null);+ setExecuting(false);}};- const daemonCmd = daemonStartCmd();-- const copyDaemon = () => {- navigator.clipboard.writeText(daemonCmd);- toast.success("Copied to clipboard");- };-- const executeDaemonStart = async () => {- if (!isTauri()) return;- setExecuting("daemon");- try {- const result = await tauriInvoke<{ success: boolean; message: string }>("daemon_start");- if (result.success) {- toast.success("Daemon started");- } else {- toast.error(result.message || "Failed to start daemon");- }- } catch {- toast.error("Failed to start daemon");- } finally {- setExecuting(null);- }- };+ if (connected) {+ return (+ <div className="flex items-center gap-2 text-sm text-emerald-600">+ <Check className="size-4" />+ Computer connected+ </div>+ );+ }return (- <div className="space-y-6">- {/* Step 1 */}- <div className="space-y-2">- <p className="text-sm font-medium flex items-center gap-2">- <StepIndicator step={1} completed={registered} />- Register your CLI- {registered && <span className="text-xs text-emerald-500 font-normal">Done</span>}- </p>- {!registered && (- <>- <p className="text-xs text-muted-foreground pl-7">- {isDesktopApp- ? "Click to register your machine with Alook."- : "Run this in your terminal to link your machine."}- </p>- {generatingToken ? (- <div className="pl-7">- <div className="rounded-md bg-muted p-2.5 font-mono text-xs text-muted-foreground animate-pulse">- Generating token...- </div>- </div>- ) : generatedToken ? (- <div className="pl-7 space-y-2">- {isDesktopApp ? (- <Button- size="sm"- onClick={executeRegister}- disabled={executing === "register"}- className="w-full"- title={cliPrefix ? `${cliPrefix} register --token <token>` : undefined}- >- {executing === "register" ? (- <><Loader2 className="size-3 animate-spin mr-1" /> Registering...</>- ) : (- <><Play className="size-3 mr-1" /> Register CLI</>- )}- </Button>- ) : (- <>- <Tooltip>- <TooltipTrigger- render={- <div- className="rounded-md bg-muted p-2.5 font-mono text-xs text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors break-all"- onClick={copyRegister}- />- }- >- {cliCmd()} register --token{" "}- <span className="text-foreground/70">- {generatedToken}- </span>- </TooltipTrigger>- <TooltipContent>Click to copy</TooltipContent>- </Tooltip>- <Button- size="sm"+ <div className="space-y-3">+ <p className="text-sm font-medium">Connect a computer</p>+ <p className="text-xs text-muted-foreground">+ {isDesktopApp+ ? "Click to register your machine with Alook."+ : "Run this in your terminal to link your machine."}+ </p>+ {generatingToken ? (+ <div className="rounded-md bg-muted p-2.5 font-mono text-xs text-muted-foreground animate-pulse">+ Generating token...+ </div>+ ) : generatedToken ? (+ <div className="space-y-2">+ {isDesktopApp ? (+ <Button+ size="sm"+ onClick={executeRegister}+ disabled={executing}+ className="w-full"+ title={cliPrefix ? `${cliPrefix} register --token <token>` : undefined}+ >+ {executing ? (+ <><Loader2 className="size-3 animate-spin mr-1" /> Registering...</>+ ) : (+ <><Play className="size-3 mr-1" /> Register</>+ )}+ </Button>+ ) : (+ <>+ <Tooltip>+ <TooltipTrigger+ render={+ <div+ className="rounded-md bg-muted p-2.5 font-mono text-xs text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors break-all"onClick={copyRegister}- className="w-full"- >- Copy Command- </Button>- </>- )}- </div>- ) : null}- </>- )}- </div>-- {/* Step 2 */}- <div- 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={daemonOnline} />- Start the daemon- {daemonOnline && <span className="text-xs text-emerald-500 font-normal">Done</span>}- </p>- {!daemonOnline && (- <>- <p className="text-xs text-muted-foreground pl-7">- The daemon connects your local agents to Alook.- </p>- {isDesktopApp ? (- <div className="pl-7">- <Button- size="sm"- onClick={executeDaemonStart}- disabled={executing === "daemon"}- className="w-full"- title={cliPrefix ? `${cliPrefix} daemon start` : undefined}+ />+ }>- {executing === "daemon" ? (- <><Loader2 className="size-3 animate-spin mr-1" /> Starting...</>- ) : (- <><Play className="size-3 mr-1" /> Start Daemon</>- )}- </Button>- </div>- ) : (- <>- <Tooltip>- <TooltipTrigger- render={- <div- className="ml-7 rounded-md bg-muted p-2.5 font-mono text-xs text-muted-foreground cursor-pointer hover:bg-muted/80 transition-colors"- onClick={copyDaemon}- />- }- >- {daemonCmd}- </TooltipTrigger>- <TooltipContent>Click to copy</TooltipContent>- </Tooltip>- {registered && (- <div className="pl-7">- <Button- size="sm"- onClick={copyDaemon}- className="w-full"- >- Copy Command- </Button>- </div>- )}- </>- )}- </>- )}- </div>+ {command}+ </TooltipTrigger>+ <TooltipContent>Click to copy</TooltipContent>+ </Tooltip>+ <Button size="sm" onClick={copyRegister} className="w-full">+ Copy Command+ </Button>+ </>+ )}+ </div>+ ) : null}</div>);}diff --git a/src/web/src/lib/api.ts b/src/web/src/lib/api.tsindex 22930a507..26f44216a 100644--- a/src/web/src/lib/api.ts+++ b/src/web/src/lib/api.ts@@ -443,7 +443,7 @@ export const createMachineToken = (name?: string, workspaceId?: string) =>);export const getMachineTokenStatus = () =>- apiFetch<{ status: "pending" | "registered" | "active" | null; token?: string; workspace_id?: string; hostname?: string; daemon_online?: boolean; runtimes?: Array<{ id: string; type: string; version: string; status: string }> }>(+ apiFetch<{ status: "pending" | "active" | null; token?: string; workspace_id?: string; hostname?: string; daemon_online?: boolean }>("/api/machine-tokens/status",);diff --git a/src/web/src/lib/api/responses.test.ts b/src/web/src/lib/api/responses.test.tsindex 043f9ef5c..0158c10db 100644--- a/src/web/src/lib/api/responses.test.ts+++ b/src/web/src/lib/api/responses.test.ts@@ -310,10 +310,10 @@ describe("UserResponse shape", () => {});describe("WorkspaceResponse shape", () => {- it("has expected keys: id, name, slug, created_at, updated_at", () => {+ it("has expected keys: id, name, slug, onboarded, created_at, updated_at", () => {const res = workspaceToResponse({ id: "w1", name: "WS", slug: "ws", ...baseFields() });expect(Object.keys(res).sort()).toEqual(- ["created_at", "id", "name", "slug", "updated_at"]+ ["created_at", "id", "name", "onboarded", "slug", "updated_at"]);});});@@ -408,9 +408,9 @@ describe("MessageResponse shape", () => {});describe("MachineTokenResponse shape", () => {- it("has expected keys: id, name, last_used_at, created_at", () => {- const res = machineTokenToResponse({ id: "mt1", name: "Token", lastUsedAt: ts, createdAt: ts });- expect(Object.keys(res).sort()).toEqual(["created_at", "id", "last_used_at", "name"]);+ it("has expected keys: id, name, status, last_used_at, created_at", () => {+ const res = machineTokenToResponse({ id: "mt1", name: "Token", status: "active", lastUsedAt: ts, createdAt: ts });+ expect(Object.keys(res).sort()).toEqual(["created_at", "id", "last_used_at", "name", "status"]);});});diff --git a/src/web/src/lib/api/responses.ts b/src/web/src/lib/api/responses.tsindex 3170f8af8..fdf2d1d53 100644--- a/src/web/src/lib/api/responses.ts+++ b/src/web/src/lib/api/responses.ts@@ -22,6 +22,7 @@ export function workspaceToResponse(w: any) {id: w.id,name: w.name,slug: w.slug,+ onboarded: !!w.onboarded,created_at: formatTimestamp(w.createdAt),updated_at: formatTimestamp(w.updatedAt),};@@ -199,6 +200,7 @@ export function machineTokenToResponse(mt: any) {return {id: mt.id,name: mt.name,+ status: mt.status,last_used_at: formatTimestampNullable(mt.lastUsedAt),created_at: formatTimestamp(mt.createdAt),};diff --git a/src/web/src/test/e2e/device-code.test.ts b/src/web/src/test/e2e/device-code.test.tsindex 802c0f175..9f6668af6 100644--- a/src/web/src/test/e2e/device-code.test.ts+++ b/src/web/src/test/e2e/device-code.test.ts@@ -254,7 +254,7 @@ describe("device-code-flow workspace reuse", () => {const machineToken = mtData.token as stringexpect(machineToken).toBeTruthy()- // Activate with the machine token (transitions to "registered", no workspace binding)+ // Activate with the machine token (creates machine + runtime, token becomes active)const activateRes = await fetch(`${APP_URL}/api/machine-tokens/activate`, {method: "POST",headers: { "Content-Type": "application/json" },@@ -266,9 +266,10 @@ describe("device-code-flow workspace reuse", () => {})expect(activateRes.status).toBe(200)const activateBody = await activateRes.json() as Record<string, unknown>- expect(activateBody.token_status).toBe("registered")+ expect(activateBody.workspace_id).toBe(originalWorkspaceId)+ expect(activateBody.daemon_id).toBe("e2e-test-host")- // Verify user still has exactly 1 workspace (activate no longer creates workspaces)+ // Verify user still has exactly 1 workspace (activate uses existing workspace from token)const wsAfterRes = await sessionRequest("/api/workspaces", wsCookie)const wsAfter = await wsAfterRes.json() as { id: string }[]expect(wsAfter).toHaveLength(1)diff --git a/src/web/src/test/e2e/machine-token.test.ts b/src/web/src/test/e2e/machine-token.test.tsindex f24bdd4c2..059d91ab4 100644--- a/src/web/src/test/e2e/machine-token.test.ts+++ b/src/web/src/test/e2e/machine-token.test.ts@@ -83,11 +83,11 @@ describe("machine tokens", () => {})describe("machine token activation (decoupled — no workspace creation)", () => {- it("activation sets token to registered status and stores hostname/runtimes", async () => {+ it("activation sets token to active status and creates machine/runtime rows", async () => {const tokenId = `mt_${randomUUID().replace(/-/g, "").slice(0, 21)}`const rawToken = `al_${randomUUID().replace(/-/g, "")}`const now = new Date().toISOString()- sqlRun(`INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, created_at) VALUES (?, ?, NULL, ?, ?, ?, ?)`, tokenId, seed.userId, rawToken, 'activate-test', 'pending', now)+ sqlRun(`INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)`, tokenId, seed.userId, seed.workspaceId, rawToken, 'activate-test', 'pending', now)const APP_URL = process.env.APP_URL ?? "http://localhost:3000"const res = await fetchWithRetry(`${APP_URL}/api/machine-tokens/activate`, {@@ -100,21 +100,18 @@ describe("machine token activation (decoupled — no workspace creation)", () =>}),})expect(res.status).toBe(200)- const data = await res.json() as { daemon_id: string; token_status: string }+ const data = await res.json() as { daemon_id: string; workspace_id: string; runtimes: Array<{ id: string }> }- expect(data.token_status).toBe("registered")expect(data.daemon_id).toBe("e2e-activate-machine")+ expect(data.workspace_id).toBe(seed.workspaceId)+ expect(data.runtimes.length).toBeGreaterThan(0)// Verify DB state- const rows = sqlQuery<{ status: string; hostname: string; runtimes_json: string }>(- `SELECT status, hostname, runtimes_json FROM machine_token WHERE id = ?`, tokenId,+ const rows = sqlQuery<{ status: string; hostname: string }>(+ `SELECT status, hostname FROM machine_token WHERE id = ?`, tokenId,)- expect(rows[0]!.status).toBe("registered")+ expect(rows[0]!.status).toBe("active")expect(rows[0]!.hostname).toBe("e2e-activate-machine")- expect(JSON.parse(rows[0]!.runtimes_json)).toEqual([{ type: "claude", version: "4.0" }])-- // No workspace should be created- expect(data).not.toHaveProperty("workspace_id")})it("activation rejects already-used token with 409", async () => {diff --git a/src/web/src/test/e2e/onboard-flow.test.ts b/src/web/src/test/e2e/onboard-flow.test.tsindex 507768c1d..f3fa91e8e 100644--- a/src/web/src/test/e2e/onboard-flow.test.ts+++ b/src/web/src/test/e2e/onboard-flow.test.ts@@ -1,13 +1,10 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"+import { describe, it, expect, beforeAll } from "vitest"import { randomUUID } from "crypto"-import { signUp, signIn, sessionRequest, tokenRequest, sqlRun, sqlQuery, fetchWithRetry } from "@alook/test-utils"+import { signUp, signIn, sessionRequest, tokenRequest, sqlRun, sqlQuery } from "@alook/test-utils"const APP_URL = process.env.APP_URL ?? "http://localhost:3000"const TEST_CLIENT_ID = "e2e-test-client"-function genTokenId() { return `mt_${randomUUID().replace(/-/g, "").slice(0, 21)}` }-function genToken() { return `al_${randomUUID().replace(/-/g, "")}` }-async function deviceCodeLogin(sessionCookie: string): Promise<string> {const codeRes = await fetch(`${APP_URL}/api/auth/device/code`, {method: "POST",@@ -38,21 +35,16 @@ async function deviceCodeLogin(sessionCookie: string): Promise<string> {return tokenData.access_token}-describe("onboard flow — user scenarios", () => {+describe("onboard flow — simplified model", () => {- // ─────────────────────────────────────────────────────────────────────────- // Scenario 1: Brand-new user complete onboard flow- // login → session token stored → no workspace → daemon standby →- // workspace init → create workspace + bind → studio success- // ─────────────────────────────────────────────────────────────────────────+ // Scenario 1: New user → create workspace → get token → activate → runtimes availabledescribe("Scenario 1: New user complete onboard flow", () => {const email = `e2e_onboard_new_${randomUUID().slice(0, 8)}@test.local`const password = "TestPass123!"let sessionCookie: stringlet accessToken: string- let machineToken: string- let machineTokenId: stringlet workspaceId: string+ let machineToken: stringbeforeAll(async () => {await signUp(email, password, "E2E New User")@@ -62,537 +54,112 @@ describe("onboard flow — user scenarios", () => {it("login via device code auth stores session token", async () => {accessToken = await deviceCodeLogin(sessionCookie)expect(accessToken).toBeTruthy()-- // Verify session token worksconst meRes = await tokenRequest("/api/me", accessToken)expect(meRes.status).toBe(200)- const me = await meRes.json() as { email: string }- expect(me.email).toBe(email)})- it("new user has no workspaces (only machine token, status: registered)", async () => {- // Verify no workspaces exist+ it("new user has no workspaces initially", async () => {const wsRes = await sessionRequest("/api/workspaces", sessionCookie)- expect(wsRes.status).toBe(200)const workspaces = await wsRes.json() as Array<{ id: string }>expect(workspaces).toHaveLength(0)-- // Create machine token (no workspace_id since none exist)- const mtRes = await tokenRequest("/api/machine-tokens", accessToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "new-user-device" }),- })- expect(mtRes.status).toBe(201)- const mtData = await mtRes.json() as { token: string; id: string }- machineToken = mtData.token- machineTokenId = mtData.id-- // Activate → registered (no workspace binding yet)- const activateRes = await fetchWithRetry(`${APP_URL}/api/machine-tokens/activate`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- token: machineToken,- hostname: "NewUserHost.local",- runtimes: [{ type: "claude", version: "4.0" }],- }),- })- expect(activateRes.status).toBe(200)- const activateData = await activateRes.json() as { token_status: string }- expect(activateData.token_status).toBe("registered")- })-- it("daemon start in standby mode (no workspace)", async () => {- const res = await tokenRequest("/api/daemon/register", machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- daemon_id: "new-user-daemon",- device_name: "NewUserHost.local",- cli_version: "1.0.0",- runtimes: [{ type: "claude", version: "4.0" }],- }),- })- expect(res.status).toBe(200)- const data = await res.json() as { standby: boolean; runtimes: unknown[] }- expect(data.standby).toBe(true)- expect(data.runtimes).toEqual([])})- it("workspace init creates new workspace + bind → runtimes available", async () => {- // Create workspace- const wsRes = await sessionRequest("/api/workspaces", sessionCookie, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "My First Company", slug: `first-co-${randomUUID().slice(0, 8)}` }),- })- expect(wsRes.status).toBe(201)- const wsData = await wsRes.json() as { id: string; name: string }- expect(wsData.id).toMatch(/^sp_/)- workspaceId = wsData.id-- // Bind machine token to workspace- const bindRes = await tokenRequest("/api/machine-tokens/bind-workspace", machineToken, {+ it("create workspace", async () => {+ const res = await sessionRequest("/api/workspaces", sessionCookie, {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ workspace_id: workspaceId }),+ body: JSON.stringify({ name: "Personal", slug: `e2e-${randomUUID().slice(0, 8)}` }),})- expect(bindRes.status).toBe(200)- const bindData = await bindRes.json() as { workspace_id: string; runtimes: Array<{ id: string }> }- expect(bindData.workspace_id).toBe(workspaceId)- expect(bindData.runtimes.length).toBeGreaterThanOrEqual(1)- })-- it("config updated: workspace entry has id (not null) and active status", async () => {- // Verify token is now active with workspace- const statusRes = await tokenRequest("/api/machine-tokens/status", machineToken)- expect(statusRes.status).toBe(200)- const statusData = await statusRes.json() as { status: string; workspace_id: string }- expect(statusData.status).toBe("active")- expect(statusData.workspace_id).toBe(workspaceId)+ expect(res.status).toBe(201)+ const body = await res.json() as { id: string }+ workspaceId = body.id+ expect(workspaceId).toBeTruthy()})- afterAll(() => {- try {- sqlRun(`DELETE FROM agent_runtime WHERE daemon_id = 'NewUserHost.local' AND workspace_id = ?`, workspaceId)- sqlRun(`DELETE FROM machine WHERE daemon_id = 'NewUserHost.local' AND workspace_id = ?`, workspaceId)- sqlRun(`DELETE FROM machine_token WHERE id = ?`, machineTokenId)- sqlRun(`DELETE FROM member WHERE workspace_id = ?`, workspaceId)- sqlRun(`DELETE FROM workspace WHERE id = ?`, workspaceId)- sqlRun(`DELETE FROM "deviceCode" WHERE "userId" IN (SELECT id FROM "user" WHERE email = ?)`, email)- sqlRun(`DELETE FROM "session" WHERE "userId" IN (SELECT id FROM "user" WHERE email = ?)`, email)- sqlRun(`DELETE FROM "account" WHERE "userId" IN (SELECT id FROM "user" WHERE email = ?)`, email)- sqlRun(`DELETE FROM "user" WHERE email = ?`, email)- } catch { /* ignore cleanup errors */ }- })- })-- // ─────────────────────────────────────────────────────────────────────────- // Scenario 2: Existing user, new computer- // Server already has workspace + agents.- // login → session token + workspace syncs to config (status: active)- // daemon start → normal registration (not standby)- // workspace init → server has workspace with agents → create new workspace + bind- // ─────────────────────────────────────────────────────────────────────────- describe("Scenario 2: Existing user, new computer", () => {- const email = `e2e_onboard_old_${randomUUID().slice(0, 8)}@test.local`- const password = "TestPass123!"- let sessionCookie: string- let accessToken: string- let existingWorkspaceId: string- let newWorkspaceId: string- let machineToken: string- let machineTokenId: string-- beforeAll(async () => {- await signUp(email, password, "E2E Existing User")- sessionCookie = await signIn(email, password)-- // Create existing workspace (as if user already has one from web)- const wsRes = await sessionRequest("/api/workspaces", sessionCookie, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "Existing Co", slug: `existing-co-${randomUUID().slice(0, 8)}` }),- })- const wsData = await wsRes.json() as { id: string }- existingWorkspaceId = wsData.id-- // Add an agent to the existing workspace (simulates existing setup)- const userId = sqlQuery<{ id: string }>(`SELECT id FROM "user" WHERE email = ?`, email)[0]!.id- const now = new Date().toISOString()- const rtId = `rt_e2e_${Date.now()}`- sqlRun(- `INSERT INTO agent_runtime (id, workspace_id, daemon_id, runtime_mode, provider, status, device_info, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,- rtId, existingWorkspaceId, "old-daemon", "local", "claude", "online", "old-device", now, now,- )- sqlRun(- `INSERT INTO agent (id, workspace_id, name, runtime_id, email_handle, owner_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,- `ag_e2e_${Date.now()}`, existingWorkspaceId, "Existing Agent", rtId, "existing", userId, now, now,+ it("create machine token for workspace", async () => {+ const res = await sessionRequest(+ `/api/machine-tokens?workspace_id=${workspaceId}`,+ sessionCookie,+ { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "cli" }) },)+ expect(res.status).toBe(201)+ const body = await res.json() as { token: string; status: string }+ machineToken = body.token+ expect(body.status).toBe("pending")})- it("login syncs existing workspace to config (status: active)", async () => {- accessToken = await deviceCodeLogin(sessionCookie)-- // After login, user's workspace list includes the existing workspace- const wsListRes = await sessionRequest("/api/workspaces", sessionCookie)- expect(wsListRes.status).toBe(200)- const workspaces = await wsListRes.json() as Array<{ id: string; name: string }>- expect(workspaces.length).toBeGreaterThanOrEqual(1)- expect(workspaces.some(w => w.id === existingWorkspaceId)).toBe(true)- })-- it("create machine token bound to existing workspace", async () => {- const mtRes = await tokenRequest(- `/api/machine-tokens?workspace_id=${existingWorkspaceId}`,- accessToken,- { method: "POST", headers: { "Content-Type": "application/json" } },- )- expect(mtRes.status).toBeLessThan(300)- const mtData = await mtRes.json() as { token: string; id: string }- machineToken = mtData.token- machineTokenId = mtData.id-- // Activate- const activateRes = await fetchWithRetry(`${APP_URL}/api/machine-tokens/activate`, {+ it("activate creates machine + runtime rows", async () => {+ const res = await fetch(`${APP_URL}/api/machine-tokens/activate`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({token: machineToken,- hostname: "NewPC.local",- runtimes: [{ type: "claude", version: "4.0" }],- }),- })- expect(activateRes.status).toBe(200)- })-- it("daemon start → normal registration (not standby) since workspace exists", async () => {- // Bind to workspace first- const bindRes = await tokenRequest("/api/machine-tokens/bind-workspace", machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ workspace_id: existingWorkspaceId }),- })- expect(bindRes.status).toBe(200)-- // Register daemon — should NOT be standby since token now has workspace- const res = await tokenRequest("/api/daemon/register", machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- daemon_id: "NewPC.local",- device_name: "NewPC.local",- cli_version: "1.0.0",- runtimes: [{ type: "claude", version: "4.0" }],+ hostname: "E2EMachine.local",+ runtimes: [{ type: "claude", version: "4.0.0" }],}),})expect(res.status).toBe(200)- const data = await res.json() as { standby?: boolean; runtimes: Array<{ id: string }> }- expect(data.standby).toBeFalsy()- expect(data.runtimes.length).toBeGreaterThanOrEqual(1)+ const body = await res.json() as { workspace_id: string; runtimes: Array<{ id: string }> }+ expect(body.workspace_id).toBe(workspaceId)+ expect(body.runtimes.length).toBeGreaterThan(0)})- it("workspace init → existing workspace has agents → create new workspace + bind → studio succeeds", async () => {- // Verify existing workspace has agents- const agentsRes = await tokenRequest(- `/api/agents?workspace_id=${existingWorkspaceId}`,- machineToken,- )- expect(agentsRes.status).toBe(200)- const existingAgents = await agentsRes.json() as Array<{ id: string }>- expect(existingAgents.length).toBeGreaterThan(0)-- // CLI logic: workspace has agents → create new workspace instead- const newWsRes = await tokenRequest("/api/workspaces", machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "New Setup", slug: `new-setup-${randomUUID().slice(0, 8)}` }),- })- expect(newWsRes.status).toBe(201)- const newWs = await newWsRes.json() as { id: string; name: string }- expect(newWs.id).toBeTruthy()- expect(newWs.id).not.toBe(existingWorkspaceId)- newWorkspaceId = newWs.id-- // Create runtime in new workspace for studio- const now = new Date().toISOString()- const rtId = `rt_e2e_new_${Date.now()}`- sqlRun(- `INSERT INTO agent_runtime (id, workspace_id, daemon_id, runtime_mode, provider, status, device_info, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,- rtId, newWorkspaceId, "NewPC.local", "local", "claude", "online", "new-device", now, now,- )-- // Create studio in new workspace- const studioRes = await tokenRequest(- `/api/studios?workspace_id=${newWorkspaceId}`,- machineToken,- {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- name: "Fresh Start",- members: [- {- role: "leader",- runtime_id: rtId,- instructions: "You are the new leader",- },- ],- }),- },- )- expect(studioRes.status).toBe(201)- const studioData = await studioRes.json() as { agents: Array<{ id: string }> }- expect(studioData.agents.length).toBe(1)- })-- afterAll(() => {- try {- // Clean new workspace- if (newWorkspaceId) {- sqlRun(`DELETE FROM agent_link WHERE workspace_id = ?`, newWorkspaceId)- sqlRun(`DELETE FROM agent_whitelist WHERE agent_id IN (SELECT id FROM agent WHERE workspace_id = ?)`, newWorkspaceId)- sqlRun(`DELETE FROM agent WHERE workspace_id = ?`, newWorkspaceId)- sqlRun(`DELETE FROM agent_runtime WHERE workspace_id = ?`, newWorkspaceId)- sqlRun(`DELETE FROM machine WHERE workspace_id = ?`, newWorkspaceId)- sqlRun(`DELETE FROM member WHERE workspace_id = ?`, newWorkspaceId)- sqlRun(`DELETE FROM workspace WHERE id = ?`, newWorkspaceId)- }- // Clean existing workspace- sqlRun(`DELETE FROM agent_link WHERE workspace_id = ?`, existingWorkspaceId)- sqlRun(`DELETE FROM agent_whitelist WHERE agent_id IN (SELECT id FROM agent WHERE workspace_id = ?)`, existingWorkspaceId)- sqlRun(`DELETE FROM agent WHERE workspace_id = ?`, existingWorkspaceId)- sqlRun(`DELETE FROM agent_runtime WHERE workspace_id = ?`, existingWorkspaceId)- sqlRun(`DELETE FROM machine WHERE workspace_id = ?`, existingWorkspaceId)- sqlRun(`DELETE FROM machine_token WHERE id = ?`, machineTokenId)- sqlRun(`DELETE FROM member WHERE workspace_id = ?`, existingWorkspaceId)- sqlRun(`DELETE FROM workspace WHERE id = ?`, existingWorkspaceId)- sqlRun(`DELETE FROM "deviceCode" WHERE "userId" IN (SELECT id FROM "user" WHERE email = ?)`, email)- sqlRun(`DELETE FROM "session" WHERE "userId" IN (SELECT id FROM "user" WHERE email = ?)`, email)- sqlRun(`DELETE FROM "account" WHERE "userId" IN (SELECT id FROM "user" WHERE email = ?)`, email)- sqlRun(`DELETE FROM "user" WHERE email = ?`, email)- } catch { /* ignore cleanup errors */ }- })- })-- // ─────────────────────────────────────────────────────────────────────────- // Scenario 3: Existing user, same computer (config already exists)- // login → checkExistingAuth valid → "Already logged in"- // workspace init → resolveClientOpts gets workspace_id → normal logic works- // ─────────────────────────────────────────────────────────────────────────- describe("Scenario 3: Existing user, same computer (already configured)", () => {- const email = `e2e_onboard_same_${randomUUID().slice(0, 8)}@test.local`- const password = "TestPass123!"- let sessionCookie: string- let accessToken: string- let workspaceId: string- let machineToken: string- let machineTokenId: string-- beforeAll(async () => {- await signUp(email, password, "E2E Same PC User")- sessionCookie = await signIn(email, password)-- // Setup: workspace + machine token already exist and are active- const wsRes = await sessionRequest("/api/workspaces", sessionCookie, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "Same PC Co", slug: `same-pc-co-${randomUUID().slice(0, 8)}` }),- })- const wsData = await wsRes.json() as { id: string }- workspaceId = wsData.id-- // Simulate first-time login + activation- accessToken = await deviceCodeLogin(sessionCookie)- const mtRes = await tokenRequest(- `/api/machine-tokens?workspace_id=${workspaceId}`,- accessToken,- { method: "POST", headers: { "Content-Type": "application/json" } },- )- const mtData = await mtRes.json() as { token: string; id: string }- machineToken = mtData.token- machineTokenId = mtData.id-- await fetchWithRetry(`${APP_URL}/api/machine-tokens/activate`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- token: machineToken,- hostname: "SamePC.local",- runtimes: [{ type: "claude", version: "4.0" }],- }),- })-- // Bind to workspace- await tokenRequest("/api/machine-tokens/bind-workspace", machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ workspace_id: workspaceId }),- })- })-- it("checkExistingAuth: session token still valid → workspaces return data", async () => {- // Simulates what checkExistingAuth does: verify auth is still valid- const wsRes = await tokenRequest("/api/workspaces", accessToken)- expect(wsRes.status).toBe(200)- const workspaces = await wsRes.json() as Array<{ id: string }>- expect(workspaces.length).toBeGreaterThanOrEqual(1)- expect(workspaces.some(w => w.id === workspaceId)).toBe(true)- })-- it("workspace init: resolveClientOpts gets workspace_id → existing logic works (no regression)", async () => {- // Machine token is already active and bound to workspace- const statusRes = await tokenRequest("/api/machine-tokens/status", machineToken)- expect(statusRes.status).toBe(200)- const statusData = await statusRes.json() as { status: string; workspace_id: string }- expect(statusData.status).toBe("active")- expect(statusData.workspace_id).toBe(workspaceId)-- // Daemon register with workspace works normally- const regRes = await tokenRequest("/api/daemon/register", machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- daemon_id: "SamePC.local",- device_name: "SamePC.local",- cli_version: "1.0.0",- runtimes: [{ type: "claude", version: "4.0" }],- }),- })- expect(regRes.status).toBe(200)- const regData = await regRes.json() as { standby?: boolean; runtimes: Array<{ id: string }> }- expect(regData.standby).toBeFalsy()- expect(regData.runtimes.length).toBeGreaterThanOrEqual(1)- })-- afterAll(() => {- try {- sqlRun(`DELETE FROM agent_runtime WHERE daemon_id = 'SamePC.local' AND workspace_id = ?`, workspaceId)- sqlRun(`DELETE FROM machine WHERE daemon_id = 'SamePC.local' AND workspace_id = ?`, workspaceId)- sqlRun(`DELETE FROM machine_token WHERE id = ?`, machineTokenId)- sqlRun(`DELETE FROM member WHERE workspace_id = ?`, workspaceId)- sqlRun(`DELETE FROM workspace WHERE id = ?`, workspaceId)- sqlRun(`DELETE FROM "deviceCode" WHERE "userId" IN (SELECT id FROM "user" WHERE email = ?)`, email)- sqlRun(`DELETE FROM "session" WHERE "userId" IN (SELECT id FROM "user" WHERE email = ?)`, email)- sqlRun(`DELETE FROM "account" WHERE "userId" IN (SELECT id FROM "user" WHERE email = ?)`, email)- sqlRun(`DELETE FROM "user" WHERE email = ?`, email)- } catch { /* ignore cleanup errors */ }+ it("runtimes are now available for the workspace", async () => {+ const res = await sessionRequest(`/api/runtimes?workspace_id=${workspaceId}`, sessionCookie)+ expect(res.status).toBe(200)+ const runtimes = await res.json() as Array<{ id: string; status: string }>+ expect(runtimes.length).toBeGreaterThan(0)})})- // ─────────────────────────────────────────────────────────────────────────- // Scenario 4: Workspace deleted on server- // Local config has workspace A → login syncs → server deleted A →- // workspace init → skip deleted workspace → creates new one- // ─────────────────────────────────────────────────────────────────────────- describe("Scenario 4: Workspace deleted on server", () => {- const email = `e2e_onboard_del_${randomUUID().slice(0, 8)}@test.local`+ // Scenario 2: Existing user, already has workspace with agents+ describe("Scenario 2: Existing user adds new workspace", () => {+ const email = `e2e_onboard_exist_${randomUUID().slice(0, 8)}@test.local`const password = "TestPass123!"let sessionCookie: string- let accessToken: string- let deletedWorkspaceId: string+ let existingWorkspaceId: stringlet newWorkspaceId: string- let machineToken: string- let machineTokenId: stringbeforeAll(async () => {- await signUp(email, password, "E2E Deleted WS User")+ await signUp(email, password, "E2E Existing User")sessionCookie = await signIn(email, password)- // Create workspace that will be "deleted"const wsRes = await sessionRequest("/api/workspaces", sessionCookie, {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "Doomed Co", slug: `doomed-co-${randomUUID().slice(0, 8)}` }),+ body: JSON.stringify({ name: "Existing", slug: `e2e-exist-${randomUUID().slice(0, 8)}` }),})- const wsData = await wsRes.json() as { id: string }- deletedWorkspaceId = wsData.id-- // Create and activate machine token for this workspace- accessToken = await deviceCodeLogin(sessionCookie)- const mtRes = await tokenRequest(- `/api/machine-tokens?workspace_id=${deletedWorkspaceId}`,- accessToken,- { method: "POST", headers: { "Content-Type": "application/json" } },- )- const mtData = await mtRes.json() as { token: string; id: string }- machineToken = mtData.token- machineTokenId = mtData.id-- await fetchWithRetry(`${APP_URL}/api/machine-tokens/activate`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- token: machineToken,- hostname: "DelWS.local",- runtimes: [{ type: "claude", version: "4.0" }],- }),- })- })-- it("after workspace deletion, workspace list no longer includes it", async () => {- // Delete the workspace (simulates server-side deletion)- sqlRun(`DELETE FROM member WHERE workspace_id = ?`, deletedWorkspaceId)- sqlRun(`DELETE FROM workspace WHERE id = ?`, deletedWorkspaceId)-- // Login sync: server no longer returns deleted workspace- const wsRes = await sessionRequest("/api/workspaces", sessionCookie)- expect(wsRes.status).toBe(200)- const workspaces = await wsRes.json() as Array<{ id: string }>- expect(workspaces.every(w => w.id !== deletedWorkspaceId)).toBe(true)+ const ws = await wsRes.json() as { id: string }+ existingWorkspaceId = ws.id})- it("workspace init skips deleted workspace and creates new one", async () => {- // User sees no workspaces → creates new one- const newWsRes = await sessionRequest("/api/workspaces", sessionCookie, {+ it("can create a second workspace", async () => {+ const res = await sessionRequest("/api/workspaces", sessionCookie, {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "Phoenix Co", slug: `phoenix-co-${randomUUID().slice(0, 8)}` }),+ body: JSON.stringify({ name: "Second WS", slug: `e2e-new-${randomUUID().slice(0, 8)}` }),})- expect(newWsRes.status).toBe(201)- const newWs = await newWsRes.json() as { id: string; name: string }- expect(newWs.id).toBeTruthy()- expect(newWs.id).not.toBe(deletedWorkspaceId)- newWorkspaceId = newWs.id+ expect(res.status).toBe(201)+ const body = await res.json() as { id: string }+ newWorkspaceId = body.id+ })- // Create a new machine token for the new workspace- const mtRes = await tokenRequest(+ it("token for new workspace can be activated independently", async () => {+ const tokenRes = await sessionRequest(`/api/machine-tokens?workspace_id=${newWorkspaceId}`,- accessToken,- { method: "POST", headers: { "Content-Type": "application/json" } },+ sessionCookie,+ { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "cli" }) },)- expect(mtRes.status).toBeLessThan(300)- const mtData = await mtRes.json() as { token: string; id: string }- const newMachineToken = mtData.token+ const { token } = await tokenRes.json() as { token: string }- // Activate new token- await fetchWithRetry(`${APP_URL}/api/machine-tokens/activate`, {+ const activateRes = await fetch(`${APP_URL}/api/machine-tokens/activate`, {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({- token: newMachineToken,- hostname: "DelWS.local",- runtimes: [{ type: "claude", version: "4.0" }],- }),+ body: JSON.stringify({ token, hostname: "Machine2.local", runtimes: [{ type: "claude", version: "4.0" }] }),})-- // Bind to new workspace- const bindRes = await tokenRequest("/api/machine-tokens/bind-workspace", newMachineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ workspace_id: newWorkspaceId }),- })- expect(bindRes.status).toBe(200)- const bindData = await bindRes.json() as { workspace_id: string; runtimes: Array<{ id: string }> }- expect(bindData.workspace_id).toBe(newWorkspaceId)- expect(bindData.runtimes.length).toBeGreaterThanOrEqual(1)-- // Verify new workspace is usable- const statusRes = await tokenRequest("/api/machine-tokens/status", newMachineToken)- expect(statusRes.status).toBe(200)- const statusData = await statusRes.json() as { status: string; workspace_id: string }- expect(statusData.status).toBe("active")- expect(statusData.workspace_id).toBe(newWorkspaceId)-- // Clean up the extra machine token- sqlRun(`DELETE FROM machine_token WHERE id = ?`, mtData.id)- })-- afterAll(() => {- try {- if (newWorkspaceId) {- sqlRun(`DELETE FROM agent_runtime WHERE workspace_id = ?`, newWorkspaceId)- sqlRun(`DELETE FROM machine WHERE workspace_id = ?`, newWorkspaceId)- sqlRun(`DELETE FROM member WHERE workspace_id = ?`, newWorkspaceId)- sqlRun(`DELETE FROM workspace WHERE id = ?`, newWorkspaceId)- }- sqlRun(`DELETE FROM machine_token WHERE id = ?`, machineTokenId)- sqlRun(`DELETE FROM "deviceCode" WHERE "userId" IN (SELECT id FROM "user" WHERE email = ?)`, email)- sqlRun(`DELETE FROM "session" WHERE "userId" IN (SELECT id FROM "user" WHERE email = ?)`, email)- sqlRun(`DELETE FROM "account" WHERE "userId" IN (SELECT id FROM "user" WHERE email = ?)`, email)- sqlRun(`DELETE FROM "user" WHERE email = ?`, email)- } catch { /* ignore cleanup errors */ }+ expect(activateRes.status).toBe(200)+ const body = await activateRes.json() as { workspace_id: string }+ expect(body.workspace_id).toBe(newWorkspaceId)})})})diff --git a/src/web/src/test/e2e/token-workspace-lifecycle.test.ts b/src/web/src/test/e2e/token-workspace-lifecycle.test.tsindex 4a02f251d..2871ee2be 100644--- a/src/web/src/test/e2e/token-workspace-lifecycle.test.ts+++ b/src/web/src/test/e2e/token-workspace-lifecycle.test.ts@@ -1,972 +1,107 @@-import { describe, it, expect, beforeAll, afterAll } from "vitest"+import { describe, it, expect, beforeAll } from "vitest"import { randomUUID } from "crypto"-import { seedTestData, cleanupTestData, type TestSeed, tokenRequest, sessionRequest, signUp, signIn, sqlRun, sqlQuery, fetchWithRetry } from "@alook/test-utils"--let seed: TestSeed--beforeAll(() => {- seed = seedTestData()- // Ensure seed token has hostname + runtimes for status API tests- sqlRun(- `UPDATE machine_token SET hostname = ?, runtimes_json = ? WHERE id = ?`,- "SeedHost.local", '[{"type":"claude","version":"4.0"}]', seed.machineTokenId,- )-})-afterAll(() => {- // Clean up any leftover tokens with NULL workspace_id (not caught by cleanupTestData)- sqlRun(`DELETE FROM machine_token WHERE user_id = ? AND id != ?`, seed.userId, seed.machineTokenId)- cleanupTestData(seed)-})--function ensureSeedIsLatest() {- sqlRun(`DELETE FROM machine_token WHERE user_id = ? AND id != ?`, seed.userId, seed.machineTokenId)-}+import { signUp, signIn, sessionRequest, sqlRun, sqlQuery } from "@alook/test-utils"const APP_URL = process.env.APP_URL ?? "http://localhost:3000"-const WS_DO_PORT = Number(process.env.NEXT_PUBLIC_WS_DO_PORT) || 8789-const WS_DO_HTTP = `http://localhost:${WS_DO_PORT}`-const WS_DO_WS = `ws://localhost:${WS_DO_PORT}`--async function wsReachable(): Promise<boolean> {- try {- const res = await fetch(WS_DO_HTTP, { method: "GET" })- return res.status < 500- } catch {- return false- }-}--function openWs(userId: string): Promise<WebSocket> {- return new Promise((resolve, reject) => {- const ws = new WebSocket(`${WS_DO_WS}/?userId=${userId}`)- const onError = () => reject(new Error("ws failed to open"))- ws.addEventListener("open", () => {- ws.removeEventListener("error", onError)- resolve(ws)- }, { once: true })- ws.addEventListener("error", onError, { once: true })- })-}--function waitForMessage<T = unknown>(- ws: WebSocket,- predicate: (msg: T) => boolean,- timeoutMs = 5000,-): Promise<T> {- return new Promise((resolve, reject) => {- const timer = setTimeout(() => {- ws.removeEventListener("message", handler)- reject(new Error(`waitForMessage timed out after ${timeoutMs}ms`))- }, timeoutMs)- const handler = (e: MessageEvent) => {- try {- const msg = JSON.parse(e.data as string) as T- if (predicate(msg)) {- clearTimeout(timer)- ws.removeEventListener("message", handler)- resolve(msg)- }- } catch { /* ignore non-JSON */ }- }- ws.addEventListener("message", handler)- })-}--function genTokenId() { return `mt_${randomUUID().replace(/-/g, "").slice(0, 21)}` }-function genToken() { return `al_${randomUUID().replace(/-/g, "")}` }--describe("token/workspace lifecycle — decoupled activate + bind", () => {-- // ─────────────────────────────────────────────────────────────────────────- // Token 状态流转 (Cases 1–8)- // ─────────────────────────────────────────────────────────────────────────- describe("Token state transitions", () => {-- describe("Case 1: create token → pending", () => {- let createdTokenId: string-- it("POST /machine-tokens creates a new token with status=pending", async () => {- // Clean up any existing pending/registered tokens for this user first- sqlRun(`DELETE FROM machine_token WHERE user_id = ? AND status IN ('pending','registered') AND id != ?`, seed.userId, seed.machineTokenId)-- const res = await tokenRequest("/api/machine-tokens", seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "e2e-case1" }),- })- expect(res.status).toBe(201)- const data = await res.json() as { token: string; id: string }- expect(data.token).toMatch(/^al_/)- expect(data.id).toBeTruthy()- createdTokenId = data.id-- const rows = sqlQuery<{ status: string }>(`SELECT status FROM machine_token WHERE id = ?`, data.id)- expect(rows[0]!.status).toBe("pending")- })-- afterAll(() => {- if (createdTokenId) sqlRun(`DELETE FROM machine_token WHERE id = ?`, createdTokenId)- })- })-- describe("Case 2: register → pending → registered (stores hostname + runtimes_json)", () => {- let tokenId: string- let token: string-- beforeAll(() => {- tokenId = genTokenId()- token = genToken()- sqlRun(- `INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, created_at) VALUES (?, ?, NULL, ?, ?, ?, ?)`,- tokenId, seed.userId, token, "case2", "pending", new Date().toISOString(),- )- })-- it("activate transitions to registered with hostname and runtimes", async () => {- const res = await fetchWithRetry(`${APP_URL}/api/machine-tokens/activate`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ token, hostname: "Case2Host.local", runtimes: [{ type: "claude", version: "4.0" }, { type: "codex", version: "1.0" }] }),- })- expect(res.status).toBe(200)- const data = await res.json() as { daemon_id: string; token_status: string }- expect(data.token_status).toBe("registered")- expect(data.daemon_id).toBe("Case2Host.local")-- const rows = sqlQuery<{ status: string; hostname: string; runtimes_json: string }>(- `SELECT status, hostname, runtimes_json FROM machine_token WHERE id = ?`, tokenId,- )- expect(rows[0]!.status).toBe("registered")- expect(rows[0]!.hostname).toBe("Case2Host.local")- expect(JSON.parse(rows[0]!.runtimes_json)).toHaveLength(2)- })-- afterAll(() => { sqlRun(`DELETE FROM machine_token WHERE id = ?`, tokenId) })- })-- describe("Case 3: bind-workspace → registered → active (creates machine + runtime rows)", () => {- let tokenId: string- let token: string-- beforeAll(() => {- tokenId = genTokenId()- token = genToken()- sqlRun(- `INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, hostname, runtimes_json, created_at) VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?)`,- tokenId, seed.userId, token, "case3", "registered", "Case3Host.local", '[{"type":"claude","version":"4.0"}]', new Date().toISOString(),- )- })-- it("bind transitions to active and creates machine/runtime", async () => {- const res = await tokenRequest("/api/machine-tokens/bind-workspace", token, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ workspace_id: seed.workspaceId }),- })- expect(res.status).toBe(200)- const data = await res.json() as { workspace_id: string; runtimes: Array<{ id: string }> }- expect(data.workspace_id).toBe(seed.workspaceId)- expect(data.runtimes.length).toBeGreaterThanOrEqual(1)-- const tokenRows = sqlQuery<{ status: string; workspace_id: string }>(- `SELECT status, workspace_id FROM machine_token WHERE id = ?`, tokenId,- )- expect(tokenRows[0]!.status).toBe("active")- expect(tokenRows[0]!.workspace_id).toBe(seed.workspaceId)-- const machineRows = sqlQuery<{ daemon_id: string }>(- `SELECT daemon_id FROM machine WHERE daemon_id = 'Case3Host.local' AND workspace_id = ?`, seed.workspaceId,- )- expect(machineRows.length).toBeGreaterThanOrEqual(1)- })-- afterAll(() => {- sqlRun(`DELETE FROM agent_runtime WHERE daemon_id = 'Case3Host.local' AND workspace_id = ?`, seed.workspaceId)- sqlRun(`DELETE FROM machine WHERE daemon_id = 'Case3Host.local' AND workspace_id = ?`, seed.workspaceId)- sqlRun(`DELETE FROM machine_token WHERE id = ?`, tokenId)- })- })-- describe("Case 4: existing pending token → create endpoint reuses it", () => {- let pendingId: string- let pendingToken: string-- beforeAll(() => {- // Clear any existing pending/registered tokens- sqlRun(`DELETE FROM machine_token WHERE user_id = ? AND status IN ('pending','registered') AND id != ?`, seed.userId, seed.machineTokenId)- pendingId = genTokenId()- pendingToken = genToken()- sqlRun(- `INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, created_at) VALUES (?, ?, NULL, ?, ?, ?, ?)`,- pendingId, seed.userId, pendingToken, "case4-pending", "pending", new Date().toISOString(),- )- })-- it("returns the existing pending token", async () => {- const res = await tokenRequest("/api/machine-tokens", seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({}),- })- expect(res.status).toBe(200)- const data = await res.json() as { token: string; id: string }- expect(data.id).toBe(pendingId)- expect(data.token).toBe(pendingToken)- })-- afterAll(() => { sqlRun(`DELETE FROM machine_token WHERE id = ?`, pendingId) })- })-- describe("Case 5: existing registered token → create endpoint reuses it", () => {- let registeredId: string- let registeredToken: string-- beforeAll(() => {- sqlRun(`DELETE FROM machine_token WHERE user_id = ? AND status IN ('pending','registered') AND id != ?`, seed.userId, seed.machineTokenId)- registeredId = genTokenId()- registeredToken = genToken()- sqlRun(- `INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, hostname, runtimes_json, created_at) VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?)`,- registeredId, seed.userId, registeredToken, "case5", "registered", "Host.local", '[{"type":"claude"}]', new Date().toISOString(),- )- })-- it("returns existing registered token", async () => {- const res = await tokenRequest("/api/machine-tokens", seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({}),- })- expect(res.status).toBe(200)- const data = await res.json() as { token: string; id: string }- expect(data.id).toBe(registeredId)- expect(data.token).toBe(registeredToken)- })-- afterAll(() => { sqlRun(`DELETE FROM machine_token WHERE id = ?`, registeredId) })- })-- describe("Case 6: existing active token → create endpoint creates new (no reuse)", () => {- beforeAll(() => {- // seed already has an active machineToken; clear any pending/registered- sqlRun(`DELETE FROM machine_token WHERE user_id = ? AND status IN ('pending','registered') AND id != ?`, seed.userId, seed.machineTokenId)- })-- it("creates a new pending token when only active tokens exist", async () => {- const res = await tokenRequest("/api/machine-tokens", seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "case6-new" }),- })- expect(res.status).toBe(201)- const data = await res.json() as { id: string }- expect(data.id).not.toBe(seed.machineTokenId)-- const rows = sqlQuery<{ status: string }>(`SELECT status FROM machine_token WHERE id = ?`, data.id)- expect(rows[0]!.status).toBe("pending")-- sqlRun(`DELETE FROM machine_token WHERE id = ?`, data.id)- })- })-- describe("Case 7: multiple registered tokens → bind picks earliest", () => {- let olderId: string- let newerId: string- let olderToken: string- let newerToken: string-- beforeAll(() => {- olderId = genTokenId()- newerId = genTokenId()- olderToken = genToken()- newerToken = genToken()- sqlRun(- `INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, hostname, runtimes_json, created_at) VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?)`,- olderId, seed.userId, olderToken, "older", "registered", "OldHost7.local", '[{"type":"claude"}]', "2025-01-01T00:00:00Z",- )- sqlRun(- `INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, hostname, runtimes_json, created_at) VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?)`,- newerId, seed.userId, newerToken, "newer", "registered", "NewHost7.local", '[{"type":"claude"}]', "2025-06-01T00:00:00Z",- )- })- it("bind selects the earliest registered token", async () => {- const res = await tokenRequest("/api/machine-tokens/bind-workspace", olderToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ workspace_id: seed.workspaceId }),- })- expect(res.status).toBe(200)+describe("token/workspace lifecycle — simplified activate flow", () => {+ const email = `e2e_token_${randomUUID().slice(0, 8)}@test.local`+ const password = "TestPass123!"+ let sessionCookie: string+ let workspaceId: string+ let firstToken: string- const older = sqlQuery<{ status: string }>(`SELECT status FROM machine_token WHERE id = ?`, olderId)- expect(older[0]!.status).toBe("active")+ beforeAll(async () => {+ await signUp(email, password, "E2E Token User")+ sessionCookie = await signIn(email, password)- const newer = sqlQuery<{ status: string }>(`SELECT status FROM machine_token WHERE id = ?`, newerId)- expect(newer[0]!.status).toBe("registered")- })-- afterAll(() => {- sqlRun(`DELETE FROM agent_runtime WHERE daemon_id = 'OldHost7.local' AND workspace_id = ?`, seed.workspaceId)- sqlRun(`DELETE FROM machine WHERE daemon_id = 'OldHost7.local' AND workspace_id = ?`, seed.workspaceId)- sqlRun(`DELETE FROM machine_token WHERE id IN (?, ?)`, olderId, newerId)- })- })-- describe("Case 8: bind with no registered token → 409 error", () => {- beforeAll(() => {- // Ensure no registered tokens exist- sqlRun(`DELETE FROM machine_token WHERE user_id = ? AND status = 'registered'`, seed.userId)- })-- it("returns 404/409 when no registered token exists", async () => {- const res = await tokenRequest("/api/machine-tokens/bind-workspace", seed.machineToken, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ workspace_id: seed.workspaceId }),- })- expect([404, 409]).toContain(res.status)- })+ const wsRes = await sessionRequest("/api/workspaces", sessionCookie, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name: "TokenTest", slug: `e2e-tok-${randomUUID().slice(0, 8)}` }),})+ const ws = await wsRes.json() as { id: string }+ workspaceId = ws.id})- // ─────────────────────────────────────────────────────────────────────────- // Workspace 创建 (Cases 9–12)- // ─────────────────────────────────────────────────────────────────────────- describe("Workspace creation", () => {- let cookie: string- const testEmail = `e2e_twl_${randomUUID().slice(0, 8)}@test.local`-- beforeAll(async () => {- await signUp(testEmail, "TestPass123!", "E2E Lifecycle")- cookie = await signIn(testEmail, "TestPass123!")- })-- afterAll(() => {- sqlRun(`DELETE FROM member WHERE user_id IN (SELECT id FROM "user" WHERE email = ?)`, testEmail)- sqlRun(`DELETE FROM "session" WHERE userId IN (SELECT id FROM "user" WHERE email = ?)`, testEmail)- sqlRun(`DELETE FROM "account" WHERE userId IN (SELECT id FROM "user" WHERE email = ?)`, testEmail)- sqlRun(`DELETE FROM "user" WHERE email = ?`, testEmail)- })+ describe("Token state transitions", () => {- it("Case 9: New workspace (no initialWorkspaceId) creates a new workspace", async () => {- const res = await sessionRequest("/api/workspaces", cookie, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "E2E NewCo", slug: `e2e-newco-${randomUUID().slice(0, 8)}` }),- })+ it("POST /machine-tokens creates a new token with status=pending", async () => {+ const res = await sessionRequest(+ `/api/machine-tokens?workspace_id=${workspaceId}`,+ sessionCookie,+ { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "cli" }) },+ )expect(res.status).toBe(201)- const data = await res.json() as { id: string; name: string }- expect(data.name).toBe("E2E NewCo")- expect(data.id).toMatch(/^sp_/)-- sqlRun(`DELETE FROM member WHERE workspace_id = ?`, data.id)- sqlRun(`DELETE FROM workspace WHERE id = ?`, data.id)+ const body = await res.json() as { token: string; status: string }+ expect(body.token).toMatch(/^al_/)+ expect(body.status).toBe("pending")+ firstToken = body.token})- it("Case 10: initialWorkspaceId reuses existing workspace (workspace already exists)", async () => {- // Create workspace first- const createRes = await sessionRequest("/api/workspaces", cookie, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "E2E ReuseCo", slug: `e2e-reuseco-${randomUUID().slice(0, 8)}` }),- })- expect(createRes.status).toBe(201)- const ws = await createRes.json() as { id: string }-- // Verify workspace exists and can be fetched- const listRes = await sessionRequest("/api/workspaces", cookie)- expect(listRes.status).toBe(200)- const workspaces = await listRes.json() as Array<{ id: string }>- expect(workspaces.some((w) => w.id === ws.id)).toBe(true)-- sqlRun(`DELETE FROM member WHERE workspace_id = ?`, ws.id)- sqlRun(`DELETE FROM workspace WHERE id = ?`, ws.id)+ it("calling create again returns the same pending token", async () => {+ const res = await sessionRequest(+ `/api/machine-tokens?workspace_id=${workspaceId}`,+ sessionCookie,+ { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "cli" }) },+ )+ expect(res.status).toBe(200)+ const body = await res.json() as { token: string }+ expect(body.token).toBe(firstToken)})- it("Case 11: after successful Launch, creating again makes a new workspace", async () => {- const res1 = await sessionRequest("/api/workspaces", cookie, {+ it("activate transitions to active and creates machine/runtime", async () => {+ const res = await fetch(`${APP_URL}/api/machine-tokens/activate`, {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "First Launch", slug: `first-launch-${randomUUID().slice(0, 8)}` }),+ body: JSON.stringify({+ token: firstToken,+ hostname: "TestMachine.local",+ runtimes: [{ type: "claude", version: "4.0.0" }],+ }),})- expect(res1.status).toBe(201)- const ws1 = await res1.json() as { id: string }+ expect(res.status).toBe(200)+ const body = await res.json() as { daemon_id: string; workspace_id: string; runtimes: Array<{ id: string }> }+ expect(body.daemon_id).toBe("TestMachine.local")+ expect(body.workspace_id).toBe(workspaceId)+ expect(body.runtimes.length).toBeGreaterThan(0)+ })- const res2 = await sessionRequest("/api/workspaces", cookie, {+ it("activate rejects already-active token", async () => {+ const res = await fetch(`${APP_URL}/api/machine-tokens/activate`, {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "Second Launch", slug: `second-launch-${randomUUID().slice(0, 8)}` }),+ body: JSON.stringify({+ token: firstToken,+ hostname: "TestMachine.local",+ runtimes: [{ type: "claude", version: "4.0.0" }],+ }),})- expect(res2.status).toBe(201)- const ws2 = await res2.json() as { id: string }- expect(ws2.id).not.toBe(ws1.id)-- sqlRun(`DELETE FROM member WHERE workspace_id IN (?, ?)`, ws1.id, ws2.id)- sqlRun(`DELETE FROM workspace WHERE id IN (?, ?)`, ws1.id, ws2.id)+ expect(res.status).toBe(409)})- it("Case 12: status API does not set workspaceId on recovery", async () => {- const tokenId = genTokenId()- const token = genToken()- const userId = sqlQuery<{ id: string }>(`SELECT id FROM "user" WHERE email = ?`, testEmail)[0]!.id+ it("activate rejects token without workspace_id", async () => {+ const tokenVal = `al_${randomUUID().replace(/-/g, "")}`sqlRun(- `INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, hostname, runtimes_json, created_at) VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?)`,- tokenId, userId, token, "case12", "registered", "Case12Host.local", '[{"type":"claude"}]', new Date().toISOString(),+ `INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, created_at) VALUES (?, ?, NULL, ?, 'cli', 'pending', datetime('now'))`,+ `mt_${randomUUID().slice(0, 21)}`, sqlQuery(`SELECT id FROM "user" WHERE email = ?`, email)[0]?.id, tokenVal,)-- const res = await tokenRequest("/api/machine-tokens/status", token)- expect(res.status).toBe(200)- const data = await res.json() as { status: string; workspace_id?: string }- expect(data.status).toBe("registered")- expect(data.workspace_id).toBeUndefined()-- sqlRun(`DELETE FROM machine_token WHERE id = ?`, tokenId)- })- })-- // ─────────────────────────────────────────────────────────────────────────- // Daemon 状态 (Cases 13–18)- // ─────────────────────────────────────────────────────────────────────────- describe("Daemon state", () => {- describe("Case 13: daemon standby mode → register → broadcast online", () => {- let tokenId: string- let token: string-- beforeAll(() => {- tokenId = genTokenId()- token = genToken()- sqlRun(- `INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, hostname, runtimes_json, created_at) VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?)`,- tokenId, seed.userId, token, "case13", "registered", "Case13Host.local", '[{"type":"claude"}]', new Date().toISOString(),- )- })-- it("register returns standby=true when token has no workspace", async () => {- const res = await tokenRequest("/api/daemon/register", token, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ daemon_id: "case13-daemon", device_name: "Case13Host.local", cli_version: "1.0.0", runtimes: [{ type: "claude", version: "4.0" }] }),- })- expect(res.status).toBe(200)- const data = await res.json() as { standby: boolean; runtimes: unknown[] }- expect(data.standby).toBe(true)- expect(data.runtimes).toEqual([])- })-- afterAll(() => { sqlRun(`DELETE FROM machine_token WHERE id = ?`, tokenId) })- })-- describe("Case 14: daemon WS connect → broadcast online to user DO", () => {- let wsAvailable: boolean-- beforeAll(async () => {- wsAvailable = await wsReachable()- })-- it("broadcasts runtime.status online when daemon authenticates via WS", async () => {- if (!wsAvailable) return-- const userWs = await openWs(seed.userId)- const wsTokenRes = await sessionRequest("/api/ws/token", await signIn(seed.authEmail, seed.authPassword))- const { token: wsToken } = await wsTokenRes.json() as { token: string }- userWs.send(JSON.stringify({ type: "auth", token: wsToken }))- await waitForMessage(userWs, (m: { type: string }) => m.type === "auth.ok")-- // Daemon connects- const daemonWs = await openWs(seed.userId)- daemonWs.send(JSON.stringify({ type: "auth", machineToken: seed.machineToken, daemonId: seed.daemonId }))- await waitForMessage(daemonWs, (m: { type: string }) => m.type === "auth.ok")-- // User should receive online broadcast- const msg = await waitForMessage<{ type: string; status: string }>(- userWs,- (m) => m.type === "runtime.status" && m.status === "online",- )- expect(msg.status).toBe("online")-- userWs.close()- daemonWs.close()- })- })-- describe("Case 15: daemon WS disconnect → broadcast offline to user DO", () => {- let wsAvailable: boolean-- beforeAll(async () => {- wsAvailable = await wsReachable()- })-- it("broadcasts runtime.status offline when daemon WS closes", async () => {- if (!wsAvailable) return-- const userWs = await openWs(seed.userId)- const wsTokenRes = await sessionRequest("/api/ws/token", await signIn(seed.authEmail, seed.authPassword))- const { token: wsToken } = await wsTokenRes.json() as { token: string }- userWs.send(JSON.stringify({ type: "auth", token: wsToken }))- await waitForMessage(userWs, (m: { type: string }) => m.type === "auth.ok")-- const daemonWs = await openWs(seed.userId)- daemonWs.send(JSON.stringify({ type: "auth", machineToken: seed.machineToken, daemonId: seed.daemonId }))- await waitForMessage(daemonWs, (m: { type: string }) => m.type === "auth.ok")-- // Drain online notification- await waitForMessage<{ type: string }>(userWs, (m) => m.type === "runtime.status").catch(() => {})-- // Close daemon — should trigger offline broadcast- daemonWs.close()-- const msg = await waitForMessage<{ type: string; status: string }>(- userWs,- (m) => m.type === "runtime.status" && m.status === "offline",- 5000,- )- expect(msg.status).toBe("offline")-- userWs.close()- })- })-- describe("Case 16: check_daemon_status → cross-DO fetch /check-alive", () => {- let wsAvailable: boolean-- beforeAll(async () => {- wsAvailable = await wsReachable()- })-- it("check_daemon_status returns correct alive state", async () => {- if (!wsAvailable) return-- const userWs = await openWs(seed.userId)- const wsTokenRes = await sessionRequest("/api/ws/token", await signIn(seed.authEmail, seed.authPassword))- const { token: wsToken } = await wsTokenRes.json() as { token: string }- userWs.send(JSON.stringify({ type: "auth", token: wsToken }))- await waitForMessage(userWs, (m: { type: string }) => m.type === "auth.ok")-- // Ask for daemon status — with no daemon connected, should get no online response- userWs.send(JSON.stringify({ type: "check_daemon_status" }))-- // Should either get nothing (timeout) or a status response- try {- const msg = await waitForMessage<{ type: string; status: string }>(- userWs,- (m) => m.type === "runtime.status",- 2000,- )- // If we get a response, it's based on actual daemon state- expect(["online", "offline"]).toContain(msg.status)- } catch {- // Timeout = no daemon connected = expected behavior- }-- userWs.close()- })- })-- describe("Case 17: frontend connects first → daemon connects later → frontend receives online", () => {- let wsAvailable: boolean-- beforeAll(async () => {- wsAvailable = await wsReachable()- })-- it("frontend receives online when daemon connects after", async () => {- if (!wsAvailable) return-- // Frontend connects first- const userWs = await openWs(seed.userId)- const wsTokenRes = await sessionRequest("/api/ws/token", await signIn(seed.authEmail, seed.authPassword))- const { token: wsToken } = await wsTokenRes.json() as { token: string }- userWs.send(JSON.stringify({ type: "auth", token: wsToken }))- await waitForMessage(userWs, (m: { type: string }) => m.type === "auth.ok")-- // Daemon connects after- const daemonWs = await openWs(seed.userId)- daemonWs.send(JSON.stringify({ type: "auth", machineToken: seed.machineToken, daemonId: seed.daemonId }))- await waitForMessage(daemonWs, (m: { type: string }) => m.type === "auth.ok")-- // Frontend should get online notification- const msg = await waitForMessage<{ type: string; status: string }>(- userWs,- (m) => m.type === "runtime.status" && m.status === "online",- )- expect(msg.status).toBe("online")-- userWs.close()- daemonWs.close()- })- })-- describe("Case 18: daemon connects first → frontend connects later → check returns online", () => {- let wsAvailable: boolean-- beforeAll(async () => {- wsAvailable = await wsReachable()- })-- it("check_daemon_status returns online when daemon already connected", async () => {- if (!wsAvailable) return-- // Daemon connects first- const daemonWs = await openWs(seed.userId)- daemonWs.send(JSON.stringify({ type: "auth", machineToken: seed.machineToken, daemonId: seed.daemonId }))- await waitForMessage(daemonWs, (m: { type: string }) => m.type === "auth.ok")-- // Then frontend connects- const userWs = await openWs(seed.userId)- const wsTokenRes = await sessionRequest("/api/ws/token", await signIn(seed.authEmail, seed.authPassword))- const { token: wsToken } = await wsTokenRes.json() as { token: string }- userWs.send(JSON.stringify({ type: "auth", token: wsToken }))- await waitForMessage(userWs, (m: { type: string }) => m.type === "auth.ok")-- // Frontend asks for daemon status — cross-DO check may not work in all envs- userWs.send(JSON.stringify({ type: "check_daemon_status" }))- try {- const msg = await waitForMessage<{ type: string; status: string }>(- userWs,- (m) => m.type === "runtime.status" && m.status === "online",- 5000,- )- expect(msg.status).toBe("online")- } catch {- // Cross-DO communication may not be available in local/CI — skip gracefully- }-- userWs.close()- daemonWs.close()- })- })- })-- // ─────────────────────────────────────────────────────────────────────────- // Runtime (Cases 19–23)- // ─────────────────────────────────────────────────────────────────────────- describe("Runtime", () => {-- describe("Case 19: status API returns runtimes_json → frontend displays runtime selector", () => {- let tokenId: string- let token: string-- beforeAll(() => {- tokenId = genTokenId()- token = genToken()- sqlRun(- `INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, hostname, runtimes_json, created_at) VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?)`,- tokenId, seed.userId, token, "case19", "registered", "Case19Host.local",- '[{"type":"claude","version":"4.0"},{"type":"codex","version":"1.0"}]', new Date().toISOString(),- )- })-- it("status returns runtimes array from runtimes_json", async () => {- const res = await tokenRequest("/api/machine-tokens/status", token)- expect(res.status).toBe(200)- const data = await res.json() as { runtimes?: Array<{ id: string; type: string; version: string }> }- expect(data.runtimes).toBeDefined()- expect(data.runtimes!.length).toBe(2)- expect(data.runtimes![0].type).toBe("claude")- expect(data.runtimes![1].type).toBe("codex")- })-- afterAll(() => { sqlRun(`DELETE FROM machine_token WHERE id = ?`, tokenId) })- })-- describe("Case 20: WS online → runtimes status updates to online", () => {- it("status API returns daemon_online=true for recently active token", async () => {- ensureSeedIsLatest()- sqlRun(`UPDATE machine_token SET last_used_at = ? WHERE id = ?`, new Date().toISOString(), seed.machineTokenId)- const res = await tokenRequest("/api/machine-tokens/status", seed.machineToken)- expect(res.status).toBe(200)- const data = await res.json() as { daemon_online: boolean }- expect(data.daemon_online).toBe(true)- })- })-- describe("Case 21: WS offline → runtimes status updates to offline", () => {- it("status API returns daemon_online=false when last_used_at is stale", async () => {- const tokenId = genTokenId()- const token = genToken()- const staleTime = new Date(Date.now() - 300_000).toISOString() // 5 min ago- sqlRun(- `INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, hostname, runtimes_json, last_used_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,- tokenId, seed.userId, seed.workspaceId, token, "case21", "active", "Case21Host.local",- '[{"type":"claude"}]', staleTime, new Date().toISOString(),- )-- const res = await tokenRequest("/api/machine-tokens/status", token)- expect(res.status).toBe(200)- const data = await res.json() as { daemon_online: boolean; runtimes?: Array<{ status: string }> }- expect(data.daemon_online).toBe(false)- if (data.runtimes) {- expect(data.runtimes[0].status).toBe("offline")- }-- sqlRun(`DELETE FROM machine_token WHERE id = ?`, tokenId)- })- })-- describe("Case 22: bind creates runtimes → poll returns real runtime IDs", () => {- let tokenId: string- let token: string-- beforeAll(() => {- tokenId = genTokenId()- token = genToken()- sqlRun(- `INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, hostname, runtimes_json, created_at) VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?)`,- tokenId, seed.userId, token, "case22", "registered", "Case22Host.local", '[{"type":"claude","version":"4.0"}]', new Date().toISOString(),- )- })-- it("bind returns real runtime IDs (not temp_ prefix)", async () => {- const res = await tokenRequest("/api/machine-tokens/bind-workspace", token, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ workspace_id: seed.workspaceId }),- })- expect(res.status).toBe(200)- const data = await res.json() as { runtimes: Array<{ id: string }> }- expect(data.runtimes.length).toBeGreaterThanOrEqual(1)- // Real runtime IDs from agent_runtime table (nanoid, not temp_ prefix)- expect(data.runtimes[0].id).toBeTruthy()- expect(data.runtimes[0].id).not.toMatch(/^temp_/)- })-- afterAll(() => {- sqlRun(`DELETE FROM agent_runtime WHERE daemon_id = 'Case22Host.local' AND workspace_id = ?`, seed.workspaceId)- sqlRun(`DELETE FROM machine WHERE daemon_id = 'Case22Host.local' AND workspace_id = ?`, seed.workspaceId)- sqlRun(`DELETE FROM machine_token WHERE id = ?`, tokenId)- })- })-- describe("Case 23: Tauri and browser both use getMachineTokenStatus()", () => {- it("status endpoint works with token auth (covers both Tauri and browser paths)", async () => {- const res = await tokenRequest("/api/machine-tokens/status", seed.machineToken)- expect(res.status).toBe(200)- const data = await res.json() as { status: string }- expect(data.status).toBeTruthy()- })- })- })-- // ─────────────────────────────────────────────────────────────────────────- // 页面恢复 (Cases 24–26)- // ─────────────────────────────────────────────────────────────────────────- describe("Page recovery", () => {-- describe("Case 24: after register + refresh → machineRegistered recovers to true", () => {- let tokenId: string- let token: string-- beforeAll(() => {- tokenId = genTokenId()- token = genToken()- sqlRun(- `INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, hostname, runtimes_json, created_at) VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?)`,- tokenId, seed.userId, token, "case24", "registered", "Case24Host.local", '[{"type":"claude"}]', new Date().toISOString(),- )- })-- it("status returns registered (frontend uses this to restore machineRegistered)", async () => {- const res = await tokenRequest("/api/machine-tokens/status", token)- expect(res.status).toBe(200)- const data = await res.json() as { status: string; hostname: string }- expect(data.status).toBe("registered")- expect(data.hostname).toBe("Case24Host.local")- })-- afterAll(() => { sqlRun(`DELETE FROM machine_token WHERE id = ?`, tokenId) })- })-- describe("Case 25: daemon online + refresh → daemonOnline recovers to true", () => {- it("status returns daemon_online=true when last_used_at is recent", async () => {- ensureSeedIsLatest()- sqlRun(`UPDATE machine_token SET last_used_at = ? WHERE id = ?`, new Date().toISOString(), seed.machineTokenId)- const res = await tokenRequest("/api/machine-tokens/status", seed.machineToken)- expect(res.status).toBe(200)- const data = await res.json() as { daemon_online: boolean }- expect(data.daemon_online).toBe(true)- })- })-- describe("Case 26: refresh does not restore workspaceId (comes from URL or handleCreate)", () => {- let tokenId: string- let token: string-- beforeAll(() => {- tokenId = genTokenId()- token = genToken()- sqlRun(- `INSERT INTO machine_token (id, user_id, workspace_id, token, name, status, hostname, runtimes_json, created_at) VALUES (?, ?, NULL, ?, ?, ?, ?, ?, ?)`,- tokenId, seed.userId, token, "case26", "registered", "Case26Host.local", '[{"type":"claude"}]', new Date().toISOString(),- )- })-- it("status does not return workspace_id for registered token", async () => {- const res = await tokenRequest("/api/machine-tokens/status", token)- expect(res.status).toBe(200)- const data = await res.json() as { status: string; workspace_id?: string }- expect(data.status).toBe("registered")- expect(data.workspace_id).toBeUndefined()+ const res = await fetch(`${APP_URL}/api/machine-tokens/activate`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ token: tokenVal, hostname: "host", runtimes: [{ type: "claude" }] }),})-- afterAll(() => { sqlRun(`DELETE FROM machine_token WHERE id = ?`, tokenId) })+ expect(res.status).toBe(422)})})- // ─────────────────────────────────────────────────────────────────────────- // UI 状态 (Cases 27–31)- // ─────────────────────────────────────────────────────────────────────────- describe("UI state (API-level verification)", () => {-- describe("Case 27: connect steps done + daemon online → shows connected", () => {- it("status returns all signals needed to show '1 computer connected'", async () => {- ensureSeedIsLatest()- sqlRun(`UPDATE machine_token SET last_used_at = ? WHERE id = ?`, new Date().toISOString(), seed.machineTokenId)- const res = await tokenRequest("/api/machine-tokens/status", seed.machineToken)- expect(res.status).toBe(200)- const data = await res.json() as { status: string; daemon_online: boolean; hostname: string }- expect(data.status).toBe("active")- expect(data.daemon_online).toBe(true)- expect(data.hostname).toBeTruthy()- })- })-- describe("Case 28: name not checked → Launch button disabled (slug check)", () => {- let cookie: string- const email = `e2e_c28_${randomUUID().slice(0, 8)}@test.local`-- beforeAll(async () => {- await signUp(email, "TestPass123!", "E2E Case28")- cookie = await signIn(email, "TestPass123!")- })-- it("creating workspace with duplicate slug returns 409", async () => {- // Create first- const res1 = await sessionRequest("/api/workspaces", cookie, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "Dup Check", slug: "dupcheck-e2e-unique-slug" }),- })- expect(res1.status).toBe(201)- const ws1 = await res1.json() as { id: string; slug: string }-- // Slug collision is handled by auto-suffixing, but we can verify slug uniqueness- const res2 = await sessionRequest("/api/workspaces", cookie, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "Dup Check 2", slug: "dupcheck-e2e-unique-slug" }),- })- // Server auto-appends suffix on collision, so it should succeed with different slug- expect(res2.status).toBe(201)- const ws2 = await res2.json() as { id: string; slug: string }- expect(ws2.slug).not.toBe(ws1.slug)-- sqlRun(`DELETE FROM member WHERE workspace_id IN (?, ?)`, ws1.id, ws2.id)- sqlRun(`DELETE FROM workspace WHERE id IN (?, ?)`, ws1.id, ws2.id)- })-- afterAll(() => {- sqlRun(`DELETE FROM member WHERE user_id IN (SELECT id FROM "user" WHERE email = ?)`, email)- sqlRun(`DELETE FROM "session" WHERE userId IN (SELECT id FROM "user" WHERE email = ?)`, email)- sqlRun(`DELETE FROM "account" WHERE userId IN (SELECT id FROM "user" WHERE email = ?)`, email)- sqlRun(`DELETE FROM "user" WHERE email = ?`, email)- })- })-- describe("Case 29: name check passes → slug locked + Launch enabled", () => {- let cookie: string- const email = `e2e_c29_${randomUUID().slice(0, 8)}@test.local`-- beforeAll(async () => {- await signUp(email, "TestPass123!", "E2E Case29")- cookie = await signIn(email, "TestPass123!")- })-- it("workspace creation succeeds with valid name and slug", async () => {- const slug = `valid-slug-${randomUUID().slice(0, 8)}`- const res = await sessionRequest("/api/workspaces", cookie, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "Valid Company", slug }),- })- expect(res.status).toBe(201)- const data = await res.json() as { id: string; slug: string; name: string }- expect(data.name).toBe("Valid Company")- expect(data.slug).toBe(slug)-- sqlRun(`DELETE FROM member WHERE workspace_id = ?`, data.id)- sqlRun(`DELETE FROM workspace WHERE id = ?`, data.id)- })-- afterAll(() => {- sqlRun(`DELETE FROM member WHERE user_id IN (SELECT id FROM "user" WHERE email = ?)`, email)- sqlRun(`DELETE FROM "session" WHERE userId IN (SELECT id FROM "user" WHERE email = ?)`, email)- sqlRun(`DELETE FROM "account" WHERE userId IN (SELECT id FROM "user" WHERE email = ?)`, email)- sqlRun(`DELETE FROM "user" WHERE email = ?`, email)- })- })-- describe("Case 30: Edit unlocks name → nameAvailable resets", () => {- let cookie: string- const email = `e2e_c30_${randomUUID().slice(0, 8)}@test.local`-- beforeAll(async () => {- await signUp(email, "TestPass123!", "E2E Case30")- cookie = await signIn(email, "TestPass123!")- })-- it("can create workspace with different slug after slug change (simulates Edit)", async () => {- const slug1 = `edit-test-${randomUUID().slice(0, 8)}`- const slug2 = `edit-test-${randomUUID().slice(0, 8)}`-- const res1 = await sessionRequest("/api/workspaces", cookie, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "Original Name", slug: slug1 }),- })- expect(res1.status).toBe(201)- const ws1 = await res1.json() as { id: string }-- // "Edit" = user changes name and creates again- const res2 = await sessionRequest("/api/workspaces", cookie, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ name: "Edited Name", slug: slug2 }),- })- expect(res2.status).toBe(201)- const ws2 = await res2.json() as { id: string }- expect(ws2.id).not.toBe(ws1.id)-- sqlRun(`DELETE FROM member WHERE workspace_id IN (?, ?)`, ws1.id, ws2.id)- sqlRun(`DELETE FROM workspace WHERE id IN (?, ?)`, ws1.id, ws2.id)- })-- afterAll(() => {- sqlRun(`DELETE FROM member WHERE user_id IN (SELECT id FROM "user" WHERE email = ?)`, email)- sqlRun(`DELETE FROM "session" WHERE userId IN (SELECT id FROM "user" WHERE email = ?)`, email)- sqlRun(`DELETE FROM "account" WHERE userId IN (SELECT id FROM "user" WHERE email = ?)`, email)- sqlRun(`DELETE FROM "user" WHERE email = ?`, email)- })- })-- describe("Case 31: completed steps collapse (API always returns full state)", () => {- it("status API returns complete state for frontend to determine step completion", async () => {- ensureSeedIsLatest()- sqlRun(`UPDATE machine_token SET last_used_at = ? WHERE id = ?`, new Date().toISOString(), seed.machineTokenId)- const res = await tokenRequest("/api/machine-tokens/status", seed.machineToken)- expect(res.status).toBe(200)- const data = await res.json() as {- status: string- hostname?: string- daemon_online?: boolean- workspace_id?: string- runtimes?: Array<{ id: string; type: string; status: string }>- }- // All fields present — frontend uses these to determine which steps are done- expect(data.status).toBe("active")- expect(data.hostname).toBeTruthy()- expect(data.daemon_online).toBe(true)- expect(data.workspace_id).toBe(seed.workspaceId)- })+ describe("Status API", () => {+ it("returns active status after activation", async () => {+ const res = await sessionRequest("/api/machine-tokens/status", sessionCookie)+ expect(res.status).toBe(200)+ const body = await res.json() as { status: string; hostname?: string; daemon_online?: boolean }+ expect(body.status).toBe("active")+ expect(body.hostname).toBe("TestMachine.local")})})})diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.tsindex 7e1b605fd..cf57b2845 100644--- a/src/ws-do/src/ws-durable.test.ts+++ b/src/ws-do/src/ws-durable.test.ts@@ -317,10 +317,10 @@ describe("WebSocketDurableObject", () => {})describe("webSocketMessage — daemon auth flow", () => {- it("authenticates daemon with registered token (standby mode)", async () => {+ it("rejects daemon with pending token (not yet activated)", async () => {const { durable } = createDO()mockGetMachineTokenByToken.mockResolvedValue({- id: "mt_1", userId: "u1", status: "registered", workspaceId: null,+ id: "mt_1", userId: "u1", status: "pending", workspaceId: null,})const ws = createMockWebSocket()@@ -328,11 +328,10 @@ describe("WebSocketDurableObject", () => {await durable.webSocketMessage(ws as any,- JSON.stringify({ type: "auth", machineToken: "al_standby123", daemonId: "my-daemon" }),+ JSON.stringify({ type: "auth", machineToken: "al_pending123", daemonId: "my-daemon" }),)- expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok" }))- expect(ws.deserializeAttachment()).toEqual({ type: "daemon", daemonId: "my-daemon", userId: "u1", authenticated: true })+ expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")expect(mockGetRuntimeIdsByDaemon).not.toHaveBeenCalled()})diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.tsindex d8cc7155f..eae0800d2 100644--- a/src/ws-do/src/ws-durable.ts+++ b/src/ws-do/src/ws-durable.ts@@ -165,7 +165,6 @@ export class WebSocketDurableObject extends DurableObject<Env> {const db = createDb(this.env.DB)const mt = await queries.machineToken.getMachineTokenByToken(db, token)if (!mt) return null- if (mt.status === "registered") return { userId: mt.userId }if (mt.status !== "active" || !mt.workspaceId) return nullconst runtimes = await queries.runtime.getRuntimeIdsByDaemon(db, daemonId, mt.workspaceId)return runtimes.length > 0 ? { userId: mt.userId } : null