Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(auth): hand off session to Desktop when web is already logged in (#1364)
Bohan Jiang4ce3e5ddf48d
diff --git a/apps/web/app/(auth)/login/page.test.tsx b/apps/web/app/(auth)/login/page.test.tsxindex 15f9403c10..05ecd45c00 100644--- a/apps/web/app/(auth)/login/page.test.tsx+++ b/apps/web/app/(auth)/login/page.test.tsx@@ -11,16 +11,32 @@ function createWrapper() {);}-const { mockSendCode, mockVerifyCode } = vi.hoisted(() => ({+const {+ mockSendCode,+ mockVerifyCode,+ mockIssueCliToken,+ searchParamsState,+ authStateRef,+} = vi.hoisted(() => ({mockSendCode: vi.fn(),mockVerifyCode: vi.fn(),+ mockIssueCliToken: vi.fn(),+ searchParamsState: { params: new URLSearchParams() },+ authStateRef: {+ state: {+ sendCode: vi.fn(),+ verifyCode: vi.fn(),+ user: null as null | { id: string; email: string },+ isLoading: false,+ },+ },}));// Mock next/navigationvi.mock("next/navigation", () => ({useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),usePathname: () => "/login",- useSearchParams: () => new URLSearchParams(),+ useSearchParams: () => searchParamsState.params,}));// Mock auth store — shared LoginPage uses getState().sendCode/verifyCode,@@ -32,15 +48,12 @@ vi.mock("@multica/core/auth", async () => {await vi.importActual<typeof import("@multica/core/auth")>("@multica/core/auth",);- const authState = {- sendCode: mockSendCode,- verifyCode: mockVerifyCode,- user: null,- isLoading: false,- };+ authStateRef.state.sendCode = mockSendCode;+ authStateRef.state.verifyCode = mockVerifyCode;const useAuthStore = Object.assign(- (selector: (s: typeof authState) => unknown) => selector(authState),- { getState: () => authState },+ (selector: (s: typeof authStateRef.state) => unknown) =>+ selector(authStateRef.state),+ { getState: () => authStateRef.state },);return { ...actual, useAuthStore };});@@ -57,6 +70,7 @@ vi.mock("@multica/core/api", () => ({verifyCode: vi.fn(),setToken: vi.fn(),getMe: vi.fn(),+ issueCliToken: mockIssueCliToken,},}));@@ -65,6 +79,9 @@ import LoginPage from "./page";describe("LoginPage", () => {beforeEach(() => {vi.clearAllMocks();+ searchParamsState.params = new URLSearchParams();+ authStateRef.state.user = null;+ authStateRef.state.isLoading = false;});it("renders login form with email input and continue button", () => {@@ -137,4 +154,44 @@ describe("LoginPage", () => {expect(screen.getByText("Network error")).toBeInTheDocument();});});++ // Regression: MUL-1080 — if the user is already authenticated on the web+ // and the Desktop app redirects them to /login?platform=desktop, the web+ // must exchange the cookie session for a bearer token and hand it off via+ // the multica:// deep link, not silently redirect to the workspace page.+ it("mints a token and deep-links to Desktop when already logged in with platform=desktop", async () => {+ searchParamsState.params = new URLSearchParams({ platform: "desktop" });+ authStateRef.state.user = { id: "u1", email: "[email protected]" };+ mockIssueCliToken.mockImplementation(() =>+ Promise.resolve({ token: "handoff-jwt" }),+ );++ const hrefSetter = vi.fn();+ const originalLocation = window.location;+ Object.defineProperty(window, "location", {+ configurable: true,+ value: { ...originalLocation, set href(value: string) { hrefSetter(value); } },+ });++ try {+ render(<LoginPage />, { wrapper: createWrapper() });++ await waitFor(() => {+ expect(mockIssueCliToken).toHaveBeenCalledTimes(1);+ });+ await waitFor(() => {+ expect(hrefSetter).toHaveBeenCalledWith(+ "multica://auth/callback?token=handoff-jwt",+ );+ });+ expect(+ await screen.findByRole("button", { name: "Open Multica Desktop" }),+ ).toBeInTheDocument();+ } finally {+ Object.defineProperty(window, "location", {+ configurable: true,+ value: originalLocation,+ });+ }+ });});diff --git a/apps/web/app/(auth)/login/page.tsx b/apps/web/app/(auth)/login/page.tsxindex fb227021fb..7693b6725e 100644--- a/apps/web/app/(auth)/login/page.tsx+++ b/apps/web/app/(auth)/login/page.tsx@@ -1,12 +1,22 @@"use client";-import { Suspense, useEffect } from "react";+import { Suspense, useEffect, useState } from "react";import { useSearchParams, useRouter } from "next/navigation";import { useQueryClient } from "@tanstack/react-query";import { sanitizeNextUrl, useAuthStore } from "@multica/core/auth";import { workspaceKeys } from "@multica/core/workspace/queries";import { paths } from "@multica/core/paths";+import { api } from "@multica/core/api";import type { Workspace } from "@multica/core/types";+import {+ Card,+ CardHeader,+ CardTitle,+ CardDescription,+ CardContent,+} from "@multica/ui/components/ui/card";+import { Button } from "@multica/ui/components/ui/button";+import { Loader2 } from "lucide-react";import { setLoggedInCookie } from "@/features/auth/auth-cookie";import { LoginPage, validateCliCallback } from "@multica/views/auth";@@ -22,6 +32,7 @@ function LoginPageContent() {const cliCallbackRaw = searchParams.get("cli_callback");const cliState = searchParams.get("cli_state") || "";const platform = searchParams.get("platform");+ const isDesktopHandoff = platform === "desktop" && !cliCallbackRaw;// `next` carries a protected URL the user was originally headed to// (e.g. /invite/{id}). With URL-driven workspaces there is no legacy// "/issues" default — if `next` is absent we decide after login based on@@ -29,11 +40,31 @@ function LoginPageContent() {// cannot bounce the user off-origin after a successful login.const nextUrl = sanitizeNextUrl(searchParams.get("next"));+ const [desktopToken, setDesktopToken] = useState<string | null>(null);+ const [desktopError, setDesktopError] = useState("");+// Already authenticated — honor ?next= or fall back to first workspace// (or /workspaces/new if the user has none). Skip this entire path when// the user arrived to authorize the CLI.useEffect(() => {if (isLoading || !user || cliCallbackRaw) return;+ if (isDesktopHandoff) {+ // Desktop opened the browser for login but the web session is already+ // authenticated — mint a bearer token from the cookie session and hand+ // it off via deep link instead of silently redirecting to the workspace.+ api+ .issueCliToken()+ .then(({ token }) => {+ setDesktopToken(token);+ window.location.href = `multica://auth/callback?token=${encodeURIComponent(token)}`;+ })+ .catch((err) => {+ setDesktopError(+ err instanceof Error ? err.message : "Failed to prepare Desktop sign-in",+ );+ });+ return;+ }if (nextUrl) {router.replace(nextUrl);return;@@ -43,7 +74,7 @@ function LoginPageContent() {router.replace(first ? paths.workspace(first.slug).issues() : paths.newWorkspace(),);- }, [isLoading, user, router, nextUrl, cliCallbackRaw, qc]);+ }, [isLoading, user, router, nextUrl, cliCallbackRaw, isDesktopHandoff, qc]);const handleSuccess = () => {if (nextUrl) {@@ -68,6 +99,52 @@ function LoginPageContent() {.filter(Boolean).join(",") || undefined;+ // While the desktop handoff is in progress (or has produced a token/error),+ // render a dedicated screen instead of flashing the login form or redirecting+ // away to a workspace page.+ if (isDesktopHandoff && user) {+ if (desktopError) {+ return (+ <div className="flex min-h-screen items-center justify-center">+ <Card className="w-full max-w-sm">+ <CardHeader className="text-center">+ <CardTitle className="text-2xl">Sign-in Failed</CardTitle>+ <CardDescription>{desktopError}</CardDescription>+ </CardHeader>+ </Card>+ </div>+ );+ }+ return (+ <div className="flex min-h-screen items-center justify-center">+ <Card className="w-full max-w-sm">+ <CardHeader className="text-center">+ <CardTitle className="text-2xl">Opening Multica</CardTitle>+ <CardDescription>+ {desktopToken+ ? "You should see a prompt to open the Multica desktop app. If nothing happens, click the button below."+ : "Preparing Desktop sign-in..."}+ </CardDescription>+ </CardHeader>+ <CardContent className="flex justify-center">+ {desktopToken ? (+ <Button+ variant="outline"+ onClick={() => {+ window.location.href = `multica://auth/callback?token=${encodeURIComponent(desktopToken)}`;+ }}+ >+ Open Multica Desktop+ </Button>+ ) : (+ <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />+ )}+ </CardContent>+ </Card>+ </div>+ );+ }+return (<LoginPageonSuccess={handleSuccess}