Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): scope otp errors to inputs (#719)

Generbf47d03b5f34
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.ts
new file mode 100644
index 000000000..7eb5f818a
--- /dev/null
+++ b/src/web/src/app/(auth)/sign-in/sign-in-client.test.ts
@@ -0,0 +1,59 @@
+import { createElement } from "react"
+import { renderToStaticMarkup } from "react-dom/server"
+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", () => {
+ const html = renderToStaticMarkup(createElement(SignInEmailField, {
+ email: "[email protected]",
+ error: "Failed to send code",
+ onChange: vi.fn(),
+ }))
+
+ expect(html.match(/Failed to send code/g)).toHaveLength(1)
+ 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"')
+ })
+
+ it("renders an OTP error once after the six slots and links the OTP input to it", () => {
+ const html = renderToStaticMarkup(createElement(SignInOtpField, {
+ code: "",
+ error: "Invalid OTP",
+ loading: false,
+ onChange: vi.fn(),
+ }))
+
+ expect(html.match(/data-slot="input-otp-slot"/g)).toHaveLength(6)
+ expect(html.match(/Invalid OTP/g)).toHaveLength(1)
+ expect(html.lastIndexOf('data-slot="input-otp-slot"')).toBeLessThan(
+ html.indexOf('id="sign-in-otp-error"'),
+ )
+ expect(html).toContain('aria-label="Verification code"')
+ expect(html).toContain('aria-invalid="true"')
+ expect(html).toContain('aria-describedby="sign-in-otp-error"')
+ expect(html).toContain('data-slot="sign-in-otp-field"')
+ expect(html).toMatch(/class="[^"]*mx-auto[^"]*w-fit![^"]*items-center[^"]*"/)
+ expect(html).toContain("w-full text-center")
+ expect(html).toContain("text-center")
+ })
+
+ it("does not reserve or link an alert when a field has no error", () => {
+ const email = renderToStaticMarkup(createElement(SignInEmailField, {
+ email: "",
+ onChange: vi.fn(),
+ }))
+ const otp = renderToStaticMarkup(createElement(SignInOtpField, {
+ code: "",
+ loading: false,
+ onChange: vi.fn(),
+ }))
+
+ expect(email).not.toContain('role="alert"')
+ expect(email).not.toContain("aria-describedby")
+ expect(otp).not.toContain('role="alert"')
+ expect(otp).not.toContain("aria-describedby")
+ })
+})
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.tsx
index 4af85cb69..4e0602883 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
@@ -6,19 +6,12 @@ import { signIn, signUp, authClient } from "@/lib/auth-client"
import { parseRetryAfterSeconds } from "@/lib/retry-after"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
-import { Input } from "@/components/ui/input"
-import {
- InputOTP,
- InputOTPGroup,
- InputOTPSlot,
-} from "@/components/ui/input-otp"
import {
Field,
- FieldError,
FieldGroup,
- FieldLabel,
FieldSeparator,
} from "@/components/ui/field"
+import { SignInEmailField, SignInOtpField } from "./sign-in-fields"
import { SiGithub, SiGoogle } from "@icons-pack/react-simple-icons"
import { GradientBackground } from "@/components/gradient-background"
import { Logo } from "@/components/logo"
@@ -44,7 +37,8 @@ function safeRedirectUrl(redirect: string | null): string {
function SignInForm({ postLoginUrl, isProd }: { postLoginUrl: string; isProd: boolean }) {
const [email, setEmail] = useState("")
- const [error, setError] = useState("")
+ const [emailError, setEmailError] = useState("")
+ const [otpError, setOtpError] = useState("")
const [loading, setLoading] = useState(false)
const [code, setCode] = useState("")
@@ -62,6 +56,7 @@ function SignInForm({ postLoginUrl, isProd }: { postLoginUrl: string; isProd: bo
const rateLimitHandler = {
onError: (ctx: { response: Response }) => {
if (ctx.response.status === 429) {
+ setEmailError("")
const seconds = parseRetryAfterSeconds(ctx.response.headers)
if (seconds != null) setRetryAfter(seconds)
}
@@ -71,7 +66,7 @@ function SignInForm({ postLoginUrl, isProd }: { postLoginUrl: string; isProd: bo
async function handleSendCode(e: React.FormEvent) {
e.preventDefault()
if (retryAfter != null) return
- setError("")
+ setEmailError("")
setRetryAfter(null)
setLoading(true)
try {
@@ -81,21 +76,23 @@ function SignInForm({ postLoginUrl, isProd }: { postLoginUrl: string; isProd: bo
fetchOptions: rateLimitHandler,
})
if (error) {
- if (error.status !== 429) setError(error.message ?? "Failed to send code")
+ if (error.status !== 429) setEmailError(error.message ?? "Failed to send code")
} else {
+ setEmailError("")
+ setOtpError("")
setStep("code")
}
} catch {
- setError("Failed to send code")
+ setEmailError("Failed to send code")
}
setLoading(false)
}
async function handleVerifyCode(value: string) {
setCode(value)
+ setOtpError("")
if (value.length !== 6) return
- setError("")
setLoading(true)
try {
const { error } = await authClient.signIn.emailOtp({
@@ -103,14 +100,15 @@ function SignInForm({ postLoginUrl, isProd }: { postLoginUrl: string; isProd: bo
otp: value,
})
if (error) {
- setError(error.message ?? "Invalid code")
+ setOtpError(error.message ?? "Invalid code")
setCode("")
} else {
+ setOtpError("")
window.location.href = postLoginUrl
return
}
} catch {
- setError("Invalid code")
+ setOtpError("Invalid code")
setCode("")
}
setLoading(false)
@@ -118,7 +116,7 @@ function SignInForm({ postLoginUrl, isProd }: { postLoginUrl: string; isProd: bo
async function handleDevSignIn(e: React.FormEvent) {
e.preventDefault()
- setError("")
+ setEmailError("")
setLoading(true)
const { error: signInErr } = await signIn.email(
{ email, password: DEV_PASSWORD },
@@ -130,7 +128,7 @@ function SignInForm({ postLoginUrl, isProd }: { postLoginUrl: string; isProd: bo
{ onError: () => {} },
)
if (signUpErr) {
- setError(signUpErr.message ?? "Failed to sign in")
+ setEmailError(signUpErr.message ?? "Failed to sign in")
setLoading(false)
return
}
@@ -139,6 +137,9 @@ function SignInForm({ postLoginUrl, isProd }: { postLoginUrl: string; isProd: bo
}
const isCoolingDown = retryAfter != null
+ const emailFeedback = isCoolingDown
+ ? `Too many requests. Try again in ${retryAfter}s.`
+ : emailError
const sendLabel = loading
? "Sending..."
: isCoolingDown
@@ -161,29 +162,18 @@ function SignInForm({ postLoginUrl, isProd }: { postLoginUrl: string; isProd: bo
)}
</div>
- {isCoolingDown && (
- <FieldError>
- Too many requests. Try again in {retryAfter}s.
- </FieldError>
- )}
- {error && !isCoolingDown && <FieldError>{error}</FieldError>}
-
{isProd ? (
step === "email" ? (
<form onSubmit={handleSendCode}>
<FieldGroup>
- <Field>
- <FieldLabel htmlFor="email">Email</FieldLabel>
- <Input
- id="email"
- type="email"
- placeholder="[email protected]"
- value={email}
- onChange={(e) => setEmail(e.target.value)}
- required
- autoFocus
- />
- </Field>
+ <SignInEmailField
+ email={email}
+ error={emailFeedback}
+ onChange={(event) => {
+ setEmail(event.target.value)
+ setEmailError("")
+ }}
+ />
<Field>
<Button
type="submit"
@@ -200,31 +190,20 @@ function SignInForm({ postLoginUrl, isProd }: { postLoginUrl: string; isProd: bo
<p className="text-sm text-muted-foreground text-center">
We sent a code to <strong>{email}</strong>
</p>
- <div className="flex justify-center">
- <InputOTP
- maxLength={6}
- value={code}
- onChange={handleVerifyCode}
- disabled={loading}
- autoFocus
- >
- <InputOTPGroup>
- <InputOTPSlot index={0} />
- <InputOTPSlot index={1} />
- <InputOTPSlot index={2} />
- <InputOTPSlot index={3} />
- <InputOTPSlot index={4} />
- <InputOTPSlot index={5} />
- </InputOTPGroup>
- </InputOTP>
- </div>
+ <SignInOtpField
+ code={code}
+ error={otpError}
+ loading={loading}
+ onChange={handleVerifyCode}
+ />
<Button
variant="ghost"
className="w-full"
onClick={() => {
setStep("email")
setCode("")
- setError("")
+ setOtpError("")
+ setEmailError("")
}}
>
Use a different email
@@ -234,18 +213,14 @@ function SignInForm({ postLoginUrl, isProd }: { postLoginUrl: string; isProd: bo
) : (
<form onSubmit={handleDevSignIn}>
<FieldGroup>
- <Field>
- <FieldLabel htmlFor="email">Email</FieldLabel>
- <Input
- id="email"
- type="email"
- placeholder="[email protected]"
- value={email}
- onChange={(e) => setEmail(e.target.value)}
- required
- autoFocus
- />
- </Field>
+ <SignInEmailField
+ email={email}
+ error={emailError}
+ onChange={(event) => {
+ setEmail(event.target.value)
+ setEmailError("")
+ }}
+ />
<Field>
<Button type="submit" disabled={loading} className="w-full">
{loading ? "Signing in..." : "Sign in"}
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.tsx
new file mode 100644
index 000000000..1203ea4eb
--- /dev/null
+++ b/src/web/src/app/(auth)/sign-in/sign-in-fields.tsx
@@ -0,0 +1,81 @@
+import { Input } from "@/components/ui/input"
+import {
+ InputOTP,
+ InputOTPGroup,
+ InputOTPSlot,
+} from "@/components/ui/input-otp"
+import { Field, FieldError, FieldLabel } from "@/components/ui/field"
+
+export function SignInEmailField({
+ email,
+ error,
+ onChange,
+}: {
+ email: string
+ error?: string
+ onChange: React.ChangeEventHandler<HTMLInputElement>
+}) {
+ return (
+ <Field data-invalid={!!error}>
+ <FieldLabel htmlFor="email">Email</FieldLabel>
+ <Input
+ id="email"
+ type="email"
+ placeholder="[email protected]"
+ 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>
+ )
+}
+
+export function SignInOtpField({
+ code,
+ error,
+ loading,
+ onChange,
+}: {
+ code: string
+ error?: string
+ loading: boolean
+ onChange: (value: string) => void
+}) {
+ return (
+ <Field data-invalid={!!error}>
+ <div
+ data-slot="sign-in-otp-field"
+ className="mx-auto flex w-fit! flex-col items-center gap-2"
+ >
+ <InputOTP
+ maxLength={6}
+ value={code}
+ onChange={onChange}
+ disabled={loading}
+ aria-label="Verification code"
+ aria-invalid={!!error}
+ aria-describedby={error ? "sign-in-otp-error" : undefined}
+ autoFocus
+ >
+ <InputOTPGroup>
+ <InputOTPSlot index={0} />
+ <InputOTPSlot index={1} />
+ <InputOTPSlot index={2} />
+ <InputOTPSlot index={3} />
+ <InputOTPSlot index={4} />
+ <InputOTPSlot index={5} />
+ </InputOTPGroup>
+ </InputOTP>
+ {error && (
+ <FieldError id="sign-in-otp-error" className="w-full text-center">
+ {error}
+ </FieldError>
+ )}
+ </div>
+ </Field>
+ )
+}
diff --git a/src/web/src/test/e2e-ui/01-auth.spec.ts b/src/web/src/test/e2e-ui/01-auth.spec.ts
index 744896f83..f72f345d0 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,32 @@
import { test, expect } from "./_fixtures/community-fixture"
+import {
+ test as browserTest,
+ expect as browserExpect,
+ type Locator,
+} from "@playwright/test"
+
+async function expectSameHorizontalCenter(first: Locator, second: Locator) {
+ const [firstBox, secondBox] = await Promise.all([
+ first.boundingBox(),
+ second.boundingBox(),
+ ])
+ browserExpect(firstBox).not.toBeNull()
+ browserExpect(secondBox).not.toBeNull()
+ browserExpect(Math.abs(
+ firstBox!.x + firstBox!.width / 2 -
+ (secondBox!.x + secondBox!.width / 2),
+ )).toBeLessThanOrEqual(1)
+}
+
+async function expectSameWidth(first: Locator, second: Locator) {
+ const [firstBox, secondBox] = await Promise.all([
+ first.boundingBox(),
+ second.boundingBox(),
+ ])
+ browserExpect(firstBox).not.toBeNull()
+ browserExpect(secondBox).not.toBeNull()
+ browserExpect(Math.abs(firstBox!.width - secondBox!.width)).toBeLessThanOrEqual(1)
+}
// Journey 1 — login & first screen. storageState is established in
// global-setup, so this journey re-verifies the redirect/auth contract with a
@@ -21,3 +49,160 @@ test.describe.serial("auth & first screen", () => {
await page.waitForURL(/\/c/, { timeout: 20_000 , waitUntil: "commit" })
})
})
+
+browserTest.describe("production OTP error placement", () => {
+ browserTest("centers an invalid OTP on mobile and desktop and clears it before retry", async ({ page }, testInfo) => {
+ await page.setViewportSize({ width: 390, height: 844 })
+
+ const attempts: string[] = []
+ await page.route("**/api/auth/email-otp/send-verification-otp", (route) => route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({ success: true }),
+ }))
+ await page.route("**/api/auth/sign-in/email-otp", async (route) => {
+ const body = route.request().postDataJSON() as { otp: string }
+ attempts.push(body.otp)
+ if (attempts.length <= 2) {
+ await route.fulfill({
+ status: 401,
+ contentType: "application/json",
+ body: JSON.stringify({ code: "INVALID_OTP", message: "Invalid OTP" }),
+ })
+ return
+ }
+ await route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({ token: "test", user: { id: "user_test" } }),
+ })
+ })
+ await page.route("**/c/me", (route) => route.fulfill({
+ status: 200,
+ contentType: "text/html",
+ body: "<main>Signed in</main>",
+ }))
+
+ await page.goto("/sign-in")
+ const sendCode = page.getByRole("button", { name: "Send Code" })
+ browserTest.skip(!(await sendCode.isVisible()), "production Email OTP UI is not active")
+
+ await page.getByRole("textbox", { name: "Email" }).fill("[email protected]")
+ await sendCode.click()
+
+ const otp = page.getByRole("textbox", { name: "Verification code" })
+ await otp.fill("123456")
+ const alert = page.getByRole("alert").filter({ hasText: "Invalid OTP" })
+ await browserExpect(alert).toHaveCount(1)
+ await browserExpect(otp).toHaveAttribute("aria-invalid", "true")
+ await browserExpect(otp).toHaveAttribute("aria-describedby", "sign-in-otp-error")
+
+ const slots = page.locator('[data-slot="input-otp-slot"]')
+ const otpField = page.locator('[data-slot="sign-in-otp-field"]')
+ const otpGroup = page.locator('[data-slot="input-otp-group"]')
+ const authPane = page.locator('[data-slot="card-content"] > div').first()
+ const lastSlot = await slots.last().boundingBox()
+ const alertBox = await alert.boundingBox()
+ browserExpect(lastSlot).not.toBeNull()
+ browserExpect(alertBox).not.toBeNull()
+ browserExpect(alertBox!.y).toBeGreaterThanOrEqual(lastSlot!.y + lastSlot!.height)
+ await expectSameHorizontalCenter(otpField, authPane)
+ await expectSameHorizontalCenter(otpGroup, authPane)
+ await expectSameHorizontalCenter(alert, otpGroup)
+ await expectSameWidth(otpField, otpGroup)
+
+ const mobileScreenshot = testInfo.outputPath("mobile-otp-centered.png")
+ await page.screenshot({ path: mobileScreenshot })
+ await testInfo.attach("mobile OTP centered", {
+ path: mobileScreenshot,
+ contentType: "image/png",
+ })
+
+ await page.setViewportSize({ width: 1280, height: 800 })
+ await expectSameHorizontalCenter(otpField, authPane)
+ await expectSameHorizontalCenter(otpGroup, authPane)
+ await expectSameHorizontalCenter(alert, otpGroup)
+ await expectSameWidth(otpField, otpGroup)
+
+ const desktopScreenshot = testInfo.outputPath("desktop-otp-centered.png")
+ await page.screenshot({ path: desktopScreenshot })
+ await testInfo.attach("desktop OTP centered", {
+ path: desktopScreenshot,
+ contentType: "image/png",
+ })
+
+ await otp.fill("7")
+ await browserExpect(alert).toHaveCount(0)
+ await browserExpect(otp).toHaveAttribute("aria-invalid", "false")
+
+ await otp.fill("111111")
+ await browserExpect(alert).toHaveCount(1)
+ await page.getByRole("button", { name: "Use a different email" }).click()
+ await browserExpect(alert).toHaveCount(0)
+ await browserExpect(page.getByRole("textbox", { name: "Email" })).toBeVisible()
+ await page.getByRole("button", { name: "Send Code" }).click()
+
+ await otp.fill("654321")
+ await page.waitForURL("**/c/me")
+ browserExpect(attempts).toEqual(["123456", "111111", "654321"])
+ })
+
+ browserTest("keeps send failures and cooldown feedback inside the desktop email field", async ({ page }) => {
+ await page.setViewportSize({ width: 1280, height: 800 })
+
+ let sends = 0
+ await page.route("**/api/auth/email-otp/send-verification-otp", async (route) => {
+ sends += 1
+ if (sends === 1) {
+ await route.fulfill({
+ status: 400,
+ contentType: "application/json",
+ body: JSON.stringify({ code: "SEND_FAILED", message: "Failed to send code" }),
+ })
+ return
+ }
+ await route.fulfill({
+ status: 429,
+ headers: { "Retry-After": "4" },
+ contentType: "application/json",
+ body: JSON.stringify({ code: "TOO_MANY_REQUESTS", message: "Too many requests" }),
+ })
+ })
+
+ await page.goto("/sign-in")
+ const sendCode = page.getByRole("button", { name: "Send Code" })
+ 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 sendCode.click()
+
+ let alert = page.getByRole("alert").filter({ hasText: "Failed to send code" })
+ await browserExpect(alert).toHaveCount(1)
+ await browserExpect(email).toHaveAttribute("aria-describedby", "sign-in-email-error")
+ const inputBox = await email.boundingBox()
+ const sendBox = await sendCode.boundingBox()
+ let alertBox = await alert.boundingBox()
+ browserExpect(inputBox).not.toBeNull()
+ browserExpect(sendBox).not.toBeNull()
+ browserExpect(alertBox).not.toBeNull()
+ browserExpect(alertBox!.y).toBeGreaterThanOrEqual(inputBox!.y + inputBox!.height)
+ browserExpect(alertBox!.y + alertBox!.height).toBeLessThanOrEqual(sendBox!.y)
+
+ await email.fill("[email protected]")
+ await browserExpect(alert).toHaveCount(0)
+ await sendCode.click()
+
+ alert = page.getByRole("alert").filter({
+ hasText: /Too many requests\. Try again in \d+s\./,
+ })
+ await browserExpect(alert).toHaveCount(1)
+ alertBox = await alert.boundingBox()
+ browserExpect(alertBox).not.toBeNull()
+ 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()
+ })
+})