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(web): optimize sign-in UI/UX and close image lightbox on outside click (#1129)
Gustavo Ye3a79bae29920
diff --git a/src/web/src/app/(auth)/sign-in/page.test.ts b/src/web/src/app/(auth)/sign-in/page.test.tsindex 16a0e1ef9..1cdd7daca 100644--- a/src/web/src/app/(auth)/sign-in/page.test.ts+++ b/src/web/src/app/(auth)/sign-in/page.test.ts@@ -1,12 +1,16 @@-import { describe, expect, it, vi } from "vitest"+import { beforeEach, describe, expect, it, vi } from "vitest"const mocks = vi.hoisted(() => ({getCloudflareContext: vi.fn(),+ cookies: vi.fn(),}))vi.mock("@opennextjs/cloudflare", () => ({getCloudflareContext: mocks.getCloudflareContext,}))+vi.mock("next/headers", () => ({+ cookies: mocks.cookies,+}))vi.mock("./sign-in-client", () => ({default: () => null,}))@@ -14,14 +18,25 @@ vi.mock("./sign-in-client", () => ({import SignInPage from "./page"describe("sign-in server configuration", () => {- it("passes a disabled Apple flag when all Apple secrets are absent", async () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mocks.cookies.mockResolvedValue({+ get: vi.fn(() => undefined),+ })+ })++ it("passes a disabled Apple flag and null last-used method when absent", async () => {mocks.getCloudflareContext.mockResolvedValueOnce({env: { NODE_ENV: "production" },})const page = await SignInPage()- expect(page.props).toMatchObject({ isProd: true, appleEnabled: false })+ expect(page.props).toMatchObject({+ isProd: true,+ appleEnabled: false,+ initialLastUsedMethod: null,+ })})it("passes only an enabled boolean when all Apple secrets are present", async () => {@@ -41,8 +56,29 @@ describe("sign-in server configuration", () => {expect(JSON.stringify(page.props)).not.toContain("private-key-never-passed-to-the-client")})+ it("normalizes remembered login method cookies and drops unknown values", async () => {+ mocks.cookies.mockResolvedValueOnce({+ get: vi.fn((name: string) =>+ name === "alook_last_login_method" ? { value: "email-otp" } : undefined),+ })+ mocks.getCloudflareContext.mockResolvedValueOnce({+ env: { NODE_ENV: "production" },+ })+ expect((await SignInPage()).props.initialLastUsedMethod).toBe("email")++ mocks.cookies.mockResolvedValueOnce({+ get: vi.fn(() => ({ value: "unexpected-provider" })),+ })+ mocks.getCloudflareContext.mockResolvedValueOnce({+ env: { NODE_ENV: "production" },+ })+ expect((await SignInPage()).props.initialLastUsedMethod).toBeNull()+ })+it("shows the real OTP form for the explicit local QA configuration", async () => {- mocks.getCloudflareContext.mockResolvedValueOnce({ env: { NODE_ENV: "development", DEV_AUTH_OTP: "1" } })+ mocks.getCloudflareContext.mockResolvedValueOnce({+ env: { NODE_ENV: "development", DEV_AUTH_OTP: "1" },+ })expect((await SignInPage()).props.isProd).toBe(true)})diff --git a/src/web/src/app/(auth)/sign-in/page.tsx b/src/web/src/app/(auth)/sign-in/page.tsxindex 9ebe1c50c..f69e8f39a 100644--- a/src/web/src/app/(auth)/sign-in/page.tsx+++ b/src/web/src/app/(auth)/sign-in/page.tsx@@ -1,13 +1,27 @@+import { cookies } from "next/headers"import { getCloudflareContext } from "@opennextjs/cloudflare"import { resolveMode } from "@alook/shared"import { resolveAppleAuthConfig } from "@/lib/apple-auth"+import { LAST_LOGIN_METHOD_COOKIE, normalizeLoginMethod } from "@/lib/last-login-method"import SignInPageClient from "./sign-in-client"export default async function SignInPage() {- const { env } = await getCloudflareContext({ async: true })+ const [{ env }, cookieStore] = await Promise.all([+ getCloudflareContext({ async: true }),+ cookies(),+ ])const mode = resolveMode({ nodeEnv: env.NODE_ENV ?? process.env.NODE_ENV })const isProd = mode === "production" || (mode === "dev" && env.DEV_AUTH_OTP === "1")const appleEnabled = resolveAppleAuthConfig(env).enabled+ const initialLastUsedMethod = normalizeLoginMethod(+ cookieStore.get(LAST_LOGIN_METHOD_COOKIE)?.value,+ )- return <SignInPageClient isProd={isProd} appleEnabled={appleEnabled} />+ return (+ <SignInPageClient+ isProd={isProd}+ appleEnabled={appleEnabled}+ initialLastUsedMethod={initialLastUsedMethod}+ />+ )}diff --git a/src/web/src/app/(auth)/sign-in/sign-in-client.dom.test.ts b/src/web/src/app/(auth)/sign-in/sign-in-client.dom.test.tsindex afe7fb2a9..e7ef4bb3b 100644--- a/src/web/src/app/(auth)/sign-in/sign-in-client.dom.test.ts+++ b/src/web/src/app/(auth)/sign-in/sign-in-client.dom.test.ts@@ -1,6 +1,7 @@import { createElement } from "react"import { beforeEach, describe, expect, it, vi } from "vitest"-import { act, render, screen, setupUser, waitFor } from "@/test/react-dom-harness"+import { act, fireEvent, render, screen, setupUser } from "@/test/react-dom-harness"+import type { LoginMethod } from "@/lib/last-login-method"const mocks = vi.hoisted(() => ({searchParams: new URLSearchParams(),@@ -9,8 +10,10 @@ const mocks = vi.hoisted(() => ({verify: vi.fn(),devSignIn: vi.fn(),devSignUp: vi.fn(),+ getLastUsedLoginMethod: vi.fn<() => string | null>(() => null),+ rememberLastLoginMethod: vi.fn(),verifyInput: undefined as undefined | ((value: string) => Promise<void>),- socialGate: undefined as undefined | ((continuation: () => void) => void),+ selectSocial: undefined as undefined | ((method: "github" | "google" | "apple") => void),}))vi.mock("@/lib/product-analytics", () => ({ captureProductAnalytics: mocks.capture }))@@ -18,28 +21,55 @@ vi.mock("next/navigation", () => ({useSearchParams: () => mocks.searchParams,}))vi.mock("@/lib/auth-client", () => ({- authClient: { emailOtp: { sendVerificationOtp: mocks.send }, signIn: { emailOtp: mocks.verify } },+ authClient: {+ emailOtp: { sendVerificationOtp: mocks.send },+ signIn: { emailOtp: mocks.verify },+ getLastUsedLoginMethod: mocks.getLastUsedLoginMethod,+ },signIn: { email: mocks.devSignIn },signUp: { email: mocks.devSignUp },}))-vi.mock("./sign-in-fields", async importOriginal => ({- ...await importOriginal<typeof import("./sign-in-fields")>(),- SignInOtpField: ({ onChange }: { onChange: (value: string) => Promise<void> }) => { mocks.verifyInput = onChange; return null },+vi.mock("@/lib/last-login-method", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/lib/last-login-method")>()),+ rememberLastLoginMethod: mocks.rememberLastLoginMethod,+}))+vi.mock("./sign-in-fields", async (importOriginal) => ({+ ...(await importOriginal<typeof import("./sign-in-fields")>()),+ SignInOtpField: ({+ autoFocus = true,+ onChange,+ }: {+ autoFocus?: boolean+ onChange: (value: string) => Promise<void>+ }) => {+ mocks.verifyInput = onChange+ return createElement("input", {+ "aria-label": "Verification code",+ "data-testid": "otp-field-stub",+ "data-autofocus": String(autoFocus),+ })+ },}))vi.mock("./social-sign-in", () => ({SocialSignIn: ({postLoginUrl,appleEnabled,- requestConsent,+ lastUsedMethod,+ onSelectMethod,}: {postLoginUrl: stringappleEnabled: boolean- requestConsent: (continuation: () => void) => void- }) => { mocks.socialGate = requestConsent; return createElement("div", {- "data-testid": "social-sign-in-props",- "data-post-login-url": postLoginUrl,- "data-apple-enabled": String(appleEnabled),- }) },+ lastUsedMethod?: LoginMethod | null+ onSelectMethod?: (method: "github" | "google" | "apple") => void+ }) => {+ mocks.selectSocial = onSelectMethod+ return createElement("div", {+ "data-testid": "social-sign-in-props",+ "data-post-login-url": postLoginUrl,+ "data-apple-enabled": String(appleEnabled),+ "data-last-used": lastUsedMethod ?? "",+ })+ },}))vi.mock("@/components/gradient-background", () => ({GradientBackground: () => null,@@ -53,12 +83,20 @@ vi.mock("@/components/home/landing-shell-motion", () => ({vi.mock("@/components/home/landing-shell-motion.module.css", () => ({default: {},}))+vi.mock("@/components/typewriter-visual", () => ({+ TypewriterVisual: () => createElement("div", { "data-testid": "mobile-typewriter-stub" }),+}))import SignInPageClient from "./sign-in-client"-describe("sign-in client Apple availability", () => {+describe("sign-in client layout, consent-on-continue, and last-used method", () => {beforeEach(() => {- vi.clearAllMocks(); mocks.send.mockResolvedValue({}); mocks.verify.mockResolvedValue({ error: { code: "INVALID_OTP", status: 400 } }); mocks.verifyInput = undefined; mocks.socialGate = undefined+ vi.clearAllMocks()+ mocks.send.mockResolvedValue({})+ mocks.verify.mockResolvedValue({ error: { code: "INVALID_OTP", status: 400 } })+ mocks.getLastUsedLoginMethod.mockReturnValue(null)+ mocks.verifyInput = undefined+ mocks.selectSocial = undefinedmocks.searchParams = new URLSearchParams("redirect=%2Fc%2Fme")window.matchMedia = vi.fn(() => ({matches: false,@@ -67,6 +105,33 @@ describe("sign-in client Apple availability", () => {})) as never})+ it("places social quick-sign-in above the separator, email form, and passive terms footer without auto-focusing email", () => {+ render(createElement(SignInPageClient, { isProd: true, appleEnabled: true }))++ expect(screen.queryByRole("checkbox")).toBeNull()+ expect(screen.queryByRole("dialog")).toBeNull()++ const heading = screen.getByRole("heading", { name: /Welcome to\s+Alook/i })+ expect(heading).toHaveClass("whitespace-nowrap")+ expect(heading.querySelector('img[src="/alook.svg"]')).not.toBeNull()++ const social = screen.getByTestId("social-sign-in-props")+ const emailInput = screen.getByRole("textbox", { name: "Email" })+ const emailButton = screen.getByRole("button", { name: "Continue with email" })+ const terms = screen.getByTestId("sign-in-terms")++ expect(emailInput).not.toHaveFocus()+ expect(+ social.compareDocumentPosition(emailInput) & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy()+ expect(+ emailInput.compareDocumentPosition(emailButton) & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy()+ expect(+ emailButton.compareDocumentPosition(terms) & Node.DOCUMENT_POSITION_FOLLOWING,+ ).toBeTruthy()+ })+it("does not claim removal is complete while deletion remains pending", () => {mocks.searchParams = new URLSearchParams("account_deleted=pending")render(createElement(SignInPageClient, { isProd: true, appleEnabled: false }))@@ -75,195 +140,124 @@ describe("sign-in client Apple availability", () => {expect(screen.queryByText("Your account and its data were removed.")).toBeNull()})- it("holds email, verification and the passed social continuation behind the same agreement", async () => {+ it("sends OTP and verifies code immediately without requiring a checkbox or modal, then allows switching email", async () => {render(createElement(SignInPageClient, { isProd: true, appleEnabled: true }))const user = setupUser()- await user.click(screen.getByRole("button", { name: "Send Code" }))- expect(mocks.send).not.toHaveBeenCalled()- const social = vi.fn()- await act(async () => mocks.socialGate!(social))- expect(social).not.toHaveBeenCalled()+await user.type(screen.getByRole("textbox", { name: "Email" }), "[email protected]")- await user.click(screen.getByRole("checkbox"))- await user.click(screen.getByRole("button", { name: "Send Code" }))+ await user.click(screen.getByRole("button", { name: "Continue with email" }))+expect(mocks.send).toHaveBeenCalledOnce()- await act(async () => mocks.socialGate!(social))- expect(social).toHaveBeenCalledOnce()- await user.click(screen.getByRole("checkbox"))- await act(async () => { await mocks.verifyInput!("123456") })- expect(mocks.verify).not.toHaveBeenCalled()- await user.click(screen.getByRole("checkbox"))- await act(async () => { await mocks.verifyInput!("123456") })- expect(mocks.verify).toHaveBeenCalledExactlyOnceWith({ email: "[email protected]", otp: "123456" })- })+ expect(mocks.send).toHaveBeenCalledWith(+ expect.objectContaining({ email: "[email protected]", type: "sign-in" }),+ )+ expect(mocks.rememberLastLoginMethod).toHaveBeenCalledWith("email")+ expect(screen.queryByTestId("social-sign-in-props")).toBeNull()+ expect(screen.getByRole("heading", { name: "Check your email" })).toBeVisible()- it("mobile confirmation starts email once and keeps the existing OTP error flow", async () => {- window.matchMedia = vi.fn((query: string) => ({ matches: query.includes("max-width"), addEventListener: vi.fn(), removeEventListener: vi.fn() })) as never- render(createElement(SignInPageClient, { isProd: true, appleEnabled: false }))- const user = setupUser()- await user.type(screen.getByRole("textbox", { name: "Email" }), "[email protected]")- await user.click(screen.getByRole("button", { name: "Send Code" }))- expect(mocks.send).not.toHaveBeenCalled()- await user.click(screen.getByTestId("sign-in-terms-cancel"))- expect(mocks.send).not.toHaveBeenCalled()+ await act(async () => {+ await mocks.verifyInput!("123456")+ })+ expect(mocks.verify).toHaveBeenCalledExactlyOnceWith({+ email: "[email protected]",+ otp: "123456",+ })++ await user.click(screen.getByRole("button", { name: "Use a different email" }))expect(screen.getByRole("textbox", { name: "Email" })).toHaveValue("[email protected]")- await user.click(screen.getByRole("button", { name: "Send Code" }))- await user.click(screen.getByTestId("sign-in-terms-confirm"))- expect(mocks.send).toHaveBeenCalledOnce()- expect(mocks.send).toHaveBeenCalledWith(expect.objectContaining({ email: "[email protected]", type: "sign-in" }))- expect(screen.getByRole("checkbox")).toBeChecked()- await act(async () => { await mocks.verifyInput!("123456") })- expect(mocks.verify).toHaveBeenCalledOnce()- expect(mocks.capture).toHaveBeenLastCalledWith(expect.objectContaining({ failureStage: "verify_code" }))+ expect(screen.getByTestId("last-used-email")).toHaveTextContent("Last used")})- it("guards development login and preserves its signup fallback after agreement", async () => {+ it("preserves development sign-in and signup fallback immediately on submit", async () => {mocks.devSignIn.mockResolvedValue({ error: { message: "Account not found" } })mocks.devSignUp.mockResolvedValue({ error: { message: "Try again" } })render(createElement(SignInPageClient, { isProd: false, appleEnabled: false }))const user = setupUser()+await user.type(screen.getByRole("textbox", { name: "Email" }), "[email protected]")await user.click(screen.getByRole("button", { name: "Sign in", exact: true }))- expect(mocks.devSignIn).not.toHaveBeenCalled()- expect(mocks.devSignUp).not.toHaveBeenCalled()- await user.click(screen.getByRole("checkbox"))- await user.click(screen.getByRole("button", { name: "Sign in", exact: true }))+expect(mocks.devSignIn).toHaveBeenCalledOnce()- expect(mocks.devSignUp).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ email: "[email protected]", name: "person" }), expect.any(Object))+ expect(mocks.devSignUp).toHaveBeenCalledExactlyOnceWith(+ expect.objectContaining({ email: "[email protected]", name: "person" }),+ expect.any(Object),+ )+ expect(mocks.rememberLastLoginMethod).not.toHaveBeenCalled()expect(screen.getByRole("button", { name: "Sign in", exact: true })).toBeEnabled()})- it.each([375, 640].flatMap(width => [true, false].flatMap(isProd => ["", "not-an-email"].map(email => ({ width, isProd, email })))))- ("at $width with isProd=$isProd, checks consent before validating email '$email' on button clicks", async ({ width, isProd, email }) => {- window.matchMedia = vi.fn((query: string) => ({ matches: query.includes("max-width") && width < 640, addEventListener: vi.fn(), removeEventListener: vi.fn() })) as never- mocks.devSignIn.mockResolvedValue({ error: { message: "Account not found" } })- mocks.devSignUp.mockResolvedValue({ error: { message: "Try again" } })- render(createElement(SignInPageClient, { isProd, appleEnabled: false }))- const user = setupUser()- const input = screen.getByRole("textbox", { name: "Email" }) as HTMLInputElement- const checkbox = screen.getByRole("checkbox") as HTMLInputElement- const label = isProd ? "Send Code" : "Sign in"- const request = isProd ? mocks.send : mocks.devSignIn- const invalidStates: { checked: boolean; dialog: boolean }[] = []- input.addEventListener("invalid", () => { invalidStates.push({ checked: checkbox.checked, dialog: screen.queryByRole("dialog") !== null }) })- expect(input).toBeRequired()- expect(input).toHaveAttribute("type", "email")- if (email) await user.type(input, email)- expect(input.validity.valid).toBe(false)- await user.click(screen.getByRole("button", { name: label }))- expect(document.getElementById("sign-in-terms-copy")).toHaveClass("text-destructive")- if (width < 640) {- expect(screen.getByRole("dialog")).toBeVisible()- await user.click(screen.getByTestId("sign-in-terms-cancel"))- }- expect(invalidStates).toEqual([])- expect(request).not.toHaveBeenCalled()- await user.click(checkbox)- await user.click(checkbox)- await user.click(screen.getByRole("button", { name: label }))- expect(document.getElementById("sign-in-terms-copy")).toHaveClass("text-destructive")- expect(request).not.toHaveBeenCalled()- if (width < 640) {- const confirm = screen.getByRole("button", { name: "Agree" })- await user.click(confirm)- await act(async () => confirm.click())- } else {- await user.click(checkbox)- await user.click(screen.getByRole("button", { name: label }))- }- expect(invalidStates).toEqual([{ checked: true, dialog: false }])- expect(request).not.toHaveBeenCalled()- expect(mocks.devSignUp).not.toHaveBeenCalled()- expect(checkbox).toBeChecked()- await user.clear(input)- await user.type(input, "[email protected]")- await user.click(screen.getByRole("button", { name: label }))- expect(request).toHaveBeenCalledOnce()- expect(request).toHaveBeenCalledWith(expect.objectContaining({ email: "[email protected]" }), ...isProd ? [] : [expect.any(Object)])- })+ it.each(+ [true, false].flatMap((isProd) =>+ ["", "not-an-email"].map((email) => ({ isProd, email })),+ ),+ )(+ "with isProd=$isProd, validates '$email' natively before sending",+ async ({ isProd, email }) => {+ render(createElement(SignInPageClient, { isProd, appleEnabled: false }))+ const user = setupUser()+ const input = screen.getByRole("textbox", { name: "Email" }) as HTMLInputElement+ const label = isProd ? "Continue with email" : "Sign in"+ const request = isProd ? mocks.send : mocks.devSignIn+ const onInvalid = vi.fn()+ input.addEventListener("invalid", onInvalid)- it.each([375, 640].flatMap(width => [true, false].map(isProd => ({ width, isProd }))))- ("at $width with isProd=$isProd, uses the same consent and email validation order on Enter", async ({ width, isProd }) => {- window.matchMedia = vi.fn((query: string) => ({ matches: query.includes("max-width") && width < 640, addEventListener: vi.fn(), removeEventListener: vi.fn() })) as never- mocks.devSignIn.mockResolvedValue({ error: { message: "Account not found" } })- mocks.devSignUp.mockResolvedValue({ error: { message: "Try again" } })- render(createElement(SignInPageClient, { isProd, appleEnabled: false }))- const user = setupUser()- const input = screen.getByRole("textbox", { name: "Email" })- const request = isProd ? mocks.send : mocks.devSignIn- await user.click(input)- await user.keyboard("{Enter}")- expect(document.getElementById("sign-in-terms-copy")).toHaveClass("text-destructive")- expect(request).not.toHaveBeenCalled()- if (width < 640) await user.click(screen.getByRole("button", { name: "Agree" }))- else {- await user.click(screen.getByRole("checkbox"))- await user.click(input)- await user.keyboard("{Enter}")- }- expect(request).not.toHaveBeenCalled()- expect(input).toBeInvalid()- await user.type(input, "[email protected]{Enter}")- expect(request).toHaveBeenCalledOnce()- })+ expect(input).toBeRequired()+ expect(input).toHaveAttribute("type", "email")+ if (email) await user.type(input, email)+ await user.click(screen.getByRole("button", { name: label, exact: true }))- it.each([true, false])("with isProd=%s, submits the email validated after the dialog finishes closing", async isProd => {- window.matchMedia = vi.fn((query: string) => ({ matches: query.includes("max-width"), addEventListener: vi.fn(), removeEventListener: vi.fn() })) as never- mocks.devSignIn.mockResolvedValue({ error: { message: "Account not found" } })- mocks.devSignUp.mockResolvedValue({ error: { message: "Try again" } })- render(createElement(SignInPageClient, { isProd, appleEnabled: false }))- const user = setupUser()- const input = screen.getByRole("textbox", { name: "Email" })- const request = isProd ? mocks.send : mocks.devSignIn- await user.type(input, "[email protected]")- await user.click(screen.getByRole("button", { name: isProd ? "Send Code" : "Sign in" }))- const popup = screen.getByRole("dialog")- let finish!: () => void- const finished = new Promise<void>(resolve => { finish = resolve })- const getAnimations = vi.fn(() => [{ finished }])- Object.defineProperty(popup, "getAnimations", { value: getAnimations })- await user.click(screen.getByRole("button", { name: "Agree" }))- await waitFor(() => expect(getAnimations).toHaveBeenCalled())- expect(request).not.toHaveBeenCalled()- await user.clear(input)- await user.type(input, "[email protected]")- await act(async () => { finish(); await finished })- await waitFor(() => expect(request).toHaveBeenCalledOnce())- expect(request.mock.calls[0][0]).toEqual(expect.objectContaining({ email: "[email protected]" }))- })+ expect(onInvalid).toHaveBeenCalledOnce()+ expect(request).not.toHaveBeenCalled()+ },+ )- it.each([true, false].flatMap(isProd => ["", "not-an-email"].flatMap(email => ["button", "enter"].map(submission => ({ isProd, email, submission })))))("with isProd=$isProd, email='$email' and $submission, preserves native invalid-email focus after the mobile dialog closes", async ({ isProd, email, submission }) => {- window.matchMedia = vi.fn((query: string) => ({ matches: query.includes("max-width"), addEventListener: vi.fn(), removeEventListener: vi.fn() })) as never- render(createElement(SignInPageClient, { isProd, appleEnabled: false }))- const user = setupUser()- const input = screen.getByRole("textbox", { name: "Email" })- const invalid = vi.fn(() => input.focus())- input.addEventListener("invalid", invalid)- if (email) await user.type(input, email)- if (submission === "button") {- await user.click(screen.getByRole("button", { name: isProd ? "Send Code" : "Sign in" }))- } else {- await user.click(input)- await user.keyboard("{Enter}")- }- await user.click(screen.getByRole("button", { name: "Agree" }))- await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull())- await act(async () => { await Promise.resolve() })- expect(invalid).toHaveBeenCalledOnce()- expect(input).toHaveFocus()- expect(mocks.send).not.toHaveBeenCalled()- expect(mocks.devSignIn).not.toHaveBeenCalled()+ it("renders Last used from SSR prop or client cookie and keeps exact button accessible names intact", () => {+ const first = render(+ createElement(SignInPageClient, {+ isProd: true,+ appleEnabled: true,+ initialLastUsedMethod: "email",+ }),+ )+ const emailButton = screen.getByRole("button", {+ name: "Continue with email",+ exact: true,+ })+ expect(emailButton).toHaveAttribute("aria-describedby", "last-used-email-badge")+ expect(screen.getByTestId("last-used-email")).toHaveTextContent("Last used")+ first.unmount()++ mocks.getLastUsedLoginMethod.mockReturnValue("github")+ render(createElement(SignInPageClient, { isProd: true, appleEnabled: true }))+ expect(screen.getByTestId("social-sign-in-props")).toHaveAttribute(+ "data-last-used",+ "github",+ )++ act(() => {+ mocks.selectSocial?.("apple")+ })+ expect(screen.getByTestId("social-sign-in-props")).toHaveAttribute(+ "data-last-used",+ "apple",+ )})it("counts login entry once and records only bounded OTP failure dimensions", async () => {render(createElement(SignInPageClient, { isProd: true, appleEnabled: false }))expect(mocks.capture).toHaveBeenCalledWith({ event: "login_page_view" })await setupUser().type(screen.getByRole("textbox", { name: "Email" }), "[email protected]")- await setupUser().click(screen.getByRole("checkbox"))- await setupUser().click(screen.getByRole("button", { name: "Send Code" }))+ await setupUser().click(screen.getByRole("button", { name: "Continue with email" }))expect(mocks.capture).toHaveBeenCalledTimes(1)- await act(async () => { await mocks.verifyInput!("123456") })- expect(mocks.capture).toHaveBeenLastCalledWith({ event: "sign_in_failed", method: "email_otp", failureStage: "verify_code", error: { code: "INVALID_OTP", status: 400 } })+ await act(async () => {+ await mocks.verifyInput!("123456")+ })+ expect(mocks.capture).toHaveBeenLastCalledWith({+ event: "sign_in_failed",+ method: "email_otp",+ failureStage: "verify_code",+ error: { code: "INVALID_OTP", status: 400 },+ })expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain("123456")expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain("bad code")})@@ -272,9 +266,13 @@ describe("sign-in client Apple availability", () => {mocks.send.mockResolvedValueOnce({ error: { status: 429 } })render(createElement(SignInPageClient, { isProd: true, appleEnabled: false }))await setupUser().type(screen.getByRole("textbox", { name: "Email" }), "[email protected]")- await setupUser().click(screen.getByRole("checkbox"))- await setupUser().click(screen.getByRole("button", { name: "Send Code" }))- expect(mocks.capture).toHaveBeenLastCalledWith({ event: "sign_in_failed", method: "email_otp", failureStage: "send_code", error: { status: 429 } })+ await setupUser().click(screen.getByRole("button", { name: "Continue with email" }))+ expect(mocks.capture).toHaveBeenLastCalledWith({+ event: "sign_in_failed",+ method: "email_otp",+ failureStage: "send_code",+ error: { status: 429 },+ })expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain("private detail")expect(JSON.stringify(mocks.capture.mock.calls)).not.toContain("sign_in_success")})@@ -284,13 +282,24 @@ describe("sign-in client Apple availability", () => {mocks.send.mockRejectedValueOnce(error)render(createElement(SignInPageClient, { isProd: true, appleEnabled: false }))await setupUser().type(screen.getByRole("textbox", { name: "Email" }), "[email protected]")- await setupUser().click(screen.getByRole("checkbox"))- await setupUser().click(screen.getByRole("button", { name: "Send Code" }))- expect(mocks.capture).toHaveBeenLastCalledWith({ event: "sign_in_failed", method: "email_otp", failureStage: "send_code", error })- await setupUser().click(screen.getByRole("button", { name: "Send Code" }))+ await setupUser().click(screen.getByRole("button", { name: "Continue with email" }))+ expect(mocks.capture).toHaveBeenLastCalledWith({+ event: "sign_in_failed",+ method: "email_otp",+ failureStage: "send_code",+ error,+ })+ await setupUser().click(screen.getByRole("button", { name: "Continue with email" }))mocks.verify.mockRejectedValueOnce(error)- await act(async () => { await mocks.verifyInput!("123456") })- expect(mocks.capture).toHaveBeenLastCalledWith({ event: "sign_in_failed", method: "email_otp", failureStage: "verify_code", error })+ await act(async () => {+ await mocks.verifyInput!("123456")+ })+ expect(mocks.capture).toHaveBeenLastCalledWith({+ event: "sign_in_failed",+ method: "email_otp",+ failureStage: "verify_code",+ error,+ })})it.each([true, false])("passes server-derived appleEnabled=%s unchanged", (appleEnabled) => {@@ -302,17 +311,228 @@ describe("sign-in client Apple availability", () => {})it.each([- [true, "Send Code"],+ [true, "Continue with email"],[false, "Sign in"],- ] as const)("uses the former social outline style for the email action when isProd=%s", (isProd, label) => {- render(createElement(SignInPageClient, { isProd, appleEnabled: true }))-- expect(screen.getByRole("button", { name: label })).toHaveClass(- "h-9",- "border-border",- "bg-background",- "text-base",- "w-full",- )+ ] as const)(+ "uses the outline secondary style and 44px touch target for the email action when isProd=%s",+ (isProd, label) => {+ render(createElement(SignInPageClient, { isProd, appleEnabled: true }))++ const button = screen.getByRole("button", { name: label, exact: true })+ expect(button).toHaveClass(+ "h-11",+ "justify-start",+ "border-border",+ "bg-background",+ "w-full",+ )+ expect(button.querySelector("svg")).not.toBeNull()+ },+ )++ it("renders the borderless mobile typewriter above login and collapses it when the viewport shrinks for keyboard or short screens", () => {+ window.matchMedia = vi.fn((query: string) => ({+ matches: query.includes("max-width"),+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ })) as never+ Object.defineProperty(window, "innerHeight", { configurable: true, value: 844 })++ render(createElement(SignInPageClient, { isProd: true, appleEnabled: true }))+ const stage = screen.getByTestId("sign-in-mobile-typewriter")+ expect(stage).toHaveAttribute("data-collapsed", "false")+ expect(screen.getByTestId("mobile-typewriter-stub")).toBeVisible()++ act(() => {+ Object.defineProperty(window, "innerHeight", { configurable: true, value: 460 })+ window.dispatchEvent(new Event("resize"))+ })+ expect(stage).toHaveAttribute("data-collapsed", "true")+ expect(screen.queryByTestId("mobile-typewriter-stub")).toBeNull()+ })++ it("slides the mobile typewriter and login pane left into a pure centered OTP pane and focuses the OTP input on completion", async () => {+ const rafQueue: FrameRequestCallback[] = []+ const origRaf = window.requestAnimationFrame+ const origCancelRaf = window.cancelAnimationFrame+ window.requestAnimationFrame = ((cb: FrameRequestCallback) => {+ rafQueue.push(cb)+ return rafQueue.length+ }) as typeof window.requestAnimationFrame+ window.cancelAnimationFrame = vi.fn()+ window.matchMedia = vi.fn((query: string) => ({+ matches: query.includes("max-width"),+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ })) as never+ Object.defineProperty(window, "innerHeight", { configurable: true, value: 844 })++ try {+ render(createElement(SignInPageClient, { isProd: true, appleEnabled: true }))+ const user = setupUser()++ await user.type(screen.getByRole("textbox", { name: "Email" }), "[email protected]")+ await user.click(screen.getByRole("button", { name: "Continue with email" }))++ const track = screen.getByTestId("sign-in-step-track")+ expect(track).toHaveAttribute("data-step-view", "prepare-to-code")+ expect(screen.getByTestId("sign-in-email-pane")).toHaveAttribute("aria-hidden", "true")+ expect(screen.getByTestId("sign-in-code-pane")).toBeVisible()+ expect(screen.getByTestId("otp-field-stub")).toHaveAttribute("data-autofocus", "false")+ expect(screen.getByTestId("otp-field-stub")).not.toHaveFocus()++ act(() => {+ const next = rafQueue.shift()+ next?.(16)+ })+ expect(track).toHaveAttribute("data-step-view", "sliding-to-code")+ expect(track.style.transform).toBe("translate3d(-100%, 0, 0)")++ act(() => {+ const ev = new Event("transitionend", { bubbles: true })+ Object.defineProperty(ev, "propertyName", { value: "transform" })+ fireEvent(track, ev)+ })+ expect(track).toHaveAttribute("data-step-view", "code")+ expect(screen.queryByTestId("sign-in-email-pane")).toBeNull()+ expect(screen.queryByTestId("sign-in-mobile-typewriter")).toBeNull()+ expect(screen.getByTestId("otp-field-stub")).toHaveFocus()++ await user.click(screen.getByRole("button", { name: "Use a different email" }))+ expect(track).toHaveAttribute("data-step-view", "prepare-to-email")+ expect(track.style.transform).toBe("translate3d(-100%, 0, 0)")++ act(() => {+ while (rafQueue.length > 0) {+ rafQueue.shift()?.(32)+ }+ })+ expect(track).toHaveAttribute("data-step-view", "sliding-to-email")+ expect(track.style.transform).toBe("translate3d(0%, 0, 0)")++ act(() => {+ const ev = new Event("transitionend", { bubbles: true })+ Object.defineProperty(ev, "propertyName", { value: "transform" })+ fireEvent(track, ev)+ })+ expect(track).toHaveAttribute("data-step-view", "email")+ expect(screen.queryByTestId("sign-in-code-pane")).toBeNull()+ expect(screen.getByTestId("sign-in-mobile-typewriter")).toBeVisible()+ } finally {+ window.requestAnimationFrame = origRaf+ window.cancelAnimationFrame = origCancelRaf+ }+ })++ it("preserves delayed blur viewport recovery on mobile while deduplicating consecutive blurs and clearing pending timers on unmount", () => {+ vi.useFakeTimers()+ window.matchMedia = vi.fn((query: string) => ({+ matches: query.includes("max-width"),+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ })) as never+ Object.defineProperty(window, "innerHeight", { configurable: true, value: 640 })++ try {+ const firstView = render(+ createElement(SignInPageClient, { isProd: true, appleEnabled: true }),+ )+ const stage = screen.getByTestId("sign-in-mobile-typewriter")+ const email = screen.getByRole("textbox", { name: "Email" })+ expect(stage).toHaveAttribute("data-collapsed", "false")++ act(() => {+ fireEvent.focusIn(email)+ })+ expect(stage).toHaveAttribute("data-collapsed", "true")++ act(() => {+ fireEvent.focusOut(email)+ fireEvent.focusOut(email)+ })+ expect(vi.getTimerCount()).toBe(1)+ expect(stage).toHaveAttribute("data-collapsed", "true")++ act(() => {+ vi.advanceTimersByTime(49)+ })+ expect(stage).toHaveAttribute("data-collapsed", "true")++ act(() => {+ vi.advanceTimersByTime(1)+ })+ expect(stage).toHaveAttribute("data-collapsed", "false")+ expect(vi.getTimerCount()).toBe(0)++ act(() => {+ fireEvent.focusOut(email)+ fireEvent.focusOut(email)+ })+ expect(vi.getTimerCount()).toBe(1)+ firstView.unmount()+ expect(vi.getTimerCount()).toBe(0)+ } finally {+ vi.clearAllTimers()+ vi.useRealTimers()+ }+ })++ it("clears pending blur timers and prevents stale mobile viewport updates after switching to desktop", () => {+ vi.useFakeTimers()+ let mobile = true+ const mobileListeners = new Set<() => void>()+ const mobileMql = {+ get matches() {+ return mobile+ },+ addEventListener: vi.fn((_event: string, listener: () => void) => {+ mobileListeners.add(listener)+ }),+ removeEventListener: vi.fn((_event: string, listener: () => void) => {+ mobileListeners.delete(listener)+ }),+ }+ window.matchMedia = vi.fn((query: string) =>+ query.includes("max-width")+ ? mobileMql+ : {+ matches: false,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ },+ ) as never+ Object.defineProperty(window, "innerHeight", { configurable: true, value: 640 })++ try {+ const view = render(+ createElement(SignInPageClient, { isProd: true, appleEnabled: true }),+ )+ const stage = screen.getByTestId("sign-in-mobile-typewriter")+ const email = screen.getByRole("textbox", { name: "Email" })++ act(() => {+ fireEvent.focusIn(email)+ fireEvent.focusOut(email)+ })+ expect(stage).toHaveAttribute("data-collapsed", "true")+ expect(vi.getTimerCount()).toBe(1)++ act(() => {+ Object.defineProperty(window, "innerHeight", { configurable: true, value: 460 })+ mobile = false+ for (const listener of mobileListeners) listener()+ })+ expect(vi.getTimerCount()).toBe(0)+ expect(stage).toHaveAttribute("data-collapsed", "false")++ act(() => {+ vi.advanceTimersByTime(100)+ })+ expect(stage).toHaveAttribute("data-collapsed", "false")+ view.unmount()+ } finally {+ vi.clearAllTimers()+ vi.useRealTimers()+ }})})diff --git a/src/web/src/app/(auth)/sign-in/sign-in-client.test.ts b/src/web/src/app/(auth)/sign-in/sign-in-client.test.tsindex 7eb5f818a..558efe796 100644--- a/src/web/src/app/(auth)/sign-in/sign-in-client.test.ts+++ b/src/web/src/app/(auth)/sign-in/sign-in-client.test.ts@@ -4,8 +4,8 @@ import { describe, expect, it, vi } from "vitest"import { SignInEmailField, SignInOtpField } from "./sign-in-fields"-describe("sign-in field errors", () => {- it("renders an email error once after its input and links the input to it", () => {+describe("sign-in field errors and focus policy", () => {+ it("renders an email error once after its input, hides the visual label for screen readers, and omits initial autofocus", () => {const html = renderToStaticMarkup(createElement(SignInEmailField, {email: "[email protected]",error: "Failed to send code",@@ -16,6 +16,8 @@ describe("sign-in field errors", () => {expect(html.indexOf('id="email"')).toBeLessThan(html.indexOf('id="sign-in-email-error"'))expect(html).toContain('aria-invalid="true"')expect(html).toContain('aria-describedby="sign-in-email-error"')+ expect(html).toContain("sr-only")+ expect(html.toLowerCase()).not.toContain("autofocus")})it("renders an OTP error once after the six slots and links the OTP input to it", () => {diff --git a/src/web/src/app/(auth)/sign-in/sign-in-client.tsx b/src/web/src/app/(auth)/sign-in/sign-in-client.tsxindex 5bb95879d..7dd332c21 100644--- a/src/web/src/app/(auth)/sign-in/sign-in-client.tsx+++ b/src/web/src/app/(auth)/sign-in/sign-in-client.tsx@@ -3,23 +3,29 @@import { captureProductAnalytics } from "@/lib/product-analytics"import { startAction, finishAction } from "@/lib/observability/context"import { ObservedStaticContent } from "@/lib/observability/regions"-import { useAtom, useCreateAtom } from "@tanstack/react-store";-import { useEffect } from "react"+import { useAtom, useCreateAtom } from "@tanstack/react-store"+import { useCallback, useEffect, useRef } from "react"import { useSearchParams } from "next/navigation"import { signIn, signUp, authClient } from "@/lib/auth-client"+import {+ normalizeLoginMethod,+ rememberLastLoginMethod,+ type LoginMethod,+} from "@/lib/last-login-method"import { parseRetryAfterSeconds } from "@/lib/retry-after"import { tid } from "@/lib/community/testids"import { Button } from "@/components/ui/button"import { Card, CardContent } from "@/components/ui/card"import {- Field,FieldGroup,FieldSeparator,} from "@/components/ui/field"import { SignInEmailField, SignInOtpField } from "./sign-in-fields"import { SocialSignIn } from "./social-sign-in"-import { useSignInTerms } from "./sign-in-terms"+import { SignInTermsNotice } from "./sign-in-terms"+import { SignInMobileTypewriter } from "./sign-in-mobile-typewriter"import { GradientBackground } from "@/components/gradient-background"+import { useIsMobile } from "@/hooks/use-mobile"import { Logo } from "@/components/logo"import { LandingShellMotion } from "@/components/home/landing-shell-motion"import {@@ -28,8 +34,10 @@ import {} from "@/components/home/landing-shell-motion-timeline"import galleryStyles from "@/components/home/landing-shell-motion.module.css"import { DEV_PASSWORD } from "@alook/shared"-import { CircleCheck } from "lucide-react"+import { CircleCheck, Mail } from "lucide-react"+import Image from "next/image"import { safeRedirectPath } from "@/lib/safe-redirect"+import { cn } from "@/lib/utils"// Default post-login landing when no explicit `?redirect=` is present. Points// at the community home (/c/me); the old `/workspaces` target was the legacy@@ -40,32 +48,113 @@ function safeRedirectUrl(redirect: string | null): string {return safeRedirectPath(redirect, DEFAULT_POST_LOGIN)}+function readClientLastLoginMethod(): LoginMethod | null {+ const getter = (authClient as { getLastUsedLoginMethod?: () => string | null })+ .getLastUsedLoginMethod+ return normalizeLoginMethod(getter?.())+}++type StepViewState =+ | "email"+ | "prepare-to-code"+ | "sliding-to-code"+ | "code"+ | "prepare-to-email"+ | "sliding-to-email"++const STEP_SLIDE_FALLBACK_MS = 560+function SignInForm({postLoginUrl,isProd,accountDeleted,accountDeletionPending,appleEnabled,+ initialLastUsedMethod = null,+ isMobile,+ mobileTypewriterCollapsed,+ onSlideActiveChange,}: {postLoginUrl: stringisProd: booleanaccountDeleted: booleanaccountDeletionPending: booleanappleEnabled: boolean+ initialLastUsedMethod?: LoginMethod | null+ isMobile: boolean+ mobileTypewriterCollapsed: boolean+ onSlideActiveChange?: (active: boolean) => void}) {- useEffect(() => { void captureProductAnalytics({ event: "login_page_view" }) }, [])+ useEffect(() => {+ void captureProductAnalytics({ event: "login_page_view" })+ }, [])+const failed = (failureStage: "send_code" | "verify_code", error: unknown) => {- void captureProductAnalytics({ event: "sign_in_failed", method: "email_otp", failureStage, error })+ void captureProductAnalytics({+ event: "sign_in_failed",+ method: "email_otp",+ failureStage,+ error,+ })}++ const trackRef = useRef<HTMLDivElement>(null)+ const codePaneRef = useRef<HTMLDivElement>(null)const [email, setEmail] = useAtom(useCreateAtom(""))const [emailError, setEmailError] = useAtom(useCreateAtom(""))const [otpError, setOtpError] = useAtom(useCreateAtom(""))const [loading, setLoading] = useAtom(useCreateAtom(false))-const [code, setCode] = useAtom(useCreateAtom(""))- const [step, setStep] = useAtom(useCreateAtom<"email" | "code">("email"))+ const [viewState, setViewState] = useAtom(useCreateAtom<StepViewState>("email"))const [retryAfter, setRetryAfter] = useAtom(useCreateAtom<number | null>(null))- const terms = useSignInTerms()+ const [lastUsedMethod, setLastUsedMethod] = useAtom(+ useCreateAtom<LoginMethod | null>(initialLastUsedMethod),+ )++ const finishSlide = useCallback(+ (target: "email" | "code") => {+ onSlideActiveChange?.(false)+ setViewState(target)+ },+ [onSlideActiveChange, setViewState],+ )++ const shouldAnimateSlide = () =>+ isMobile+ && typeof window !== "undefined"+ && !window.matchMedia("(prefers-reduced-motion: reduce)").matches++ const enterCodeStep = () => {+ if (!shouldAnimateSlide()) {+ setViewState("code")+ return+ }+ if (document.activeElement instanceof HTMLElement) {+ document.activeElement.blur()+ }+ onSlideActiveChange?.(true)+ setViewState("prepare-to-code")+ }++ const returnToEmailStep = () => {+ setCode("")+ setOtpError("")+ setEmailError("")+ if (!shouldAnimateSlide()) {+ setViewState("email")+ return+ }+ if (document.activeElement instanceof HTMLElement) {+ document.activeElement.blur()+ }+ onSlideActiveChange?.(true)+ setViewState("prepare-to-email")+ }++ useEffect(() => {+ const stored = readClientLastLoginMethod()+ if (stored) setLastUsedMethod(stored)+ }, [setLastUsedMethod])useEffect(() => {if (retryAfter == null) return@@ -75,6 +164,50 @@ function SignInForm({return () => clearTimeout(id)}, [retryAfter, setRetryAfter])+ useEffect(() => {+ if (viewState !== "prepare-to-code" && viewState !== "prepare-to-email") return+ void trackRef.current?.getBoundingClientRect()+ const rafId = window.requestAnimationFrame(() => {+ setViewState(+ viewState === "prepare-to-code" ? "sliding-to-code" : "sliding-to-email",+ )+ })+ return () => window.cancelAnimationFrame(rafId)+ }, [setViewState, viewState])++ useEffect(() => {+ if (viewState !== "sliding-to-code" && viewState !== "sliding-to-email") return+ const target = viewState === "sliding-to-code" ? "code" : "email"+ const timerId = window.setTimeout(() => {+ finishSlide(target)+ }, STEP_SLIDE_FALLBACK_MS)+ return () => window.clearTimeout(timerId)+ }, [finishSlide, viewState])++ useEffect(() => {+ if (isMobile) return+ if (viewState === "prepare-to-code" || viewState === "sliding-to-code") {+ finishSlide("code")+ } else if (viewState === "prepare-to-email" || viewState === "sliding-to-email") {+ finishSlide("email")+ }+ }, [finishSlide, isMobile, viewState])++ useEffect(() => {+ if (!isProd || viewState !== "code") return+ const focusOtp = () => {+ const otpInput = codePaneRef.current?.querySelector<HTMLInputElement>(+ 'input[aria-label="Verification code"]',+ )+ if (otpInput && document.activeElement !== otpInput) {+ otpInput.focus({ preventScroll: true })+ }+ }+ focusOtp()+ const rafId = window.requestAnimationFrame(focusOtp)+ return () => window.cancelAnimationFrame(rafId)+ }, [isProd, viewState])+const rateLimitHandler = {onError: (ctx: { response: Response }) => {if (ctx.response.status === 429) {@@ -88,16 +221,14 @@ function SignInForm({function handleEmailSubmit(e: React.SubmitEvent<HTMLFormElement>) {e.preventDefault()const form = e.currentTarget- terms.requestConsent(() => {- if (!form.reportValidity()) return- const emailInput = form.elements.namedItem("email")- if (!(emailInput instanceof HTMLInputElement)) return- if (isProd) void sendCode(emailInput.value)- else void devSignIn(emailInput.value)- })+ if (!form.reportValidity()) return+ const emailInput = form.elements.namedItem("email")+ if (!(emailInput instanceof HTMLInputElement)) return+ if (isProd) void sendCode(emailInput.value)+ else void devSignIn(emailInput.value)}- async function sendCode(email: string) {+ async function sendCode(targetEmail: string) {if (retryAfter != null) returnconst observation = startAction("auth_send_code")setEmailError("")@@ -105,7 +236,7 @@ function SignInForm({setLoading(true)try {const { error } = await authClient.emailOtp.sendVerificationOtp({- email,+ email: targetEmail,type: "sign-in",fetchOptions: rateLimitHandler,})@@ -114,9 +245,12 @@ function SignInForm({failed("send_code", error)if (error.status !== 429) setEmailError(error.message ?? "Failed to send code")} else {+ rememberLastLoginMethod("email")+ setLastUsedMethod("email")+ setEmail(targetEmail)setEmailError("")setOtpError("")- setStep("code")+ enterCodeStep()}} catch (error) {finishAction(observation, "error")@@ -130,12 +264,11 @@ function SignInForm({setCode(value)setOtpError("")if (value.length !== 6) return- terms.requestConsent(() => { void verifyCode(value) })+ await verifyCode(value)}async function verifyCode(value: string) {const observation = startAction("auth_verify_code")-setLoading(true)try {const { error } = await authClient.signIn.emailOtp({@@ -148,6 +281,8 @@ function SignInForm({setOtpError(error.message ?? "Invalid code")setCode("")} else {+ rememberLastLoginMethod("email")+ setLastUsedMethod("email")setOtpError("")window.location.href = postLoginUrlreturn@@ -161,17 +296,17 @@ function SignInForm({setLoading(false)}- async function devSignIn(email: string) {+ async function devSignIn(targetEmail: string) {const observation = startAction("auth_dev_sign_in")setEmailError("")setLoading(true)const { error: signInErr } = await signIn.email(- { email, password: DEV_PASSWORD },+ { email: targetEmail, password: DEV_PASSWORD },{ onError: () => {} },)if (signInErr) {const { error: signUpErr } = await signUp.email(- { name: email.split("@")[0], email, password: DEV_PASSWORD },+ { name: targetEmail.split("@")[0], email: targetEmail, password: DEV_PASSWORD },{ onError: () => {} },)if (signUpErr) {@@ -181,6 +316,8 @@ function SignInForm({return}}+ rememberLastLoginMethod("email")+ setLastUsedMethod("email")finishAction(observation, "success")window.location.href = postLoginUrl}@@ -193,124 +330,225 @@ function SignInForm({? "Sending...": isCoolingDown? `Wait ${retryAfter}s`- : "Send Code"+ : "Continue with email"+ const isEmailLastUsed = lastUsedMethod === "email"+ const showEmailPane = !isProd || viewState !== "code"+ const showCodePane = isProd && viewState !== "email"+ const isSliding = viewState === "sliding-to-code" || viewState === "sliding-to-email"+ const isExitingEmail =+ viewState === "prepare-to-code" || viewState === "sliding-to-code"+ const isExitingCode =+ viewState === "prepare-to-email" || viewState === "sliding-to-email"+ const deferOtpFocus =+ viewState === "prepare-to-code" || viewState === "sliding-to-code"+ const trackTransform =+ viewState === "sliding-to-code" || viewState === "prepare-to-email"+ ? "translate3d(-100%, 0, 0)"+ : viewState === "prepare-to-code" || viewState === "sliding-to-email"+ ? "translate3d(0%, 0, 0)"+ : undefined- const subtitle = isProd && step === "code"- ? "Enter the code we sent you"- : isProd- ? "Enter your email — we’ll send you a verification code"- : undefined+ const handleTrackTransitionEnd = (event: React.TransitionEvent<HTMLDivElement>) => {+ if (event.target !== event.currentTarget || event.propertyName !== "transform") {+ return+ }+ if (viewState === "sliding-to-code") {+ finishSlide("code")+ } else if (viewState === "sliding-to-email") {+ finishSlide("email")+ }+ }return (- <FieldGroup>+ <div className="relative flex min-h-0 w-full flex-1 overflow-clip sm:min-h-124"><ObservedStaticContent />- {accountDeleted || accountDeletionPending ? (- <div- className="flex gap-3 rounded-xl bg-muted/70 p-4 text-left"- role="status"- data-testid={tid.accountDeletionComplete}- >- <CircleCheck className="mt-0.5 size-5 shrink-0 text-muted-foreground" aria-hidden />- <div>- <div className="text-sm font-medium">{accountDeletionPending ? "Account deletion requested" : "Account deleted"}</div>- <p className="mt-0.5 text-sm text-muted-foreground">- {accountDeletionPending- ? "Sign-in is disabled. We’re stopping billing and removing your data. Cleanup will retry automatically."- : "Your account and its data were removed."}- </p>- </div>- </div>- ) : null}- <div className="flex flex-col items-center gap-2 text-center">- <h1 className="text-2xl font-bold">Sign in</h1>- <p className="text-sm text-muted-foreground">or create an account to get started</p>- {subtitle && (- <p className="text-balance text-muted-foreground">{subtitle}</p>+ <div+ ref={trackRef}+ data-testid={tid.signInStepTrack}+ data-step-view={viewState}+ onTransitionEnd={handleTrackTransitionEnd}+ style={trackTransform ? { transform: trackTransform } : undefined}+ className={cn(+ "flex min-h-0 w-full flex-1",+ isSliding+ && "transition-transform duration-500 ease-in-out will-change-transform motion-reduce:transition-none",)}- </div>+ >+ {showEmailPane ? (+ <div+ key="email-pane"+ data-testid="sign-in-email-pane"+ aria-hidden={isExitingEmail || undefined}+ inert={isExitingEmail || undefined}+ className={cn(+ "flex h-full min-h-0 w-full shrink-0 flex-col sm:h-auto sm:justify-center sm:overflow-visible sm:p-8",+ mobileTypewriterCollapsed+ ? "overflow-y-auto py-4"+ : "justify-center gap-4 overflow-hidden pt-[max(0.5rem,env(safe-area-inset-top))] pb-[max(1rem,env(safe-area-inset-bottom))] [@media(min-height:740px)]:gap-8",+ )}+ >+ <SignInMobileTypewriter collapsed={mobileTypewriterCollapsed} />+ <div+ className={cn(+ "w-full shrink-0 px-4 sm:px-0",+ mobileTypewriterCollapsed && "my-auto sm:my-0",+ )}+ >+ <div className="mx-auto w-full max-w-80 sm:max-w-88">+ <FieldGroup className="gap-4 sm:gap-4 [@media(max-height:579px)]:gap-2">+ {accountDeleted || accountDeletionPending ? (+ <div+ className="flex gap-3 rounded-xl bg-muted/70 p-4 text-left"+ role="status"+ data-testid={tid.accountDeletionComplete}+ >+ <CircleCheck+ className="mt-0.5 size-5 shrink-0 text-muted-foreground"+ aria-hidden+ />+ <div>+ <div className="text-sm font-medium">+ {accountDeletionPending+ ? "Account deletion requested"+ : "Account deleted"}+ </div>+ <p className="mt-0.5 text-sm text-muted-foreground">+ {accountDeletionPending+ ? "Sign-in is disabled. We’re stopping billing and removing your data. Cleanup will retry automatically."+ : "Your account and its data were removed."}+ </p>+ </div>+ </div>+ ) : null}- {isProd ? (- step === "email" ? (- <form noValidate onSubmit={handleEmailSubmit}>- <FieldGroup>- <SignInEmailField- email={email}- error={emailFeedback}- onChange={(event) => {- setEmail(event.target.value)- setEmailError("")- }}- />- <Field>+ <h1+ aria-label="Welcome to Alook"+ className="mb-0 flex w-full items-center justify-start gap-2 text-left text-[1.375rem] leading-7 font-semibold tracking-tight whitespace-nowrap sm:mb-4 sm:text-2xl sm:leading-8 [@media(min-height:740px)]:mb-4"+ >+ <span>Welcome to</span>+ <Image+ src="/alook.svg"+ alt=""+ width={24}+ height={24}+ priority+ className="size-5.5 shrink-0 sm:size-6"+ />+ <span className="font-brand text-[1.5625rem] leading-none font-bold tracking-tight sm:text-[1.6875rem]">+ Alook+ </span>+ </h1>++ <SocialSignIn+ postLoginUrl={postLoginUrl}+ appleEnabled={appleEnabled}+ lastUsedMethod={lastUsedMethod}+ onSelectMethod={setLastUsedMethod}+ />++ <FieldSeparator className="*:data-[slot=field-separator-content]:bg-background *:data-[slot=field-separator-content]:text-xs sm:*:data-[slot=field-separator-content]:bg-card">+ or+ </FieldSeparator>++ <form noValidate onSubmit={handleEmailSubmit}>+ <div className="flex flex-col gap-2">+ <SignInEmailField+ email={email}+ error={isProd ? emailFeedback : emailError}+ onChange={(event) => {+ setEmail(event.target.value)+ setEmailError("")+ }}+ />+ <div className="relative">+ <Button+ variant="outline"+ size="lg"+ type="submit"+ disabled={loading || isSliding || (isProd && isCoolingDown)}+ aria-describedby={+ isEmailLastUsed ? "last-used-email-badge" : undefined+ }+ className={cn(+ "peer h-11 w-full justify-start px-4 text-sm font-medium",+ isEmailLastUsed && "pr-22",+ )}+ >+ <span className="flex min-w-0 items-center gap-2">+ <span+ className="grid h-9 w-6 shrink-0 place-items-center"+ aria-hidden+ >+ <Mail className="size-4" aria-hidden />+ </span>+ <span className="truncate">+ {isProd ? sendLabel : loading ? "Signing in..." : "Sign in"}+ </span>+ </span>+ </Button>+ {isEmailLastUsed ? (+ <span+ id="last-used-email-badge"+ data-testid="last-used-email"+ className="pointer-events-none absolute top-1/2 right-3 -translate-y-1/2 rounded-full border border-border bg-secondary px-2 py-0.5 text-[11px] leading-none font-medium text-secondary-foreground peer-disabled:opacity-50"+ >+ Last used+ </span>+ ) : null}+ </div>+ </div>+ </form>++ <SignInTermsNotice />+ </FieldGroup>+ </div>+ </div>+ </div>+ ) : null}++ {showCodePane ? (+ <div+ key="code-pane"+ ref={codePaneRef}+ data-testid="sign-in-code-pane"+ aria-hidden={isExitingCode || undefined}+ inert={isExitingCode || undefined}+ className="flex h-full min-h-0 w-full shrink-0 flex-col overflow-y-auto px-4 pt-[max(1rem,env(safe-area-inset-top))] pb-[max(1.5rem,env(safe-area-inset-bottom))] sm:h-auto sm:justify-center sm:overflow-visible sm:p-8"+ >+ <div className="mx-auto my-auto w-full max-w-80 sm:my-0 sm:max-w-88">+ <FieldGroup className="gap-4">+ <div className="mb-4 flex flex-col items-center gap-2 text-center sm:mb-0 [@media(max-height:579px)]:mb-0">+ <Logo size="lg" iconOnly className="size-11 justify-center rounded-lg" />+ <h1 className="text-xl font-semibold tracking-tight sm:text-2xl">+ Check your email+ </h1>+ <p className="max-w-full wrap-break-word text-sm text-muted-foreground">+ We sent a code to{" "}+ <strong className="font-medium text-foreground">{email}</strong>+ </p>+ </div>+ <SignInOtpField+ code={code}+ error={otpError}+ loading={loading}+ autoFocus={!deferOtpFocus}+ onChange={handleVerifyCode}+ /><Button- variant="outline"- size="lg"- type="submit"- disabled={loading || isCoolingDown}- className="w-full text-base"+ variant="ghost"+ type="button"+ className="h-11 w-full sm:h-9"+ disabled={isSliding}+ onClick={returnToEmailStep}>- {sendLabel}+ Use a different email</Button>- </Field>- </FieldGroup>- </form>- ) : (- <>- <p className="text-sm text-muted-foreground text-center">- We sent a code to <strong>{email}</strong>- </p>- <SignInOtpField- code={code}- error={otpError}- loading={loading}- onChange={handleVerifyCode}- />- <Button- variant="ghost"- className="w-full"- onClick={() => {- setStep("email")- setCode("")- setOtpError("")- setEmailError("")- }}- >- Use a different email- </Button>- </>- )- ) : (- <form noValidate onSubmit={handleEmailSubmit}>- <FieldGroup>- <SignInEmailField- email={email}- error={emailError}- onChange={(event) => {- setEmail(event.target.value)- setEmailError("")- }}- />- <Field>- <Button- variant="outline"- size="lg"- type="submit"- disabled={loading}- className="w-full text-base"- >- {loading ? "Signing in..." : "Sign in"}- </Button>- </Field>- </FieldGroup>- </form>- )}-- {terms.control}- <FieldSeparator className="*:data-[slot=field-separator-content]:bg-card">- Or continue with- </FieldSeparator>- <SocialSignIn postLoginUrl={postLoginUrl} appleEnabled={appleEnabled} requestConsent={terms.requestConsent} />- </FieldGroup>+ </FieldGroup>+ </div>+ </div>+ ) : null}+ </div>+ </div>)}@@ -370,7 +608,7 @@ function ProductGallery() {if (!enabled) return nullreturn (- <div className={`${galleryStyles.galleryContainer} flex h-full min-h-0 flex-col items-center justify-center p-5 lg:p-7`}>+ <div className={`${galleryStyles.galleryContainer} flex h-full min-h-0 flex-col items-center justify-center p-4 lg:p-8`}><divclassName={`${galleryStyles.galleryFrame} w-full bg-background ring-1 ring-border/60 shadow-lg`}role="img"@@ -423,40 +661,125 @@ function ProductGallery() {export default function SignInPageClient({isProd,appleEnabled,+ initialLastUsedMethod = null,}: {isProd: booleanappleEnabled: boolean+ initialLastUsedMethod?: LoginMethod | null}) {const searchParams = useSearchParams()const postLoginUrl = safeRedirectUrl(searchParams.get("redirect"))const accountDeleted = searchParams.get("account_deleted") === "1"const accountDeletionPending = searchParams.get("account_deleted") === "pending"+ const isMobile = useIsMobile()+ const mobileSlideActiveRef = useRef(false)+ const syncViewportRef = useRef<(() => void) | null>(null)+ const [mobileTypewriterCollapsed, setMobileTypewriterCollapsed] = useAtom(+ useCreateAtom(false),+ )+ const [mobileViewportHeight, setMobileViewportHeight] = useAtom(+ useCreateAtom<number | null>(null),+ )++ const handleSlideActiveChange = useCallback((active: boolean) => {+ mobileSlideActiveRef.current = active+ if (!active) {+ syncViewportRef.current?.()+ }+ }, [])++ useEffect(() => {+ if (!isMobile) {+ mobileSlideActiveRef.current = false+ syncViewportRef.current = null+ setMobileTypewriterCollapsed(false)+ setMobileViewportHeight(null)+ return+ }+ let active = true+ let inputFocused = false+ let blurTimerId: number | null = null+ const clearBlurTimer = () => {+ if (blurTimerId !== null) {+ window.clearTimeout(blurTimerId)+ blurTimerId = null+ }+ }+ const syncViewport = () => {+ if (!active || mobileSlideActiveRef.current) return+ const layoutHeight = window.innerHeight+ const visualHeight = window.visualViewport?.height ?? layoutHeight+ const keyboardLikelyOpen = layoutHeight - visualHeight > 80+ const shortSpace = visualHeight < 580 || (inputFocused && visualHeight < 700)+ setMobileTypewriterCollapsed(keyboardLikelyOpen || shortSpace)+ setMobileViewportHeight(+ keyboardLikelyOpen ? Math.round(visualHeight) : null,+ )+ }+ syncViewportRef.current = syncViewport+ const onFocusIn = (event: FocusEvent) => {+ if (+ event.target instanceof HTMLInputElement+ || event.target instanceof HTMLTextAreaElement+ ) {+ clearBlurTimer()+ inputFocused = true+ syncViewport()+ }+ }+ const onFocusOut = () => {+ inputFocused = false+ clearBlurTimer()+ blurTimerId = window.setTimeout(() => {+ blurTimerId = null+ syncViewport()+ }, 50)+ }+ syncViewport()+ window.addEventListener("resize", syncViewport)+ window.visualViewport?.addEventListener("resize", syncViewport)+ document.addEventListener("focusin", onFocusIn)+ document.addEventListener("focusout", onFocusOut)+ return () => {+ active = false+ clearBlurTimer()+ syncViewportRef.current = null+ window.removeEventListener("resize", syncViewport)+ window.visualViewport?.removeEventListener("resize", syncViewport)+ document.removeEventListener("focusin", onFocusIn)+ document.removeEventListener("focusout", onFocusOut)+ }+ }, [isMobile, setMobileTypewriterCollapsed, setMobileViewportHeight])return (- <div className="relative flex min-h-svh flex-col items-center justify-center p-6 sm:p-10">+ <div+ style={+ isMobile && mobileViewportHeight !== null+ ? { height: `${mobileViewportHeight}px` }+ : undefined+ }+ className="relative flex h-dvh flex-col overflow-hidden p-0 sm:h-auto sm:min-h-svh sm:items-center sm:justify-center sm:overflow-visible sm:p-8"+ ><GradientBackground />- <div className="w-full max-w-sm sm:max-w-6xl">- <div className="flex flex-col gap-6">- <div className="flex justify-center mb-2">- <Logo size="lg" />- </div>- <Card className="overflow-hidden p-0">- <CardContent className="grid p-0 sm:grid-cols-[minmax(320px,0.82fr)_minmax(0,1.35fr)]">- <div className="flex flex-col justify-center p-6 sm:min-h-120 sm:p-8">- <SignInForm- postLoginUrl={postLoginUrl}- isProd={isProd}- accountDeleted={accountDeleted}- accountDeletionPending={accountDeletionPending}- appleEnabled={appleEnabled}- />- </div>- <div className="relative hidden min-h-120 overflow-hidden bg-muted sm:block">- <ProductGallery />- </div>- </CardContent>- </Card>- </div>+ <div className="flex min-h-0 w-full flex-1 flex-col sm:max-w-5xl sm:flex-none">+ <Card className="min-h-0 flex-1 overflow-hidden rounded-none bg-transparent p-0 shadow-none ring-0 sm:flex-none sm:rounded-xl sm:bg-card sm:ring-1 sm:ring-foreground/10">+ <CardContent className="flex min-h-0 flex-1 flex-col p-0 sm:grid sm:flex-none sm:grid-cols-[minmax(352px,0.88fr)_minmax(0,1.25fr)]">+ <SignInForm+ postLoginUrl={postLoginUrl}+ isProd={isProd}+ accountDeleted={accountDeleted}+ accountDeletionPending={accountDeletionPending}+ appleEnabled={appleEnabled}+ initialLastUsedMethod={initialLastUsedMethod}+ isMobile={isMobile}+ mobileTypewriterCollapsed={mobileTypewriterCollapsed}+ onSlideActiveChange={handleSlideActiveChange}+ />+ <div className="relative hidden min-h-124 overflow-hidden bg-muted sm:block">+ <ProductGallery />+ </div>+ </CardContent>+ </Card></div></div>)diff --git a/src/web/src/app/(auth)/sign-in/sign-in-fields.tsx b/src/web/src/app/(auth)/sign-in/sign-in-fields.tsxindex 1203ea4eb..e7e3a15b5 100644--- a/src/web/src/app/(auth)/sign-in/sign-in-fields.tsx+++ b/src/web/src/app/(auth)/sign-in/sign-in-fields.tsx@@ -17,17 +17,21 @@ export function SignInEmailField({}) {return (<Field data-invalid={!!error}>- <FieldLabel htmlFor="email">Email</FieldLabel>+ <FieldLabel htmlFor="email" className="sr-only">+ </FieldLabel><Inputid="email"+ name="email"type="email"+ autoComplete="email"placeholder="[email protected]"+ className="h-11 px-4"value={email}onChange={onChange}aria-invalid={!!error}aria-describedby={error ? "sign-in-email-error" : undefined}required- autoFocus/>{error && <FieldError id="sign-in-email-error">{error}</FieldError>}</Field>@@ -38,11 +42,13 @@ export function SignInOtpField({code,error,loading,+ autoFocus = true,onChange,}: {code: stringerror?: stringloading: boolean+ autoFocus?: booleanonChange: (value: string) => void}) {return (@@ -59,15 +65,16 @@ export function SignInOtpField({aria-label="Verification code"aria-invalid={!!error}aria-describedby={error ? "sign-in-otp-error" : undefined}- autoFocus+ autoFocus={autoFocus}+ className="text-base"><InputOTPGroup>- <InputOTPSlot index={0} />- <InputOTPSlot index={1} />- <InputOTPSlot index={2} />- <InputOTPSlot index={3} />- <InputOTPSlot index={4} />- <InputOTPSlot index={5} />+ <InputOTPSlot index={0} className="size-11 text-base sm:size-10" />+ <InputOTPSlot index={1} className="size-11 text-base sm:size-10" />+ <InputOTPSlot index={2} className="size-11 text-base sm:size-10" />+ <InputOTPSlot index={3} className="size-11 text-base sm:size-10" />+ <InputOTPSlot index={4} className="size-11 text-base sm:size-10" />+ <InputOTPSlot index={5} className="size-11 text-base sm:size-10" /></InputOTPGroup></InputOTP>{error && (diff --git a/src/web/src/app/(auth)/sign-in/sign-in-mobile-typewriter.dom.test.tsx b/src/web/src/app/(auth)/sign-in/sign-in-mobile-typewriter.dom.test.tsxnew file mode 100644index 000000000..b04428180--- /dev/null+++ b/src/web/src/app/(auth)/sign-in/sign-in-mobile-typewriter.dom.test.tsx@@ -0,0 +1,219 @@+import { createElement } from "react"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { act, fireEvent, render, screen } from "@/test/react-dom-harness"++vi.mock("@/components/typewriter-visual", () => ({+ TypewriterVisual: ({ className }: { className?: string }) =>+ createElement("div", { "data-testid": "typewriter-visual-stub", className }),+}))++import { SignInMobileTypewriter } from "./sign-in-mobile-typewriter"++function mockMatchMedia({ mobile, reducedMotion = false }: { mobile: boolean; reducedMotion?: boolean }) {+ window.matchMedia = vi.fn((query: string) => ({+ matches: query.includes("max-width") ? mobile : query.includes("prefers-reduced-motion") ? reducedMotion : false,+ media: query,+ onchange: null,+ addListener: vi.fn(),+ removeListener: vi.fn(),+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ dispatchEvent: vi.fn(),+ })) as never+}++describe("SignInMobileTypewriter", () => {+ let rafQueue: FrameRequestCallback[] = []++ function flushNextFrame(ts = 16) {+ const next = rafQueue.shift()+ next?.(ts)+ }++ function drainFrames() {+ let guard = 0+ while (rafQueue.length > 0 && guard < 120) {+ flushNextFrame(16 * (guard + 1))+ guard += 1+ }+ }++ beforeEach(() => {+ rafQueue = []+ vi.stubGlobal("requestAnimationFrame", (cb: FrameRequestCallback) => {+ rafQueue.push(cb)+ return rafQueue.length+ })+ vi.stubGlobal("cancelAnimationFrame", vi.fn())+ })++ afterEach(() => {+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+ delete (window as Window & { DeviceOrientationEvent?: unknown }).DeviceOrientationEvent+ delete (window as Window & { DeviceMotionEvent?: unknown }).DeviceMotionEvent+ })++ it("mounts TypewriterVisual only on mobile when not collapsed", () => {+ mockMatchMedia({ mobile: false })+ const desktop = render(createElement(SignInMobileTypewriter, { collapsed: false }))+ expect(screen.queryByTestId("typewriter-visual-stub")).toBeNull()+ desktop.unmount()++ mockMatchMedia({ mobile: true })+ const mobile = render(createElement(SignInMobileTypewriter, { collapsed: false }))+ expect(screen.getByTestId("typewriter-visual-stub")).toBeVisible()+ expect(screen.getByTestId("sign-in-mobile-typewriter")).toHaveAttribute("data-collapsed", "false")++ mobile.rerender(createElement(SignInMobileTypewriter, { collapsed: true }))+ expect(screen.queryByTestId("typewriter-visual-stub")).toBeNull()+ expect(screen.getByTestId("sign-in-mobile-typewriter")).toHaveAttribute("data-collapsed", "true")+ })++ it("tilts with gyroscope orientation and shakes on accelerometer spikes before decaying to rest", () => {+ mockMatchMedia({ mobile: true })+ render(createElement(SignInMobileTypewriter, { collapsed: false }))+ const stage = screen.getByTestId("sign-in-mobile-typewriter")++ act(() => {+ const rest = new Event("deviceorientation") as DeviceOrientationEvent+ Object.defineProperties(rest, { beta: { value: 40 }, gamma: { value: 0 } })+ window.dispatchEvent(rest)++ const tilted = new Event("deviceorientation") as DeviceOrientationEvent+ Object.defineProperties(tilted, { beta: { value: 55 }, gamma: { value: 15 } })+ window.dispatchEvent(tilted)+ })++ expect(Number.parseFloat(stage.style.getPropertyValue("--tw-ry"))).toBeGreaterThan(-19)+ expect(Number.parseFloat(stage.style.getPropertyValue("--tw-rx"))).toBeLessThan(11)++ const beforeTx = Number.parseFloat(stage.style.getPropertyValue("--tw-tx"))+ act(() => {+ const shake = new Event("devicemotion") as DeviceMotionEvent+ Object.defineProperties(shake, {+ acceleration: { value: { x: 8, y: -5, z: 0 } },+ })+ window.dispatchEvent(shake)+ flushNextFrame()+ })+ expect(Number.parseFloat(stage.style.getPropertyValue("--tw-tx"))).not.toBe(beforeTx)++ act(() => {+ drainFrames()+ })+ expect(Number.parseFloat(stage.style.getPropertyValue("--tw-tx"))).toBeCloseTo(beforeTx, 1)+ })++ it("defers iOS sensor permission until tapping the typewriter stage and falls back to touch drag when denied", async () => {+ mockMatchMedia({ mobile: true })+ const requestPermission = vi.fn().mockResolvedValue("denied")+ ;(window as Window & { DeviceOrientationEvent?: unknown }).DeviceOrientationEvent = {+ requestPermission,+ }++ render(createElement(SignInMobileTypewriter, { collapsed: false }))+ const stage = screen.getByTestId("sign-in-mobile-typewriter")+ vi.spyOn(stage, "getBoundingClientRect").mockReturnValue({+ x: 0,+ y: 0,+ left: 0,+ top: 0,+ right: 390,+ bottom: 420,+ width: 390,+ height: 420,+ toJSON: () => ({}),+ })+ expect(requestPermission).not.toHaveBeenCalled()++ await act(async () => {+ fireEvent.pointerDown(stage, { pointerId: 1, clientX: 330, clientY: 120 })+ await Promise.resolve()+ })+ expect(requestPermission).toHaveBeenCalledOnce()+ expect(Number.parseFloat(stage.style.getPropertyValue("--tw-ry"))).toBeGreaterThan(-19)++ await act(async () => {+ fireEvent.pointerUp(stage, { pointerId: 1, clientX: 330, clientY: 120 })+ fireEvent.pointerDown(stage, { pointerId: 2, clientX: 60, clientY: 300 })+ await Promise.resolve()+ })+ expect(requestPermission).toHaveBeenCalledOnce()+ expect(Number.parseFloat(stage.style.getPropertyValue("--tw-ry"))).toBeLessThan(-19)+ })++ it("reattaches sensors when permission is granted while still active", async () => {+ mockMatchMedia({ mobile: true })+ const requestOrientation = vi.fn().mockResolvedValue("granted")+ const requestMotion = vi.fn().mockResolvedValue("granted")+ ;(window as Window & { DeviceOrientationEvent?: unknown }).DeviceOrientationEvent = {+ requestPermission: requestOrientation,+ }+ ;(window as Window & { DeviceMotionEvent?: unknown }).DeviceMotionEvent = {+ requestPermission: requestMotion,+ }+ const add = vi.spyOn(window, "addEventListener")+ const remove = vi.spyOn(window, "removeEventListener")+ const isSensorEvent = ([name]: readonly unknown[]) =>+ name === "deviceorientation" || name === "devicemotion"++ render(createElement(SignInMobileTypewriter, { collapsed: false }))+ add.mockClear()+ remove.mockClear()++ await act(async () => {+ fireEvent.pointerDown(screen.getByTestId("sign-in-mobile-typewriter"), { pointerId: 1 })+ await Promise.resolve()+ await Promise.resolve()+ })++ expect(requestOrientation).toHaveBeenCalledOnce()+ expect(requestMotion).toHaveBeenCalledOnce()+ expect(remove.mock.calls.filter(isSensorEvent)).toHaveLength(2)+ expect(add.mock.calls.filter(isSensorEvent)).toHaveLength(2)+ })++ it("does not reattach sensors after a late permission result following unmount or collapse", async () => {+ mockMatchMedia({ mobile: true })+ const isSensorEvent = ([name]: readonly unknown[]) =>+ name === "deviceorientation" || name === "devicemotion"+ let grantUnmount!: (value: "granted") => void+ const unmountPermission = new Promise<"granted">((resolve) => {+ grantUnmount = resolve+ })+ ;(window as Window & { DeviceOrientationEvent?: unknown }).DeviceOrientationEvent = {+ requestPermission: vi.fn(() => unmountPermission),+ }+ const add = vi.spyOn(window, "addEventListener")+ const unmountedView = render(createElement(SignInMobileTypewriter, { collapsed: false }))+ fireEvent.pointerDown(screen.getByTestId("sign-in-mobile-typewriter"), { pointerId: 1 })+ unmountedView.unmount()+ add.mockClear()+ await act(async () => {+ grantUnmount("granted")+ await unmountPermission+ await Promise.resolve()+ })+ expect(add.mock.calls.filter(isSensorEvent)).toHaveLength(0)++ let grantCollapse!: (value: "granted") => void+ const collapsePermission = new Promise<"granted">((resolve) => {+ grantCollapse = resolve+ })+ ;(window as Window & { DeviceOrientationEvent?: unknown }).DeviceOrientationEvent = {+ requestPermission: vi.fn(() => collapsePermission),+ }+ const collapsedView = render(createElement(SignInMobileTypewriter, { collapsed: false }))+ fireEvent.pointerDown(screen.getByTestId("sign-in-mobile-typewriter"), { pointerId: 2 })+ collapsedView.rerender(createElement(SignInMobileTypewriter, { collapsed: true }))+ add.mockClear()+ await act(async () => {+ grantCollapse("granted")+ await collapsePermission+ await Promise.resolve()+ })+ expect(add.mock.calls.filter(isSensorEvent)).toHaveLength(0)+ collapsedView.unmount()+ })+})diff --git a/src/web/src/app/(auth)/sign-in/sign-in-mobile-typewriter.module.css b/src/web/src/app/(auth)/sign-in/sign-in-mobile-typewriter.module.cssnew file mode 100644index 000000000..e76eb01ba--- /dev/null+++ b/src/web/src/app/(auth)/sign-in/sign-in-mobile-typewriter.module.css@@ -0,0 +1,91 @@+.stage {+ --tw-blob-theme: var(--muted);+ --tw-scale: 0.46;+ --tw-rx: 11deg;+ --tw-ry: -19deg;+ --tw-tx: 0px;+ --tw-ty: 0px;+}++.typewriter:global(.typewriter-visual) {+ pointer-events: none;+ flex-shrink: 0;+ zoom: 1;+ width: 420px;+ height: 260px;+ justify-content: center;+ transform: translate3d(var(--tw-tx), var(--tw-ty), 0);+ transition: transform 90ms ease-out;+ will-change: transform;+}++.typewriter :global(.tw-paper-track) {+ overflow: visible;+ bottom: calc(100% - 24px);+ transform: translateX(-50%) translateZ(78px);+}++.typewriter :global(.tw-paper) {+ pointer-events: none;+}++.typewriter :global(.tw-paper.tw-paper-city) {+ padding: 8px 8px 22px;+}++.typewriter :global(.tw-body-left),+.typewriter :global(.tw-body-right),+.typewriter :global(.tw-body-top),+.typewriter :global(.tw-body-back),+.typewriter :global(.tw-body-bottom) {+ display: none;+}++.typewriter :global(.tw-body-front) {+ box-shadow:+ 4px 2px 0 var(--tw-body-lo),+ 8px 4px 0 var(--tw-body-lo),+ 12px 6px 0 var(--tw-body-lo),+ 16px 8px 0 var(--tw-body-lo),+ 20px 10px 0 var(--tw-body-lo),+ 18px 22px 32px color-mix(in oklch, var(--foreground) 18%, transparent);+}++.typewriter :global(.typewriter-blob) {+ top: 50%;+ bottom: auto;+ left: 50%;+ width: 560px;+ height: 460px;+ opacity: 0.72;+ transform: translate3d(+ calc(-50% + var(--tw-tx) * -0.55),+ calc(-50% + 16px * var(--tw-scale) + var(--tw-ty) * -0.55),+ 0+ )+ scale(calc(var(--tw-scale) * var(--blob-scale, 0.95)));+ transition: transform 120ms ease-out;+}++.typewriter :global(.typewriter-scene) {+ perspective: 1400px;+ transform: none !important;+}++.typewriter :global(.tw-machine) {+ transform-origin: 50% 15px;+ transform: translate3d(0, 115px, 0)+ scale3d(var(--tw-scale), var(--tw-scale), var(--tw-scale))+ rotateY(var(--tw-ry))+ rotateX(var(--tw-rx));+ transition: transform 90ms ease-out;+ will-change: transform;+}++@media (prefers-reduced-motion: reduce) {+ .typewriter:global(.typewriter-visual),+ .typewriter :global(.typewriter-blob),+ .typewriter :global(.tw-machine) {+ transition: none;+ }+}diff --git a/src/web/src/app/(auth)/sign-in/sign-in-mobile-typewriter.tsx b/src/web/src/app/(auth)/sign-in/sign-in-mobile-typewriter.tsxnew file mode 100644index 000000000..68aed7ad9--- /dev/null+++ b/src/web/src/app/(auth)/sign-in/sign-in-mobile-typewriter.tsx@@ -0,0 +1,277 @@+"use client"++import { useCallback, useEffect, useRef, type PointerEvent } from "react"+import { TypewriterVisual } from "@/components/typewriter-visual"+import { useIsMobile } from "@/hooks/use-mobile"+import { cn } from "@/lib/utils"+import styles from "./sign-in-mobile-typewriter.module.css"++type PermissionCapableEvent = {+ requestPermission?: () => Promise<"granted" | "denied" | "default">+}++const REST_RX = 11+const REST_RY = -19++function clamp(value: number, min: number, max: number): number {+ return Math.min(max, Math.max(min, value))+}++export function SignInMobileTypewriter({ collapsed }: { collapsed: boolean }) {+ const isMobile = useIsMobile()+ const stageRef = useRef<HTMLDivElement>(null)+ const sensorsActiveRef = useRef(false)+ const sensorsAttachedRef = useRef(false)+ const receivedSensorEventRef = useRef(false)+ const permissionAttemptedRef = useRef(false)+ const detachSensorsRef = useRef<(() => void) | null>(null)+ const poseRef = useRef({+ tiltRx: REST_RX,+ tiltRy: REST_RY,+ tiltTx: 0,+ tiltTy: 0,+ shakeX: 0,+ shakeY: 0,+ velX: 0,+ velY: 0,+ })+ const rafRef = useRef<number | null>(null)+ const dragPointerRef = useRef<number | null>(null)++ const commitPose = useCallback(() => {+ const el = stageRef.current+ if (!el) return+ const p = poseRef.current+ const rx = clamp(p.tiltRx + p.shakeY * 0.45, -2, 25)+ const ry = clamp(p.tiltRy + p.shakeX * 0.65, -36, -2)+ const tx = clamp(p.tiltTx + p.shakeX, -22, 22)+ const ty = clamp(p.tiltTy + p.shakeY, -16, 16)+ el.style.setProperty("--tw-rx", `${rx.toFixed(2)}deg`)+ el.style.setProperty("--tw-ry", `${ry.toFixed(2)}deg`)+ el.style.setProperty("--tw-tx", `${tx.toFixed(2)}px`)+ el.style.setProperty("--tw-ty", `${ty.toFixed(2)}px`)+ }, [])++ const stepSpring = useCallback(function tick() {+ const p = poseRef.current+ p.velX = (p.velX - p.shakeX * 0.22) * 0.82+ p.velY = (p.velY - p.shakeY * 0.22) * 0.82+ p.shakeX += p.velX+ p.shakeY += p.velY+ commitPose()+ if (+ Math.abs(p.shakeX) > 0.08+ || Math.abs(p.shakeY) > 0.08+ || Math.abs(p.velX) > 0.08+ || Math.abs(p.velY) > 0.08+ ) {+ rafRef.current = window.requestAnimationFrame(tick)+ } else {+ p.shakeX = 0+ p.shakeY = 0+ p.velX = 0+ p.velY = 0+ rafRef.current = null+ commitPose()+ }+ }, [commitPose])++ const attachSensors = useCallback(() => {+ if (!sensorsActiveRef.current || sensorsAttachedRef.current || typeof window === "undefined") return+ if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return+ sensorsAttachedRef.current = true++ let baselineBeta: number | null = null+ let baselineGamma: number | null = null+ let prevRawX: number | null = null+ let prevRawY: number | null = null++ const onOrientation = (event: DeviceOrientationEvent) => {+ if (typeof event.beta !== "number" || typeof event.gamma !== "number") return+ if (!Number.isFinite(event.beta) || !Number.isFinite(event.gamma)) return+ receivedSensorEventRef.current = true+ if (dragPointerRef.current !== null) return+ if (baselineBeta === null || baselineGamma === null) {+ baselineBeta = event.beta+ baselineGamma = event.gamma+ }+ const dGamma = clamp(event.gamma - baselineGamma, -30, 30)+ const dBeta = clamp(event.beta - baselineBeta, -25, 25)+ poseRef.current.tiltRy = REST_RY + (dGamma / 30) * 16+ poseRef.current.tiltRx = REST_RX - (dBeta / 25) * 12+ poseRef.current.tiltTx = (dGamma / 30) * 16+ poseRef.current.tiltTy = (dBeta / 25) * 11+ commitPose()+ }++ const onMotion = (event: DeviceMotionEvent) => {+ const linear = event.acceleration+ const gravity = event.accelerationIncludingGravity+ let dx = 0+ let dy = 0+ if (+ linear+ && typeof linear.x === "number"+ && typeof linear.y === "number"+ && (Math.abs(linear.x) > 0.1 || Math.abs(linear.y) > 0.1)+ ) {+ receivedSensorEventRef.current = true+ dx = linear.x+ dy = -linear.y+ } else if (gravity && typeof gravity.x === "number" && typeof gravity.y === "number") {+ receivedSensorEventRef.current = true+ if (prevRawX !== null && prevRawY !== null) {+ dx = gravity.x - prevRawX+ dy = -(gravity.y - prevRawY)+ }+ prevRawX = gravity.x+ prevRawY = gravity.y+ }+ if (Math.hypot(dx, dy) < 1.8) return+ poseRef.current.velX = clamp(poseRef.current.velX + dx * 0.9, -15, 15)+ poseRef.current.velY = clamp(poseRef.current.velY + dy * 0.7, -11, 11)+ if (rafRef.current === null) {+ rafRef.current = window.requestAnimationFrame(stepSpring)+ }+ }++ window.addEventListener("deviceorientation", onOrientation)+ window.addEventListener("devicemotion", onMotion)+ detachSensorsRef.current = () => {+ window.removeEventListener("deviceorientation", onOrientation)+ window.removeEventListener("devicemotion", onMotion)+ sensorsAttachedRef.current = false+ }+ }, [commitPose, stepSpring])++ useEffect(() => {+ if (!isMobile || collapsed) {+ sensorsActiveRef.current = false+ return+ }+ sensorsActiveRef.current = true+ attachSensors()+ return () => {+ sensorsActiveRef.current = false+ detachSensorsRef.current?.()+ detachSensorsRef.current = null+ if (rafRef.current !== null) {+ window.cancelAnimationFrame(rafRef.current)+ rafRef.current = null+ }+ }+ }, [attachSensors, collapsed, isMobile])++ useEffect(() => {+ if (!isMobile || collapsed) return+ const el = stageRef.current+ if (!el || typeof ResizeObserver !== "function") return+ const updateScale = () => {+ const rect = el.getBoundingClientRect()+ if (rect.width <= 0 || rect.height <= 0) return+ const fitW = ((rect.width - 48) / 468) * 0.72+ const fitH = (rect.height - 12) / 512+ const scale = clamp(Math.min(fitW, fitH), 0.24, 0.465)+ el.style.setProperty("--tw-scale", scale.toFixed(3))+ }+ updateScale()+ const observer = new ResizeObserver(updateScale)+ observer.observe(el)+ return () => observer.disconnect()+ }, [collapsed, isMobile])++ const unlockSensorsOnGesture = () => {+ if (!sensorsActiveRef.current || typeof window === "undefined") return+ if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return+ if (receivedSensorEventRef.current || permissionAttemptedRef.current) return+ const orientationCtor = (+ window as Window & { DeviceOrientationEvent?: PermissionCapableEvent }+ ).DeviceOrientationEvent+ const motionCtor = (+ window as Window & { DeviceMotionEvent?: PermissionCapableEvent }+ ).DeviceMotionEvent+ if (typeof orientationCtor?.requestPermission === "function") {+ permissionAttemptedRef.current = true+ void Promise.all([+ orientationCtor.requestPermission().catch(() => "denied" as const),+ typeof motionCtor?.requestPermission === "function"+ ? motionCtor.requestPermission().catch(() => "denied" as const)+ : Promise.resolve("denied" as const),+ ]).then(([oriResult, motResult]) => {+ if (!sensorsActiveRef.current) return+ if (oriResult === "granted" || motResult === "granted") {+ detachSensorsRef.current?.()+ detachSensorsRef.current = null+ attachSensors()+ }+ })+ }+ }++ const updateTouchTilt = (clientX: number, clientY: number) => {+ const el = stageRef.current+ if (!el || window.matchMedia("(prefers-reduced-motion: reduce)").matches) return+ const rect = el.getBoundingClientRect()+ if (rect.width <= 0 || rect.height <= 0) return+ const nx = clamp((clientX - (rect.left + rect.width / 2)) / (rect.width / 2), -1, 1)+ const ny = clamp((clientY - (rect.top + rect.height / 2)) / (rect.height / 2), -1, 1)+ poseRef.current.tiltRy = REST_RY + nx * 16+ poseRef.current.tiltRx = REST_RX - ny * 12+ poseRef.current.tiltTx = nx * 14+ poseRef.current.tiltTy = ny * 10+ commitPose()+ }++ const handlePointerDown = (event: PointerEvent<HTMLDivElement>) => {+ unlockSensorsOnGesture()+ dragPointerRef.current = event.pointerId+ event.currentTarget.setPointerCapture?.(event.pointerId)+ updateTouchTilt(event.clientX, event.clientY)+ }++ const handlePointerMove = (event: PointerEvent<HTMLDivElement>) => {+ if (dragPointerRef.current !== event.pointerId) return+ updateTouchTilt(event.clientX, event.clientY)+ }++ const handlePointerEnd = (event: PointerEvent<HTMLDivElement>) => {+ if (dragPointerRef.current !== event.pointerId) return+ dragPointerRef.current = null+ if (event.currentTarget.hasPointerCapture?.(event.pointerId)) {+ event.currentTarget.releasePointerCapture(event.pointerId)+ }+ poseRef.current.tiltRy = REST_RY+ poseRef.current.tiltRx = REST_RX+ poseRef.current.tiltTx = 0+ poseRef.current.tiltTy = 0+ commitPose()+ }++ return (+ <div+ ref={stageRef}+ aria-hidden="true"+ data-testid="sign-in-mobile-typewriter"+ data-collapsed={collapsed ? "true" : "false"}+ onPointerDown={handlePointerDown}+ onPointerMove={handlePointerMove}+ onPointerUp={handlePointerEnd}+ onPointerCancel={handlePointerEnd}+ className={cn(+ styles.stage,+ "relative flex w-full touch-none items-center justify-center transition-opacity duration-200 select-none sm:hidden",+ collapsed+ ? "pointer-events-none h-0 flex-none overflow-hidden opacity-0"+ : "h-48 min-h-0 shrink overflow-visible opacity-100 [@media(min-height:740px)]:h-62",+ )}+ >+ {isMobile && !collapsed ? (+ <TypewriterVisual+ animateEntrance={false}+ blobScale={0.95}+ className={styles.typewriter}+ />+ ) : null}+ </div>+ )+}diff --git a/src/web/src/app/(auth)/sign-in/sign-in-terms.dom.test.tsx b/src/web/src/app/(auth)/sign-in/sign-in-terms.dom.test.tsxindex bfdf2269c..106b6369b 100644--- a/src/web/src/app/(auth)/sign-in/sign-in-terms.dom.test.tsx+++ b/src/web/src/app/(auth)/sign-in/sign-in-terms.dom.test.tsx@@ -1,204 +1,52 @@import { createElement } from "react"import { beforeEach, describe, expect, it, vi } from "vitest"-import { act, render, screen, setupUser, waitFor } from "@/test/react-dom-harness"-import { useSignInTerms } from "./sign-in-terms"+import { render, screen, setupUser } from "@/test/react-dom-harness"-let width = 640-let reducedMotion = false-const continued = vi.fn()-const animate = vi.fn()+const externalLink = vi.hoisted(() => ({+ click: vi.fn(),+}))-function SignIn() {- const terms = useSignInTerms()- return <>{terms.control}- <button onClick={() => terms.requestConsent(() => continued("email"))}>Email</button>- <button onClick={() => terms.requestConsent(() => continued("google"))}>Google</button>- </>-}+vi.mock("@/components/community/messages/message-external-link", () => ({+ handleMessageExternalLinkClick: externalLink.click,+}))++import { SignInTermsNotice } from "./sign-in-terms"beforeEach(() => {vi.clearAllMocks()- width = 640- reducedMotion = false- animate.mockImplementation(() => ({ cancel: vi.fn() }))- window.matchMedia = vi.fn((query: string) => ({- matches: query.includes("max-width") ? width < 640 : query.includes("reduced-motion") && reducedMotion,- addEventListener: vi.fn(), removeEventListener: vi.fn(),- })) as never- HTMLElement.prototype.animate = animate})-const agreement = () => screen.getByRole("checkbox", { name: "I agree to the Terms of Service" })--describe("sign-in agreement", () => {- it("starts unchecked and keeps policy links separate from agreement", async () => {- render(createElement(SignIn))- expect(agreement()).not.toBeChecked()- for (const [name, href] of [["Terms of Service", "/terms"], ["Privacy Policy", "/privacy"]]) {- const link = screen.getByRole("link", { name })- expect(link).toHaveAttribute("href", href)- expect(link).toHaveAttribute("target", "_blank")- await setupUser().click(link)- expect(agreement()).not.toBeChecked()- }- expect(continued).not.toHaveBeenCalled()- })+describe("sign-in passive terms notice", () => {+ it("renders passive consent-on-continue copy without any checkbox or confirmation dialog", () => {+ render(createElement(SignInTermsNotice))- it.each([640, 1280])("at %spx focuses and shakes without starting login or opening a dialog", async value => {- width = value- render(createElement(SignIn))- await setupUser().click(screen.getByRole("button", { name: "Google" }))- expect(agreement()).toHaveFocus()- expect(agreement()).not.toBeChecked()- expect(screen.getByRole("alert")).toHaveTextContent("I agree to the Terms of Service")- expect(screen.getByRole("alert")).toHaveClass("text-destructive")- expect(screen.queryByText("Please agree to the Terms of Service to continue.")).toBeNull()- expect(animate).toHaveBeenCalledOnce()+ expect(screen.queryByRole("checkbox")).toBeNull()expect(screen.queryByRole("dialog")).toBeNull()- expect(continued).not.toHaveBeenCalled()+ const notice = screen.getByTestId("sign-in-terms")+ expect(notice).toHaveTextContent(+ "By continuing, you agree to our Terms of Service and Privacy Policy.",+ )})- it("keeps the desktop reminder and focus without motion when reduced motion is enabled", async () => {- reducedMotion = true- render(createElement(SignIn))- await setupUser().click(screen.getByRole("button", { name: "Email" }))- expect(agreement()).toHaveFocus()- expect(screen.getByRole("alert")).toHaveTextContent("I agree to the Terms of Service")- expect(screen.getByRole("alert")).toHaveClass("text-destructive")- expect(animate).not.toHaveBeenCalled()- expect(continued).not.toHaveBeenCalled()- })-- it("restarts one finite shake for every unchecked attempt and stops it on agreement or unmount", async () => {- const result = render(createElement(SignIn))+ it("wires Terms of Service and Privacy Policy through the external link handler", async () => {const user = setupUser()- await user.click(screen.getByRole("button", { name: "Email" }))- const first = animate.mock.results[0].value- await user.click(screen.getByRole("button", { name: "Google" }))- const second = animate.mock.results[1].value- expect(first.cancel).toHaveBeenCalledOnce()- expect(second.cancel).not.toHaveBeenCalled()- expect(animate).toHaveBeenCalledTimes(2)- for (const [frames, options] of animate.mock.calls) {- expect(frames[0]).toEqual({ transform: "translateX(0)" })- expect(frames.at(-1)).toEqual({ transform: "translateX(0)" })- expect(options).toEqual({ duration: 280, easing: "ease-in-out" })- }- expect(agreement()).toHaveFocus()- expect(continued).not.toHaveBeenCalled()- await user.click(agreement())- expect(second.cancel).toHaveBeenCalledOnce()- await user.click(agreement())- await user.click(screen.getByRole("button", { name: "Email" }))- const third = animate.mock.results[2].value- result.unmount()- expect(third.cancel).toHaveBeenCalledOnce()- expect(continued).not.toHaveBeenCalled()- })+ render(createElement(SignInTermsNotice))- it.each([375, 639])("at %spx cancels without accepting and confirms the selected method only once", async value => {- width = value- render(createElement(SignIn))- const checkbox = agreement()- const user = setupUser()- await user.click(screen.getByRole("button", { name: "Email" }))- expect(screen.getByRole("dialog")).toHaveTextContent("Agree to continue")- expect(checkbox).not.toBeChecked()- expect(checkbox).toHaveAttribute("aria-invalid", "true")- expect(document.getElementById("sign-in-terms-copy")).toHaveClass("text-destructive")- expect(continued).not.toHaveBeenCalled()- await user.click(screen.getByTestId("sign-in-terms-cancel"))- expect(agreement()).not.toBeChecked()- expect(screen.getByRole("button", { name: "Email" })).toHaveFocus()- expect(screen.getByRole("alert")).toHaveClass("text-destructive")- expect(continued).not.toHaveBeenCalled()- await user.click(screen.getByRole("button", { name: "Google" }))- expect(document.getElementById("sign-in-terms-copy")).toHaveClass("text-destructive")- const confirm = screen.getByTestId("sign-in-terms-confirm")- expect(confirm).toHaveTextContent(/^Agree$/)- await user.click(confirm)- await act(async () => confirm.click())- expect(agreement()).toBeChecked()- expect(continued).toHaveBeenCalledExactlyOnceWith("google")- expect(animate).not.toHaveBeenCalled()- })-- it("discards a pending mobile action when dismissed or unmounted", async () => {- width = 375- const result = render(createElement(SignIn))- const user = setupUser()- await user.click(screen.getByRole("button", { name: "Email" }))- await user.keyboard("{Escape}")- expect(agreement()).not.toBeChecked()- expect(screen.getByRole("button", { name: "Email" })).toHaveFocus()- expect(continued).not.toHaveBeenCalled()- await user.click(screen.getByRole("button", { name: "Google" }))- const confirm = screen.getByTestId("sign-in-terms-confirm")- result.unmount()- await act(async () => confirm.click())- expect(continued).not.toHaveBeenCalled()- })-- it.each(["replace", "uncheck", "unmount"])("handles %s while the confirmed dialog is still closing", async action => {- width = 375- const result = render(createElement(SignIn))- const user = setupUser()- const checkbox = agreement()- await user.click(screen.getByRole("button", { name: "Google" }))- const popup = screen.getByRole("dialog")- let finish!: () => void- const finished = new Promise<void>(resolve => { finish = resolve })- const getAnimations = vi.fn(() => [{ finished }])- Object.defineProperty(popup, "getAnimations", { value: getAnimations })- await user.click(screen.getByRole("button", { name: "Agree" }))- await waitFor(() => expect(getAnimations).toHaveBeenCalled())- expect(continued).not.toHaveBeenCalled()- if (action === "replace") {- await user.click(screen.getByRole("button", { name: "Email" }))- expect(continued).not.toHaveBeenCalled()- } else if (action === "uncheck") {- await user.click(checkbox)- } else result.unmount()- await act(async () => { finish(); await finished })- if (action === "replace") {- await waitFor(() => expect(continued).toHaveBeenCalledExactlyOnceWith("email"))- } else {- if (action === "uncheck") await user.click(checkbox)- expect(continued).not.toHaveBeenCalled()- }- })-- it.each([375, 639, 640, 1280])("at %spx rechecks current agreement when switching methods after unchecking", async value => {- width = value- render(createElement(SignIn))- const user = setupUser()- await user.click(agreement())- expect(screen.queryByRole("alert")).toBeNull()- expect(document.getElementById("sign-in-terms-copy")).not.toHaveClass("text-destructive")- await user.click(screen.getByRole("button", { name: "Email" }))- expect(continued).toHaveBeenCalledExactlyOnceWith("email")- await user.click(agreement())- await user.click(screen.getByRole("button", { name: "Google" }))- expect(continued).toHaveBeenCalledOnce()- const checkbox = document.getElementById("sign-in-terms-checkbox")- expect(checkbox).not.toBeChecked()- expect(checkbox).toHaveAttribute("aria-invalid", "true")- expect(document.getElementById("sign-in-terms-copy")).toHaveClass("text-destructive")- if (value < 640) {- expect(screen.getByRole("dialog")).toBeVisible()- await user.click(screen.getByTestId("sign-in-terms-cancel"))- await user.click(screen.getByRole("button", { name: "Email" }))- expect(document.getElementById("sign-in-terms-copy")).toHaveClass("text-destructive")- await user.click(screen.getByRole("button", { name: "Agree" }))- expect(continued.mock.calls).toEqual([["email"], ["email"]])- expect(agreement()).toBeChecked()- expect(screen.queryByRole("alert")).toBeNull()- expect(animate).not.toHaveBeenCalled()- } else {- expect(screen.getByRole("alert")).toBeVisible()- expect(screen.queryByRole("dialog")).toBeNull()- expect(checkbox).toHaveFocus()- expect(animate).toHaveBeenCalledOnce()+ for (const [name, path] of [+ ["Terms of Service", "/terms"],+ ["Privacy Policy", "/privacy"],+ ] as const) {+ const link = screen.getByRole("link", { name })+ expect(link).toHaveAttribute("href", path)+ expect(link).toHaveAttribute("target", "_blank")+ expect(link).toHaveAttribute("rel", "noopener noreferrer")+ link.addEventListener("click", (event) => event.preventDefault())+ await user.click(link)+ expect(externalLink.click).toHaveBeenLastCalledWith(+ expect.any(Object),+ expect.stringContaining(path),+ )}+ expect(externalLink.click).toHaveBeenCalledTimes(2)})})diff --git a/src/web/src/app/(auth)/sign-in/sign-in-terms.tsx b/src/web/src/app/(auth)/sign-in/sign-in-terms.tsxindex af03522da..642cddb4a 100644--- a/src/web/src/app/(auth)/sign-in/sign-in-terms.tsx+++ b/src/web/src/app/(auth)/sign-in/sign-in-terms.tsx@@ -1,105 +1,40 @@"use client"-import { useEffect, useRef } from "react"-import { useAtom, useCreateAtom } from "@tanstack/react-store"-import { useIsMobile } from "@/hooks/use-mobile"-import { Button } from "@/components/ui/button"-import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"import { handleMessageExternalLinkClick } from "@/components/community/messages/message-external-link"-function PolicyLinks() {- const linkClass = "underline underline-offset-3 hover:text-foreground"- return <>- I agree to the <a href="/terms" target="_blank" rel="noopener noreferrer" className={linkClass} onClick={event => { void handleMessageExternalLinkClick(event, event.currentTarget.href) }}>Terms of Service</a>.- {" "}See our <a href="/privacy" target="_blank" rel="noopener noreferrer" className={linkClass} onClick={event => { void handleMessageExternalLinkClick(event, event.currentTarget.href) }}>Privacy Policy</a>.- </>-}--export function useSignInTerms() {- const [accepted, setAccepted] = useAtom(useCreateAtom(false))- const [open, setOpen] = useAtom(useCreateAtom(false))- const [dialogClosed, setDialogClosed] = useAtom(useCreateAtom(true))- const [reminder, setReminder] = useAtom(useCreateAtom(false))- const pending = useRef<(() => void) | null>(null)- const checkbox = useRef<HTMLInputElement>(null)- const area = useRef<HTMLDivElement>(null)- const shake = useRef<Animation | null>(null)- const mobile = useIsMobile()-- useEffect(() => () => { pending.current = null; shake.current?.cancel() }, [])- useEffect(() => {- if (!accepted || open || !dialogClosed) return- const continuation = pending.current- pending.current = null- continuation?.()- }, [accepted, open, dialogClosed])-- const requestConsent = (continueSignIn: () => void) => {- if (accepted) {- if (!dialogClosed) pending.current = continueSignIn- else {- pending.current = null- continueSignIn()- }- return- }- setReminder(true)- shake.current?.cancel()- shake.current = null- if (mobile) {- pending.current = continueSignIn- setDialogClosed(false)- setOpen(true)- return- }- checkbox.current?.focus()- if (!window.matchMedia("(prefers-reduced-motion: reduce)").matches) {- shake.current = area.current?.animate?.([- { transform: "translateX(0)" },- { transform: "translateX(-6px)" },- { transform: "translateX(6px)" },- { transform: "translateX(-4px)" },- { transform: "translateX(0)" },- ], { duration: 280, easing: "ease-in-out" }) ?? null- }- }-- const changeOpen = (next: boolean) => {- setOpen(next)- if (!next) pending.current = null- }- const confirm = () => {- setAccepted(true)- setReminder(false)- setOpen(false)- }+export function SignInTermsNotice() {+ const linkClass =+ "rounded-xs underline underline-offset-3 transition-colors hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"- return {- requestConsent,- control: <>- <div ref={area} className="space-y-2" data-testid="sign-in-terms">- <div className="flex items-start gap-2 text-sm text-muted-foreground">- <label className="-mx-3.5 grid size-11 shrink-0 cursor-pointer place-items-center" htmlFor="sign-in-terms-checkbox">- <input id="sign-in-terms-checkbox" ref={checkbox} type="checkbox" className="size-4 accent-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring"- checked={accepted} onChange={event => { pending.current = null; setAccepted(event.target.checked); setReminder(false); shake.current?.cancel(); shake.current = null }}- aria-label="I agree to the Terms of Service" aria-invalid={reminder || undefined}- aria-describedby={reminder ? "sign-in-terms-copy" : undefined} />- </label>- <span id="sign-in-terms-copy" role={reminder ? "alert" : undefined} className={`py-2${reminder ? " text-destructive" : ""}`}><PolicyLinks /></span>- </div>- </div>- <Dialog open={open} onOpenChange={changeOpen} onOpenChangeComplete={next => setDialogClosed(!next)}>- <DialogContent showCloseButton={false} finalFocus={!accepted} className="w-[calc(100%-2rem)] max-w-sm">- <DialogHeader>- <DialogTitle>Agree to continue</DialogTitle>- <DialogDescription><PolicyLinks /></DialogDescription>- </DialogHeader>- <DialogFooter className="flex-row">- <Button type="button" variant="outline" className="h-11 flex-1" data-testid="sign-in-terms-cancel" onClick={() => changeOpen(false)}>Cancel</Button>- <Button type="button" className="h-11 flex-1" data-testid="sign-in-terms-confirm" onClick={confirm}>Agree</Button>- </DialogFooter>- </DialogContent>- </Dialog>- </>,- }+ return (+ <p+ className="border-t border-border/60 pt-2 text-left text-xs leading-relaxed text-muted-foreground sm:pt-4 [@media(min-height:740px)]:pt-4"+ data-testid="sign-in-terms"+ >+ By continuing, you agree to our{" "}+ <a+ href="/terms"+ target="_blank"+ rel="noopener noreferrer"+ className={linkClass}+ onClick={(event) => {+ void handleMessageExternalLinkClick(event, event.currentTarget.href)+ }}+ >+ Terms of Service+ </a>{" "}+ and{" "}+ <a+ href="/privacy"+ target="_blank"+ rel="noopener noreferrer"+ className={linkClass}+ onClick={(event) => {+ void handleMessageExternalLinkClick(event, event.currentTarget.href)+ }}+ >+ Privacy Policy+ </a>{"."}+ </p>+ )}diff --git a/src/web/src/app/(auth)/sign-in/social-sign-in.dom.test.ts b/src/web/src/app/(auth)/sign-in/social-sign-in.dom.test.tsindex 545dbb6b7..1dcc674c3 100644--- a/src/web/src/app/(auth)/sign-in/social-sign-in.dom.test.ts+++ b/src/web/src/app/(auth)/sign-in/social-sign-in.dom.test.ts@@ -1,4 +1,4 @@-import { createElement, type ComponentProps } from "react"+import { createElement } from "react"import { createHash } from "node:crypto"import { existsSync, readFileSync } from "node:fs"import { resolve } from "node:path"@@ -17,15 +17,20 @@ const mocks = vi.hoisted(() => ({start: vi.fn(),cancel: vi.fn(),dispose: vi.fn(),+ remember: vi.fn(),emit: undefined as undefined | ((view: NativeOauthView) => void),}))vi.mock("@/lib/product-analytics", () => ({ captureProductAnalytics: mocks.capture }))-vi.mock("@alook/shared", async importOriginal => ({- ...await importOriginal<typeof import("@alook/shared")>(),+vi.mock("@alook/shared", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@alook/shared")>()),isTauri: () => mocks.tauri,}))vi.mock("@/lib/auth-client", () => ({ signIn: { social: mocks.social } }))+vi.mock("@/lib/last-login-method", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/lib/last-login-method")>()),+ rememberLastLoginMethod: mocks.remember,+}))vi.mock("@/lib/native-oauth-client", () => ({nativeOauthBrowserDeps: {},createNativeOauthController: (@@ -42,11 +47,7 @@ vi.mock("@/lib/native-oauth-client", () => ({},}))-import { SocialSignIn as SocialSignInComponent } from "./social-sign-in"--function SocialSignIn(props: Omit<ComponentProps<typeof SocialSignInComponent>, "requestConsent">) {- return createElement(SocialSignInComponent, { ...props, requestConsent: continuation => continuation() })-}+import { SocialSignIn } from "./social-sign-in"beforeEach(() => {mocks.tauri = false@@ -67,57 +68,72 @@ const attempt = {waiting: true,}-describe("social sign-in native boundary", () => {- it.each([false, true])("holds the selected provider until the shared consent gate admits it, native=%s", async native => {- mocks.tauri = native- let continuation: (() => void) | undefined- const gate = vi.fn((next: () => void) => { continuation = next })- render(createElement(SocialSignInComponent, { postLoginUrl: "/c/me?tab=1", appleEnabled: true, requestConsent: gate }))- await setupUser().click(button("native-oauth-apple"))- expect(gate).toHaveBeenCalledOnce()- expect(mocks.social).not.toHaveBeenCalled()- expect(mocks.start).not.toHaveBeenCalled()- await act(async () => continuation!())- if (native) expect(mocks.start).toHaveBeenCalledExactlyOnceWith("apple", "/c/me?tab=1")- else expect(mocks.social).toHaveBeenCalledExactlyOnceWith({ provider: "apple", callbackURL: "/c/me?tab=1" })- })- it.each(["google", "github"])("forwards %s rejection details and does not count successful starts as failures", async provider => {- const error = { code: "PROVIDER_NOT_FOUND", message: "Provider not found", status: 404 }- mocks.social.mockResolvedValueOnce({ error })- render(createElement(SocialSignIn, { postLoginUrl: "/c/me" }))- await setupUser().click(button(`native-oauth-${provider}`))- expect(mocks.capture).toHaveBeenCalledExactlyOnceWith({ event: "sign_in_failed", method: provider, failureStage: "social_start", error })- await setupUser().click(button(`native-oauth-${provider}`))- expect(mocks.capture).toHaveBeenCalledOnce()- })+describe("social sign-in stack and native boundary", () => {+ it.each([false, true])(+ "starts the selected provider immediately and records last-used method, native=%s",+ async (native) => {+ mocks.tauri = native+ const onSelectMethod = vi.fn()+ render(+ createElement(SocialSignIn, {+ postLoginUrl: "/c/me?tab=1",+ appleEnabled: true,+ onSelectMethod,+ }),+ )+ await setupUser().click(button("native-oauth-apple"))+ expect(mocks.remember).toHaveBeenCalledExactlyOnceWith("apple")+ expect(onSelectMethod).toHaveBeenCalledExactlyOnceWith("apple")+ if (native) expect(mocks.start).toHaveBeenCalledExactlyOnceWith("apple", "/c/me?tab=1")+ else {+ expect(mocks.social).toHaveBeenCalledExactlyOnceWith({+ provider: "apple",+ callbackURL: "/c/me?tab=1",+ })+ }+ },+ )++ it.each(["google", "github"])(+ "forwards %s rejection details and does not count successful starts as failures",+ async (provider) => {+ const error = { code: "PROVIDER_NOT_FOUND", message: "Provider not found", status: 404 }+ mocks.social.mockResolvedValueOnce({ error })+ render(createElement(SocialSignIn, { postLoginUrl: "/c/me" }))+ await setupUser().click(button(`native-oauth-${provider}`))+ expect(mocks.capture).toHaveBeenCalledExactlyOnceWith({+ event: "sign_in_failed",+ method: provider,+ failureStage: "social_start",+ error,+ })+ await setupUser().click(button(`native-oauth-${provider}`))+ expect(mocks.capture).toHaveBeenCalledOnce()+ },+ )it("forwards a social fetch rejection instead of discarding the error", async () => {const error = new TypeError("Failed to fetch")mocks.social.mockRejectedValueOnce(error)render(createElement(SocialSignIn, { postLoginUrl: "/c/me" }))await setupUser().click(button("native-oauth-google"))- expect(mocks.capture).toHaveBeenCalledExactlyOnceWith({ event: "sign_in_failed", method: "google", failureStage: "social_start", error })- })-- it("preserves normal browser social login and callback destination", async () => {- const user = setupUser()- render(createElement(SocialSignIn, { postLoginUrl: "/c/me?tab=1" }))-- await user.click(button("native-oauth-google"))-- expect(mocks.social).toHaveBeenCalledWith({- provider: "google",- callbackURL: "/c/me?tab=1",+ expect(mocks.capture).toHaveBeenCalledExactlyOnceWith({+ event: "sign_in_failed",+ method: "google",+ failureStage: "social_start",+ error,})- expect(mocks.start).not.toHaveBeenCalled()})- it("keeps every provider's icon and title together at the visual center", async () => {+ it("renders a full-width vertical stack with aligned icons, 44px touch targets, and Last used indicator", async () => {const user = setupUser()- render(createElement(SocialSignIn, {- postLoginUrl: "/c/me?tab=1",- appleEnabled: true,- }))+ render(+ createElement(SocialSignIn, {+ postLoginUrl: "/c/me?tab=1",+ appleEnabled: true,+ lastUsedMethod: "google",+ }),+ )const socialButtons = screen.getAllByRole("button")expect(socialButtons.map((item) => item.dataset.testid)).toEqual([@@ -128,33 +144,42 @@ describe("social sign-in native boundary", () => {const github = button("native-oauth-github")const google = button("native-oauth-google")const apple = button("native-oauth-apple")+ expect(github).toHaveAccessibleName("Continue with GitHub")+ expect(google).toHaveAccessibleName("Continue with Google")+ expect(apple).toHaveAccessibleName("Continue with Apple")+for (const provider of [github, google, apple]) {expect(provider).toHaveClass(- "h-9",+ "h-11",+ "w-full",+ "justify-start","border-0","bg-apple-signin",- "text-base","text-apple-signin-foreground","hover:bg-apple-signin",)}for (const provider of ["github", "google", "apple"]) {- expect(screen.getByTestId(`native-oauth-${provider}-content`))- .toHaveClass("inline-flex", "items-center", "gap-2")+ expect(screen.getByTestId(`native-oauth-${provider}-content`)).toHaveClass(+ "flex",+ "min-w-0",+ "items-center",+ "gap-2",+ )}- expect(apple).toHaveClass("col-span-2")- expect(apple).toHaveClass("min-w-35")- expect(apple).toHaveAccessibleName("Continue with Apple")- expect(apple.tabIndex).toBe(0)++ expect(screen.getByTestId("last-used-google")).toHaveTextContent("Last used")+ expect(google).toHaveAttribute("aria-describedby", "last-used-google-badge")+ expect(screen.queryByTestId("last-used-github")).toBeNull()+ expect(screen.queryByTestId("last-used-apple")).toBeNull()+apple.focus()expect(apple).toHaveFocus()-await user.click(apple)expect(mocks.social).toHaveBeenCalledWith({provider: "apple",callbackURL: "/c/me?tab=1",})- expect(mocks.start).not.toHaveBeenCalled()})it("keeps every provider on Apple's mandated black-on-light and white-on-dark tokens", () => {@@ -169,19 +194,21 @@ describe("social sign-in native boundary", () => {})it("embeds Apple's official left-aligned logo-with-text artwork", () => {- render(createElement(SocialSignIn, {- postLoginUrl: "/c/me",- appleEnabled: true,- }))-- const source = readFileSync(resolve(- webRoot,- "src/app/(auth)/sign-in/social-sign-in.tsx",- ), "utf8")- const artwork = readFileSync(resolve(- webRoot,- "src/app/(auth)/sign-in/apple-sign-in-artwork.ts",- ), "utf8")+ render(+ createElement(SocialSignIn, {+ postLoginUrl: "/c/me",+ appleEnabled: true,+ }),+ )++ const source = readFileSync(+ resolve(webRoot, "src/app/(auth)/sign-in/social-sign-in.tsx"),+ "utf8",+ )+ const artwork = readFileSync(+ resolve(webRoot, "src/app/(auth)/sign-in/apple-sign-in-artwork.ts"),+ "utf8",+ )expect(source).not.toContain("SiApple")expect(source).not.toContain("appleid.cdn-apple.com/appleid/button/logo")expect(artwork).not.toContain("appleid.cdn-apple.com/appleid/button/logo")@@ -203,17 +230,28 @@ describe("social sign-in native boundary", () => {expect(black).toHaveAttribute("width", "31")expect(black).toHaveAttribute("height", "44")expect(black).toHaveClass("col-start-1", "row-start-1", "h-9", "w-auto", "dark:block")- expect([white, black].map((image) => createHash("sha256")- .update(Buffer.from(image.getAttribute("src")!.split(",")[1], "base64"))- .digest("hex"))).toEqual([+ expect(+ [white, black].map((image) =>+ createHash("sha256")+ .update(Buffer.from(image.getAttribute("src")!.split(",")[1], "base64"))+ .digest("hex"),+ ),+ ).toEqual(["f43d1ed5be59bcffdf4c20b5e29f8de041858678f549515377d0ba4f5ebd115e","0f56330a7a4fe2db06ec79fdbfed1eec1d434557f052add6d848daa31877f380",])})- it("does not expose Apple when server configuration is absent", () => {- render(createElement(SocialSignIn, { postLoginUrl: "/c/me" }))+ it("does not expose Apple or an Apple Last used badge when server configuration is absent", () => {+ render(+ createElement(SocialSignIn, {+ postLoginUrl: "/c/me",+ appleEnabled: false,+ lastUsedMethod: "apple",+ }),+ )expect(screen.queryByTestId("native-oauth-apple")).not.toBeInTheDocument()+ expect(screen.queryByTestId("last-used-apple")).not.toBeInTheDocument()})it("never falls back to embedded social OAuth in Tauri, including unsupported apps", async () => {@@ -233,16 +271,20 @@ describe("social sign-in native boundary", () => {it("disables only Apple when an older app rejects that provider", () => {mocks.tauri = true- render(createElement(SocialSignIn, {- postLoginUrl: "/c/me",- appleEnabled: true,- }))+ render(+ createElement(SocialSignIn, {+ postLoginUrl: "/c/me",+ appleEnabled: true,+ }),+ )- act(() => mocks.emit!({- phase: "error",- message: "apple_update_required",- attempt: null,- }))+ act(() =>+ mocks.emit!({+ phase: "error",+ message: "apple_update_required",+ attempt: null,+ }),+ )expect(button("native-oauth-apple")).toBeDisabled()expect(button("native-oauth-github")).toBeEnabled()@@ -306,11 +348,7 @@ describe("social sign-in native boundary", () => {expect(status).toHaveAttribute("role", role)expect(status).toHaveTextContent(copy)expect(status).toHaveClass("text-center")- expect(status.nextElementSibling).toHaveClass(- "flex",- "justify-center",- "gap-2",- )+ expect(status.nextElementSibling).toHaveClass("flex", "justify-center", "gap-2")const cancel = button("native-oauth-cancel")const retry = button("native-oauth-retry")diff --git a/src/web/src/app/(auth)/sign-in/social-sign-in.tsx b/src/web/src/app/(auth)/sign-in/social-sign-in.tsxindex 2a24f8fdd..de92b9659 100644--- a/src/web/src/app/(auth)/sign-in/social-sign-in.tsx+++ b/src/web/src/app/(auth)/sign-in/social-sign-in.tsx@@ -1,10 +1,8 @@"use client"import { captureProductAnalytics } from "@/lib/product-analytics"-import { startAction, finishAction, type Action } from "@/lib/observability/context"-import { useAtom, useCreateAtom } from "@tanstack/react-store";-+import { useAtom, useCreateAtom } from "@tanstack/react-store"import { useEffect, useRef } from "react"import { safeRedirectPath } from "@/lib/safe-redirect"import { isTauri, type NativeOauthProvider } from "@alook/shared"@@ -13,7 +11,13 @@ import Image from "next/image"import { Button } from "@/components/ui/button"import { Field } from "@/components/ui/field"import { signIn } from "@/lib/auth-client"-import { createNativeOauthController, nativeOauthBrowserDeps, type NativeOauthView } from "@/lib/native-oauth-client"+import { rememberLastLoginMethod, type LoginMethod } from "@/lib/last-login-method"+import {+ createNativeOauthController,+ nativeOauthBrowserDeps,+ type NativeOauthView,+} from "@/lib/native-oauth-client"+import { cn } from "@/lib/utils"import {APPLE_LEFT_ALIGNED_LOGO_BLACK,APPLE_LEFT_ALIGNED_LOGO_WHITE,@@ -32,91 +36,114 @@ const messages = {export function SocialSignIn({postLoginUrl,appleEnabled = false,- requestConsent,+ lastUsedMethod = null,+ onSelectMethod,}: {postLoginUrl: stringappleEnabled?: boolean- requestConsent: (continuation: () => void) => void+ lastUsedMethod?: LoginMethod | null+ onSelectMethod?: (method: NativeOauthProvider) => void}) {const observed = useRef<Action | undefined>(undefined)const controller = useRef<ReturnType<typeof createNativeOauthController> | null>(null)const [native, setNative] = useAtom(useCreateAtom<NativeOauthView | null>(null))const lastProvider = useRef<NativeOauthProvider>("github")+useEffect(() => {if (!isTauri()) return- const instance = createNativeOauthController(nativeOauthBrowserDeps, view => {+ const instance = createNativeOauthController(nativeOauthBrowserDeps, (view) => {setNative(view)- if (["waiting", "error", "unsupported", "idle"].includes(view.phase)) finishAction(observed.current, view.phase === "error" ? "error" : view.phase === "idle" ? "cancelled" : "observed")+ if (["waiting", "error", "unsupported", "idle"].includes(view.phase)) {+ finishAction(+ observed.current,+ view.phase === "error" ? "error" : view.phase === "idle" ? "cancelled" : "observed",+ )+ }})controller.current = instancevoid instance.connect()- return () => { instance.dispose(); if (controller.current === instance) controller.current = null }+ return () => {+ instance.dispose()+ if (controller.current === instance) controller.current = null+ }}, [setNative])- const begin = (provider: NativeOauthProvider) => requestConsent(() => start(provider))+const start = (provider: NativeOauthProvider) => {+ rememberLastLoginMethod(provider)+ onSelectMethod?.(provider)finishAction(observed.current, "superseded")observed.current = startAction("auth_social", { capability: "limited", phase: "auth" })lastProvider.current = providerconst action = observed.currentif (!isTauri()) {- const failed = (error: unknown) => { void captureProductAnalytics({ event: "sign_in_failed", method: provider, failureStage: "social_start", error }) }- void signIn.social({ provider, callbackURL: postLoginUrl }).then(result => {- finishAction(action, result.error ? "error" : "observed")- if (result.error) failed(result.error)- }, error => { finishAction(action, "error"); failed(error) })+ const failed = (error: unknown) => {+ void captureProductAnalytics({+ event: "sign_in_failed",+ method: provider,+ failureStage: "social_start",+ error,+ })+ }+ void signIn.social({ provider, callbackURL: postLoginUrl }).then(+ (result) => {+ finishAction(action, result.error ? "error" : "observed")+ if (result.error) failed(result.error)+ },+ (error) => {+ finishAction(action, "error")+ failed(error)+ },+ )return}if (controller.current) void controller.current.start(provider, safeRedirectPath(postLoginUrl))}- const busy = native?.phase === "initializing" || native?.phase === "preparing" || native?.phase === "exchanging" || native?.phase === "checking_status"++ const busy =+ native?.phase === "initializing"+ || native?.phase === "preparing"+ || native?.phase === "exchanging"+ || native?.phase === "checking_status"const unsupported = native?.phase === "unsupported"const appleUpdateRequired = native?.message === "apple_update_required"- const text = unsupported ? "Update Alook to use social sign-in. You can still use email."- : native?.message ? messages[native.message]- : native?.phase === "preparing" ? "Opening sign-in in your browser…"- : native?.phase === "exchanging" || native?.phase === "checking_status" ? "Confirming sign-in…"- : native?.phase === "waiting" ? "Finish signing in in your browser."+ const text = unsupported+ ? "Update Alook to use social sign-in. You can still use email."+ : native?.message+ ? messages[native.message]+ : native?.phase === "preparing"+ ? "Opening sign-in in your browser…"+ : native?.phase === "exchanging" || native?.phase === "checking_status"+ ? "Confirming sign-in…"+ : native?.phase === "waiting"+ ? "Finish signing in in your browser.": undefined- return (- <>- <Field className="grid grid-cols-2 gap-4">- <Button- size="lg"- type="button"- disabled={busy || unsupported}- className="border-0 bg-apple-signin text-base text-apple-signin-foreground hover:bg-apple-signin"- data-testid="native-oauth-github"- onClick={() => begin("github")}- >- <span className="inline-flex items-center gap-2" data-testid="native-oauth-github-content">- <SiGithub className="size-4" aria-hidden />- <span>GitHub</span>- </span>- </Button>- <Button- size="lg"- type="button"- disabled={busy || unsupported}- className="border-0 bg-apple-signin text-base text-apple-signin-foreground hover:bg-apple-signin"- data-testid="native-oauth-google"- onClick={() => begin("google")}- >- <span className="inline-flex items-center gap-2" data-testid="native-oauth-google-content">- <SiGoogle className="size-4" aria-hidden />- <span>Google</span>- </span>- </Button>- {appleEnabled ? (- <Button- type="button"- size="lg"- disabled={busy || unsupported || appleUpdateRequired}- className="col-span-2 min-w-35 border-0 bg-apple-signin text-base text-apple-signin-foreground hover:bg-apple-signin"- data-testid="native-oauth-apple"- onClick={() => begin("apple")}- >- <span className="inline-flex items-center gap-2" data-testid="native-oauth-apple-content">- <span className="grid h-9 place-items-center" aria-hidden>++ const providers: {+ id: NativeOauthProvider+ label: string+ disabled: boolean+ icon: React.ReactNode+ }[] = [+ {+ id: "github",+ label: "Continue with GitHub",+ disabled: busy || unsupported,+ icon: <SiGithub className="size-4" aria-hidden />,+ },+ {+ id: "google",+ label: "Continue with Google",+ disabled: busy || unsupported,+ icon: <SiGoogle className="size-4" aria-hidden />,+ },+ ...(appleEnabled+ ? [+ {+ id: "apple" as const,+ label: "Continue with Apple",+ disabled: busy || unsupported || appleUpdateRequired,+ icon: (+ <><Imagesrc={APPLE_LEFT_ALIGNED_LOGO_WHITE}alt=""@@ -135,19 +162,95 @@ export function SocialSignIn({className="col-start-1 row-start-1 hidden h-9 w-auto dark:block"data-testid="apple-official-left-aligned-logo-black"/>- </span>- <span>Continue with Apple</span>- </span>- </Button>- ) : null}+ </>+ ),+ },+ ]+ : []),+ ]++ return (+ <>+ <Field className="flex flex-col gap-2">+ {providers.map((provider) => {+ const isLastUsed = lastUsedMethod === provider.id+ const badgeId = `last-used-${provider.id}-badge`+ return (+ <div key={provider.id} className="relative">+ <Button+ size="lg"+ type="button"+ disabled={provider.disabled}+ aria-describedby={isLastUsed ? badgeId : undefined}+ className={cn(+ "peer h-11 w-full justify-start border-0 bg-apple-signin px-4 text-sm font-medium text-apple-signin-foreground hover:bg-apple-signin hover:opacity-90",+ isLastUsed && "pr-22",+ )}+ data-testid={`native-oauth-${provider.id}`}+ onClick={() => start(provider.id)}+ >+ <span+ className="flex min-w-0 items-center gap-2"+ data-testid={`native-oauth-${provider.id}-content`}+ >+ <span className="grid h-9 w-6 shrink-0 place-items-center" aria-hidden>+ {provider.icon}+ </span>+ <span className="truncate">{provider.label}</span>+ </span>+ </Button>+ {isLastUsed ? (+ <span+ id={badgeId}+ data-testid={`last-used-${provider.id}`}+ className="pointer-events-none absolute top-1/2 right-3 -translate-y-1/2 rounded-full border border-apple-signin-foreground/25 bg-apple-signin-foreground/14 px-2 py-0.5 text-[11px] leading-none font-medium text-apple-signin-foreground peer-disabled:opacity-50"+ >+ Last used+ </span>+ ) : null}+ </div>+ )+ })}</Field>- {text && <p role={native?.phase === "error" || unsupported ? "alert" : "status"} className="text-center text-sm text-muted-foreground" data-testid="native-oauth-status">{text}</p>}- {!unsupported && !appleUpdateRequired && native && (native.attempt || native.phase === "error" || native.phase === "preparing") && (- <div className="flex justify-center gap-2">- {(native.attempt || native.phase === "preparing") && <Button type="button" variant="link" className="h-11 px-3 sm:h-8" data-testid="native-oauth-cancel" onClick={() => { void controller.current?.cancel() }}>Cancel</Button>}- <Button type="button" variant="link" className="h-11 px-3 sm:h-8" disabled={busy} data-testid="native-oauth-retry" onClick={() => begin(native.attempt?.provider ?? lastProvider.current)}>Try again</Button>- </div>+ {text && (+ <p+ role={native?.phase === "error" || unsupported ? "alert" : "status"}+ className="text-center text-sm text-muted-foreground"+ data-testid="native-oauth-status"+ >+ {text}+ </p>)}+ {!unsupported+ && !appleUpdateRequired+ && native+ && (native.attempt || native.phase === "error" || native.phase === "preparing") && (+ <div className="flex justify-center gap-2">+ {(native.attempt || native.phase === "preparing") && (+ <Button+ type="button"+ variant="link"+ className="h-11 px-3 sm:h-8"+ data-testid="native-oauth-cancel"+ onClick={() => {+ void controller.current?.cancel()+ }}+ >+ Cancel+ </Button>+ )}+ <Button+ type="button"+ variant="link"+ className="h-11 px-3 sm:h-8"+ disabled={busy}+ data-testid="native-oauth-retry"+ onClick={() => start(native.attempt?.provider ?? lastProvider.current)}+ >+ Try again+ </Button>+ </div>+ )}</>)}diff --git a/src/web/src/app/api/auth/native/native-routes.test.ts b/src/web/src/app/api/auth/native/native-routes.test.tsindex e6004ef89..15be8e79f 100644--- a/src/web/src/app/api/auth/native/native-routes.test.ts+++ b/src/web/src/app/api/auth/native/native-routes.test.ts@@ -535,6 +535,9 @@ describe("native OAuth routes", () => {expect(response.headers.getSetCookie().join(";")).toContain("is_sign_in=github",);+ expect(response.headers.getSetCookie().join(";")).toContain(+ "alook_last_login_method=github",+ );expect(queryMocks.claimExchange).toHaveBeenCalledWith(db, {attemptId: ATTEMPT,stateHash: await sha256Hex(STATE),diff --git a/src/web/src/components/community/messages/image-lightbox-layout.test.ts b/src/web/src/components/community/messages/image-lightbox-layout.test.tsindex 28d37b413..a2ebc559b 100644--- a/src/web/src/components/community/messages/image-lightbox-layout.test.ts+++ b/src/web/src/components/community/messages/image-lightbox-layout.test.ts@@ -1,11 +1,139 @@import { describe, expect, it } from "vitest"-import { validImageDimensions } from "./image-lightbox-layout"+import { isPointInsidePaintedImage, validImageDimensions } from "./image-lightbox-layout"describe("image lightbox layout", () => {it("rejects incomplete or invalid dimensions", () => {expect(validImageDimensions(640, 480)).toEqual({ width: 640, height: 480 })expect(validImageDimensions(undefined, 480)).toBeUndefined()+ expect(validImageDimensions(640, undefined)).toBeUndefined()expect(validImageDimensions(0, 480)).toBeUndefined()+ expect(validImageDimensions(640, 0)).toBeUndefined()expect(validImageDimensions(Number.NaN, 480)).toBeUndefined()+ expect(validImageDimensions(640, Number.NaN)).toBeUndefined()+ })++ it("hit-tests only the painted object-contain bitmap, excluding letterbox space and honoring zoom/pan", () => {+ const frame = { left: 20, top: 60, width: 1400, height: 800 }+ const natural = { width: 800, height: 1600 }++ expect(+ isPointInsidePaintedImage({+ point: { x: 720, y: 460 },+ frame: { ...frame, width: 0 },+ natural,+ maxDimensions: natural,+ view: { scale: 1, x: 0, y: 0 },+ }),+ ).toBe(false)++ expect(+ isPointInsidePaintedImage({+ point: { x: 720, y: 460 },+ frame: { ...frame, height: 0 },+ natural,+ maxDimensions: natural,+ view: { scale: 1, x: 0, y: 0 },+ }),+ ).toBe(false)++ expect(+ isPointInsidePaintedImage({+ point: { x: 720, y: 460 },+ frame,+ natural: undefined,+ maxDimensions: natural,+ view: { scale: 1, x: 0, y: 0 },+ }),+ ).toBe(false)++ expect(+ isPointInsidePaintedImage({+ point: { x: 720, y: 460 },+ frame,+ natural,+ maxDimensions: { width: 0, height: 800 },+ view: { scale: 1, x: 0, y: 0 },+ }),+ ).toBe(false)++ expect(+ isPointInsidePaintedImage({+ point: { x: 720, y: 460 },+ frame,+ natural,+ maxDimensions: { width: 800, height: 0 },+ view: { scale: 1, x: 0, y: 0 },+ }),+ ).toBe(false)++ expect(+ isPointInsidePaintedImage({+ point: { x: 720, y: 460 },+ frame,+ natural,+ maxDimensions: undefined,+ view: { scale: 1, x: 0, y: 0 },+ }),+ ).toBe(true)++ expect(+ isPointInsidePaintedImage({+ point: { x: 720, y: 460 },+ frame,+ natural,+ maxDimensions: natural,+ view: { scale: 1, x: 0, y: 0 },+ }),+ ).toBe(true)++ expect(+ isPointInsidePaintedImage({+ point: { x: 400, y: 460 },+ frame,+ natural,+ maxDimensions: natural,+ view: { scale: 1, x: 0, y: 0 },+ }),+ ).toBe(false)++ expect(+ isPointInsidePaintedImage({+ point: { x: 1100, y: 460 },+ frame,+ natural,+ maxDimensions: natural,+ view: { scale: 1, x: 0, y: 0 },+ }),+ ).toBe(false)++ expect(+ isPointInsidePaintedImage({+ point: { x: 720, y: 40 },+ frame,+ natural,+ maxDimensions: natural,+ view: { scale: 1, x: 0, y: 0 },+ }),+ ).toBe(false)++ expect(+ isPointInsidePaintedImage({+ point: { x: 720, y: 900 },+ frame,+ natural,+ maxDimensions: natural,+ view: { scale: 1, x: 0, y: 0 },+ }),+ ).toBe(false)++ expect(+ isPointInsidePaintedImage({+ point: { x: 400, y: 460 },+ frame,+ natural,+ maxDimensions: natural,+ view: { scale: 2, x: 0, y: 0 },+ }),+ ).toBe(true)})})diff --git a/src/web/src/components/community/messages/image-lightbox-layout.ts b/src/web/src/components/community/messages/image-lightbox-layout.tsindex 4f89508e0..eb07f6201 100644--- a/src/web/src/components/community/messages/image-lightbox-layout.ts+++ b/src/web/src/components/community/messages/image-lightbox-layout.ts@@ -1,4 +1,5 @@export type ImageDimensions = { width: number; height: number }+export type RectBounds = { left: number; top: number; width: number; height: number }export function validImageDimensions(width?: number, height?: number): ImageDimensions | undefined {if (@@ -12,3 +13,33 @@ export function validImageDimensions(width?: number, height?: number): ImageDimereturn { width, height }}++export function isPointInsidePaintedImage({+ point,+ frame,+ natural,+ maxDimensions,+ view,+}: {+ point: { x: number; y: number }+ frame: RectBounds+ natural: ImageDimensions | undefined+ maxDimensions: ImageDimensions | undefined+ view: { scale: number; x: number; y: number }+}): boolean {+ if (frame.width <= 0 || frame.height <= 0 || !natural) return false+ const boxWidth = Math.min(frame.width, maxDimensions?.width ?? frame.width)+ const boxHeight = Math.min(frame.height, maxDimensions?.height ?? frame.height)+ if (boxWidth <= 0 || boxHeight <= 0) return false+ const fitScale = Math.min(boxWidth / natural.width, boxHeight / natural.height)+ const paintedWidth = natural.width * fitScale * view.scale+ const paintedHeight = natural.height * fitScale * view.scale+ const centerX = frame.left + frame.width / 2 + view.x+ const centerY = frame.top + frame.height / 2 + view.y+ return (+ point.x >= centerX - paintedWidth / 2+ && point.x <= centerX + paintedWidth / 2+ && point.y >= centerY - paintedHeight / 2+ && point.y <= centerY + paintedHeight / 2+ )+}diff --git a/src/web/src/components/community/messages/image-lightbox.dom.test.ts b/src/web/src/components/community/messages/image-lightbox.dom.test.tsindex 323945b88..24b928683 100644--- a/src/web/src/components/community/messages/image-lightbox.dom.test.ts+++ b/src/web/src/components/community/messages/image-lightbox.dom.test.ts@@ -602,4 +602,27 @@ describe("ImageLightbox", () => {expect(original.style.transform).toBe("translate(0px, 0px) scale(1)")})+ it("closes when clicking non-image backdrop or letterbox space, but stays open when clicking the painted image, controls, or dragging", async () => {+ const { frame, original, renderer, onClose } = await readyPreview(100, 400)++ fireEvent.click(original, { clientX: 300, clientY: 250 })+ expect(onClose).not.toHaveBeenCalled()++ fireEvent.click(renderer.getByRole("toolbar", { name: "Image controls" }))+ expect(onClose).not.toHaveBeenCalled()++ pointer(frame, "pointerdown", 1, 300, 250)+ pointer(frame, "pointermove", 1, 160, 250)+ pointer(frame, "pointerup", 1, 160, 250)+ fireEvent.click(frame, { clientX: 160, clientY: 250 })+ expect(onClose).not.toHaveBeenCalled()+ fireEvent.click(renderer.getByRole("button", { name: "Fit image" }))++ fireEvent.click(original, { clientX: 160, clientY: 250 })+ expect(onClose).toHaveBeenCalledTimes(1)++ fireEvent.click(frame.parentElement!, { clientX: 120, clientY: 40 })+ expect(onClose).toHaveBeenCalledTimes(2)+ })+})diff --git a/src/web/src/components/community/messages/image-lightbox.tsx b/src/web/src/components/community/messages/image-lightbox.tsxindex 4922b1e57..592e1e765 100644--- a/src/web/src/components/community/messages/image-lightbox.tsx+++ b/src/web/src/components/community/messages/image-lightbox.tsx@@ -2,7 +2,7 @@import { useAtom, useCreateAtom } from "@tanstack/react-store";-import { useLayoutEffect, useMemo, useState } from "react"+import { useLayoutEffect, useMemo, useRef, useState, type MouseEvent, type PointerEvent } from "react"import { Dialog, DialogContent } from "@/components/ui/dialog"import { Button } from "@/components/ui/button"import { MinusIcon, PlusIcon, RotateCcwIcon, XIcon } from "lucide-react"@@ -10,6 +10,7 @@ import type { ImagePreview } from "@/lib/community/models/message"import { tid } from "@/lib/community/testids"import {type ImageDimensions,+ isPointInsidePaintedImage,validImageDimensions,} from "./image-lightbox-layout"import { useRemoteImageAttempt } from "@/components/remote-image/remote-image-attempt"@@ -24,7 +25,7 @@ function PreviewFrame({ image, onClose }: { image: ImagePreview; onClose: () =>const [thumbnailStatus,thumbnailAttempt,- ,+ thumbnailImage,thumbnailRef,onThumbnailLoad,onThumbnailError,@@ -42,6 +43,8 @@ function PreviewFrame({ image, onClose }: { image: ImagePreview; onClose: () =>const thumbnailReady = !!image.thumbnailUrl && thumbnailStatus === "ready"const originalReady = originalStatus === "ready"const { frameRef, view, reset, zoomIn, zoomOut, handlers } = useImageLightboxZoom(originalReady)+ const gestureRef = useRef<{ pointerId: number; x: number; y: number; suppressClose: boolean } | null>(null)+ const activePointersRef = useRef(new Set<number>())const imageStyle = {maxWidth: dimensions?.width,maxHeight: dimensions?.height,@@ -54,8 +57,82 @@ function PreviewFrame({ image, onClose }: { image: ImagePreview; onClose: () =>setDimensions(knownDimensions ?? naturalDimensions)}, [knownDimensions, originalImage, originalStatus, setDimensions])+ function handleRootPointerDown(event: PointerEvent<HTMLDivElement>) {+ activePointersRef.current.add(event.pointerId)+ if (event.button !== 0 || activePointersRef.current.size > 1) {+ if (gestureRef.current) gestureRef.current.suppressClose = true+ return+ }+ gestureRef.current = {+ pointerId: event.pointerId,+ x: event.clientX,+ y: event.clientY,+ suppressClose: false,+ }+ }++ function handleRootPointerMove(event: PointerEvent<HTMLDivElement>) {+ const gesture = gestureRef.current+ if (!gesture || gesture.pointerId !== event.pointerId) return+ if (Math.hypot(event.clientX - gesture.x, event.clientY - gesture.y) > 6) {+ gesture.suppressClose = true+ }+ }++ function handleRootPointerEnd(event: PointerEvent<HTMLDivElement>) {+ activePointersRef.current.delete(event.pointerId)+ }++ function handleBackdropClick(event: MouseEvent<HTMLDivElement>) {+ const gesture = gestureRef.current+ gestureRef.current = null+ if (gesture?.suppressClose) return+ const target = event.target instanceof Element ? event.target : null+ if (+ target?.closest(+ `[role="toolbar"], [data-testid="${tid.imageLightboxLoading}"], [data-testid="${tid.imageLightboxError}"]`,+ )+ ) {+ return+ }+ const activeImage = originalReady+ ? originalImage+ : thumbnailReady+ ? thumbnailImage+ : null+ const bounds = frameRef.current?.getBoundingClientRect()+ if (bounds && bounds.width > 0 && bounds.height > 0) {+ const natural =+ dimensions ?? validImageDimensions(activeImage?.naturalWidth, activeImage?.naturalHeight)+ if (+ activeImage+ && natural+ && isPointInsidePaintedImage({+ point: { x: event.clientX, y: event.clientY },+ frame: bounds,+ natural,+ maxDimensions: dimensions,+ view,+ })+ ) {+ return+ }+ onClose()+ return+ }+ if (activeImage && (target === activeImage || activeImage.contains(target))) return+ onClose()+ }+return (- <div className="relative flex size-full min-h-0 flex-col gap-2">+ <div+ className="relative flex size-full min-h-0 flex-col gap-2"+ onPointerDownCapture={handleRootPointerDown}+ onPointerMoveCapture={handleRootPointerMove}+ onPointerUpCapture={handleRootPointerEnd}+ onPointerCancelCapture={handleRootPointerEnd}+ onClick={handleBackdropClick}+ ><divrole="toolbar"aria-label="Image controls"diff --git a/src/web/src/lib/auth-client.test.ts b/src/web/src/lib/auth-client.test.tsindex 1c349892f..e70f05099 100644--- a/src/web/src/lib/auth-client.test.ts+++ b/src/web/src/lib/auth-client.test.ts@@ -18,6 +18,7 @@ vi.mock("better-auth/react", () => ({vi.mock("better-auth/client/plugins", () => ({emailOTPClient: vi.fn(() => ({})),+ lastLoginMethodClient: vi.fn((cfg: unknown) => ({ __plugin: "lastLoginMethodClient", cfg })),}))vi.mock("@/lib/community/mobile-system-notification", () => ({diff --git a/src/web/src/lib/auth-client.ts b/src/web/src/lib/auth-client.tsindex 23c34653f..1eb5e7164 100644--- a/src/web/src/lib/auth-client.ts+++ b/src/web/src/lib/auth-client.ts@@ -1,6 +1,7 @@"use client"import { createAuthClient } from "better-auth/react"-import { emailOTPClient } from "better-auth/client/plugins"+import { emailOTPClient, lastLoginMethodClient } from "better-auth/client/plugins"+import { LAST_LOGIN_METHOD_COOKIE } from "@/lib/last-login-method"import { captureTelemetryIdentityRetirement } from "@/lib/observability/client"import {resumeMobileSystemNotificationRegistration,@@ -10,7 +11,7 @@ import {export const authClient = createAuthClient({baseURL: process.env.NEXT_PUBLIC_APP_URL || "",- plugins: [emailOTPClient()],+ plugins: [emailOTPClient(), lastLoginMethodClient({ cookieName: LAST_LOGIN_METHOD_COOKIE })],})export const { signIn, signUp, useSession } = authClientdiff --git a/src/web/src/lib/auth.test.ts b/src/web/src/lib/auth.test.tsindex ed3df5630..9e12bc370 100644--- a/src/web/src/lib/auth.test.ts+++ b/src/web/src/lib/auth.test.ts@@ -31,6 +31,7 @@ vi.mock("better-auth/plugins", () => ({deviceAuthorization: vi.fn((cfg: unknown) => ({ __plugin: "deviceAuthorization", cfg })),bearer: vi.fn(() => ({ __plugin: "bearer" })),oneTimeToken: vi.fn((cfg: unknown) => ({ __plugin: "oneTimeToken", cfg })),+ lastLoginMethod: vi.fn((cfg: unknown) => ({ __plugin: "lastLoginMethod", cfg })),}))vi.mock("@/lib/apple-auth", async (importOriginal) => {@@ -1024,4 +1025,28 @@ describe("development OTP opt-in", () => {const defaultOptions = (createAuth(makeEnv({ NODE_ENV: "development" }) as never) as { __options: AuthOptions }).__optionsexpect(defaultOptions.plugins).not.toContainEqual(expect.objectContaining({ __plugin: "emailOTP" }))})++ it("registers lastLoginMethod across auth modes and resolves OAuth callback and email endpoints", async () => {+ const { LAST_LOGIN_METHOD_COOKIE, LAST_LOGIN_METHOD_MAX_AGE } = await import("@/lib/last-login-method")+ const createAuth = await loadCreateAuth()+ for (const env of [+ makeEnv({ NODE_ENV: "production" }),+ makeEnv({ NODE_ENV: "development" }),+ ]) {+ const options = (createAuth(env as never) as { __options: AuthOptions }).__options+ const plugin = (options.plugins as Array<{+ __plugin?: string+ cfg?: {+ cookieName?: string+ maxAge?: number+ customResolveMethod?: (ctx: { path: string }) => string | null+ }+ }>).find((entry) => entry.__plugin === "lastLoginMethod")+ expect(plugin?.cfg?.cookieName).toBe(LAST_LOGIN_METHOD_COOKIE)+ expect(plugin?.cfg?.maxAge).toBe(LAST_LOGIN_METHOD_MAX_AGE)+ expect(plugin?.cfg?.customResolveMethod?.({ path: "/callback/github" })).toBe("github")+ expect(plugin?.cfg?.customResolveMethod?.({ path: "/sign-in/email-otp" })).toBe("email")+ expect(plugin?.cfg?.customResolveMethod?.({ path: "/get-session" })).toBeNull()+ }+ })})diff --git a/src/web/src/lib/auth.ts b/src/web/src/lib/auth.tsindex 1a93fa6cc..d2c0daa57 100644--- a/src/web/src/lib/auth.ts+++ b/src/web/src/lib/auth.ts@@ -1,6 +1,11 @@import { annotateWorkerSpan, observeWorkerOperation } from "./observability/worker"import { betterAuth } from "better-auth"-import { emailOTP, oneTimeToken } from "better-auth/plugins"+import { emailOTP, lastLoginMethod, oneTimeToken } from "better-auth/plugins"+import {+ LAST_LOGIN_METHOD_COOKIE,+ LAST_LOGIN_METHOD_MAX_AGE,+ resolveAuthPathLoginMethod,+} from "@/lib/last-login-method"import { getCloudflareContext } from "@opennextjs/cloudflare"import { nanoid } from "nanoid"import {@@ -118,6 +123,19 @@ export function createAuth(env: Env) {const applePlugins = appleAuth.enabled? [appleOauthHardeningPlugin(appleAuth.config.clientId)]: []+ const sharedPlugins = [+ ...applePlugins,+ lastLoginMethod({+ cookieName: LAST_LOGIN_METHOD_COOKIE,+ maxAge: LAST_LOGIN_METHOD_MAX_AGE,+ customResolveMethod: (ctx) => resolveAuthPathLoginMethod(ctx.path),+ }),+ oneTimeToken({+ expiresIn: 2,+ disableClientRequest: true,+ storeToken: "hashed",+ }),+ ]return betterAuth({baseURL: env.BETTER_AUTH_URL,@@ -332,12 +350,7 @@ export function createAuth(env: Env) {},plugins: (isProd || (mode === "dev" && env.DEV_AUTH_OTP === "1"))? [- ...applePlugins,- oneTimeToken({- expiresIn: 2,- disableClientRequest: true,- storeToken: "hashed",- }),+ ...sharedPlugins,emailOTP({expiresIn: 5 * 60,allowedAttempts: 3,@@ -392,14 +405,7 @@ export function createAuth(env: Env) {},}),]- : [- ...applePlugins,- oneTimeToken({- expiresIn: 2,- disableClientRequest: true,- storeToken: "hashed",- }),- ],+ : sharedPlugins,})}diff --git a/src/web/src/lib/community/testids.test.ts b/src/web/src/lib/community/testids.test.tsindex cac3fd211..9fcaf47cd 100644--- a/src/web/src/lib/community/testids.test.ts+++ b/src/web/src/lib/community/testids.test.ts@@ -139,4 +139,8 @@ describe("community QA selectors", () => {expect(tid.botReportProblemSubmit).toBe("bot-report-problem-submit")expect(tid.botReportProblemStatus).toBe("bot-report-problem-status")})++ it("exposes the sign-in horizontal step track selector from the canonical registry", () => {+ expect(tid.signInStepTrack).toBe("sign-in-step-track")+ })})diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.tsindex 768bb9828..09b0b866f 100644--- a/src/web/src/lib/community/testids.ts+++ b/src/web/src/lib/community/testids.ts@@ -315,4 +315,5 @@ export const tid = {inboxTabScroll: (tab: "unreads" | "mentions" | "marked") =>`community-inbox-${tab}-scroll`,channelRefPill: (id: string) => `community-channel-ref-pill-${id}`,+ signInStepTrack: "sign-in-step-track",} as constdiff --git a/src/web/src/lib/last-login-method.test.ts b/src/web/src/lib/last-login-method.test.tsnew file mode 100644index 000000000..8d364c3fd--- /dev/null+++ b/src/web/src/lib/last-login-method.test.ts@@ -0,0 +1,68 @@+import { afterEach, describe, expect, it, vi } from "vitest"+import {+ formatLastLoginMethodSetCookie,+ LAST_LOGIN_METHOD_COOKIE,+ LAST_LOGIN_METHOD_MAX_AGE,+ normalizeLoginMethod,+ rememberLastLoginMethod,+ resolveAuthPathLoginMethod,+} from "./last-login-method"++describe("last-login-method helpers", () => {+ afterEach(() => {+ vi.unstubAllGlobals()+ })+ it("normalizes known providers and email aliases while rejecting unknown values", () => {+ expect(normalizeLoginMethod("github")).toBe("github")+ expect(normalizeLoginMethod("GOOGLE")).toBe("google")+ expect(normalizeLoginMethod(" apple ")).toBe("apple")+ expect(normalizeLoginMethod("email")).toBe("email")+ expect(normalizeLoginMethod("email-otp")).toBe("email")+ expect(normalizeLoginMethod("email_otp")).toBe("email")+ expect(normalizeLoginMethod("")).toBeNull()+ expect(normalizeLoginMethod("discord")).toBeNull()+ expect(normalizeLoginMethod(null)).toBeNull()+ expect(normalizeLoginMethod(undefined)).toBeNull()+ })++ it("resolves Better Auth callback and email endpoints to canonical methods", () => {+ expect(resolveAuthPathLoginMethod("/callback/github")).toBe("github")+ expect(resolveAuthPathLoginMethod("/callback/google")).toBe("google")+ expect(resolveAuthPathLoginMethod("/callback/apple")).toBe("apple")+ expect(resolveAuthPathLoginMethod("/callback/unknown")).toBeNull()+ expect(resolveAuthPathLoginMethod("/sign-in/email")).toBe("email")+ expect(resolveAuthPathLoginMethod("/sign-up/email")).toBe("email")+ expect(resolveAuthPathLoginMethod("/sign-in/email-otp")).toBe("email")+ expect(resolveAuthPathLoginMethod("/one-time-token/verify")).toBeNull()+ expect(resolveAuthPathLoginMethod(null)).toBeNull()+ })++ it("formats a non-better-auth-prefixed cookie string with Lax and optional Secure attributes", () => {+ expect(LAST_LOGIN_METHOD_COOKIE.startsWith("better-auth")).toBe(false)+ expect(formatLastLoginMethodSetCookie("github", false)).toBe(+ `${LAST_LOGIN_METHOD_COOKIE}=github; Max-Age=${LAST_LOGIN_METHOD_MAX_AGE}; Path=/; SameSite=Lax`,+ )+ expect(formatLastLoginMethodSetCookie("apple", true)).toBe(+ `${LAST_LOGIN_METHOD_COOKIE}=apple; Max-Age=${LAST_LOGIN_METHOD_MAX_AGE}; Path=/; SameSite=Lax; Secure`,+ )+ })++ it("no-ops without document and writes insecure or Secure document.cookie based on window protocol", () => {+ vi.stubGlobal("document", undefined)+ expect(() => rememberLastLoginMethod("github")).not.toThrow()++ const cookieDoc = { cookie: "" }+ vi.stubGlobal("document", cookieDoc)+ vi.stubGlobal("window", { location: { protocol: "http:" } })+ rememberLastLoginMethod("google")+ expect(cookieDoc.cookie).toBe(formatLastLoginMethodSetCookie("google", false))++ vi.stubGlobal("window", { location: { protocol: "https:" } })+ rememberLastLoginMethod("email")+ expect(cookieDoc.cookie).toBe(formatLastLoginMethodSetCookie("email", true))++ vi.stubGlobal("window", undefined)+ rememberLastLoginMethod("apple")+ expect(cookieDoc.cookie).toBe(formatLastLoginMethodSetCookie("apple", false))+ })+})diff --git a/src/web/src/lib/last-login-method.ts b/src/web/src/lib/last-login-method.tsnew file mode 100644index 000000000..d00d475d8--- /dev/null+++ b/src/web/src/lib/last-login-method.ts@@ -0,0 +1,41 @@+export const LAST_LOGIN_METHOD_COOKIE = "alook_last_login_method"+export const LAST_LOGIN_METHOD_MAX_AGE = 60 * 60 * 24 * 30++export type LoginMethod = "github" | "google" | "apple" | "email"++export function normalizeLoginMethod(value: string | null | undefined): LoginMethod | null {+ if (!value) return null+ const normalized = value.trim().toLowerCase()+ if (normalized === "github" || normalized === "google" || normalized === "apple") {+ return normalized+ }+ if (normalized === "email" || normalized === "email-otp" || normalized === "email_otp") {+ return "email"+ }+ return null+}++export function resolveAuthPathLoginMethod(path: string | null | undefined): LoginMethod | null {+ if (!path) return null+ if (path.startsWith("/callback/")) {+ return normalizeLoginMethod(path.slice("/callback/".length).split("/")[0])+ }+ if (+ path === "/sign-in/email"+ || path === "/sign-up/email"+ || path === "/sign-in/email-otp"+ ) {+ return "email"+ }+ return null+}++export function formatLastLoginMethodSetCookie(method: LoginMethod, secure: boolean): string {+ return `${LAST_LOGIN_METHOD_COOKIE}=${method}; Max-Age=${LAST_LOGIN_METHOD_MAX_AGE}; Path=/; SameSite=Lax${secure ? "; Secure" : ""}`+}++export function rememberLastLoginMethod(method: LoginMethod): void {+ if (typeof document === "undefined") return+ const secure = typeof window !== "undefined" && window.location?.protocol === "https:"+ document.cookie = formatLastLoginMethodSetCookie(method, secure)+}diff --git a/src/web/src/lib/native-oauth.ts b/src/web/src/lib/native-oauth.tsindex 5fa9d8704..91e58e14e 100644--- a/src/web/src/lib/native-oauth.ts+++ b/src/web/src/lib/native-oauth.ts@@ -7,6 +7,7 @@ import {type NativeOauthPlatform,type NativeOauthProvider,} from "@alook/shared";+import { formatLastLoginMethodSetCookie } from "@/lib/last-login-method";export {nativeOauthExchangeSchema,nativeOauthProofSchema,@@ -251,6 +252,7 @@ export function setWebViewAnalyticsCookie(const name = authKind === "signup" ? "is_new_signup" : "is_sign_in";const suffix = `Max-Age=60; Path=/; SameSite=Lax${secure ? "; Secure" : ""}`;headers.append("Set-Cookie", `${name}=${provider}; ${suffix}`);+ headers.append("Set-Cookie", formatLastLoginMethodSetCookie(provider, secure));}export function isNativeOauthAttemptId(value: string | null): value is string {diff --git a/src/web/src/test/e2e-fixture-isolation.test.ts b/src/web/src/test/e2e-fixture-isolation.test.tsindex 1612807af..1c817a3b2 100644--- a/src/web/src/test/e2e-fixture-isolation.test.ts+++ b/src/web/src/test/e2e-fixture-isolation.test.ts@@ -889,7 +889,8 @@ describe("real login helper context exit", () => {expect(result).toMatchObject({ key: "alice", userId: "unit-login-user", storageState: "unit-state.json" })expect(result.name).toBe(result.email.split("@")[0])expect(s.page.goto).toHaveBeenCalledWith("http://fixture.test/c", { waitUntil: "load" })- expect(s.page.getByRole).toHaveBeenCalledWith("checkbox", { name: "I agree to the Terms of Service" })+ expect(s.page.getByRole).toHaveBeenCalledWith("button", { name: "Sign in", exact: true })+ expect(s.page.getByRole).not.toHaveBeenCalledWith("checkbox", expect.anything())expect(s.context.request.get).toHaveBeenCalledWith("http://fixture.test/api/ws/token")expect(s.context.addCookies).toHaveBeenCalledOnce()expect(s.context.clearCookies).toHaveBeenCalledWith({ name: /^(?:is_new_signup|is_sign_in)$/ })diff --git a/src/web/src/test/e2e-ui/01-auth.spec.ts b/src/web/src/test/e2e-ui/01-auth.spec.tsindex d686aa866..c369b783e 100644--- a/src/web/src/test/e2e-ui/01-auth.spec.ts+++ b/src/web/src/test/e2e-ui/01-auth.spec.ts@@ -1,4 +1,5 @@import { test, expect } from "./_fixtures/case-fixture"+import { tid } from "./_fixtures/testids"import {test as browserTest,expect as browserExpect,@@ -139,12 +140,13 @@ browserTest.describe("production OTP error placement", () => {}))await page.goto("/sign-in")- const sendCode = page.getByRole("button", { name: "Send Code" })+ const sendCode = page.getByRole("button", { name: "Continue with email" })browserTest.skip(!(await sendCode.isVisible()), "production Email OTP UI is not active")await page.getByRole("textbox", { name: "Email" }).fill("[email protected]")- await page.getByRole("checkbox", { name: "I agree to the Terms of Service" }).check()await sendCode.click()+ const stepTrack = page.getByTestId(tid.signInStepTrack)+ await browserExpect(stepTrack).toHaveAttribute("data-step-view", "code")const otp = page.getByRole("textbox", { name: "Verification code" })await otp.fill("123456")@@ -194,9 +196,11 @@ browserTest.describe("production OTP error placement", () => {await otp.fill("111111")await browserExpect(alert).toHaveCount(1)await page.getByRole("button", { name: "Use a different email" }).click()+ await browserExpect(stepTrack).toHaveAttribute("data-step-view", "email")await browserExpect(alert).toHaveCount(0)await browserExpect(page.getByRole("textbox", { name: "Email" })).toBeVisible()- await page.getByRole("button", { name: "Send Code" }).click()+ await page.getByRole("button", { name: "Continue with email" }).click()+ await browserExpect(stepTrack).toHaveAttribute("data-step-view", "code")await otp.fill("654321")await page.waitForURL("**/c/me")@@ -226,12 +230,11 @@ browserTest.describe("production OTP error placement", () => {})await page.goto("/sign-in")- const sendCode = page.getByRole("button", { name: "Send Code" })+ const sendCode = page.getByRole("button", { name: "Continue with email" })browserTest.skip(!(await sendCode.isVisible()), "production Email OTP UI is not active")const email = page.getByRole("textbox", { name: "Email" })await email.fill("[email protected]")- await page.getByRole("checkbox", { name: "I agree to the Terms of Service" }).check()await sendCode.click()let alert = page.getByRole("alert").filter({ hasText: "Failed to send code" })@@ -259,8 +262,8 @@ browserTest.describe("production OTP error placement", () => {browserExpect(alertBox!.y).toBeGreaterThanOrEqual(inputBox!.y + inputBox!.height)browserExpect(alertBox!.y + alertBox!.height).toBeLessThanOrEqual(sendBox!.y)await browserExpect(page.getByRole("button", { name: /Wait \d+s/ })).toBeDisabled()- await browserExpect(page.getByRole("button", { name: "GitHub" })).toBeVisible()- await browserExpect(page.getByRole("button", { name: "Google" })).toBeVisible()+ await browserExpect(page.getByRole("button", { name: "Continue with GitHub" })).toBeVisible()+ await browserExpect(page.getByRole("button", { name: "Continue with Google" })).toBeVisible()})})@@ -337,9 +340,8 @@ browserTest.describe("native OAuth status actions", () => {await page.setViewportSize({ width: 390, height: 844 })await page.goto("/sign-in")- await browserExpect(page.getByRole("button", { name: "GitHub" })).toBeEnabled()- await page.getByRole("checkbox", { name: "I agree to the Terms of Service" }).check()- await page.getByRole("button", { name: "GitHub" }).click()+ await browserExpect(page.getByRole("button", { name: "Continue with GitHub" })).toBeEnabled()+ await page.getByRole("button", { name: "Continue with GitHub" }).click()await expectCenteredNativeOauthState(page, {copy: "Opening sign-in in your browser…",role: "status",diff --git a/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.tsindex 0782cf1df..0d1f9eb71 100644--- a/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts+++ b/src/web/src/test/e2e-ui/20-community-attachment-thumbnails.spec.ts@@ -706,7 +706,39 @@ test("image previews keep one frame through loading, decode, failure, retry, andconst mobileLandscapeLoaded = await previewRects(mobilePage, { width: 800, height: 450 })expectSameRect(mobileLandscapeLoaded.container, mobileLandscapeLoading.container)await attachScreenshot(testInfo, "mobile-landscape-loaded", mobilePage)- await mobilePage.keyboard.press("Escape")+ const mobileLandscapeFrame = mobilePage.getByTestId(tid.imageLightbox)+ const mobileLandscapeOriginal = mobilePage.getByTestId(tid.imageLightboxOriginal)+ const paintedLandscape = mobileLandscapeLoaded.originalPainted!+ const imageCenter = {+ x: paintedLandscape.x + paintedLandscape.width / 2,+ y: paintedLandscape.y + paintedLandscape.height / 2,+ }+ await mobilePage.mouse.click(imageCenter.x, imageCenter.y)+ await expect(mobileLandscapeFrame).toBeVisible()+ await mobilePage.getByRole("toolbar", { name: "Image controls" }).click({ position: { x: 2, y: 2 } })+ await expect(mobileLandscapeFrame).toBeVisible()+ expect(paintedLandscape.y - mobileLandscapeLoaded.original.y).toBeGreaterThan(24)+ const letterbox = {+ x: imageCenter.x,+ y: (mobileLandscapeLoaded.original.y + paintedLandscape.y) / 2,+ }+ expect(await mobileLandscapeOriginal.evaluate((element, point) => (+ document.elementFromPoint(point.x, point.y) === element+ ), letterbox)).toBe(true)+ await mobilePage.mouse.move(letterbox.x, letterbox.y)+ await mobilePage.mouse.down()+ await mobilePage.mouse.move(letterbox.x + 12, letterbox.y, { steps: 3 })+ await mobilePage.mouse.up()+ await expect(mobileLandscapeFrame).toBeVisible()+ expect((await previewImageGeometry(mobileLandscapeOriginal)).translation.x).toBeCloseTo(12, 1)+ await mobilePage.getByRole("button", { name: "Fit image", exact: true }).click()+ await expect(mobileLandscapeFrame).toHaveAttribute("data-zoom-scale", "1")+ expectSameRect(await boundingRect(mobileLandscapeOriginal), mobileLandscapeLoaded.original)+ expect(await mobileLandscapeOriginal.evaluate((element, point) => (+ document.elementFromPoint(point.x, point.y) === element+ ), letterbox)).toBe(true)+ await mobilePage.mouse.click(letterbox.x, letterbox.y)+ await expect(mobileLandscapeFrame).toHaveCount(0)await mobilePage.unroute(`**${landscape.originalPath}`)let releaseMobilePortrait!: () => voiddiff --git a/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts b/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.tsindex 687943ac7..60b50c600 100644--- a/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts+++ b/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts@@ -272,7 +272,6 @@ let caseJourneyFailure1Present = falseawait page.getByRole("textbox", { name: "Email" }).fill(`guide-reconnect-${process.pid}-${Date.now()}@example.com`,)- await page.getByRole("checkbox", { name: "I agree to the Terms of Service" }).check()await page.getByRole("button", { name: "Sign in", exact: true }).click()await page.waitForURL("**/c/me/machines", { waitUntil: "commit" })const onboarding = page.getByTestId(tid.onboardingHarnessDialog)diff --git a/src/web/src/test/e2e-ui/31-machine-guide-motion.spec.ts b/src/web/src/test/e2e-ui/31-machine-guide-motion.spec.tsindex a564511eb..8e649dd5e 100644--- a/src/web/src/test/e2e-ui/31-machine-guide-motion.spec.ts+++ b/src/web/src/test/e2e-ui/31-machine-guide-motion.spec.ts@@ -7,7 +7,6 @@ test("first-signup mobile starts onboarding once and retains it on desktop", asyawait page.getByRole("textbox", { name: "Email" }).fill(`direct-onboarding-mobile-${process.pid}-${Date.now()}@example.com`,)- await page.getByRole("checkbox", { name: "I agree to the Terms of Service" }).check()await page.getByRole("button", { name: "Sign in", exact: true }).click()await page.waitForURL("**/c/me/machines", { waitUntil: "commit" })@@ -35,7 +34,6 @@ test("first-signup desktop opens onboarding before the empty Machines guide", asawait page.getByRole("textbox", { name: "Email" }).fill(`direct-onboarding-desktop-${process.pid}-${Date.now()}@example.com`,)- await page.getByRole("checkbox", { name: "I agree to the Terms of Service" }).check()await page.getByRole("button", { name: "Sign in", exact: true }).click()await page.waitForURL("**/c/me/machines", { waitUntil: "commit" })diff --git a/src/web/src/test/e2e-ui/45-desktop-thread-split-view.spec.ts b/src/web/src/test/e2e-ui/45-desktop-thread-split-view.spec.tsindex 242eb4c8d..121d24d5b 100644--- a/src/web/src/test/e2e-ui/45-desktop-thread-split-view.spec.ts+++ b/src/web/src/test/e2e-ui/45-desktop-thread-split-view.spec.ts@@ -298,6 +298,7 @@ test.describe("desktop thread split view", () => {await expect(shell).toHaveAttribute("data-layout", "split", { timeout: 20_000 })await expect(thread.getByText("Switch reply A", { exact: false })).toBeVisible()await resizeThreadPanel(page, 520)+ await expect(list.locator('[data-message-list-content][data-read-position-ready="true"][aria-hidden="false"]')).toBeVisible()await list.evaluate((node) => { node.scrollTop = node.scrollHeight })await expect(parent.getByTestId(tid.forumThreadCard(forumPostId))).toBeVisible()const scrollTop = await list.evaluate((node) => node.scrollTop)diff --git a/src/web/src/test/e2e-ui/_setup/auth.ts b/src/web/src/test/e2e-ui/_setup/auth.tsindex ecdb2bc7e..d8bfbdc31 100644--- a/src/web/src/test/e2e-ui/_setup/auth.ts+++ b/src/web/src/test/e2e-ui/_setup/auth.ts@@ -21,7 +21,6 @@ export async function signIn(page: Page, email: string, options: { singleAttemptconst emailInput = page.getByRole("textbox", { name: "Email" })await emailInput.waitFor({ state: "visible", timeout: 15_000 })await emailInput.fill(email)- await page.getByRole("checkbox", { name: "I agree to the Terms of Service" }).check()options.onSubmission?.()await page.getByRole("button", { name: "Sign in", exact: true }).click()await page.waitForURL((current) => !current.pathname.startsWith("/sign-in"), {