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: simplify device auth flow + handle existing login (#257)
Generf1eb80d146fc
diff --git a/src/cli/commands/login.test.ts b/src/cli/commands/login.test.tsindex b3e04009d..d4d3a4e5b 100644--- a/src/cli/commands/login.test.ts+++ b/src/cli/commands/login.test.ts@@ -69,7 +69,7 @@ describe("alook login", () => {function mockFetchSequence(responses: { url: string; status: number; body: unknown }[]) {const queue = [...responses];- vi.stubGlobal("fetch", vi.fn(async (url: string | URL | Request) => {+ vi.stubGlobal("fetch", vi.fn(async (url: string | URL | Request, _init?: RequestInit) => {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) {@@ -203,4 +203,162 @@ describe("alook login", () => {expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("http://localhost:3000/device?user_code=ABCD-EFGH"));expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("ABCD-EFGH"));});++ describe("already authenticated", () => {+ it("exits early when token is still valid", async () => {+ mockLoadCLIConfigForProfile.mockReturnValue({+ server_url: "http://localhost:3000",+ watched_workspaces: [{ id: "sp_ws1", name: "My Workspace", token: "al_existing_tok" }],+ });++ mockFetchSequence([+ { url: "/api/workspaces", status: 200, body: [{ id: "sp_ws1", name: "My Workspace" }] },+ { 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: My Workspace).",+ );+ expect(mockSaveCLIConfigForProfile).not.toHaveBeenCalled();+ });++ it("proceeds with login when --force is set", async () => {+ mockLoadCLIConfigForProfile.mockReturnValue({+ server_url: "http://localhost:3000",+ watched_workspaces: [{ id: "sp_ws1", name: "My Workspace", token: "al_existing_tok" }],+ });++ mockFetchSequence(fullSuccessResponses());++ const cmd = loginCommand();+ await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000", "--force"]));++ expect(mockSaveCLIConfigForProfile).toHaveBeenCalled();+ expect(consoleSpy).toHaveBeenCalledWith(expect.stringContaining("Logged in as [email protected]"));+ });++ it("proceeds with login when token is invalid/expired", async () => {+ mockLoadCLIConfigForProfile.mockReturnValue({+ server_url: "http://localhost:3000",+ watched_workspaces: [{ id: "sp_ws1", name: "My Workspace", token: "al_expired_tok" }],+ });++ mockFetchSequence([+ { url: "/api/workspaces", status: 401, body: { error: "unauthorized" } },+ { 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_new_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: [] },+ ]);++ 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("proceeds with login when no workspaces in config", async () => {+ mockLoadCLIConfigForProfile.mockReturnValue({+ server_url: "http://localhost:3000",+ watched_workspaces: [],+ });++ mockFetchSequence(fullSuccessResponses());++ const cmd = loginCommand();+ await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));++ expect(mockSaveCLIConfigForProfile).toHaveBeenCalled();+ });++ it("shows message without email when /api/me fails", async () => {+ mockLoadCLIConfigForProfile.mockReturnValue({+ server_url: "http://localhost:3000",+ watched_workspaces: [{ id: "sp_ws1", name: "My Workspace", token: "al_existing_tok" }],+ });++ mockFetchSequence([+ { url: "/api/workspaces", status: 200, body: [{ id: "sp_ws1", name: "My Workspace" }] },+ { url: "/api/me", status: 500, body: { error: "internal" } },+ ]);++ const cmd = loginCommand();+ await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));++ expect(consoleSpy).toHaveBeenCalledWith(+ "Already logged in (workspace: My Workspace).",+ );+ expect(mockSaveCLIConfigForProfile).not.toHaveBeenCalled();+ });++ it("shows message without email when /api/me throws network error", async () => {+ mockLoadCLIConfigForProfile.mockReturnValue({+ server_url: "http://localhost:3000",+ watched_workspaces: [{ id: "sp_ws1", name: "My Workspace", token: "al_existing_tok" }],+ });++ let callCount = 0;+ vi.stubGlobal("fetch", vi.fn(async (url: string | URL | Request) => {+ const urlStr = typeof url === "string" ? url : url instanceof URL ? url.toString() : url.url;+ callCount++;+ if (urlStr.includes("/api/workspaces")) {+ return { ok: true, status: 200, json: async () => [{ id: "sp_ws1" }], text: async () => "[]" };+ }+ if (urlStr.includes("/api/me")) {+ throw new Error("network error");+ }+ return { ok: false, status: 404, text: async () => "not found", json: async () => ({}) };+ }));++ const cmd = loginCommand();+ await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));++ expect(consoleSpy).toHaveBeenCalledWith(+ "Already logged in (workspace: My Workspace).",+ );+ });++ it("proceeds with login when token field is empty", async () => {+ mockLoadCLIConfigForProfile.mockReturnValue({+ server_url: "http://localhost:3000",+ watched_workspaces: [{ id: "sp_ws1", name: "My Workspace", token: "" }],+ });++ mockFetchSequence(fullSuccessResponses());++ const cmd = loginCommand();+ await runWithTimers(cmd.parseAsync(["node", "login", "--server", "http://localhost:3000"]));++ expect(mockSaveCLIConfigForProfile).toHaveBeenCalled();+ });++ it("works correctly in non-TTY mode with early exit", async () => {+ Object.defineProperty(process.stdout, "isTTY", { value: false, writable: true });+ mockLoadCLIConfigForProfile.mockReturnValue({+ server_url: "http://localhost:3000",+ watched_workspaces: [{ id: "sp_ws1", name: "My Workspace", token: "al_valid_tok" }],+ });++ mockFetchSequence([+ { url: "/api/workspaces", status: 200, body: [{ id: "sp_ws1", name: "My Workspace" }] },+ { 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: My Workspace).",+ );+ expect(mockSaveCLIConfigForProfile).not.toHaveBeenCalled();+ });+ });});diff --git a/src/cli/commands/login.ts b/src/cli/commands/login.tsindex bb6bec110..0cbed1510 100644--- a/src/cli/commands/login.ts+++ b/src/cli/commands/login.ts@@ -3,6 +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";const DEVICE_CLIENT_ID = process.env.ALOOK_DEVICE_CLIENT_ID || "alook-cli";@@ -161,11 +162,51 @@ if (process.argv.includes("--__login-poll")) {pollAndActivate(data).catch(() => process.exit(1));}+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 };+ }++ const ws = workspaces[0];+ if (!ws.token) {+ return { valid: false };+ }++ try {+ const res = await fetch(`${serverUrl}/api/workspaces`, {+ headers: { Authorization: `Bearer ${ws.token}` },+ });+ if (!res.ok) {+ return { valid: false };+ }++ let email: string | undefined;+ try {+ const meRes = await fetch(`${serverUrl}/api/me`, {+ headers: { Authorization: `Bearer ${ws.token}` },+ });+ if (meRes.ok) {+ const me = await meRes.json() as { email?: string };+ email = me.email;+ }+ } catch {+ // Non-fatal — proceed without email+ }++ return { valid: true, email, workspaceName: ws.name };+ } catch {+ return { valid: false };+ }+}+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")+ .option("--force", "Re-authenticate even if already logged in").action(async (opts, command) => {const profile: string | undefined =opts.profile || command.parent?.opts().profile;@@ -175,6 +216,19 @@ export function loginCommand(): Command {process.env.ALOOK_SERVER_URL ||"https://alook.ai";+ // Check if already authenticated (skip with --force)+ if (!opts.force) {+ const existing = await checkExistingAuth(serverUrl, profile);+ if (existing.valid) {+ const parts = ["Already logged in"];+ if (existing.email) parts[0] += ` as ${existing.email}`;+ if (existing.workspaceName) parts[0] += ` (workspace: ${existing.workspaceName})`;+ parts[0] += ".";+ console.log(parts[0]);+ return;+ }+ }+// Step 1: Request device codeconsole.log("Requesting device code...");let deviceResp: DeviceCodeResponse;diff --git a/src/web/src/app/device/page.tsx b/src/web/src/app/device/page.tsxindex 2c68b22bf..779a4237e 100644--- a/src/web/src/app/device/page.tsx+++ b/src/web/src/app/device/page.tsx@@ -1,6 +1,6 @@"use client"-import { Suspense, useEffect, useState } from "react"+import { Suspense, useEffect, useState, useRef } from "react"import { useSearchParams, useRouter } from "next/navigation"import { authClient, useSession } from "@/lib/auth-client"import { Button } from "@/components/ui/button"@@ -9,7 +9,7 @@ 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"+type Step = "loading" | "code" | "approve" | "done" | "denied"export default function DeviceAuthPage() {return (@@ -24,10 +24,12 @@ function DeviceAuthPageInner() {const router = useRouter()const { data: session, isPending } = useSession()- const [userCode, setUserCode] = useState(searchParams.get("user_code") || "")- const [step, setStep] = useState<Step>("code")+ const urlCode = searchParams.get("user_code") || ""+ const [userCode, setUserCode] = useState(urlCode)+ const [step, setStep] = useState<Step>(urlCode ? "loading" : "code")const [error, setError] = useState("")const [loading, setLoading] = useState(false)+ const autoVerified = useRef(false)useEffect(() => {if (!isPending && !session) {@@ -36,6 +38,28 @@ function DeviceAuthPageInner() {}}, [isPending, session, router, userCode])+ useEffect(() => {+ if (!urlCode || !session || autoVerified.current) return+ autoVerified.current = true++ async function autoVerify() {+ try {+ const res = await authClient.device({ query: { user_code: urlCode.trim() } })+ if (res.error) {+ setError(res.error.error_description || "Invalid or expired code")+ setStep("code")+ } else {+ setStep("approve")+ }+ } catch {+ setError("Failed to verify code")+ setStep("code")+ }+ }++ autoVerify()+ }, [urlCode, session])+useEffect(() => {if (step === "done") {const timer = setTimeout(() => {@@ -103,6 +127,11 @@ function DeviceAuthPageInner() {<FieldGroup><div className="flex flex-col items-center gap-2 text-center"><h1 className="text-2xl font-bold">Authorize Device</h1>+ {step === "loading" && (+ <p className="text-sm text-muted-foreground">+ Verifying...+ </p>+ )}{step === "code" && (<p className="text-sm text-muted-foreground">Enter the code shown on your terminal@@ -117,6 +146,12 @@ function DeviceAuthPageInner() {{error && <FieldError>{error}</FieldError>}+ {step === "loading" && (+ <div className="flex justify-center py-4">+ <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent" />+ </div>+ )}+{step === "code" && (<form onSubmit={handleVerifyCode}><FieldGroup>