Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(cli): login stores session token + workspace init self-resolves (#300)

Generfb0443c7258b
diff --git a/src/cli/commands/login.test.ts b/src/cli/commands/login.test.ts
index 5e721ddf3..32a569082 100644
--- a/src/cli/commands/login.test.ts
+++ b/src/cli/commands/login.test.ts
@@ -18,6 +18,7 @@ vi.mock("../daemon/pidfile.js", () => ({
vi.mock("../lib/env.js", () => ({
cmdPrefix: () => "alook",
isDev: () => false,
+ getServerUrl: () => "http://localhost:3000",
}));
vi.mock("../lib/runtimes.js", () => ({
@@ -116,7 +117,6 @@ describe("alook login", () => {
}
async function runWithTimers(promise: Promise<unknown>) {
- // Advance timers repeatedly until the promise settles
let settled = false;
const result = promise.finally(() => { settled = true; });
while (!settled) {
@@ -131,13 +131,24 @@ 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)
expect(mockSaveCLIConfigForProfile).toHaveBeenCalledWith(
undefined,
expect.objectContaining({
server_url: "http://localhost:3000",
- watched_workspaces: [
- { id: null, name: null, token: "al_machine_tok", status: "registered", agent_ids: [] },
- ],
+ session_token: "session_tok_123",
+ watched_workspaces: expect.arrayContaining([
+ expect.objectContaining({ id: "sp_ws1", name: "My Workspace", status: "active" }),
+ ]),
+ }),
+ );
+ // activateAndSave adds the machine token entry
+ expect(mockSaveCLIConfigForProfile).toHaveBeenCalledWith(
+ undefined,
+ expect.objectContaining({
+ watched_workspaces: expect.arrayContaining([
+ expect.objectContaining({ token: "al_machine_tok", status: "registered" }),
+ ]),
}),
);
expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Logged in as [email protected]"));
@@ -361,4 +372,93 @@ describe("alook login", () => {
expect(mockSaveCLIConfigForProfile).not.toHaveBeenCalled();
});
});
+
+ describe("session token and workspace sync", () => {
+ it("stores session_token in config after login", async () => {
+ mockFetchSequence(fullSuccessResponses());
+
+ const cmd = loginCommand();
+ await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));
+
+ expect(mockSaveCLIConfigForProfile).toHaveBeenCalledWith(
+ undefined,
+ expect.objectContaining({ session_token: "session_tok_123" }),
+ );
+ });
+
+ it("syncs server workspaces to local config during login", async () => {
+ mockFetchSequence([
+ { url: "/api/auth/device/code", status: 200, body: deviceCodeResponse() },
+ { url: "/api/auth/device/token", status: 200, body: tokenSuccessResponse() },
+ { url: "/api/me", status: 200, body: { id: "u1", email: "[email protected]" } },
+ { url: "/api/workspaces", status: 200, body: [
+ { id: "sp_ws1", name: "Work" },
+ { 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" } },
+ ]);
+
+ const cmd = loginCommand();
+ await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));
+
+ expect(mockSaveCLIConfigForProfile).toHaveBeenCalledWith(
+ undefined,
+ expect.objectContaining({
+ watched_workspaces: expect.arrayContaining([
+ expect.objectContaining({ id: "sp_ws1", name: "Work", status: "active" }),
+ expect.objectContaining({ id: "sp_ws2", name: "Personal", status: "active" }),
+ ]),
+ }),
+ );
+ });
+
+ it("syncs workspaces when existing auth valid but no local workspace id", async () => {
+ mockLoadCLIConfigForProfile.mockReturnValue({
+ server_url: "http://localhost:3000",
+ session_token: "old_session_tok",
+ watched_workspaces: [{ id: null, name: null, token: "al_reg_tok", status: "registered" }],
+ });
+
+ mockFetchSequence([
+ { url: "/api/workspaces", status: 200, body: [{ id: "sp_synced", name: "Synced WS" }] },
+ { url: "/api/me", status: 200, body: { email: "[email protected]" } },
+ ]);
+
+ const cmd = loginCommand();
+ await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));
+
+ expect(mockSaveCLIConfigForProfile).toHaveBeenCalledWith(
+ undefined,
+ expect.objectContaining({
+ watched_workspaces: expect.arrayContaining([
+ expect.objectContaining({ id: "sp_synced", name: "Synced WS", status: "active" }),
+ ]),
+ }),
+ );
+ expect(consoleSpy).toHaveBeenCalledWith(
+ "Already logged in as [email protected] (workspace: Synced WS).",
+ );
+ });
+
+ it("uses session token for auth check when machine token not available", async () => {
+ mockLoadCLIConfigForProfile.mockReturnValue({
+ server_url: "http://localhost:3000",
+ session_token: "session_valid",
+ watched_workspaces: [{ id: "sp_ws1", name: "Session WS", token: "" }],
+ });
+
+ mockFetchSequence([
+ { url: "/api/workspaces", status: 200, body: [{ id: "sp_ws1", name: "Session WS" }] },
+ { url: "/api/me", status: 200, body: { email: "[email protected]" } },
+ ]);
+
+ const cmd = loginCommand();
+ await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));
+
+ expect(consoleSpy).toHaveBeenCalledWith(
+ "Already logged in as [email protected] (workspace: Session WS).",
+ );
+ });
+ });
});
diff --git a/src/cli/commands/login.ts b/src/cli/commands/login.ts
index 8f4ff9174..76f7f1616 100644
--- a/src/cli/commands/login.ts
+++ b/src/cli/commands/login.ts
@@ -3,7 +3,7 @@ import { fork, spawn } from "child_process";
import { fileURLToPath } from "url";
import { APIClient } from "../lib/client.js";
import { activateAndSave } from "../lib/activate.js";
-import { loadCLIConfigForProfile } from "../lib/config.js";
+import { loadCLIConfigForProfile, saveCLIConfigForProfile } from "../lib/config.js";
import { cmdPrefix, getServerUrl } from "../lib/env.js";
const DEVICE_CLIENT_ID = process.env.ALOOK_DEVICE_CLIENT_ID || "alook-cli";
@@ -29,6 +29,11 @@ interface TokenErrorResponse {
error_description?: string;
}
+interface WorkspaceResponse {
+ id: string;
+ name: string;
+}
+
function openBrowser(url: string): void {
try {
@@ -49,6 +54,38 @@ function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
+function syncWorkspacesToConfig(
+ serverWorkspaces: WorkspaceResponse[],
+ profile?: string,
+ sessionToken?: string,
+): void {
+ const cfg = loadCLIConfigForProfile(profile);
+ const watched = cfg.watched_workspaces || [];
+ const serverIds = new Set(serverWorkspaces.map((w) => w.id));
+
+ for (const sw of serverWorkspaces) {
+ const existing = watched.find((w) => w.id === sw.id);
+ if (existing) {
+ existing.status = "active";
+ existing.name = sw.name;
+ } else {
+ watched.push({ id: sw.id, name: sw.name, token: "", status: "active", agent_ids: [] });
+ }
+ }
+
+ for (const w of watched) {
+ if (w.id && !serverIds.has(w.id) && w.status !== "registered") {
+ w.status = "deleted";
+ }
+ }
+
+ saveCLIConfigForProfile(profile, {
+ server_url: cfg.server_url,
+ session_token: sessionToken ?? cfg.session_token,
+ watched_workspaces: watched,
+ });
+}
+
async function pollAndActivate(opts: {
deviceCode: string;
interval: number;
@@ -117,17 +154,16 @@ async function pollAndActivate(opts: {
// Non-fatal — we can proceed without the email for display
}
- // If user already has a workspace, pass it when creating machine token
- // so activate won't create a duplicate
- let existingWorkspaceId = "";
+ // Sync workspaces from server and store session token
+ let serverWorkspaces: WorkspaceResponse[] = [];
try {
- const workspaces = await client.getJSON<{ id: string }[]>("/api/workspaces");
- if (workspaces.length > 0) {
- existingWorkspaceId = workspaces[0].id;
- }
+ serverWorkspaces = await client.getJSON<WorkspaceResponse[]>("/api/workspaces");
} catch {
// Non-fatal — will create new workspace during activate
}
+ syncWorkspacesToConfig(serverWorkspaces, profile, sessionToken);
+
+ const existingWorkspaceId = serverWorkspaces.length > 0 ? serverWorkspaces[0].id : "";
const mtUrl = existingWorkspaceId
? `/api/machine-tokens?workspace_id=${existingWorkspaceId}`
@@ -165,28 +201,37 @@ if (process.argv.includes("--__login-poll")) {
async function checkExistingAuth(serverUrl: string, profile?: string): Promise<{ valid: boolean; email?: string; workspaceName?: string }> {
const config = loadCLIConfigForProfile(profile);
- const workspaces = config.watched_workspaces || [];
- if (workspaces.length === 0) {
- return { valid: false };
- }
+ // Try session token first, then machine token from workspaces
+ const sessionToken = config.session_token;
+ const workspaces = config.watched_workspaces || [];
const ws = workspaces[0];
- if (!ws.token) {
+ const authToken = sessionToken || ws?.token;
+
+ if (!authToken) {
return { valid: false };
}
try {
const res = await fetch(`${serverUrl}/api/workspaces`, {
- headers: { Authorization: `Bearer ${ws.token}` },
+ headers: { Authorization: `Bearer ${authToken}` },
});
if (!res.ok) {
return { valid: false };
}
+ const serverWorkspaces = await res.json() as WorkspaceResponse[];
+
+ // Sync workspaces when config has no workspace with a valid id
+ const hasValidWorkspace = workspaces.some((w) => w.id && w.status !== "deleted");
+ if (!hasValidWorkspace && serverWorkspaces.length > 0) {
+ syncWorkspacesToConfig(serverWorkspaces, profile);
+ }
+
let email: string | undefined;
try {
const meRes = await fetch(`${serverUrl}/api/me`, {
- headers: { Authorization: `Bearer ${ws.token}` },
+ headers: { Authorization: `Bearer ${authToken}` },
});
if (meRes.ok) {
const me = await meRes.json() as { email?: string };
@@ -196,7 +241,11 @@ async function checkExistingAuth(serverUrl: string, profile?: string): Promise<{
// Non-fatal — proceed without email
}
- return { valid: true, email, workspaceName: ws.name ?? undefined };
+ const workspaceName = (serverWorkspaces.length > 0 ? serverWorkspaces[0].name : undefined)
+ || ws?.name
+ || undefined;
+
+ return { valid: true, email, workspaceName };
} catch {
return { valid: false };
}
diff --git a/src/cli/commands/workspace.test.ts b/src/cli/commands/workspace.test.ts
index c5f70dd59..d959ace3f 100644
--- a/src/cli/commands/workspace.test.ts
+++ b/src/cli/commands/workspace.test.ts
@@ -20,9 +20,31 @@ vi.mock("../lib/resolve-client.js", () => ({
token: "test-token",
workspaceId: "ws_test",
})),
+ resolveClientOptsPartial: vi.fn(() => ({
+ serverUrl: "http://localhost:3000",
+ token: "test-token",
+ workspaceId: "ws_test",
+ })),
+}));
+
+vi.mock("../lib/config.js", () => ({
+ loadCLIConfigForProfile: vi.fn(() => ({
+ server_url: "http://localhost:3000",
+ watched_workspaces: [{ id: "ws_test", name: "Test", token: "test-token", status: "active" }],
+ })),
+ saveCLIConfigForProfile: vi.fn(),
+}));
+
+vi.mock("../lib/command-utils.js", () => ({
+ getRootOpts: vi.fn(() => ({})),
}));
import { workspaceCommand } from "./workspace";
+import { resolveClientOptsPartial } from "../lib/resolve-client.js";
+import { loadCLIConfigForProfile } from "../lib/config.js";
+
+const mockedResolvePartial = vi.mocked(resolveClientOptsPartial);
+const mockedLoadConfig = vi.mocked(loadCLIConfigForProfile);
const TMP_DIR = "/tmp/alook-workspace-test";
@@ -298,3 +320,147 @@ describe("workspace init", () => {
}));
});
});
+
+describe("workspace init — self-resolve (no workspaceId)", () => {
+ let consoleSpy: ReturnType<typeof vi.spyOn>;
+ let consoleErrSpy: ReturnType<typeof vi.spyOn>;
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
+ let mockExit: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mkdirSync(TMP_DIR, { recursive: true });
+ consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
+ consoleErrSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ consoleWarnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
+ mockExit = vi.spyOn(process, "exit").mockImplementation((code) => { throw new Error(`process.exit(${code})`); });
+
+ // Return no workspaceId — triggers self-resolve path
+ mockedResolvePartial.mockReturnValue({
+ serverUrl: "http://localhost:3000",
+ token: "test-token",
+ workspaceId: undefined,
+ });
+ mockedLoadConfig.mockReturnValue({
+ server_url: "http://localhost:3000",
+ watched_workspaces: [{ id: null, name: null, token: "test-token", status: "registered" }],
+ });
+ });
+
+ afterEach(() => {
+ rmSync(TMP_DIR, { recursive: true, force: true });
+ consoleSpy.mockRestore();
+ consoleErrSpy.mockRestore();
+ consoleWarnSpy.mockRestore();
+ mockExit.mockRestore();
+ });
+
+ function writeJson(filename: string, data: unknown) {
+ const path = join(TMP_DIR, filename);
+ writeFileSync(path, JSON.stringify(data));
+ return path;
+ }
+
+ async function runInit(args: string[]) {
+ const cmd = workspaceCommand();
+ await cmd.parseAsync(["node", "workspace", "init", ...args]);
+ }
+
+ it("finds empty workspace from server and uses it", async () => {
+ const jsonPath = writeJson("valid.json", {
+ name: "My WS",
+ members: [{ role: "leader", instructions: "You lead" }],
+ });
+
+ 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)
+
+ postJSONMock
+ .mockResolvedValueOnce({}) // POST /api/machine-tokens/bind-workspace
+ .mockResolvedValueOnce({ // POST /api/studios
+ studio: { name: "My WS" },
+ workspace: { id: "sp_ws1", name: "My WS", slug: "my-ws" },
+ agents: [{ id: "ag1", name: "Leader", email_handle: "leader" }],
+ });
+
+ 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 () => {
+ const jsonPath = writeJson("valid.json", {
+ name: "Fresh WS",
+ members: [{ role: "leader", instructions: "You lead" }],
+ });
+
+ getJSONMock
+ .mockResolvedValueOnce([{ id: "sp_ws1", name: "Full WS" }]) // GET /api/workspaces
+ .mockResolvedValueOnce([{ id: "ag_existing" }]) // GET /api/agents?workspace_id=sp_ws1 (has agents)
+ .mockResolvedValueOnce([{ id: "rt1", machineLastSeenAt: new Date().toISOString() }]); // GET /api/runtimes (polling)
+
+ postJSONMock
+ .mockResolvedValueOnce({ id: "sp_new", name: "Fresh WS" }) // POST /api/workspaces
+ .mockResolvedValueOnce({}) // POST /api/machine-tokens/bind-workspace
+ .mockResolvedValueOnce({ // POST /api/studios
+ studio: { name: "Fresh WS" },
+ workspace: { id: "sp_new", name: "Fresh WS", slug: "fresh-ws" },
+ agents: [{ id: "ag1", name: "Leader", email_handle: "leader" }],
+ });
+
+ await runInit(["--json-file", jsonPath]);
+
+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Created workspace"));
+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Workspace initialized"));
+ });
+
+ it("creates workspace with 'Personal' name when no name configured", async () => {
+ const jsonPath = writeJson("valid.json", {
+ members: [{ role: "leader", instructions: "You lead" }],
+ });
+
+ getJSONMock
+ .mockResolvedValueOnce([]) // GET /api/workspaces (empty — new user)
+ .mockResolvedValueOnce([{ id: "rt1", machineLastSeenAt: new Date().toISOString() }]); // GET /api/runtimes
+
+ postJSONMock
+ .mockResolvedValueOnce({ id: "sp_personal", name: "Personal" }) // POST /api/workspaces
+ .mockResolvedValueOnce({}) // POST /api/machine-tokens/bind-workspace
+ .mockResolvedValueOnce({ // POST /api/studios
+ studio: { name: "Personal" },
+ workspace: { id: "sp_personal", name: "Personal", slug: "personal" },
+ agents: [{ id: "ag1", name: "Leader", email_handle: "leader" }],
+ });
+
+ await runInit(["--json-file", jsonPath]);
+
+ expect(postJSONMock).toHaveBeenCalledWith("/api/workspaces", expect.objectContaining({ name: "Personal" }));
+ });
+
+ it("polls for runtimes and errors if none appear", async () => {
+ vi.useFakeTimers();
+ const jsonPath = writeJson("valid.json", {
+ members: [{ role: "leader", instructions: "x" }],
+ });
+
+ getJSONMock
+ .mockResolvedValueOnce([{ id: "sp_ws1", name: "WS" }]) // GET /api/workspaces
+ .mockResolvedValueOnce([]) // GET /api/agents (empty)
+ .mockResolvedValue([]); // GET /api/runtimes (always empty)
+
+ postJSONMock.mockResolvedValueOnce({}); // POST /api/machine-tokens/bind-workspace
+
+ const promise = runInit(["--json-file", jsonPath]).catch((e) => e);
+ for (let i = 0; i < 20; i++) {
+ await vi.advanceTimersByTimeAsync(1100);
+ }
+ const err = await promise;
+ expect(err).toBeInstanceOf(Error);
+ expect((err as Error).message).toBe("process.exit(1)");
+ expect(consoleErrSpy).toHaveBeenCalledWith(expect.stringContaining("No daemon registered after waiting"));
+ vi.useRealTimers();
+ });
+});
diff --git a/src/cli/commands/workspace.ts b/src/cli/commands/workspace.ts
index 1bb57bf10..9c89a4463 100644
--- a/src/cli/commands/workspace.ts
+++ b/src/cli/commands/workspace.ts
@@ -4,13 +4,20 @@ import { toAlookAddress } from "@alook/shared";
import { APIClient } from "../lib/client.js";
import { cmdPrefix } from "../lib/env.js";
import { printJSON } from "../lib/output.js";
-import { resolveClientOpts } from "../lib/resolve-client.js";
+import { resolveClientOptsPartial } from "../lib/resolve-client.js";
+import { loadCLIConfigForProfile, saveCLIConfigForProfile } from "../lib/config.js";
+import { getRootOpts } from "../lib/command-utils.js";
interface RuntimeResponse {
id: string;
machineLastSeenAt?: string | null;
}
+interface WorkspaceResponse {
+ id: string;
+ name: string;
+}
+
function slugify(name: string): string {
return name
.toLowerCase()
@@ -25,6 +32,43 @@ interface StudioResponse {
agents: Array<{ id: string; name: string; email_handle: string | null }>;
}
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+async function resolveWorkspaceId(client: APIClient, configName?: string): Promise<{ workspaceId: string; created: boolean }> {
+ let workspaces: WorkspaceResponse[];
+ try {
+ workspaces = await client.getJSON<WorkspaceResponse[]>("/api/workspaces");
+ } catch (err) {
+ console.error(`Error: failed to fetch workspaces: ${err instanceof Error ? err.message : err}`);
+ process.exit(1);
+ }
+
+ // Find an empty workspace (no agents)
+ for (const ws of workspaces) {
+ try {
+ const agents = await client.getJSON<Array<{ id: string }>>(`/api/agents?workspace_id=${ws.id}`);
+ if (agents.length === 0) {
+ return { workspaceId: ws.id, created: false };
+ }
+ } catch {
+ // Skip workspaces we can't check
+ }
+ }
+
+ // No empty workspace — create one
+ const wsName = configName || "Personal";
+ try {
+ const newWs = await client.postJSON<{ id: string; name: string }>("/api/workspaces", { name: wsName, slug: slugify(wsName) });
+ console.log(`Created workspace: ${newWs.name} (${newWs.id})`);
+ return { workspaceId: newWs.id, created: true };
+ } catch (err) {
+ console.error(`Error: failed to create workspace: ${err instanceof Error ? err.message : err}`);
+ process.exit(1);
+ }
+}
+
export function workspaceCommand(): Command {
const cmd = new Command("workspace").description("Manage workspaces");
@@ -35,8 +79,8 @@ export function workspaceCommand(): Command {
.option("--name <name>", "Workspace name (overrides JSON)")
.option("--json", "Output as JSON")
.action(async (opts, command) => {
- const { serverUrl, token, workspaceId } = resolveClientOpts(command);
- const client = new APIClient(serverUrl, token, workspaceId);
+ const { serverUrl, token, workspaceId: resolvedWorkspaceId } = resolveClientOptsPartial(command);
+ const client = new APIClient(serverUrl, token, resolvedWorkspaceId);
// Read local JSON file
let configJson: string;
@@ -60,10 +104,107 @@ export function workspaceCommand(): Command {
process.exit(1);
}
+ // Self-resolve workspace if not available from config/env
+ 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 appear
+ let runtimes: RuntimeResponse[] = [];
+ const wsClient = new APIClient(serverUrl, token, targetWorkspaceId);
+ for (let attempt = 0; attempt < 15; attempt++) {
+ try {
+ runtimes = await wsClient.getJSON<RuntimeResponse[]>("/api/runtimes");
+ if (runtimes.length > 0) break;
+ } catch {
+ // Retry
+ }
+ await sleep(1000);
+ }
+
+ if (runtimes.length === 0) {
+ console.error(`Error: No daemon registered after waiting. Run '${cmdPrefix()} daemon start' first.`);
+ process.exit(1);
+ }
+
+ // Pick runtime and continue
+ const OFFLINE_THRESHOLD_MS = 5 * 60 * 1000;
+ const now = Date.now();
+ const onlineRuntime = runtimes.find((r) => {
+ if (!r.machineLastSeenAt) return false;
+ const lastSeen = new Date(r.machineLastSeenAt.includes("Z") ? r.machineLastSeenAt : r.machineLastSeenAt + "Z").getTime();
+ return now - lastSeen < OFFLINE_THRESHOLD_MS;
+ });
+ const runtime = onlineRuntime || runtimes[0];
+
+ const members = config.members.map((m) => ({
+ ...m,
+ runtime_id: runtime.id,
+ }));
+
+ const payload = {
+ name: opts.name || config.name,
+ scenario: config.scenario,
+ members,
+ };
+
+ try {
+ const res = await wsClient.postJSON<StudioResponse>("/api/studios", payload);
+
+ // Update local config with the resolved workspace
+ try {
+ const freshCfg = loadCLIConfigForProfile(parentOpts.profile);
+ const watched = freshCfg.watched_workspaces || [];
+ const existing = watched.find((w) => w.id === targetWorkspaceId);
+ if (existing) {
+ existing.status = "active";
+ existing.name = res.workspace.name;
+ } else {
+ watched.push({ id: targetWorkspaceId, name: res.workspace.name, token: token, status: "active", agent_ids: [] });
+ }
+ freshCfg.watched_workspaces = watched;
+ saveCLIConfigForProfile(parentOpts.profile, freshCfg);
+ } catch {
+ // Best-effort config update
+ }
+
+ if (opts.json) return printJSON(res);
+
+ console.log(`\nWorkspace initialized: ${res.studio.name || res.workspace.name}`);
+ console.log("Agents created:");
+ for (const agent of res.agents) {
+ const email = agent.email_handle ? toAlookAddress(agent.email_handle) : "no email";
+ console.log(` - ${agent.name} (${email})`);
+ }
+ console.log(`\n Open: ${serverUrl}/w/${res.workspace.slug}`);
+ } catch (err) {
+ console.error(`Error: failed to create workspace: ${err instanceof Error ? err.message : err}`);
+ process.exit(1);
+ }
+ return;
+ }
+
+ // Existing path: workspace was resolved from config/env
+ let targetClient = new APIClient(serverUrl, token, targetWorkspaceId);
+
// Get runtimes for this workspace
let runtimes: RuntimeResponse[];
try {
- runtimes = await client.getJSON<RuntimeResponse[]>("/api/runtimes");
+ runtimes = await targetClient.getJSON<RuntimeResponse[]>("/api/runtimes");
} catch (err) {
console.error(`Error: failed to fetch runtimes: ${err instanceof Error ? err.message : err}`);
process.exit(1);
@@ -85,14 +226,12 @@ export function workspaceCommand(): Command {
let runtime = onlineRuntime || runtimes[0];
// Check if workspace already has agents — if so, create a new workspace
- let targetWorkspaceId = workspaceId;
- let targetClient = client;
try {
- const agents = await client.getJSON<Array<{ id: string }>>(`/api/agents?workspace_id=${workspaceId}`);
+ const agents = await targetClient.getJSON<Array<{ id: string }>>(`/api/agents?workspace_id=${targetWorkspaceId}`);
if (agents.length > 0) {
console.log("Current workspace has existing agents. Creating a new workspace...");
const wsName = opts.name || config.name || "New Workspace";
- const newWs = await client.postJSON<{ id: string; name: string }>("/api/workspaces", { name: wsName, slug: slugify(wsName) });
+ const newWs = await targetClient.postJSON<{ id: string; name: string }>("/api/workspaces", { name: wsName, slug: slugify(wsName) });
targetWorkspaceId = newWs.id;
targetClient = new APIClient(serverUrl, token, targetWorkspaceId);
console.log(`Created workspace: ${newWs.name} (${newWs.id})`);
diff --git a/src/cli/lib/config.ts b/src/cli/lib/config.ts
index c2ef0ef2e..ef706543d 100644
--- a/src/cli/lib/config.ts
+++ b/src/cli/lib/config.ts
@@ -6,17 +6,19 @@ interface WatchedWorkspace {
id: string | null;
name: string | null;
token: string;
- status?: "registered" | "active";
+ status?: "registered" | "active" | "deleted";
agent_ids?: string[];
}
interface ProfileConfig {
server_url: string;
+ session_token?: string;
watched_workspaces: WatchedWorkspace[];
}
interface CLIConfig {
server_url?: string;
+ session_token?: string;
watched_workspaces?: WatchedWorkspace[];
default_profile?: string;
profiles?: Record<string, ProfileConfig>;
@@ -48,6 +50,7 @@ export function loadCLIConfigForProfile(profile?: string): ProfileConfig {
}
const result: ProfileConfig = {
server_url: cfg.server_url || "",
+ session_token: cfg.session_token,
watched_workspaces: cfg.watched_workspaces || [],
};
@@ -80,6 +83,7 @@ export function saveCLIConfigForProfile(
cfg.profiles[profile] = profileConfig;
} else {
cfg.server_url = profileConfig.server_url;
+ cfg.session_token = profileConfig.session_token;
cfg.watched_workspaces = profileConfig.watched_workspaces;
// Remove legacy machine_token if present
delete (cfg as Record<string, unknown>).machine_token;
diff --git a/src/cli/lib/resolve-client.ts b/src/cli/lib/resolve-client.ts
index 8ec79c5de..acd07fdd7 100644
--- a/src/cli/lib/resolve-client.ts
+++ b/src/cli/lib/resolve-client.ts
@@ -9,12 +9,29 @@ export interface ResolvedClient {
workspaceId: string;
}
+export interface ResolvedClientPartial {
+ serverUrl: string;
+ token: string;
+ workspaceId?: string;
+}
+
export interface ResolveClientOptions {
workspace?: string;
agentId?: string;
}
export function resolveClientOpts(command: Command, opts: ResolveClientOptions = {}): ResolvedClient {
+ const result = resolveClientOptsPartial(command, opts);
+ if (!result.workspaceId) {
+ console.error(
+ "Error: cannot determine workspace. Set ALOOK_WORKSPACE_ID env var or use --workspace flag.",
+ );
+ process.exit(1);
+ }
+ return result as ResolvedClient;
+}
+
+export function resolveClientOptsPartial(command: Command, opts: ResolveClientOptions = {}): ResolvedClientPartial {
const parentOpts = getRootOpts(command) as { server?: string; profile?: string };
const cfg = loadCLIConfigForProfile(parentOpts.profile);
@@ -36,7 +53,6 @@ export function resolveClientOpts(command: Command, opts: ResolveClientOptions =
ws = workspaces.find((w) => w.id === opts.workspace);
if (!ws) {
if (envWorkspaceId === opts.workspace) {
- // workspace from flag matches env — use env-based resolution
ws = undefined;
} else {
console.error(`Error: workspace ${opts.workspace} not found in config.`);
@@ -49,15 +65,14 @@ export function resolveClientOpts(command: Command, opts: ResolveClientOptions =
if (workspaces.length === 1) {
ws = workspaces[0];
}
- // If still not found, fall through to env var resolution below
}
} else if (workspaces.length === 1) {
ws = workspaces[0];
}
- // Token resolution: env > config
+ // Token resolution: env > config > session_token
const envToken = process.env.ALOOK_TOKEN;
- const token = envToken || ws?.token;
+ const token = envToken || ws?.token || cfg.session_token;
if (!token) {
console.error(
@@ -66,15 +81,8 @@ export function resolveClientOpts(command: Command, opts: ResolveClientOptions =
process.exit(1);
}
- // Workspace ID resolution: ws from config > env > error
- const workspaceId = ws?.id || envWorkspaceId;
-
- if (!workspaceId) {
- console.error(
- "Error: cannot determine workspace. Set ALOOK_WORKSPACE_ID env var or use --workspace flag.",
- );
- process.exit(1);
- }
+ // Workspace ID resolution: ws from config > env > undefined (for partial)
+ const workspaceId = ws?.id || envWorkspaceId || undefined;
return { serverUrl, token, workspaceId };
}
diff --git a/src/web/src/test/e2e/onboard-flow.test.ts b/src/web/src/test/e2e/onboard-flow.test.ts
new file mode 100644
index 000000000..507768c1d
--- /dev/null
+++ b/src/web/src/test/e2e/onboard-flow.test.ts
@@ -0,0 +1,598 @@
+import { describe, it, expect, beforeAll, afterAll } from "vitest"
+import { randomUUID } from "crypto"
+import { signUp, signIn, sessionRequest, tokenRequest, sqlRun, sqlQuery, fetchWithRetry } 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",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ client_id: TEST_CLIENT_ID }),
+ })
+ const codeData = await codeRes.json() as { device_code: string; user_code: string }
+
+ await sessionRequest(`/api/auth/device?user_code=${codeData.user_code}`, sessionCookie)
+ await sessionRequest("/api/auth/device/approve", sessionCookie, {
+ method: "POST",
+ headers: { "Content-Type": "application/json", Origin: APP_URL },
+ body: JSON.stringify({ userCode: codeData.user_code }),
+ })
+
+ await new Promise(r => setTimeout(r, 5100))
+
+ const tokenRes = await fetch(`${APP_URL}/api/auth/device/token`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
+ device_code: codeData.device_code,
+ client_id: TEST_CLIENT_ID,
+ }),
+ })
+ const tokenData = await tokenRes.json() as { access_token: string }
+ return tokenData.access_token
+}
+
+describe("onboard flow — user scenarios", () => {
+
+ // ─────────────────────────────────────────────────────────────────────────
+ // Scenario 1: Brand-new user complete onboard flow
+ // login → session token stored → no workspace → daemon standby →
+ // workspace init → create workspace + bind → studio success
+ // ─────────────────────────────────────────────────────────────────────────
+ describe("Scenario 1: New user complete onboard flow", () => {
+ const email = `e2e_onboard_new_${randomUUID().slice(0, 8)}@test.local`
+ const password = "TestPass123!"
+ let sessionCookie: string
+ let accessToken: string
+ let machineToken: string
+ let machineTokenId: string
+ let workspaceId: string
+
+ beforeAll(async () => {
+ await signUp(email, password, "E2E New User")
+ sessionCookie = await signIn(email, password)
+ })
+
+ it("login via device code auth stores session token", async () => {
+ accessToken = await deviceCodeLogin(sessionCookie)
+ expect(accessToken).toBeTruthy()
+
+ // Verify session token works
+ const 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
+ 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, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ workspace_id: workspaceId }),
+ })
+ 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)
+ })
+
+ 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("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`, {
+ 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" }],
+ }),
+ })
+ 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)
+ })
+
+ 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 */ }
+ })
+ })
+
+ // ─────────────────────────────────────────────────────────────────────────
+ // 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`
+ const password = "TestPass123!"
+ let sessionCookie: string
+ let accessToken: string
+ let deletedWorkspaceId: string
+ let newWorkspaceId: string
+ let machineToken: string
+ let machineTokenId: string
+
+ beforeAll(async () => {
+ await signUp(email, password, "E2E Deleted WS 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)}` }),
+ })
+ 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)
+ })
+
+ 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, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ name: "Phoenix Co", slug: `phoenix-co-${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
+
+ // Create a new machine token for the new workspace
+ const mtRes = await tokenRequest(
+ `/api/machine-tokens?workspace_id=${newWorkspaceId}`,
+ accessToken,
+ { method: "POST", headers: { "Content-Type": "application/json" } },
+ )
+ expect(mtRes.status).toBeLessThan(300)
+ const mtData = await mtRes.json() as { token: string; id: string }
+ const newMachineToken = mtData.token
+
+ // Activate new token
+ await fetchWithRetry(`${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" }],
+ }),
+ })
+
+ // 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 */ }
+ })
+ })
+})