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
feat: add Device Code Flow login and /onboard.md endpoint (#188)
Gener43e4a41b3147
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 1eb62fddf..ad17d756c 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -67,7 +67,7 @@ jobs:cache: pnpm- run: pnpm install --frozen-lockfile- name: Create .dev.vars for local bindings- run: printf 'BETTER_AUTH_SECRET=ci-e2e-secret\nBETTER_AUTH_URL=http://localhost:3000\n' > src/web/.dev.vars+ run: printf 'BETTER_AUTH_SECRET=ci-e2e-secret\nBETTER_AUTH_URL=http://localhost:3000\nDEVICE_CLIENT_IDS=e2e-test-client\n' > src/web/.dev.vars- run: pnpm run db:migrate- name: Start dev serversrun: |@@ -109,7 +109,7 @@ jobs:cache: pnpm- run: pnpm install --frozen-lockfile- name: Create .dev.vars- run: printf 'BETTER_AUTH_SECRET=ci-lighthouse-secret\nBETTER_AUTH_URL=http://localhost:3000\n' > src/web/.dev.vars+ run: printf 'BETTER_AUTH_SECRET=ci-lighthouse-secret\nBETTER_AUTH_URL=http://localhost:3000\nDEVICE_CLIENT_IDS=e2e-test-client\n' > src/web/.dev.vars- name: Lighthouse CIworking-directory: src/webrun: npx @lhci/cli autorun --config=lighthouserc.json && node scripts/print-lighthouse-scores.mjsdiff --git a/src/cli/commands/login.test.ts b/src/cli/commands/login.test.tsnew file mode 100644index 000000000..b3e04009d--- /dev/null+++ b/src/cli/commands/login.test.ts@@ -0,0 +1,206 @@+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";++const mockLoadCLIConfigForProfile = vi.fn();+const mockSaveCLIConfigForProfile = vi.fn();+const mockReadDaemonPid = vi.fn();+const mockIsProcessAlive = vi.fn();++vi.mock("../lib/config.js", () => ({+ loadCLIConfigForProfile: (...args: any[]) => mockLoadCLIConfigForProfile(...args),+ saveCLIConfigForProfile: (...args: any[]) => mockSaveCLIConfigForProfile(...args),+}));++vi.mock("../daemon/pidfile.js", () => ({+ readDaemonPid: (...args: any[]) => mockReadDaemonPid(...args),+ isProcessAlive: (...args: any[]) => mockIsProcessAlive(...args),+}));++vi.mock("../lib/env.js", () => ({+ cmdPrefix: () => "alook",+ isDev: () => false,+}));++vi.mock("../lib/runtimes.js", () => ({+ isCommandAvailable: vi.fn(() => true),+ detectRuntimes: vi.fn(() => [{ type: "claude", version: "4.0.0" }]),+}));++vi.mock("child_process", () => ({+ execSync: vi.fn((cmd: string) => {+ if (cmd.includes("which claude")) return "/usr/bin/claude";+ if (cmd.includes("claude --version")) return "4.0.0";+ throw new Error("not found");+ }),+ spawn: vi.fn(() => ({ unref: vi.fn() })),+ fork: vi.fn(() => ({ unref: vi.fn() })),+}));++import { loginCommand } from "./login";++describe("alook login", () => {+ let consoleSpy: ReturnType<typeof vi.spyOn>;+ let consoleErrSpy: ReturnType<typeof vi.spyOn>;+ let mockExit: ReturnType<typeof vi.spyOn>;+ let mockKill: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ vi.useFakeTimers();+ vi.clearAllMocks();+ consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});+ consoleErrSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ mockExit = vi.spyOn(process, "exit").mockImplementation(() => undefined as never);+ mockKill = vi.spyOn(process, "kill").mockImplementation(() => true);+ Object.defineProperty(process.stdout, "isTTY", { value: true, writable: true });+ mockLoadCLIConfigForProfile.mockReturnValue({+ server_url: "http://localhost:3000",+ watched_workspaces: [],+ });+ mockReadDaemonPid.mockReturnValue(null);+ });++ afterEach(() => {+ vi.useRealTimers();+ consoleSpy.mockRestore();+ consoleErrSpy.mockRestore();+ mockExit.mockRestore();+ mockKill.mockRestore();+ vi.unstubAllGlobals();+ });++ function mockFetchSequence(responses: { url: string; status: number; body: unknown }[]) {+ const queue = [...responses];+ vi.stubGlobal("fetch", vi.fn(async (url: string | URL | Request) => {+ const urlStr = typeof url === "string" ? url : url instanceof URL ? url.toString() : url.url;+ const idx = queue.findIndex((r) => urlStr.includes(r.url));+ if (idx >= 0) {+ const resp = queue[idx];+ queue.splice(idx, 1);+ return {+ ok: resp.status >= 200 && resp.status < 300,+ status: resp.status,+ json: async () => resp.body,+ text: async (): Promise<string> => JSON.stringify(resp.body),+ };+ }+ return { ok: false, status: 404, text: async (): Promise<string> => "not found", json: async () => ({ error: "not_found" }) };+ }));+ }++ function deviceCodeResponse(overrides: Partial<Record<string, unknown>> = {}) {+ return {+ device_code: "dc_123",+ user_code: "ABCD-EFGH",+ verification_uri: "http://localhost:3000/device",+ verification_uri_complete: "http://localhost:3000/device?user_code=ABCD-EFGH",+ expires_in: 900,+ interval: 1,+ ...overrides,+ };+ }++ function tokenSuccessResponse(token = "session_tok_123") {+ return { access_token: token, token_type: "Bearer", expires_in: 2592000, scope: "" };+ }++ function fullSuccessResponses() {+ return [+ { 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: "My Workspace" }] },+ { url: "/api/machine-tokens", status: 201, body: { token: "al_machine_tok" } },+ { url: "/api/machine-tokens/activate", status: 200, body: { daemon_id: "host1", workspace_id: "sp_ws1", runtimes: [{ id: "r1", provider: "claude" }] } },+ { url: "/api/workspaces", status: 200, body: [{ id: "sp_ws1", name: "My Workspace" }] },+ { url: "/api/agents", status: 200, body: [{ id: "ag_1" }] },+ ];+ }++ async function runWithTimers(promise: Promise<unknown>) {+ // Advance timers repeatedly until the promise settles+ let settled = false;+ const result = promise.finally(() => { settled = true; });+ while (!settled) {+ await vi.advanceTimersByTimeAsync(10000);+ }+ return result;+ }++ it("completes full device code flow and saves config", async () => {+ mockFetchSequence(fullSuccessResponses());++ const cmd = loginCommand();+ await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));++ expect(mockSaveCLIConfigForProfile).toHaveBeenCalledWith(+ undefined,+ expect.objectContaining({+ server_url: "http://localhost:3000",+ watched_workspaces: [+ { id: "sp_ws1", name: "My Workspace", token: "al_machine_tok", agent_ids: ["ag_1"] },+ ],+ }),+ );+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Logged in as [email protected]"));+ });+++ it("handles authorization_pending by continuing to poll", async () => {+ mockFetchSequence([+ { url: "/api/auth/device/code", status: 200, body: deviceCodeResponse() },+ { url: "/api/auth/device/token", status: 400, body: { error: "authorization_pending" } },+ { 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_poll", name: "Poll WS" }] },+ { url: "/api/machine-tokens", status: 201, body: { token: "al_poll_tok" } },+ { url: "/api/machine-tokens/activate", status: 200, body: { daemon_id: "host1", workspace_id: "sp_poll", runtimes: [{ id: "r1", provider: "claude" }] } },+ { url: "/api/workspaces", status: 200, body: [{ id: "sp_poll", name: "Poll WS" }] },+ { url: "/api/agents", status: 200, body: [] },+ ]);++ const cmd = loginCommand();+ await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));++ expect(mockSaveCLIConfigForProfile).toHaveBeenCalled();+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Logged in as [email protected]"));+ });++ it("handles slow_down by increasing polling interval", async () => {+ mockFetchSequence([+ { url: "/api/auth/device/code", status: 200, body: deviceCodeResponse() },+ { url: "/api/auth/device/token", status: 400, body: { error: "slow_down" } },+ { 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_slow", name: "Slow WS" }] },+ { url: "/api/machine-tokens", status: 201, body: { token: "al_slow_tok" } },+ { url: "/api/machine-tokens/activate", status: 200, body: { daemon_id: "host1", workspace_id: "sp_slow", runtimes: [{ id: "r1", provider: "claude" }] } },+ { url: "/api/workspaces", status: 200, body: [{ id: "sp_slow", name: "Slow WS" }] },+ { url: "/api/agents", status: 200, body: [] },+ ]);++ const cmd = loginCommand();+ await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));++ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Logged in as [email protected]"));+ });++ it("sends SIGHUP when daemon is running after login", async () => {+ mockReadDaemonPid.mockReturnValue(99999);+ mockIsProcessAlive.mockReturnValue(true);+ mockFetchSequence(fullSuccessResponses());++ const cmd = loginCommand();+ await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));++ expect(mockKill).toHaveBeenCalledWith(99999, "SIGHUP");+ });++ it("displays verification URL and user code", async () => {+ mockFetchSequence(fullSuccessResponses());++ const cmd = loginCommand();+ await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));++ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("http://localhost:3000/device?user_code=ABCD-EFGH"));+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("ABCD-EFGH"));+ });+});diff --git a/src/cli/commands/login.ts b/src/cli/commands/login.tsnew file mode 100644index 000000000..bb6bec110--- /dev/null+++ b/src/cli/commands/login.ts@@ -0,0 +1,248 @@+import { Command } from "commander";+import { fork, spawn } from "child_process";+import { fileURLToPath } from "url";+import { APIClient } from "../lib/client.js";+import { activateAndSave } from "../lib/activate.js";++const DEVICE_CLIENT_ID = process.env.ALOOK_DEVICE_CLIENT_ID || "alook-cli";++interface DeviceCodeResponse {+ device_code: string;+ user_code: string;+ verification_uri: string;+ verification_uri_complete: string;+ expires_in: number;+ interval: number;+}++interface TokenResponse {+ access_token: string;+ token_type: string;+ expires_in: number;+ scope: string;+}++interface TokenErrorResponse {+ error: string;+ error_description?: string;+}+++function openBrowser(url: string): void {+ try {+ const cmd =+ process.platform === "darwin" ? "open" :+ process.platform === "linux" ? "xdg-open" :+ process.platform === "win32" ? "start" : null;+ if (cmd) {+ const args = process.platform === "win32" ? ["", url] : [url];+ spawn(cmd, args, { stdio: "ignore", detached: true }).unref();+ }+ } catch {+ // Browser open is best-effort+ }+}++function sleep(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms));+}++async function pollAndActivate(opts: {+ deviceCode: string;+ interval: number;+ expiresIn: number;+ serverUrl: string;+ profile?: string;+}): Promise<void> {+ const { deviceCode, expiresIn, serverUrl, profile } = opts;+ let interval = opts.interval;+ const expiresAt = Date.now() + expiresIn * 1000;+ let tokenResp: TokenResponse | undefined;++ while (Date.now() < expiresAt) {+ await sleep(interval);++ try {+ const res = await fetch(`${serverUrl}/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: deviceCode,+ client_id: DEVICE_CLIENT_ID,+ }),+ });++ if (res.ok) {+ tokenResp = await res.json() as TokenResponse;+ break;+ }++ const errBody = await res.json() as TokenErrorResponse;+ if (errBody.error === "slow_down") {+ interval += 5000;+ } else if (errBody.error === "authorization_pending") {+ // Keep polling+ } else if (errBody.error === "expired_token") {+ console.error("Error: device code expired. Please run login again.");+ process.exit(1);+ } else if (errBody.error === "access_denied") {+ console.error("Error: authorization was denied.");+ process.exit(1);+ } else {+ console.error(`Error: unexpected error: ${errBody.error_description || errBody.error}`);+ process.exit(1);+ }+ } catch {+ console.error("Error: network request failed during polling.");+ process.exit(1);+ }+ }++ if (!tokenResp) {+ console.error("Error: device code expired (timed out). Please run login again.");+ process.exit(1);+ }++ const sessionToken = tokenResp.access_token;+ const client = new APIClient(serverUrl, sessionToken);++ let email = "";+ try {+ const me = await client.getJSON<{ id: string; email: string }>("/api/me");+ email = me.email;+ } catch {+ // 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 = "";+ try {+ const workspaces = await client.getJSON<{ id: string }[]>("/api/workspaces");+ if (workspaces.length > 0) {+ existingWorkspaceId = workspaces[0].id;+ }+ } catch {+ // Non-fatal — will create new workspace during activate+ }++ const mtUrl = existingWorkspaceId+ ? `/api/machine-tokens?workspace_id=${existingWorkspaceId}`+ : "/api/machine-tokens";++ let machineToken: string;+ try {+ const mtResp = await client.postJSON<{ token: string }>(mtUrl);+ machineToken = mtResp.token;+ } catch {+ process.exit(1);+ }++ const result = await activateAndSave({ token: machineToken, serverUrl, profile });++ if (email) {+ console.log(`\nLogged in as ${email}`);+ }+ 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 mode+if (process.argv.includes("--__login-poll")) {+ const idx = process.argv.indexOf("--__login-poll");+ let data;+ try {+ data = JSON.parse(process.argv[idx + 1]);+ } catch {+ console.error("Error: invalid poll data");+ process.exit(1);+ }+ pollAndActivate(data).catch(() => process.exit(1));+}++export function loginCommand(): Command {+ const cmd = new Command("login")+ .description("Log in to Alook via browser (device code flow)")+ .option("--server <url>", "Server URL")+ .option("--profile <name>", "Profile name")+ .action(async (opts, command) => {+ const profile: string | undefined =+ opts.profile || command.parent?.opts().profile;+ const serverUrl: string =+ opts.server ||+ command.parent?.opts().server ||+ process.env.ALOOK_SERVER_URL ||+ "https://alook.ai";++ // Step 1: Request device code+ console.log("Requesting device code...");+ let deviceResp: DeviceCodeResponse;+ try {+ const res = await fetch(`${serverUrl}/api/auth/device/code`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ client_id: DEVICE_CLIENT_ID }),+ });+ if (!res.ok) {+ const text = await res.text();+ console.error(`Error: failed to get device code (${res.status}): ${text}`);+ process.exit(1);+ }+ deviceResp = await res.json() as DeviceCodeResponse;+ } catch (err) {+ console.error(+ `Error: failed to request device code: ${err instanceof Error ? err.message : err}`,+ );+ process.exit(1);+ }++ // Step 2: Display verification URL and code+ const verificationUrl = deviceResp.verification_uri_complete || deviceResp.verification_uri;+ console.log();+ console.log(` Open this URL in your browser:`);+ console.log(` ${verificationUrl}`);+ console.log();+ console.log(` Enter code: ${deviceResp.user_code}`);+ console.log();++ // Non-TTY (AI agent context): fork a background poller and exit immediately+ // so the agent gets the URL output and can prompt the user to authorize.+ if (!process.stdout.isTTY) {+ const pollData = JSON.stringify({+ deviceCode: deviceResp.device_code,+ interval: (deviceResp.interval || 5) * 1000,+ expiresIn: deviceResp.expires_in,+ serverUrl,+ profile,+ });++ const thisFile = fileURLToPath(import.meta.url);+ const child = fork(thisFile, ["--__login-poll", pollData], {+ detached: true,+ stdio: "ignore",+ });+ child.unref();++ console.log(" Polling for authorization in the background (timeout: 5min).");+ console.log(" Once approved, run `npx @alook/cli status` to verify.");+ return;+ }++ // TTY: open browser and poll in foreground+ openBrowser(verificationUrl);+ console.log(" (Browser opened automatically)");+ console.log();+ console.log("Waiting for authorization...");++ await pollAndActivate({+ deviceCode: deviceResp.device_code,+ interval: (deviceResp.interval || 5) * 1000,+ expiresIn: deviceResp.expires_in,+ serverUrl,+ profile,+ });+ });++ return cmd;+}diff --git a/src/cli/commands/register.test.ts b/src/cli/commands/register.test.tsindex 663d86f7c..f877d40e1 100644--- a/src/cli/commands/register.test.ts+++ b/src/cli/commands/register.test.ts@@ -20,6 +20,11 @@ vi.mock("../lib/env.js", () => ({isDev: () => false,}));+vi.mock("../lib/runtimes.js", () => ({+ isCommandAvailable: vi.fn(() => true),+ detectRuntimes: vi.fn(() => [{ type: "claude", version: "4.0.0" }]),+}));+vi.mock("child_process", () => ({execSync: vi.fn((cmd: string) => {if (cmd.includes("which claude")) return "/usr/bin/claude";diff --git a/src/cli/commands/register.ts b/src/cli/commands/register.tsindex 0b334ff2a..4585648d3 100644--- a/src/cli/commands/register.ts+++ b/src/cli/commands/register.ts@@ -1,57 +1,13 @@import { Command } from "commander";-import { execSync } from "child_process";-import { hostname } from "os";import { APIClient } from "../lib/client.js";-import { loadCLIConfigForProfile, saveCLIConfigForProfile } from "../lib/config.js";-import { cmdPrefix, isDev } from "../lib/env.js";-import { readDaemonPid, isProcessAlive } from "../daemon/pidfile.js";+import { cmdPrefix } from "../lib/env.js";+import { activateAndSave } from "../lib/activate.js";interface MeResponse {id: string;email: string;}-interface Workspace {- id: string;- name: string;-}--interface AgentListItem {- id: string;-}--interface ActivateResponse {- daemon_id: string;- workspace_id: string;- runtimes: { id: string; provider: string }[];-}--function isCommandAvailable(cmd: string): boolean {- try {- const check = process.platform === "win32" ? `where ${cmd}` : `which ${cmd}`;- execSync(check, { stdio: "ignore" });- return true;- } catch {- return false;- }-}--function detectRuntimes(): { type: string; version: string }[] {- const found: { type: string; version: string }[] = [];- for (const type of ["claude", "codex", "opencode"]) {- if (isCommandAvailable(type)) {- let version = "";- try {- version = execSync(`${type} --version`, { encoding: "utf-8" }).trim();- } catch {- // version detection optional- }- found.push({ type, version });- }- }- return found;-}-export function registerCommand(): Command {const cmd = new Command("register").description("Register CLI with your Alook account")@@ -95,106 +51,11 @@ export function registerCommand(): Command {process.exit(1);}- // Detect local runtimes- console.log("Scanning for AI runtimes...");- const runtimes = detectRuntimes();- if (runtimes.length === 0) {- console.error(- "Error: no runtimes found. Install claude, codex, or opencode first.",- );- process.exit(1);- }- console.log(- `Found: ${runtimes.map((r) => r.type).join(", ")}`,- );-- // Activate token — may create workspace if none exists- const host = hostname();- console.log("Registering runtime...");- let activateResp: ActivateResponse;- try {- const res = await fetch(`${serverUrl}/api/machine-tokens/activate`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ token, hostname: host, runtimes }),- });- if (!res.ok) {- const text = await res.text();- console.error(`Error: registration failed (${res.status}): ${text}`);- process.exit(1);- }- activateResp = await res.json() as ActivateResponse;- } catch (err) {- console.error(- `Error: failed to activate: ${err instanceof Error ? err.message : err}`,- );- process.exit(1);- }-- // Fetch workspaces after activation (activation may have created one)- 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);- }-- // Use the workspace_id from activate response to find the correct workspace- const ws = workspaces.find((w) => w.id === activateResp.workspace_id) || workspaces[0];-- // Fetch agents for this workspace- 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 — agent_ids will be empty- }-- // Load existing config to preserve other workspaces- const existing = loadCLIConfigForProfile(profile);- const watched = existing.watched_workspaces || [];- const idx = watched.findIndex((w) => w.id === ws.id);- if (idx >= 0) {- watched[idx] = { id: ws.id, name: ws.name, token, agent_ids: agentIds };- } else {- watched.push({ id: ws.id, name: ws.name, token, agent_ids: agentIds });- }-- saveCLIConfigForProfile(profile, {- server_url: serverUrl,- watched_workspaces: watched,- });+ const result = await activateAndSave({ token, serverUrl, profile });console.log(`\nRegistered as ${me.email}`);- console.log(`Workspace: ${ws.name} (${ws.id})`);- console.log(`Runtimes: ${activateResp.runtimes.map((r) => r.provider).join(", ")}`);-- // Notify running daemon to pick up the new workspace- const daemonPid = readDaemonPid(profile);- if (daemonPid && isProcessAlive(daemonPid)) {- try {- process.kill(daemonPid, "SIGHUP");- 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 workspace.`);- }- } else {- const startCmd = isDev()- ? `${cmdPrefix()} daemon start --foreground`- : `${cmdPrefix()} daemon start`;- console.log();- console.log(`Run '${startCmd}' to start the daemon.`);- }+ console.log(`Workspace: ${result.workspaceName} (${result.workspaceId})`);+ console.log(`Runtimes: ${result.runtimeProviders.join(", ")}`);});return cmd;diff --git a/src/cli/lib/activate.ts b/src/cli/lib/activate.tsnew file mode 100644index 000000000..25b2c9c28--- /dev/null+++ b/src/cli/lib/activate.ts@@ -0,0 +1,131 @@+import { hostname } from "os";+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 { detectRuntimes } from "./runtimes.js";++interface ActivateResponse {+ daemon_id: string;+ workspace_id: string;+ runtimes: { id: string; provider: string }[];+}++interface Workspace {+ id: string;+ name: string;+}++interface AgentListItem {+ id: string;+}++export interface ActivateResult {+ workspaceId: string;+ workspaceName: string;+ runtimeProviders: string[];+}++export async function activateAndSave(opts: {+ token: string;+ serverUrl: string;+ profile?: string;+}): Promise<ActivateResult> {+ const { token, serverUrl, profile } = opts;++ console.log("Scanning for AI runtimes...");+ const runtimes = detectRuntimes();+ if (runtimes.length === 0) {+ console.error(+ "Error: no runtimes found. Install claude, codex, or opencode first.",+ );+ process.exit(1);+ }+ console.log(`Found: ${runtimes.map((r) => r.type).join(", ")}`);++ const host = hostname();+ console.log("Registering runtime...");+ let activateResp: ActivateResponse;+ try {+ const res = await fetch(`${serverUrl}/api/machine-tokens/activate`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ token, hostname: host, runtimes }),+ });+ if (!res.ok) {+ const text = await res.text();+ console.error(`Error: registration failed (${res.status}): ${text}`);+ process.exit(1);+ }+ activateResp = await res.json() as ActivateResponse;+ } catch (err) {+ console.error(+ `Error: failed to activate: ${err instanceof Error ? err.message : err}`,+ );+ process.exit(1);+ }++ 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 || [];+ const idx = watched.findIndex((w) => w.id === ws.id);+ if (idx >= 0) {+ watched[idx] = { id: ws.id, name: ws.name, token, agent_ids: agentIds };+ } else {+ watched.push({ id: ws.id, name: ws.name, token, agent_ids: agentIds });+ }++ saveCLIConfigForProfile(profile, {+ server_url: serverUrl,+ watched_workspaces: watched,+ });++ const daemonPid = readDaemonPid(profile);+ if (daemonPid && isProcessAlive(daemonPid)) {+ try {+ process.kill(daemonPid, "SIGHUP");+ 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 workspace.`);+ }+ } else {+ const startCmd = isDev()+ ? `${cmdPrefix()} daemon start --foreground`+ : `${cmdPrefix()} daemon start`;+ console.log();+ console.log(`Run '${startCmd}' to start the daemon.`);+ }++ return {+ workspaceId: ws.id,+ workspaceName: ws.name,+ runtimeProviders: activateResp.runtimes.map((r) => r.provider),+ };+}diff --git a/src/cli/lib/runtimes.ts b/src/cli/lib/runtimes.tsnew file mode 100644index 000000000..00b398fd0--- /dev/null+++ b/src/cli/lib/runtimes.ts@@ -0,0 +1,27 @@+import { execSync } from "child_process";++export function isCommandAvailable(cmd: string): boolean {+ try {+ const check = process.platform === "win32" ? `where ${cmd}` : `which ${cmd}`;+ execSync(check, { stdio: "ignore" });+ return true;+ } catch {+ return false;+ }+}++export function detectRuntimes(): { type: string; version: string }[] {+ const found: { type: string; version: string }[] = [];+ for (const type of ["claude", "codex", "opencode"]) {+ if (isCommandAvailable(type)) {+ let version = "";+ try {+ version = execSync(`${type} --version`, { encoding: "utf-8" }).trim();+ } catch {+ // version detection optional+ }+ found.push({ type, version });+ }+ }+ return found;+}diff --git a/src/cli/src/index.ts b/src/cli/src/index.tsindex 5110c63b0..8a80e6efa 100644--- a/src/cli/src/index.ts+++ b/src/cli/src/index.ts@@ -1,6 +1,7 @@#!/usr/bin/env nodeimport { Command } from "commander";import { registerCommand } from "../commands/register.js";+import { loginCommand } from "../commands/login.js";import { statusCommand } from "../commands/status.js";import { daemonCommand } from "../commands/daemon.js";import { configCommand } from "../commands/config.js";@@ -21,6 +22,7 @@ program.option("--profile <name>", "Profile name");program.addCommand(registerCommand());+program.addCommand(loginCommand());program.addCommand(statusCommand());program.addCommand(daemonCommand());program.addCommand(emailCommand());diff --git a/src/web/.dev.vars.example b/src/web/.dev.vars.exampleindex bc482d72b..1654539cf 100644--- a/src/web/.dev.vars.example+++ b/src/web/.dev.vars.example@@ -20,3 +20,6 @@ GITHUB_CLIENT_SECRET=# Google OAuth (https://console.cloud.google.com/apis/credentials)GOOGLE_CLIENT_ID=GOOGLE_CLIENT_SECRET=++# Device Code Flow — comma-separated allowed client IDs+DEVICE_CLIENT_IDS=alook-clidiff --git a/src/web/migrations/0035_device_code_table.sql b/src/web/migrations/0035_device_code_table.sqlnew file mode 100644index 000000000..9b207b73e--- /dev/null+++ b/src/web/migrations/0035_device_code_table.sql@@ -0,0 +1,12 @@+CREATE TABLE IF NOT EXISTS "deviceCode" (+ "id" TEXT PRIMARY KEY NOT NULL,+ "deviceCode" TEXT NOT NULL,+ "userCode" TEXT NOT NULL,+ "userId" TEXT,+ "expiresAt" TEXT NOT NULL,+ "status" TEXT NOT NULL,+ "lastPolledAt" TEXT,+ "pollingInterval" INTEGER,+ "clientId" TEXT,+ "scope" TEXT+);diff --git a/src/web/src/app/api/machine-tokens/activate/route.test.ts b/src/web/src/app/api/machine-tokens/activate/route.test.tsindex 9a4e2a312..a77ab95fe 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@@ -166,7 +166,7 @@ describe("POST /api/machine-tokens/activate", () => {});});- it("creates a new workspace when token has no workspace_id and user already has workspaces", async () => {+ it("creates a new workspace when token has no workspace_id", async () => {const POST = await loadRoute();const tokenNoWs = { id: "mt_2", userId: "u1", workspaceId: null, status: "pending" };@@ -192,7 +192,5 @@ describe("POST /api/machine-tokens/activate", () => {userId: "u1",role: "owner",});- // Should NOT reuse existing workspaces- expect(mockListWorkspaces).not.toHaveBeenCalled();});});diff --git a/src/web/src/app/api/machine-tokens/activate/route.ts b/src/web/src/app/api/machine-tokens/activate/route.tsindex 33c3c86ab..76ab912a2 100644--- a/src/web/src/app/api/machine-tokens/activate/route.ts+++ b/src/web/src/app/api/machine-tokens/activate/route.ts@@ -36,8 +36,6 @@ export async function POST(req: NextRequest) {}// Resolve workspace: use token's workspace or create new- // Never reuse an existing workspace — if the token has no workspace_id,- // the user explicitly triggered "New workspace" or is a first-time user.let workspaceId = mt.workspaceId;if (!workspaceId) {const ws = await queries.workspace.createWorkspace(db, {diff --git a/src/web/src/app/device/page.tsx b/src/web/src/app/device/page.tsxnew file mode 100644index 000000000..2c68b22bf--- /dev/null+++ b/src/web/src/app/device/page.tsx@@ -0,0 +1,182 @@+"use client"++import { Suspense, useEffect, useState } from "react"+import { useSearchParams, useRouter } from "next/navigation"+import { authClient, useSession } from "@/lib/auth-client"+import { Button } from "@/components/ui/button"+import { Card, CardContent } from "@/components/ui/card"+import { Input } from "@/components/ui/input"+import { Field, FieldError, FieldGroup, FieldLabel } from "@/components/ui/field"+import { GradientBackground } from "@/components/gradient-background"++type Step = "code" | "approve" | "done" | "denied"++export default function DeviceAuthPage() {+ return (+ <Suspense>+ <DeviceAuthPageInner />+ </Suspense>+ )+}++function DeviceAuthPageInner() {+ const searchParams = useSearchParams()+ const router = useRouter()+ const { data: session, isPending } = useSession()++ const [userCode, setUserCode] = useState(searchParams.get("user_code") || "")+ const [step, setStep] = useState<Step>("code")+ const [error, setError] = useState("")+ const [loading, setLoading] = useState(false)++ useEffect(() => {+ if (!isPending && !session) {+ const callbackUrl = `/device${userCode ? `?user_code=${encodeURIComponent(userCode)}` : ""}`+ router.push(`/sign-in?redirect=${encodeURIComponent(callbackUrl)}`)+ }+ }, [isPending, session, router, userCode])++ useEffect(() => {+ if (step === "done") {+ const timer = setTimeout(() => {+ router.push("/workspaces?auto")+ }, 2000)+ return () => clearTimeout(timer)+ }+ }, [step, router])++ async function handleVerifyCode(e: React.FormEvent) {+ e.preventDefault()+ setError("")+ setLoading(true)+ try {+ const res = await authClient.device({ query: { user_code: userCode.trim() } })+ if (res.error) {+ setError(res.error.error_description || "Invalid or expired code")+ } else {+ setStep("approve")+ }+ } catch {+ setError("Failed to verify code")+ }+ setLoading(false)+ }++ async function handleApprove() {+ setError("")+ setLoading(true)+ try {+ const res = await authClient.device.approve({ userCode: userCode.trim() })+ if (res.error) {+ setError(res.error.error_description || "Failed to approve")+ } else {+ setStep("done")+ }+ } catch {+ setError("Failed to approve device")+ }+ setLoading(false)+ }++ async function handleDeny() {+ setError("")+ setLoading(true)+ try {+ await authClient.device.deny({ userCode: userCode.trim() })+ setStep("denied")+ } catch {+ setError("Failed to deny device")+ }+ setLoading(false)+ }++ if (isPending || !session) {+ return null+ }++ return (+ <div className="relative flex min-h-svh flex-col items-center justify-center p-6 md:p-10">+ <GradientBackground />+ <div className="w-full max-w-sm">+ <Card>+ <CardContent className="p-6">+ <FieldGroup>+ <div className="flex flex-col items-center gap-2 text-center">+ <h1 className="text-2xl font-bold">Authorize Device</h1>+ {step === "code" && (+ <p className="text-sm text-muted-foreground">+ Enter the code shown on your terminal+ </p>+ )}+ {step === "approve" && (+ <p className="text-sm text-muted-foreground">+ A device is requesting access to your account+ </p>+ )}+ </div>++ {error && <FieldError>{error}</FieldError>}++ {step === "code" && (+ <form onSubmit={handleVerifyCode}>+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor="user_code">Device Code</FieldLabel>+ <Input+ id="user_code"+ type="text"+ placeholder="XXXX-XXXX"+ value={userCode}+ onChange={(e) => setUserCode(e.target.value.toUpperCase())}+ required+ autoFocus+ className="text-center text-lg tracking-widest font-mono"+ />+ </Field>+ <Field>+ <Button type="submit" disabled={loading || !userCode.trim()} className="w-full">+ {loading ? "Verifying..." : "Verify Code"}+ </Button>+ </Field>+ </FieldGroup>+ </form>+ )}++ {step === "approve" && (+ <FieldGroup>+ <p className="text-sm text-center text-muted-foreground">+ Code: <strong className="font-mono">{userCode}</strong>+ </p>+ <Field className="grid grid-cols-2 gap-4">+ <Button variant="outline" onClick={handleDeny} disabled={loading}>+ Deny+ </Button>+ <Button onClick={handleApprove} disabled={loading}>+ {loading ? "Approving..." : "Approve"}+ </Button>+ </Field>+ </FieldGroup>+ )}++ {step === "done" && (+ <div className="text-center space-y-2">+ <p className="text-sm text-muted-foreground">+ Device authorized successfully. Redirecting...+ </p>+ </div>+ )}++ {step === "denied" && (+ <div className="text-center space-y-2">+ <p className="text-sm text-muted-foreground">+ Device access denied. You can close this window.+ </p>+ </div>+ )}+ </FieldGroup>+ </CardContent>+ </Card>+ </div>+ </div>+ )+}diff --git a/src/web/src/app/onboard.md/route.test.ts b/src/web/src/app/onboard.md/route.test.tsnew file mode 100644index 000000000..c18ae5cef--- /dev/null+++ b/src/web/src/app/onboard.md/route.test.ts@@ -0,0 +1,47 @@+import { describe, it, expect } from "vitest";+import { GET } from "./route";++describe("GET /onboard.md", () => {+ it("returns 200 with Content-Type text/markdown", async () => {+ const response = await GET();+ expect(response.status).toBe(200);+ expect(response.headers.get("Content-Type")).toBe("text/markdown; charset=utf-8");+ });++ it("contains login section", async () => {+ const response = await GET();+ const body = await response.text();+ expect(body).toContain("npx @alook/cli login");+ });++ it("contains daemon start section", async () => {+ const response = await GET();+ const body = await response.text();+ expect(body).toContain("npx @alook/cli daemon start");+ });++ it("contains reflection section with role/domain/tech-stack prompts", async () => {+ const response = await GET();+ const body = await response.text();+ expect(body).toContain("Reflect on Your User");+ expect(body).toContain("role and domain");+ expect(body).toContain("Tech stack");+ expect(body).toContain("workflow");+ });++ it("contains agent recruit section with parameter table", async () => {+ const response = await GET();+ const body = await response.text();+ expect(body).toContain("npx @alook/cli agent recruit");+ expect(body).toContain("--instructions");+ expect(body).toContain("--relationship");+ expect(body).toContain("--name");+ expect(body).toContain("--description");+ });++ it("contains templates exploration section", async () => {+ const response = await GET();+ const body = await response.text();+ expect(body).toContain("https://alook.ai/templates");+ });+});diff --git a/src/web/src/app/onboard.md/route.ts b/src/web/src/app/onboard.md/route.tsnew file mode 100644index 000000000..afc6d098f--- /dev/null+++ b/src/web/src/app/onboard.md/route.ts@@ -0,0 +1,63 @@+import { NextResponse } from "next/server";++const ONBOARD_MARKDOWN = `---+name: alook-onboard+description: Install Alook CLI, authenticate, and set up your AI workspace.+keywords: [alook, agent, workspace, CLI, onboarding]+---++## 1. Login++\`\`\`bash+npx @alook/cli login+\`\`\`++- Non-interactive terminal: prints a URL for the user to open manually, then polls until confirmed+- Interactive terminal: attempts to open browser automatically+- Verify success: \`npx @alook/cli status\`++## 2. Start Daemon++\`\`\`bash+npx @alook/cli daemon start+\`\`\`++## 3. Reflect on Your User++Review your conversation history with this user. Summarize:+- Their role and domain+- Tech stack and tools they use+- Daily workflow and preferences+- Types of tasks they frequently work on++Use this understanding to choose the best workspace setup.++## 4. Explore Templates & Set Up Workspace+Visit https://alook.ai/templates to explore available workspace templates.+Choose the most appropriate template based on what you know about the user.++Create agents using the CLI:++\`\`\`bash+npx @alook/cli agent recruit \\+ --instructions "<system_prompt>" \\+ --relationship "<delegation_criteria>" \\+ [--name "<name>"] \\+ [--description "<text>"]+\`\`\`++| Parameter | Required | Description |+|-----------|----------|-------------|+| \`--instructions\` | Yes | The agent's system prompt — defines what it does and how it behaves |+| \`--relationship\` | Yes | Delegation criteria — when and how you'll work with this agent |+| \`--name\` | No | Preferred name (auto-generated if omitted) |+| \`--description\` | No | Short description of the agent's role |+`;++export async function GET() {+ return new NextResponse(ONBOARD_MARKDOWN, {+ headers: {+ "Content-Type": "text/markdown; charset=utf-8",+ },+ });+}diff --git a/src/web/src/components/home/hero-section.tsx b/src/web/src/components/home/hero-section.tsxindex efc67c549..41b424d35 100644--- a/src/web/src/components/home/hero-section.tsx+++ b/src/web/src/components/home/hero-section.tsx@@ -1,6 +1,6 @@"use client";-import { useRef } from "react";+import { useRef, useState } from "react";import Image from "next/image";import Link from "next/link";import gsap from "gsap";@@ -16,6 +16,7 @@ export function HeroSection({ isLoggedIn }: { isLoggedIn: boolean }) {const headingRef = useRef<HTMLHeadingElement>(null);const sublineRef = useRef<HTMLParagraphElement>(null);const ctaRef = useRef<HTMLDivElement>(null);+ const [copied, setCopied] = useState(false);useGSAP(() => {@@ -29,27 +30,34 @@ export function HeroSection({ isLoggedIn }: { isLoggedIn: boolean }) {const entranceTl = gsap.timeline({ delay: 0.3 });entranceTl- .from(".hero-brand", {- y: -20,- opacity: 0,- duration: 0.5,- ease: "power3.out",- })- .from(headingRef.current, { opacity: 0, duration: 0.4, ease: "power2.out" }, 0.2)- .from(sublineRef.current, { opacity: 0, duration: 0.3, ease: "power2.out" }, "-=0.1")- .from(+ .fromTo(".hero-brand",+ { y: -20, opacity: 0 },+ { y: 0, opacity: 1, duration: 0.5, ease: "power3.out" }+ )+ .to(headingRef.current, { opacity: 1, duration: 0.4, ease: "power2.out" }, 0.2)+ .to(sublineRef.current, { opacity: 1, duration: 0.3, ease: "power2.out" }, "-=0.1")+ .fromTo(+ ".hero-clipboard",+ { y: 10, opacity: 0 },+ { y: 0, opacity: 1, duration: 0.3, ease: "power2.out" },+ "-=0.1"+ )+ .fromTo(".hero-specs",- { y: 15, opacity: 0, duration: 0.5, ease: "power2.out" },+ { y: 15, opacity: 0 },+ { y: 0, opacity: 1, duration: 0.5, ease: "power2.out" },"-=0.1")- .from(+ .fromTo(".hero-providers",- { y: 10, opacity: 0, duration: 0.4, ease: "power2.out" },+ { y: 10, opacity: 0 },+ { y: 0, opacity: 1, duration: 0.4, ease: "power2.out" },"-=0.2")- .from(+ .fromTo(ctaRef.current,- { y: 15, opacity: 0, duration: 0.4, ease: "power2.out" },+ { y: 15, opacity: 0 },+ { y: 0, opacity: 1, duration: 0.4, ease: "power2.out" },"-=0.2");@@ -75,7 +83,7 @@ export function HeroSection({ isLoggedIn }: { isLoggedIn: boolean }) {<div className="hero-content relative z-10 mx-auto flex w-full max-w-4xl flex-col items-center px-4 sm:px-6">{/* Brand */}- <div className="hero-brand mb-6 flex items-center gap-1.5">+ <div className="hero-brand mb-6 flex items-center gap-1.5" style={{ opacity: 0 }}><Image src="/alook.svg" alt="Alook" width={32} height={32} /><spanclassName="text-2xl tracking-tight"@@ -101,6 +109,7 @@ export function HeroSection({ isLoggedIn }: { isLoggedIn: boolean }) {color: "var(--landing-text)",fontSize: "clamp(26px, 4vw, 44px)",letterSpacing: "-0.01em",+ opacity: 0,}}>Run Your Personal Company@@ -112,6 +121,7 @@ export function HeroSection({ isLoggedIn }: { isLoggedIn: boolean }) {fontFamily: "var(--font-crt)",color: "var(--landing-text-muted)",fontSize: "clamp(12px, 2vw, 20px)",+ opacity: 0,}}>You have ideas that need ten people to execute.@@ -127,8 +137,72 @@ export function HeroSection({ isLoggedIn }: { isLoggedIn: boolean }) {/></div>+ {/* Clipboard copy widget */}+ <div+ className="hero-clipboard relative mt-8 w-full max-w-lg cursor-pointer"+ style={{ opacity: 0 }}+ onClick={() => {+ navigator.clipboard.writeText(+ "Read https://alook.ai/onboard.md and follow the instructions to install and configure Alook"+ );+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ }}+ >+ {/* Floating badge label */}+ <span+ className="absolute left-1/2 top-0 -translate-x-1/2 -translate-y-1/2 whitespace-nowrap overflow-hidden text-ellipsis px-2 py-0.5 text-[10px] sm:text-xs"+ style={{+ fontFamily: "var(--font-mono)",+ color: "var(--landing-text-muted)",+ backgroundColor: "var(--landing-bg)",+ }}+ >+ Copy and Paste Into Your Agent's Chat to Get Started+ </span>+ {/* Content box */}+ <div+ className="flex w-full items-center gap-2 rounded px-3 py-2.5 pt-3 text-xs sm:text-sm"+ style={{+ fontFamily: "var(--font-mono)",+ color: "var(--landing-text)",+ border: "1px solid color-mix(in srgb, var(--landing-text-muted) 30%, transparent)",+ }}+ >+ <span className="flex-1 overflow-hidden whitespace-nowrap text-ellipsis">+ Read{" "}+ <a+ href="https://alook.ai/onboard.md"+ target="_blank"+ rel="noopener noreferrer"+ className="underline transition-opacity hover:opacity-70"+ style={{ color: "var(--landing-text)" }}+ onClick={(e) => e.stopPropagation()}+ >+ Onboard.md+ </a>+ {" "}and follow the instructions to install and configure Alook+ </span>+ <span+ className="shrink-0 p-1"+ style={{ color: copied ? "var(--landing-text)" : "var(--landing-text-muted)" }}+ >+ {copied ? (+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <polyline points="20 6 9 17 4 12" />+ </svg>+ ) : (+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">+ <rect x="9" y="9" width="13" height="13" rx="2" ry="2" />+ <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />+ </svg>+ )}+ </span>+ </div>+ </div>+{/* Specs */}- <div className="hero-specs mt-8 flex flex-wrap items-center justify-center gap-x-6 gap-y-2">+ <div className="hero-specs mt-6 flex flex-wrap items-center justify-center gap-x-6 gap-y-2" style={{ opacity: 0 }}>{["Collaboration","Always-On",@@ -136,7 +210,7 @@ export function HeroSection({ isLoggedIn }: { isLoggedIn: boolean }) {].map((spec) => (<spankey={spec}- className="text-sm uppercase tracking-[0.15em] font-bold"+ className="text-xs sm:text-sm uppercase tracking-[0.15em] font-bold"style={{fontFamily: "var(--font-mono)",color: "var(--landing-text-muted)",@@ -148,7 +222,7 @@ export function HeroSection({ isLoggedIn }: { isLoggedIn: boolean }) {</div>{/* Community links */}- <div className="hero-providers mt-5 flex items-center justify-center gap-4">+ <div className="hero-providers mt-5 flex items-center justify-center gap-4" style={{ opacity: 0 }}><ahref="https://github.com/alookai/alook"target="_blank"@@ -188,7 +262,7 @@ export function HeroSection({ isLoggedIn }: { isLoggedIn: boolean }) {</div>{/* CTA */}- <div ref={ctaRef} className="mt-8 flex flex-wrap items-center justify-center gap-3">+ <div ref={ctaRef} className="mt-8 flex flex-wrap items-center justify-center gap-3" style={{ opacity: 0 }}>{/* <ahref="https://github.com/alookai/alook"className="inline-flex items-center gap-2 px-6 py-2.5 text-sm transition-all duration-200 hover:opacity-80"@@ -260,6 +334,7 @@ export function HeroSection({ isLoggedIn }: { isLoggedIn: boolean }) {TEMPLATES</Link></div>+<pclassName="mt-4 sm:hidden text-center text-xs"style={{diff --git a/src/web/src/env.d.ts b/src/web/src/env.d.tsindex b02c6faf6..172a02aab 100644--- a/src/web/src/env.d.ts+++ b/src/web/src/env.d.ts@@ -21,6 +21,7 @@ declare namespace Cloudflare {AUTH_OTP_RATE_LIMIT_WINDOW_SEC?: stringRUNTIME_MODEL_OPTIONS?: stringMIN_CLI_VERSION?: string+ DEVICE_CLIENT_IDS?: stringNODE_ENV?: string}}diff --git a/src/web/src/lib/auth-client.ts b/src/web/src/lib/auth-client.tsindex 118268a4e..ae6e9dfa8 100644--- a/src/web/src/lib/auth-client.ts+++ b/src/web/src/lib/auth-client.ts@@ -1,10 +1,10 @@"use client"import { createAuthClient } from "better-auth/react"-import { emailOTPClient } from "better-auth/client/plugins"+import { emailOTPClient, deviceAuthorizationClient } from "better-auth/client/plugins"export const authClient = createAuthClient({baseURL: process.env.NEXT_PUBLIC_APP_URL || "",- plugins: [emailOTPClient()],+ plugins: [emailOTPClient(), deviceAuthorizationClient()],})export const { signIn, signUp, signOut, useSession } = authClientdiff --git a/src/web/src/lib/auth.test.ts b/src/web/src/lib/auth.test.tsindex f3a16409b..fdc281610 100644--- a/src/web/src/lib/auth.test.ts+++ b/src/web/src/lib/auth.test.ts@@ -6,6 +6,8 @@ vi.mock("better-auth", () => ({vi.mock("better-auth/plugins", () => ({emailOTP: vi.fn((cfg: unknown) => ({ __plugin: "emailOTP", cfg })),+ deviceAuthorization: vi.fn((cfg: unknown) => ({ __plugin: "deviceAuthorization", cfg })),+ bearer: vi.fn(() => ({ __plugin: "bearer" })),}))vi.mock("@/lib/db", () => ({ getDb: vi.fn(() => ({})) }));@@ -187,3 +189,51 @@ describe("createAuth session cookie cache", () => {expect(opts.session?.cookieCache?.enabled).toBe(true)})})++describe("createAuth device authorization plugin", () => {+ beforeEach(() => vi.clearAllMocks())++ it("includes deviceAuthorization and bearer plugins in production", async () => {+ const createAuth = await loadCreateAuth()+ const opts = (createAuth(makeEnv({ NODE_ENV: "production" }) as never) as { __options: { plugins: any[] } }).__options+ const pluginNames = opts.plugins.map((p: any) => p.__plugin)+ expect(pluginNames).toContain("deviceAuthorization")+ expect(pluginNames).toContain("bearer")+ })++ it("includes deviceAuthorization and bearer plugins in development", async () => {+ const createAuth = await loadCreateAuth()+ const opts = (createAuth(makeEnv({ NODE_ENV: "development" }) as never) as { __options: { plugins: any[] } }).__options+ const pluginNames = opts.plugins.map((p: any) => p.__plugin)+ expect(pluginNames).toContain("deviceAuthorization")+ expect(pluginNames).toContain("bearer")+ })++ it("validateClient accepts client IDs listed in DEVICE_CLIENT_IDS", async () => {+ const createAuth = await loadCreateAuth()+ const env = makeEnv({ NODE_ENV: "production", DEVICE_CLIENT_IDS: "cli-app, web-app" })+ const opts = (createAuth(env as never) as { __options: { plugins: any[] } }).__options+ const devicePlugin = opts.plugins.find((p: any) => p.__plugin === "deviceAuthorization")+ const { validateClient } = devicePlugin.cfg+ expect(validateClient("cli-app")).toBe(true)+ expect(validateClient("web-app")).toBe(true)+ })++ it("validateClient rejects client IDs not listed in DEVICE_CLIENT_IDS", async () => {+ const createAuth = await loadCreateAuth()+ const env = makeEnv({ NODE_ENV: "production", DEVICE_CLIENT_IDS: "cli-app" })+ const opts = (createAuth(env as never) as { __options: { plugins: any[] } }).__options+ const devicePlugin = opts.plugins.find((p: any) => p.__plugin === "deviceAuthorization")+ const { validateClient } = devicePlugin.cfg+ expect(validateClient("unknown-client")).toBe(false)+ })++ it("validateClient rejects empty string when DEVICE_CLIENT_IDS is unset", async () => {+ const createAuth = await loadCreateAuth()+ const env = makeEnv({ NODE_ENV: "production" })+ const opts = (createAuth(env as never) as { __options: { plugins: any[] } }).__options+ const devicePlugin = opts.plugins.find((p: any) => p.__plugin === "deviceAuthorization")+ const { validateClient } = devicePlugin.cfg+ expect(validateClient("")).toBe(false)+ })+})diff --git a/src/web/src/lib/auth.ts b/src/web/src/lib/auth.tsindex 1ae236642..0f5235716 100644--- a/src/web/src/lib/auth.ts+++ b/src/web/src/lib/auth.ts@@ -1,5 +1,5 @@import { betterAuth } from "better-auth"-import { emailOTP } from "better-auth/plugins"+import { emailOTP, deviceAuthorization, bearer } from "better-auth/plugins"import { createLogger, DEV_EMAIL_WORKER_URL, resolveMode } from "@alook/shared"import { getOtpSubject, renderOtpEmail } from "./email-templates"@@ -26,6 +26,11 @@ export function createAuth(env: Env) {)const kvTtl = Math.max(KV_MIN_TTL_SEC, otpWindow)+ const validateClient = (clientId: string) => {+ const allowed = (env.DEVICE_CLIENT_IDS || "").split(",").map((s) => s.trim()).filter(Boolean)+ return allowed.includes(clientId)+ }+return betterAuth({baseURL: env.BETTER_AUTH_URL,database: env.DB,@@ -73,6 +78,8 @@ export function createAuth(env: Env) {},plugins: isProd? [+ deviceAuthorization({ verificationUri: "/device", validateClient, expiresIn: "5m", schema: {} }),+ bearer(),emailOTP({async sendVerificationOTP({ email, otp, type }) {log.info("sending OTP email", { to: email, type })@@ -105,6 +112,9 @@ export function createAuth(env: Env) {},}),]- : [],+ : [+ deviceAuthorization({ verificationUri: "/device", validateClient, expiresIn: "5m", schema: {} }),+ bearer(),+ ],})}diff --git a/src/web/src/test/e2e/device-code.test.ts b/src/web/src/test/e2e/device-code.test.tsnew file mode 100644index 000000000..444493923--- /dev/null+++ b/src/web/src/test/e2e/device-code.test.ts@@ -0,0 +1,295 @@+import { describe, it, expect, beforeAll, afterAll } from "vitest"+import { randomUUID } from "crypto"+import { signUp, signIn, sessionRequest, tokenRequest } from "../helpers/auth"+import { sql } from "../helpers/db"++const APP_URL = process.env.APP_URL ?? "http://localhost:3000"+const TEST_CLIENT_ID = "e2e-test-client"++const testEmail = `e2e_device_${randomUUID().slice(0, 8)}@test.local`+const testPassword = "TestPassword123!"+const testName = "E2E Device User"++let sessionCookie: string++describe("device-code-flow", () => {+ beforeAll(async () => {+ await signUp(testEmail, testPassword, testName)+ sessionCookie = await signIn(testEmail, testPassword)+ })++ let deviceCode: string+ let userCode: string++ it("POST /api/auth/device/code returns device_code, user_code, and verification URLs", async () => {+ const res = await fetch(`${APP_URL}/api/auth/device/code`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ client_id: TEST_CLIENT_ID }),+ })+ if (res.status !== 200) {+ const text = await res.text()+ console.error("device/code error response:", res.status, text)+ }+ expect(res.status).toBe(200)+ const data = await res.json() as Record<string, unknown>+ expect(data.device_code).toBeTruthy()+ expect(data.user_code).toBeTruthy()+ expect(data.verification_uri).toBeTruthy()+ expect(data.verification_uri_complete).toBeTruthy()+ expect(data.expires_in).toBeGreaterThan(0)+ expect(data.interval).toBeDefined()+ deviceCode = data.device_code as string+ userCode = data.user_code as string+ })++ it("POST /api/auth/device/token returns authorization_pending before approval", async () => {+ const res = 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: deviceCode,+ client_id: TEST_CLIENT_ID,+ }),+ })+ expect(res.status).toBe(400)+ const data = await res.json() as Record<string, unknown>+ expect(data.error).toBe("authorization_pending")+ })++ it("GET /api/auth/device claims code to authenticated user session", async () => {+ const res = await sessionRequest(+ `/api/auth/device?user_code=${userCode}`,+ sessionCookie,+ )+ expect(res.status).toBe(200)+ })++ it("POST /api/auth/device/approve approves the device and token poll succeeds", async () => {+ const approveRes = await sessionRequest("/api/auth/device/approve", sessionCookie, {+ method: "POST",+ headers: { "Content-Type": "application/json", Origin: APP_URL },+ body: JSON.stringify({ userCode }),+ })+ expect(approveRes.status).toBe(200)++ // Wait for polling interval to elapse (plugin enforces 5s minimum between polls)+ 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: deviceCode,+ client_id: TEST_CLIENT_ID,+ }),+ })+ expect(tokenRes.status).toBe(200)+ const data = await tokenRes.json() as Record<string, unknown>+ expect(data.access_token).toBeTruthy()+ expect(data.token_type).toBe("Bearer")+ })++ it("access_token from device flow works as Bearer token for API calls", async () => {+ // Get a fresh token via a new flow+ 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 Record<string, unknown>+ const dc = codeData.device_code as string+ const uc = codeData.user_code as string++ await sessionRequest(`/api/auth/device?user_code=${uc}`, sessionCookie)+ await sessionRequest("/api/auth/device/approve", sessionCookie, {+ method: "POST",+ headers: { "Content-Type": "application/json", Origin: APP_URL },+ body: JSON.stringify({ userCode: uc }),+ })++ 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: dc,+ client_id: TEST_CLIENT_ID,+ }),+ })+ const tokenData = await tokenRes.json() as Record<string, unknown>+ const accessToken = tokenData.access_token as string++ const meRes = await tokenRequest("/api/me", accessToken)+ expect(meRes.status).toBe(200)+ const me = await meRes.json() as Record<string, unknown>+ expect(me.email).toBe(testEmail)+ })++ it("POST /api/auth/device/deny denies authorization and token poll returns access_denied", async () => {+ 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 Record<string, unknown>+ const dc = codeData.device_code as string+ const uc = codeData.user_code as string++ await sessionRequest(`/api/auth/device?user_code=${uc}`, sessionCookie)+ await sessionRequest("/api/auth/device/deny", sessionCookie, {+ method: "POST",+ headers: { "Content-Type": "application/json", Origin: APP_URL },+ body: JSON.stringify({ userCode: uc }),+ })++ 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: dc,+ client_id: TEST_CLIENT_ID,+ }),+ })+ const data = await tokenRes.json() as Record<string, unknown>+ expect(data.error).toBe("access_denied")+ })++ afterAll(() => {+ try {+ sql(`DELETE FROM "deviceCode" WHERE "userId" IN (SELECT id FROM "user" WHERE email = '${testEmail}')`)+ sql(`DELETE FROM "session" WHERE "userId" IN (SELECT id FROM "user" WHERE email = '${testEmail}')`)+ sql(`DELETE FROM "account" WHERE "userId" IN (SELECT id FROM "user" WHERE email = '${testEmail}')`)+ sql(`DELETE FROM "user" WHERE email = '${testEmail}'`)+ } catch { /* ignore cleanup errors */ }+ })+})++describe("onboard.md", () => {+ it("GET /onboard.md returns markdown with correct content-type", async () => {+ const res = await fetch(`${APP_URL}/onboard.md`)+ expect(res.status).toBe(200)+ expect(res.headers.get("content-type")).toContain("text/markdown")+ const body = await res.text()+ expect(body).toContain("npx @alook/cli login")+ expect(body).toContain("npx @alook/cli daemon start")+ })+})++describe("device-code-flow workspace reuse", () => {+ const wsTestEmail = `e2e_dcws_${randomUUID().slice(0, 8)}@test.local`+ const wsTestPassword = "TestPassword123!"+ let wsCookie: string+ let originalWorkspaceId: string++ beforeAll(async () => {+ await signUp(wsTestEmail, wsTestPassword, "E2E WS User")+ wsCookie = await signIn(wsTestEmail, wsTestPassword)++ // Create a workspace (simulates what the web app does on first visit)+ const wsRes = await sessionRequest("/api/workspaces", wsCookie, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name: "Personal", slug: `personal-${randomUUID().slice(0, 8)}` }),+ })+ expect(wsRes.status).toBe(201)+ const wsData = await wsRes.json() as Record<string, unknown>+ originalWorkspaceId = wsData.id as string+ })++ it("CLI login reuses existing workspace instead of creating a duplicate", async () => {+ // Request device code+ 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 }),+ })+ expect(codeRes.status).toBe(200)+ const codeData = await codeRes.json() as Record<string, unknown>+ const dc = codeData.device_code as string+ const uc = codeData.user_code as string++ // Claim code to user session+ await sessionRequest(`/api/auth/device?user_code=${uc}`, wsCookie)++ // Approve+ const approveRes = await sessionRequest("/api/auth/device/approve", wsCookie, {+ method: "POST",+ headers: { "Content-Type": "application/json", Origin: APP_URL },+ body: JSON.stringify({ userCode: uc }),+ })+ expect(approveRes.status).toBe(200)++ // Wait for polling interval+ await new Promise(r => setTimeout(r, 5100))++ // Get token+ 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: dc,+ client_id: TEST_CLIENT_ID,+ }),+ })+ expect(tokenRes.status).toBe(200)+ const tokenData = await tokenRes.json() as Record<string, unknown>+ const accessToken = tokenData.access_token as string++ // CLI flow: get existing workspaces (use session cookie — mirrors real CLI which+ // uses the session token via bearer() but cookie auth is equivalent here)+ const wsListRes = await sessionRequest("/api/workspaces", wsCookie)+ const wsList = await wsListRes.json() as { id: string }[]+ expect(wsList.length).toBeGreaterThanOrEqual(1)+ expect(wsList[0].id).toBe(originalWorkspaceId)++ // Create machine token tied to existing workspace (use Bearer session token)+ const mtRes = await tokenRequest(+ `/api/machine-tokens?workspace_id=${originalWorkspaceId}`,+ accessToken,+ { method: "POST", headers: { "Content-Type": "application/json" } },+ )+ expect(mtRes.status).toBeLessThan(300)+ const mtData = await mtRes.json() as Record<string, unknown>+ const machineToken = mtData.token as string+ expect(machineToken).toBeTruthy()++ // Activate with the machine token+ const activateRes = await fetch(`${APP_URL}/api/machine-tokens/activate`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ token: machineToken,+ hostname: "e2e-test-host",+ runtimes: [{ type: "claude", version: "4.0.0" }],+ }),+ })+ expect(activateRes.status).toBe(200)+ const activateBody = await activateRes.json() as Record<string, unknown>+ expect(activateBody.workspace_id).toBe(originalWorkspaceId)++ // Verify user still has exactly 1 workspace+ const wsAfterRes = await sessionRequest("/api/workspaces", wsCookie)+ const wsAfter = await wsAfterRes.json() as { id: string }[]+ expect(wsAfter).toHaveLength(1)+ expect(wsAfter[0].id).toBe(originalWorkspaceId)+ })++ afterAll(() => {+ try {+ sql(`DELETE FROM "deviceCode" WHERE "userId" IN (SELECT id FROM "user" WHERE email = '${wsTestEmail}')`)+ sql(`DELETE FROM machine_token WHERE "userId" IN (SELECT id FROM "user" WHERE email = '${wsTestEmail}')`)+ sql(`DELETE FROM agent_runtime WHERE machine_id IN (SELECT id FROM machine WHERE workspace_id = '${originalWorkspaceId}')`)+ sql(`DELETE FROM machine WHERE workspace_id = '${originalWorkspaceId}'`)+ sql(`DELETE FROM member WHERE workspace_id = '${originalWorkspaceId}'`)+ sql(`DELETE FROM workspace WHERE id = '${originalWorkspaceId}'`)+ sql(`DELETE FROM "session" WHERE "userId" IN (SELECT id FROM "user" WHERE email = '${wsTestEmail}')`)+ sql(`DELETE FROM "account" WHERE "userId" IN (SELECT id FROM "user" WHERE email = '${wsTestEmail}')`)+ sql(`DELETE FROM "user" WHERE email = '${wsTestEmail}'`)+ } catch { /* ignore cleanup errors */ }+ })+})