Skip to content

Self-improving AI Employees for everyone

feat(auth): sign-in in Home's look, with a welcome while the app opens

trohitge32487b85049
diff --git a/CLAUDE.md b/CLAUDE.md
index 04e54910..6b3d4ad1 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1239,9 +1239,9 @@ The historical Docker Compose topology (4-container stack: redis / backend / fro
## Authentication System
-n8n-style JWT auth in HttpOnly cookies. `VITE_AUTH_ENABLED=false` bypasses login (anonymous owner, dev); when enabled, `AUTH_MODE=single` (first user = owner, registration then closed) or `multi` (open registration). Backend: `User` (bcrypt) + `UserAuthService` + `/api/auth/*` router + `AuthMiddleware` (public-path allowlist + `/webhook/` prefix). `/login` and `/register` are throttled by the in-process `core/rate_limit.py` sliding window (`AUTH_RATE_LIMIT_*`; no `slowapi` dependency — the primary runtime is a single uvicorn worker). Frontend: `AuthContext` (a TanStack-Query bootstrap check that never retries on its own, plus `useMutation` for login/register/logout) + `ProtectedRoute` (the sign-in gate: Connecting while the server can't be reached, then sign-in or the app, and Connecting over the app while the WebSocket is down) + `LoginPage` (RHF + zod via the shadcn `Form` primitives); all API calls send `credentials: 'include'`, and the WebSocket refuses to connect without the cookie.
+n8n-style JWT auth in HttpOnly cookies. `VITE_AUTH_ENABLED=false` bypasses login (anonymous owner, dev); when enabled, `AUTH_MODE=single` (first user = owner, registration then closed) or `multi` (open registration). Backend: `User` (bcrypt) + `UserAuthService` + `/api/auth/*` router + `AuthMiddleware` (public-path allowlist + `/webhook/` prefix). `/login` and `/register` are throttled by the in-process `core/rate_limit.py` sliding window (`AUTH_RATE_LIMIT_*`; no `slowapi` dependency — the primary runtime is a single uvicorn worker). Frontend: `AuthContext` (a TanStack-Query bootstrap check that never retries on its own, plus `useMutation` for login/register/logout) + `ProtectedRoute` (the sign-in gate: Connecting while the server can't be reached, then sign-in or the app, and Connecting over the app while the WebSocket is down) + `LoginPage` (RHF + zod via the shadcn `Form` primitives; after a sign-in its welcome, `SignedIn`, stays while `signingIn` — the login/register mutations' own state, in flight or succeeded — until `finishSignIn` resets them); all API calls send `credentials: 'include'`, and the WebSocket refuses to connect without the cookie.
-**Two context distinctions that are load-bearing, not stylistic:** `isLoading` is the bootstrap query (gates the whole app in `ProtectedRoute`) while `isSubmitting` is per-request — using the former to disable the login form disables nothing, since it has already settled by the time that form renders. And `error` means "cannot reach the server" while `submitError` is the server's own rejection text; a `setQueryData` write is a *success* value, so routing a login failure through the status cache surfaces no error at all and additionally collapses `can_register`.
+**Two context distinctions that are load-bearing, not stylistic:** `isLoading` is the bootstrap query (gates the whole app in `ProtectedRoute`) while `isSubmitting` is per-request — using the former to disable the login form disables nothing, since it has already settled by the time that form renders. And `error` means "cannot reach the server" while `submitError` is the server's own rejection text, shown as the server words it (or `AUTH_UNREACHABLE` when a sign-in got no answer); a `setQueryData` write is a *success* value, so routing a login failure through the status cache surfaces no error at all and additionally collapses `can_register`.
**Read the Known Limitations section of [authentication.md](./docs-internal/authentication.md) before building on this.** `AUTH_MODE=multi` provides authentication but no data isolation — `request.state.user_id` is written by the HTTP middleware (`middleware/auth.py`) and read by no route handler, so REST traffic shares one workflow store and one credential store. The WebSocket surface is different: `websocket.state.user_id` (`routers/websocket.py`) IS consumed by `execution_principal` (`services/authz/ws_surface.py`) to pick the principal an execution runs as, so identity is resolved there even though enforcement is missing. There is also no CSRF token and no token revocation (`User.is_active` is the only lever).
diff --git a/client/src/components/auth/LoginPage.tsx b/client/src/components/auth/LoginPage.tsx
index 0f314146..c5630e2f 100644
--- a/client/src/components/auth/LoginPage.tsx
+++ b/client/src/components/auth/LoginPage.tsx
@@ -1,49 +1,48 @@
/**
- * Login/Register Page.
+ * Sign in and register (onboarding handoff R5), inside the gate's
+ * ConnectScreen: the orb above a card that rises in, and shakes when a
+ * field is wrong or the server refuses. "Welcome back" or "Create your
+ * account", the fields, Sign in / Create account, and the way to the other
+ * mode while registration is open. Once signed in, the card gives way to
+ * SignedIn, which ends the sign-in (`finishSignIn`) when the app can show.
*
* Built on react-hook-form + zod through the shadcn `Form` primitives, the
- * same composition `EmailPanel` uses. That is not cosmetic: `FormControl`
- * emits `aria-invalid` and wires `aria-describedby` to the matching
- * `FormMessage`, which the previous hand-rolled markup did not do.
+ * same composition `EmailPanel` uses: `FormControl` emits `aria-invalid`
+ * and wires `aria-describedby` to the matching `FormMessage`.
*
- * Two failure signals are displayed, and they are not the same thing:
- * `submitError` is the server's rejection ("Invalid email or password"),
- * `error` is a connectivity failure from the bootstrap query. Before, only
- * the latter existed on the context, so a wrong password produced no
- * feedback whatsoever.
+ * The only failure shown here is what the server said (`submitError`: a
+ * wrong password, a taken email, a rate limit, or no answer at all). A
+ * server that can't be reached at all is the gate's Connecting screen, not
+ * this card's. The orb follows the form: livelier while a field has focus,
+ * more with text, most while the request is out.
*/
-import React, { useMemo, useState } from 'react';
-import { useForm } from 'react-hook-form';
+import React, { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
+import { useForm, useWatch } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
+import { ArrowRight, CircleAlert, Eye, EyeOff } from 'lucide-react';
import { useAuth } from '../../contexts/AuthContext';
-import { Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter } from '@/components/ui/card';
-import { Input } from '@/components/ui/input';
-import { Button } from '@/components/ui/button';
import { Alert, AlertDescription } from '@/components/ui/alert';
-import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
-} from '@/components/ui/form';
+import { Button } from '@/components/ui/button';
+import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form';
+import { Input } from '@/components/ui/input';
+import { RingSpinner } from '@/components/ui/ring-spinner';
+import { ENERGY, setEnergyTarget } from '@/features/home/orb/orb';
+import { OrbSlot } from '@/features/home/orb/OrbSlot';
+import { rise, shake } from '@/lib/motion';
import { createAuthFormSchema, type AuthFormValues } from './schemas/login';
+import { SignedIn } from './SignedIn';
+
+const FIELD = 'h-10 rounded-row bg-bg-app px-3 text-base md:text-base dark:bg-bg-app';
const LoginPage: React.FC = () => {
- const {
- login,
- register,
- canRegister,
- error,
- submitError,
- isSubmitting,
- resetAuthErrors,
- } = useAuth();
+ const { login, register, canRegister, submitError, isSubmitting, resetAuthErrors, isAuthenticated, user } = useAuth();
const [isRegistering, setIsRegistering] = useState(false);
+ const [showPassword, setShowPassword] = useState(false);
+ const [focused, setFocused] = useState(false);
+ const cardRef = useRef<HTMLDivElement>(null);
const schema = useMemo(() => createAuthFormSchema(isRegistering), [isRegistering]);
@@ -52,16 +51,28 @@ const LoginPage: React.FC = () => {
defaultValues: { email: '', password: '', displayName: '' },
mode: 'onSubmit',
});
+ const [email, password, displayName] = useWatch({
+ control: form.control,
+ name: ['email', 'password', 'displayName'],
+ });
+ const typed = Boolean(email || password || displayName);
+
+ useLayoutEffect(() => {
+ rise(cardRef.current);
+ }, []);
+
+ useEffect(() => {
+ setEnergyTarget(isSubmitting ? ENERGY.generating : focused ? (typed ? ENERGY.typing : ENERGY.focus) : ENERGY.idle);
+ }, [isSubmitting, focused, typed]);
+ useEffect(() => () => setEnergyTarget(ENERGY.idle), []);
- const onSubmit = async (values: AuthFormValues) => {
+ const onSubmit = async (submitted: AuthFormValues) => {
resetAuthErrors();
- if (isRegistering) {
- await register(values.email, values.password, values.displayName ?? '');
- } else {
- await login(values.email, values.password);
- }
- // Failure text lives on `submitError`; nothing to do here. The mutation
- // never rejects out of these wrappers.
+ const ok = isRegistering
+ ? await register(submitted.email, submitted.password, submitted.displayName ?? '')
+ : await login(submitted.email, submitted.password);
+ // The refusal itself is on `submitError`.
+ if (!ok) shake(cardRef.current);
};
const toggleMode = () => {
@@ -71,56 +82,60 @@ const LoginPage: React.FC = () => {
};
return (
- <div className="flex min-h-screen items-center justify-center bg-background p-5">
- <Card className="w-full max-w-md">
- <CardHeader className="text-center">
- {/* A real <h1>: the page previously had no heading landmark at all. */}
- <CardTitle className="text-3xl font-bold text-node-agent">
- <h1>OpenCompany</h1>
- </CardTitle>
- <CardDescription>
- {isRegistering ? 'Create your account' : 'Sign in to continue'}
- </CardDescription>
- </CardHeader>
-
- <CardContent className="space-y-4">
- {/* Server rejection: wrong password, duplicate email, rate limit. */}
+ <div className="flex w-full max-w-100 flex-col items-center gap-4.5">
+ <OrbSlot size="login" />
+ {isAuthenticated ? (
+ <SignedIn created={isRegistering} name={user?.display_name ?? ''} />
+ ) : (
+ <div
+ ref={cardRef}
+ className="flex w-full flex-col gap-5 rounded-draft border border-border-default bg-bg-panel p-7 shadow-float"
+ >
+ <h1 className="m-0 text-center text-xl leading-tight font-semibold tracking-hero text-fg-default">
+ {isRegistering ? 'Create your account' : 'Welcome back'}
+ </h1>
+
{submitError && (
- <Alert variant="destructive" aria-live="assertive">
+ <Alert
+ variant="destructive"
+ aria-live="assertive"
+ className="rounded-row border-danger-border bg-danger-soft px-3 py-2.5 text-sm"
+ >
+ <CircleAlert aria-hidden className="size-3.75" />
<AlertDescription>{submitError}</AlertDescription>
</Alert>
)}
- {/* Connectivity failure, distinct from a rejected credential. */}
- {error && !submitError && (
- <Alert variant="destructive" aria-live="polite">
- <AlertDescription>{error}</AlertDescription>
- </Alert>
- )}
-
<Form {...form}>
{/* noValidate: zod owns validation. Otherwise the browser's own
constraint check on type="email" silently blocks submit and
shows a native bubble, which neither matches FormMessage
styling nor respects the schema's rules. */}
- <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4" noValidate>
+ <form
+ onSubmit={form.handleSubmit(onSubmit, () => shake(cardRef.current))}
+ onFocus={() => setFocused(true)}
+ onBlur={() => setFocused(false)}
+ className="flex flex-col gap-3.5"
+ noValidate
+ >
{isRegistering && (
<FormField
control={form.control}
name="displayName"
render={({ field }) => (
- <FormItem>
- <FormLabel>Display Name</FormLabel>
+ <FormItem className="gap-1.5">
+ <FormLabel className="text-sm font-medium">Your name</FormLabel>
<FormControl>
<Input
- placeholder="Your name"
+ placeholder="Jordan Lee"
autoComplete="name"
disabled={isSubmitting}
+ className={FIELD}
{...field}
value={field.value ?? ''}
/>
</FormControl>
- <FormMessage />
+ <FormMessage className="text-meta" />
</FormItem>
)}
/>
@@ -130,18 +145,19 @@ const LoginPage: React.FC = () => {
control={form.control}
name="email"
render={({ field }) => (
- <FormItem>
- <FormLabel>Email</FormLabel>
+ <FormItem className="gap-1.5">
+ <FormLabel className="text-sm font-medium">Email</FormLabel>
<FormControl>
<Input
type="email"
placeholder="[email protected]"
autoComplete="email"
disabled={isSubmitting}
+ className={FIELD}
{...field}
/>
</FormControl>
- <FormMessage />
+ <FormMessage className="text-meta" />
</FormItem>
)}
/>
@@ -150,50 +166,73 @@ const LoginPage: React.FC = () => {
control={form.control}
name="password"
render={({ field }) => (
- <FormItem>
- <FormLabel>Password</FormLabel>
- <FormControl>
- <Input
- type="password"
- placeholder={isRegistering ? 'At least 8 characters' : 'Your password'}
- autoComplete={isRegistering ? 'new-password' : 'current-password'}
- disabled={isSubmitting}
- {...field}
- />
- </FormControl>
- <FormMessage />
+ <FormItem className="gap-1.5">
+ <FormLabel className="text-sm font-medium">Password</FormLabel>
+ <div className="relative">
+ <FormControl>
+ <Input
+ type={showPassword ? 'text' : 'password'}
+ placeholder={isRegistering ? 'At least 8 characters' : 'Your password'}
+ autoComplete={isRegistering ? 'new-password' : 'current-password'}
+ disabled={isSubmitting}
+ className={`${FIELD} pr-10`}
+ {...field}
+ />
+ </FormControl>
+ <Button
+ type="button"
+ variant="quiet"
+ size="icon-sm"
+ aria-label={showPassword ? 'Hide password' : 'Show password'}
+ aria-pressed={showPassword}
+ onClick={() => setShowPassword((on) => !on)}
+ className="absolute top-1/2 right-2 -translate-y-1/2 rounded-lg"
+ >
+ {showPassword ? <EyeOff aria-hidden /> : <Eye aria-hidden />}
+ </Button>
+ </div>
+ <FormMessage className="text-meta" />
</FormItem>
)}
/>
- <Button type="submit" className="w-full" disabled={isSubmitting}>
- {isSubmitting
- ? 'Please wait...'
- : isRegistering
- ? 'Create Account'
- : 'Sign In'}
+ <Button
+ type="submit"
+ variant="invert"
+ disabled={isSubmitting}
+ className="mt-1 h-10.5 w-full gap-2 rounded-row text-base font-semibold disabled:bg-fg-default disabled:text-bg-app disabled:opacity-70"
+ >
+ {isSubmitting ? (
+ <>
+ <RingSpinner className="size-3.5 border-fg-faint border-t-bg-app" />
+ {isRegistering ? 'Creating your account…' : 'Signing in…'}
+ </>
+ ) : (
+ <>
+ {isRegistering ? 'Create account' : 'Sign in'}
+ <ArrowRight aria-hidden strokeWidth={2.25} />
+ </>
+ )}
</Button>
</form>
</Form>
- </CardContent>
-
- {canRegister && (
- <CardFooter className="justify-center gap-2 border-t pt-4 text-sm">
- <span className="text-muted-foreground">
- {isRegistering ? 'Already have an account?' : "Don't have an account?"}
- </span>
- <Button
- type="button"
- variant="link"
- onClick={toggleMode}
- disabled={isSubmitting}
- className="h-auto p-0"
- >
- {isRegistering ? 'Sign In' : 'Register'}
- </Button>
- </CardFooter>
- )}
- </Card>
+
+ {canRegister && (
+ <p className="m-0 border-t border-border-default pt-4 text-center text-row text-fg-muted">
+ {isRegistering ? 'Already have an account?' : 'Don’t have an account?'}{' '}
+ <Button
+ type="button"
+ variant="link"
+ onClick={toggleMode}
+ disabled={isSubmitting}
+ className="h-auto p-0 text-row font-semibold text-fg-default"
+ >
+ {isRegistering ? 'Sign in' : 'Register'}
+ </Button>
+ </p>
+ )}
+ </div>
+ )}
</div>
);
};
diff --git a/client/src/components/auth/ProtectedRoute.tsx b/client/src/components/auth/ProtectedRoute.tsx
index 5320a825..f58534cc 100644
--- a/client/src/components/auth/ProtectedRoute.tsx
+++ b/client/src/components/auth/ProtectedRoute.tsx
@@ -7,13 +7,14 @@
* | the server can't be reached | Connecting: a countdown to each check, Try now |
* | the server answered | "Connected", for CONNECT_RETRY.CONNECTED_HOLD_MS |
* | then | sign-in, or the app (a good session, or login off) |
+ * | a sign-in from the form (`signingIn`) | sign-in, then its welcome until `finishSignIn` |
* | signed in, the WebSocket down | Connecting over the app |
*
- * Connecting and sign-in render in one ConnectScreen, so the orb glides
- * between their slots. Over the app, the app stays mounted and inert, and
- * the checks are HTTP session checks, so a session that expired while the
- * server was away goes to sign-in; the overlay goes once the WebSocket is
- * back. The auth check never retries on its own (AuthContext).
+ * Connecting, sign-in and the welcome render in one ConnectScreen, so the
+ * orb glides between their slots. Over the app, the app stays mounted and
+ * inert, and the checks are HTTP session checks, so a session that expired
+ * while the server was away goes to sign-in; the overlay goes once the
+ * WebSocket is back. The auth check never retries on its own (AuthContext).
*/
import React from 'react';
@@ -38,7 +39,7 @@ function ScreenLoading() {
}
const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
- const { isAuthenticated, isLoading, error, checkAuth } = useAuth();
+ const { isAuthenticated, isLoading, signingIn, error, checkAuth } = useAuth();
const { reconnecting } = useWebSocketActions();
const unreachable = error !== null && !isAuthenticated;
const connecting = useHold(unreachable, CONNECT_RETRY.CONNECTED_HOLD_MS);
@@ -47,7 +48,7 @@ const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({ children }) =
if (isLoading) return <ScreenLoading />;
- if (connecting || !isAuthenticated) {
+ if (connecting || !isAuthenticated || signingIn) {
return (
<ConnectScreen>
{connecting ? <ConnectingPanel check={checkAuth} connected={!unreachable} /> : <LoginPage />}
diff --git a/client/src/components/auth/SignedIn.tsx b/client/src/components/auth/SignedIn.tsx
new file mode 100644
index 00000000..320b5d4c
--- /dev/null
+++ b/client/src/components/auth/SignedIn.tsx
@@ -0,0 +1,55 @@
+/**
+ * Signed in (onboarding handoff R5): in place of the sign-in card, who they
+ * are and that their team is opening. It hands over the way a mode switch
+ * does (app/useShellActions): the screen the app opens on loads while this
+ * rises in, then `finishSignIn` ends the sign-in and the gate shows the app.
+ * The orb spikes as it shows.
+ */
+
+import { useLayoutEffect, useRef } from 'react';
+import { RingSpinner } from '@/components/ui/ring-spinner';
+import { useAuth } from '@/contexts/AuthContext';
+import { firstName } from '@/features/home/data/profile';
+import { SPIKE, spikeOrb } from '@/features/home/orb/orb';
+import { finished, rise } from '@/lib/motion';
+import { preloadEditor, preloadHome, useShellMode } from '../../app/ShellModeSwitch';
+
+export function SignedIn({ created, name }: { created: boolean; name: string }) {
+ const { finishSignIn } = useAuth();
+ const mode = useShellMode();
+ const ref = useRef<HTMLDivElement>(null);
+
+ useLayoutEffect(() => {
+ spikeOrb(SPIKE.signedIn);
+ let current = true;
+ const screen = (mode === 'normal' ? preloadHome() : preloadEditor()).catch((error: unknown) => {
+ // The screen's own error boundary says so once it shows.
+ console.error('[Shell] Could not load the screen:', error);
+ });
+ void Promise.all([finished(rise(ref.current)), screen]).then(() => {
+ if (current) finishSignIn();
+ });
+ return () => {
+ current = false;
+ };
+ }, [mode, finishSignIn]);
+
+ const first = firstName(name);
+ const greeting = created ? 'Welcome' : 'Welcome back';
+ return (
+ <div ref={ref} className="flex flex-col items-center gap-2.5 text-center">
+ <p className="m-0 font-mono text-2xs font-medium tracking-label text-node-agent-ink uppercase">
+ {created ? 'Account created' : 'Signed in'}
+ </p>
+ <h1 className="m-0 text-headline leading-hero font-semibold tracking-hero text-balance text-fg-default">
+ {first ? `${greeting}, ${first}` : greeting}
+ </h1>
+ <p role="status" className="m-0 flex items-center gap-2 text-base text-fg-muted">
+ <RingSpinner className="size-3 border-border-default border-t-fg-default" />
+ Opening your team…
+ </p>
+ </div>
+ );
+}
+
+export default SignedIn;
diff --git a/client/src/components/auth/__tests__/LoginPage.test.tsx b/client/src/components/auth/__tests__/LoginPage.test.tsx
index ede6e703..611fb0f3 100644
--- a/client/src/components/auth/__tests__/LoginPage.test.tsx
+++ b/client/src/components/auth/__tests__/LoginPage.test.tsx
@@ -1,53 +1,81 @@
/**
- * Tests for LoginPage.
+ * Tests for LoginPage: the sign-in card (onboarding handoff R5) and the
+ * welcome after it.
*
- * The page previously had no tests at all, and three user-visible defects
- * lived here: server rejections were never displayed, the Register link
- * disappeared after one failed login, and the submit button never disabled
- * (so the form accepted unlimited concurrent requests). Each of those has a
- * case below.
+ * The page's first tests caught three real defects, kept below: server
+ * rejections were never displayed, the Register link disappeared after one
+ * failed login, and the submit button never disabled (so the form accepted
+ * unlimited concurrent requests). The restyle adds the words for each
+ * mistake, the password toggle, the shake, the orb following the form, and
+ * the welcome, which ends the sign-in once it has risen in and the screen
+ * the app opens on has loaded.
*/
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { render, screen, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
-import LoginPage from '../LoginPage';
+import type { User } from '../../../contexts/AuthContext';
+import { preloadHome } from '../../../app/ShellModeSwitch';
+import { ENERGY, SPIKE, orbState, resetOrbForTests } from '@/features/home/orb/orb';
+import { installWaapiStub } from '../../../test/waapi';
const authState = {
login: vi.fn(),
register: vi.fn(),
canRegister: true,
- error: null as string | null,
submitError: null as string | null,
isSubmitting: false,
resetAuthErrors: vi.fn(),
+ finishSignIn: vi.fn(),
+ isAuthenticated: false,
+ user: null as User | null,
};
vi.mock('../../../contexts/AuthContext', () => ({
useAuth: () => authState,
}));
+vi.mock('../../../app/ShellModeSwitch', () => ({
+ useShellMode: () => 'normal',
+ preloadHome: vi.fn(),
+ preloadEditor: vi.fn(),
+}));
+
+import LoginPage from '../LoginPage';
+
+const JORDAN: User = { id: 1, email: '[email protected]', display_name: 'Jordan Lee', is_owner: true };
beforeEach(() => {
vi.clearAllMocks();
authState.login = vi.fn().mockResolvedValue(true);
authState.register = vi.fn().mockResolvedValue(true);
authState.canRegister = true;
- authState.error = null;
authState.submitError = null;
authState.isSubmitting = false;
authState.resetAuthErrors = vi.fn();
+ authState.finishSignIn = vi.fn();
+ authState.isAuthenticated = false;
+ authState.user = null;
+ vi.mocked(preloadHome).mockResolvedValue(undefined);
+ resetOrbForTests();
});
const fillCredentials = async (user: ReturnType<typeof userEvent.setup>) => {
- await user.type(screen.getByLabelText(/email/i), '[email protected]');
- await user.type(screen.getByLabelText(/password/i), 'hunter2hunter2');
+ await user.type(screen.getByLabelText(/^email$/i), '[email protected]');
+ await user.type(screen.getByLabelText(/^password$/i), 'hunter2hunter2');
};
+function signIn() {
+ authState.isAuthenticated = true;
+ authState.user = JORDAN;
+}
+
describe('LoginPage', () => {
- it('renders a heading and the sign-in form', () => {
+ it('says Welcome back over the sign-in form', () => {
render(<LoginPage />);
- expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('OpenCompany');
+ expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('Welcome back');
+ expect(screen.getByLabelText(/^email$/i)).toHaveAttribute('placeholder', '[email protected]');
+ expect(screen.getByLabelText(/^password$/i)).toHaveAttribute('placeholder', 'Your password');
expect(screen.getByRole('button', { name: /sign in/i })).toBeInTheDocument();
});
@@ -62,19 +90,16 @@ describe('LoginPage', () => {
});
});
- it('displays the server rejection in an alert', async () => {
+ it('displays the server rejection in an alert', () => {
authState.submitError = 'Invalid email or password';
render(<LoginPage />);
-
- const alert = screen.getByRole('alert');
- expect(alert).toHaveTextContent('Invalid email or password');
+ expect(screen.getByRole('alert')).toHaveTextContent('Invalid email or password');
});
- it('keeps the Register link visible when a login has failed', async () => {
+ it('keeps the Register link visible when a login has failed', () => {
authState.submitError = 'Invalid email or password';
authState.canRegister = true;
render(<LoginPage />);
-
expect(screen.getByRole('button', { name: /^register$/i })).toBeInTheDocument();
});
@@ -82,74 +107,75 @@ describe('LoginPage', () => {
authState.canRegister = false;
render(<LoginPage />);
expect(screen.queryByRole('button', { name: /^register$/i })).not.toBeInTheDocument();
+ expect(screen.queryByText(/have an account/i)).not.toBeInTheDocument();
});
- it('rejects a malformed email without calling login', async () => {
+ it('asks for an email', async () => {
const user = userEvent.setup();
render(<LoginPage />);
-
- await user.type(screen.getByLabelText(/email/i), 'not-an-email');
- await user.type(screen.getByLabelText(/password/i), 'hunter2hunter2');
+ await user.type(screen.getByLabelText(/^password$/i), 'hunter2hunter2');
await user.click(screen.getByRole('button', { name: /sign in/i }));
- await waitFor(() => {
- expect(screen.getByText(/valid email address/i)).toBeInTheDocument();
- });
+ expect(await screen.findByText('Enter your email.')).toBeInTheDocument();
expect(authState.login).not.toHaveBeenCalled();
});
- it('requires a password', async () => {
+ it('rejects a malformed email without calling login', async () => {
const user = userEvent.setup();
render(<LoginPage />);
+ await user.type(screen.getByLabelText(/^email$/i), 'not-an-email');
+ await user.type(screen.getByLabelText(/^password$/i), 'hunter2hunter2');
+ await user.click(screen.getByRole('button', { name: /sign in/i }));
+
+ expect(await screen.findByText(/look like an email address/i)).toBeInTheDocument();
+ expect(authState.login).not.toHaveBeenCalled();
+ });
- await user.type(screen.getByLabelText(/email/i), '[email protected]');
+ it('asks for a password', async () => {
+ const user = userEvent.setup();
+ render(<LoginPage />);
+ await user.type(screen.getByLabelText(/^email$/i), '[email protected]');
await user.click(screen.getByRole('button', { name: /sign in/i }));
- await waitFor(() => {
- expect(screen.getByText(/password is required/i)).toBeInTheDocument();
- });
+ expect(await screen.findByText('Enter your password.')).toBeInTheDocument();
expect(authState.login).not.toHaveBeenCalled();
});
- it('disables inputs and the button while submitting', () => {
+ it('disables the fields and the button while signing in', () => {
authState.isSubmitting = true;
render(<LoginPage />);
- expect(screen.getByLabelText(/email/i)).toBeDisabled();
- expect(screen.getByLabelText(/password/i)).toBeDisabled();
- const button = screen.getByRole('button', { name: /please wait/i });
- expect(button).toBeDisabled();
+ expect(screen.getByLabelText(/^email$/i)).toBeDisabled();
+ expect(screen.getByLabelText(/^password$/i)).toBeDisabled();
+ expect(screen.getByRole('button', { name: 'Signing in…' })).toBeDisabled();
});
it('does not fire a second request while one is in flight', async () => {
const user = userEvent.setup();
- // A slow login keeps the mutation pending; the component is driven by
- // `isSubmitting`, so assert the disabled attribute blocks the second click.
+ // The component is driven by `isSubmitting`, so assert the disabled
+ // attribute blocks the second click.
const { rerender } = render(<LoginPage />);
await fillCredentials(user);
authState.isSubmitting = true;
rerender(<LoginPage />);
- const button = screen.getByRole('button', { name: /please wait/i });
- await user.click(button).catch(() => undefined);
+ await user.click(screen.getByRole('button', { name: 'Signing in…' })).catch(() => undefined);
expect(authState.login).not.toHaveBeenCalled();
});
- it('switches to register mode and requires a display name', async () => {
+ it('switches to Create your account and asks for a name', async () => {
const user = userEvent.setup();
render(<LoginPage />);
await user.click(screen.getByRole('button', { name: /^register$/i }));
- expect(screen.getByRole('button', { name: /create account/i })).toBeInTheDocument();
+ expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('Create your account');
+ expect(screen.getByLabelText(/^password$/i)).toHaveAttribute('placeholder', 'At least 8 characters');
- await user.type(screen.getByLabelText(/email/i), '[email protected]');
- await user.type(screen.getByLabelText(/password/i), 'hunter2hunter2');
+ await fillCredentials(user);
await user.click(screen.getByRole('button', { name: /create account/i }));
- await waitFor(() => {
- expect(screen.getByText(/display name is required/i)).toBeInTheDocument();
- });
+ expect(await screen.findByText('Enter your name.')).toBeInTheDocument();
expect(authState.register).not.toHaveBeenCalled();
});
@@ -158,24 +184,22 @@ describe('LoginPage', () => {
render(<LoginPage />);
await user.click(screen.getByRole('button', { name: /^register$/i }));
- await user.type(screen.getByLabelText(/display name/i), 'A');
- await user.type(screen.getByLabelText(/email/i), '[email protected]');
- await user.type(screen.getByLabelText(/password/i), 'short');
+ await user.type(screen.getByLabelText(/your name/i), 'A');
+ await user.type(screen.getByLabelText(/^email$/i), '[email protected]');
+ await user.type(screen.getByLabelText(/^password$/i), 'short');
await user.click(screen.getByRole('button', { name: /create account/i }));
- await waitFor(() => {
- expect(screen.getByText(/at least 8 characters/i)).toBeInTheDocument();
- });
+ expect(await screen.findByText('Use at least 8 characters.')).toBeInTheDocument();
+ expect(authState.register).not.toHaveBeenCalled();
});
- it('registers with a display name', async () => {
+ it('registers with a name', async () => {
const user = userEvent.setup();
render(<LoginPage />);
await user.click(screen.getByRole('button', { name: /^register$/i }));
- await user.type(screen.getByLabelText(/display name/i), 'Alice');
- await user.type(screen.getByLabelText(/email/i), '[email protected]');
- await user.type(screen.getByLabelText(/password/i), 'hunter2hunter2');
+ await user.type(screen.getByLabelText(/your name/i), 'Alice');
+ await fillCredentials(user);
await user.click(screen.getByRole('button', { name: /create account/i }));
await waitFor(() => {
@@ -190,19 +214,136 @@ describe('LoginPage', () => {
expect(authState.resetAuthErrors).toHaveBeenCalled();
});
- it('shows a connectivity error when there is no submit error', () => {
- authState.error = 'Failed to connect to server';
+ it('shows and hides the password', async () => {
+ const user = userEvent.setup();
render(<LoginPage />);
- expect(screen.getByRole('alert')).toHaveTextContent('Failed to connect to server');
+ const password = screen.getByLabelText(/^password$/i);
+ expect(password).toHaveAttribute('type', 'password');
+
+ await user.click(screen.getByRole('button', { name: 'Show password' }));
+ expect(password).toHaveAttribute('type', 'text');
+ expect(screen.getByRole('button', { name: 'Hide password' })).toHaveAttribute('aria-pressed', 'true');
+
+ await user.click(screen.getByRole('button', { name: 'Hide password' }));
+ expect(password).toHaveAttribute('type', 'password');
+ expect(authState.login).not.toHaveBeenCalled();
});
- it('prefers the submit error over the connectivity error', () => {
- authState.error = 'Failed to connect to server';
- authState.submitError = 'Invalid email or password';
+ it('livens the orb while a field has focus, more with text, most while signing in', async () => {
+ const user = userEvent.setup();
+ const { rerender, unmount } = render(<LoginPage />);
+ expect(orbState.target).toBe(ENERGY.idle);
+
+ await user.click(screen.getByLabelText(/^email$/i));
+ expect(orbState.target).toBe(ENERGY.focus);
+ await user.keyboard('a');
+ expect(orbState.target).toBe(ENERGY.typing);
+ await user.click(screen.getByRole('heading', { level: 1 }));
+ expect(orbState.target).toBe(ENERGY.idle);
+
+ authState.isSubmitting = true;
+ rerender(<LoginPage />);
+ expect(orbState.target).toBe(ENERGY.generating);
+
+ unmount();
+ expect(orbState.target).toBe(ENERGY.idle);
+ });
+});
+
+describe('LoginPage motion', () => {
+ let waapi: ReturnType<typeof installWaapiStub>;
+ beforeEach(() => {
+ waapi = installWaapiStub();
+ });
+ afterEach(() => {
+ waapi.restore();
+ vi.useRealTimers();
+ });
+
+ const card = () => screen.getByRole('heading', { level: 1 }).parentElement as HTMLElement;
+ const shakes = () =>
+ waapi.callsFor(card()).filter((call) => JSON.stringify(call.keyframes).includes('translateX(-6px)'));
+
+ it('rises in, and shakes when a field is wrong', async () => {
+ const user = userEvent.setup();
+ render(<LoginPage />);
+ expect(waapi.callsFor(card())).toHaveLength(1);
+ expect(shakes()).toHaveLength(0);
+
+ await user.click(screen.getByRole('button', { name: /sign in/i }));
+ await waitFor(() => expect(shakes()).toHaveLength(1));
+ });
+
+ it('shakes when the server refuses', async () => {
+ authState.login = vi.fn().mockResolvedValue(false);
+ const user = userEvent.setup();
+ render(<LoginPage />);
+ await fillCredentials(user);
+ await user.click(screen.getByRole('button', { name: /sign in/i }));
+
+ await waitFor(() => expect(shakes()).toHaveLength(1));
+ expect(authState.login).toHaveBeenCalledTimes(1);
+ });
+
+ it('ends the sign-in only once the welcome has risen in', async () => {
+ // `finished` also gives up on an animation after its own timing; with
+ // the clock stopped, the rise ending is the only way through.
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
+ signIn();
render(<LoginPage />);
- const alerts = screen.getAllByRole('alert');
- expect(alerts).toHaveLength(1);
- expect(alerts[0]).toHaveTextContent('Invalid email or password');
+ const welcome = screen.getByRole('heading', { name: 'Welcome back, Jordan' }).parentElement as HTMLElement;
+ const [riseIn] = waapi.callsFor(welcome);
+ await act(async () => {});
+ expect(authState.finishSignIn).not.toHaveBeenCalled();
+
+ await act(async () => riseIn.animation.finish());
+ await act(async () => {});
+ expect(authState.finishSignIn).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('after signing in', () => {
+ it('says who signed in, and ends the sign-in once Home has loaded', async () => {
+ let loaded!: () => void;
+ vi.mocked(preloadHome).mockReturnValue(new Promise<void>((resolve) => (loaded = resolve)));
+ const { rerender } = render(<LoginPage />);
+ signIn();
+ rerender(<LoginPage />);
+
+ expect(screen.queryByLabelText(/^email$/i)).not.toBeInTheDocument();
+ expect(screen.getByText('Signed in')).toBeInTheDocument();
+ expect(screen.getByRole('heading', { name: 'Welcome back, Jordan' })).toBeInTheDocument();
+ expect(screen.getByRole('status')).toHaveTextContent('Opening your team…');
+ expect(orbState.spike).toBe(SPIKE.signedIn);
+ expect(preloadHome).toHaveBeenCalled();
+ await act(async () => {});
+ expect(authState.finishSignIn).not.toHaveBeenCalled();
+
+ await act(async () => loaded());
+ await waitFor(() => expect(authState.finishSignIn).toHaveBeenCalledTimes(1));
+ });
+
+ it('ends the sign-in when Home fails to load, for its own error to show', async () => {
+ const quiet = vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.mocked(preloadHome).mockRejectedValue(new Error('chunk load failed'));
+ signIn();
+ render(<LoginPage />);
+
+ await waitFor(() => expect(authState.finishSignIn).toHaveBeenCalledTimes(1));
+ expect(quiet).toHaveBeenCalled();
+ quiet.mockRestore();
+ });
+
+ it('says the account was created after registering', async () => {
+ const user = userEvent.setup();
+ const { rerender } = render(<LoginPage />);
+ await user.click(screen.getByRole('button', { name: /^register$/i }));
+
+ signIn();
+ rerender(<LoginPage />);
+
+ expect(screen.getByText('Account created')).toBeInTheDocument();
+ expect(screen.getByRole('heading', { name: 'Welcome, Jordan' })).toBeInTheDocument();
});
});
diff --git a/client/src/components/auth/__tests__/ProtectedRoute.test.tsx b/client/src/components/auth/__tests__/ProtectedRoute.test.tsx
index 90699c1f..ea2c827e 100644
--- a/client/src/components/auth/__tests__/ProtectedRoute.test.tsx
+++ b/client/src/components/auth/__tests__/ProtectedRoute.test.tsx
@@ -2,7 +2,8 @@
* The sign-in gate's states (ProtectedRoute): a loading screen while the
* session is checked; Connecting while the server can't be reached, with
* its countdown, attempts and help; "Connected" held a moment once it
- * answers, then sign-in or the app; and, signed in, Connecting over the
+ * answers, then sign-in or the app; the sign-in screen kept up while a
+ * sign-in finishes, for its welcome; and, signed in, Connecting over the
* app while the WebSocket is down, the app staying mounted, an expired
* session going to sign-in. The theme shows as its base while a
* Connecting or sign-in screen is up.
@@ -15,6 +16,7 @@ import { useEffect } from 'react';
interface Auth {
isAuthenticated: boolean;
isLoading: boolean;
+ signingIn: boolean;
error: string | null;
checkAuth: () => Promise<boolean>;
}
@@ -59,7 +61,13 @@ beforeEach(() => {
getContext = vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null);
mounts = 0;
ws = { reconnecting: false };
- auth = { isAuthenticated: false, isLoading: false, error: null, checkAuth: vi.fn(async () => false) };
+ auth = {
+ isAuthenticated: false,
+ isLoading: false,
+ signingIn: false,
+ error: null,
+ checkAuth: vi.fn(async () => false),
+ };
});
afterEach(() => {
@@ -116,6 +124,21 @@ describe('the sign-in gate', () => {
expect(useShellDialogsStore.getState().connectScreenOpen).toBe(false);
});
+ it('keeps the sign-in screen up until the sign-in finishes, for its welcome', () => {
+ const { rerender } = render(view());
+ auth = { ...auth, isAuthenticated: true, signingIn: true };
+ rerender(view());
+ expect(screen.getByText('Sign in page')).toBeInTheDocument();
+ expect(screen.queryByText('The app')).not.toBeInTheDocument();
+ expect(useShellDialogsStore.getState().connectScreenOpen).toBe(true);
+
+ auth = { ...auth, signingIn: false };
+ rerender(view());
+ expect(screen.getByText('The app')).toBeInTheDocument();
+ expect(mounts).toBe(1);
+ expect(useShellDialogsStore.getState().connectScreenOpen).toBe(false);
+ });
+
it('shows the app when the session is good, and sign-in when it is not', () => {
auth.isAuthenticated = true;
const { rerender } = render(view());
diff --git a/client/src/components/auth/schemas/login.ts b/client/src/components/auth/schemas/login.ts
index 328fd0d5..83aa285e 100644
--- a/client/src/components/auth/schemas/login.ts
+++ b/client/src/components/auth/schemas/login.ts
@@ -1,29 +1,29 @@
import { z } from 'zod';
/**
- * Validation schema for the login / register form.
+ * Validation schema for the login / register form, in the words of the
+ * onboarding handoff (R5).
*
* Mirrors the shape of `credentials/panels/schemas/email.ts` so both forms
- * are validated the same way. Previously this was hand-rolled inside
- * `LoginPage`, which meant email format was never checked client-side --
- * the server uses `EmailStr`, so a malformed address came back as a 422
+ * are validated the same way. Email format is checked here because the
+ * server uses `EmailStr`, so a malformed address would come back as a 422
* whose `detail` is a list of objects rather than a string.
*/
export function createAuthFormSchema(isRegistering: boolean) {
return z.object({
email: z
.string()
- .min(1, 'Email is required')
- .pipe(z.email('Enter a valid email address')),
+ .min(1, 'Enter your email.')
+ .pipe(z.email('That doesn’t look like an email address.')),
password: isRegistering
- ? z.string().min(8, 'Password must be at least 8 characters')
- : z.string().min(1, 'Password is required'),
+ ? z.string().min(1, 'Enter your password.').min(8, 'Use at least 8 characters.')
+ : z.string().min(1, 'Enter your password.'),
// Required only when registering. The 100-character ceiling mirrors the
// `max_length=100` column on `User.display_name`; SQLite truncates
// silently rather than raising, so an over-long name would be accepted
// and then quietly altered.
displayName: isRegistering
- ? z.string().trim().min(1, 'Display name is required').max(100, 'Display name must be 100 characters or fewer')
+ ? z.string().trim().min(1, 'Enter your name.').max(100, 'Use 100 characters or fewer.')
: z.string().optional(),
});
}
diff --git a/client/src/contexts/AuthContext.tsx b/client/src/contexts/AuthContext.tsx
index 2f1de290..36f8f2e9 100644
--- a/client/src/contexts/AuthContext.tsx
+++ b/client/src/contexts/AuthContext.tsx
@@ -31,6 +31,10 @@
* be written into the status cache as `null`, which is a *success* value:
* `isError` stayed false so nothing was ever displayed, and
* `can_register` fell back to false, hiding the Register link entirely.
+ *
+ * `signingIn` is the sign-in requests' own state: in flight, or succeeded
+ * and not yet finished. The gate keeps the sign-in screen up while it is
+ * true, for the welcome; `finishSignIn` returns the requests to idle.
*/
import React, { createContext, useContext, useCallback, useMemo } from 'react';
@@ -60,6 +64,9 @@ interface AuthContextType {
isLoading: boolean;
/** True while a login/register request is in flight. */
isSubmitting: boolean;
+ /** A login/register request is in flight, or succeeded and has not been
+ * finished (`finishSignIn`): the sign-in screen stays up for the welcome. */
+ signingIn: boolean;
authMode: 'single' | 'multi';
canRegister: boolean;
/** Connectivity error from the bootstrap query only. */
@@ -75,6 +82,8 @@ interface AuthContextType {
checkAuth: () => Promise<boolean>;
/** Clear stale submit errors (mode toggle, field edit). */
resetAuthErrors: () => void;
+ /** The welcome after signing in is over: the app takes the screen. */
+ finishSignIn: () => void;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
@@ -118,14 +127,23 @@ const extractErrorMessage = (body: unknown, fallback: string): string => {
return fallback;
};
+/** What a sign-in or registration says when the request never reached the server. */
+export const AUTH_UNREACHABLE = 'Can’t reach OpenCompany. Make sure it’s running, then try again.';
+
/** POST to an auth endpoint, throwing an Error whose message is display-ready. */
const postAuth = async (path: string, payload: unknown): Promise<{ user: User }> => {
- const response = await fetch(`${getApiBase()}${path}`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- credentials: 'include',
- body: JSON.stringify(payload),
- });
+ let response: Response;
+ try {
+ response = await fetch(`${getApiBase()}${path}`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify(payload),
+ });
+ } catch {
+ // fetch rejects only when no response arrived (each browser words it differently).
+ throw new Error(AUTH_UNREACHABLE);
+ }
let body: unknown = null;
if (isJsonResponse(response)) {
@@ -298,12 +316,18 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
return queryClient.getQueryState(AUTH_STATUS_QUERY_KEY)?.status === 'success';
}, [queryClient]);
- const resetAuthErrors = useCallback(() => {
- loginMutation.reset();
- registerMutation.reset();
- }, [loginMutation, registerMutation]);
+ // Both return the sign-in requests to idle: clearing a refusal before the
+ // next try (`resetAuthErrors`), or ending the welcome (`finishSignIn`).
+ // `reset` is stable across renders; the mutation results are not.
+ const { reset: resetLogin } = loginMutation;
+ const { reset: resetRegister } = registerMutation;
+ const resetSignIn = useCallback(() => {
+ resetLogin();
+ resetRegister();
+ }, [resetLogin, resetRegister]);
const isSubmitting = loginMutation.isPending || registerMutation.isPending;
+ const signingIn = isSubmitting || loginMutation.isSuccess || registerMutation.isSuccess;
const submitError =
(loginMutation.error instanceof Error ? loginMutation.error.message : null) ??
(registerMutation.error instanceof Error ? registerMutation.error.message : null);
@@ -314,6 +338,7 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
isAuthenticated,
isLoading,
isSubmitting,
+ signingIn,
authMode,
canRegister,
error,
@@ -323,9 +348,10 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
register,
logout,
checkAuth,
- resetAuthErrors,
- }), [user, isAuthenticated, isLoading, isSubmitting, authMode, canRegister, error,
- submitError, logoutError, login, register, logout, checkAuth, resetAuthErrors]);
+ resetAuthErrors: resetSignIn,
+ finishSignIn: resetSignIn,
+ }), [user, isAuthenticated, isLoading, isSubmitting, signingIn, authMode, canRegister, error,
+ submitError, logoutError, login, register, logout, checkAuth, resetSignIn]);
return (
<AuthContext.Provider value={value}>
diff --git a/client/src/contexts/__tests__/AuthContext.test.tsx b/client/src/contexts/__tests__/AuthContext.test.tsx
index 8e272b2e..9dba0318 100644
--- a/client/src/contexts/__tests__/AuthContext.test.tsx
+++ b/client/src/contexts/__tests__/AuthContext.test.tsx
@@ -22,7 +22,7 @@ import React from 'react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, waitFor, act } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
-import { AuthProvider, useAuth, AUTH_STATUS_QUERY_KEY } from '../AuthContext';
+import { AuthProvider, useAuth, AUTH_STATUS_QUERY_KEY, AUTH_UNREACHABLE } from '../AuthContext';
// Mock the API config so the fetch URL is predictable in test logs.
vi.mock('../../config/api', () => ({
@@ -298,6 +298,7 @@ describe('AuthContext login/register', () => {
await waitFor(() => {
expect(latest().submitError).toBe('Invalid email or password');
});
+ expect(latest().signingIn).toBe(false);
});
it('keeps canRegister true after a failed login', async () => {
@@ -385,6 +386,26 @@ describe('AuthContext login/register', () => {
});
});
+ it('says OpenCompany cannot be reached when a sign-in gets no answer', async () => {
+ // fetch rejects only when no response arrived; each browser words it
+ // differently, so the owner gets one sentence instead.
+ mockAuthEndpoints((url) => {
+ if (url.endsWith('/login')) throw new TypeError('Failed to fetch');
+ return undefined;
+ });
+
+ const { latest } = await mountProbe(makeQueryClient());
+ let returned: boolean | undefined;
+ await act(async () => {
+ returned = await latest().login('[email protected]', 'pw');
+ });
+
+ expect(returned).toBe(false);
+ await waitFor(() => {
+ expect(latest().submitError).toBe(AUTH_UNREACHABLE);
+ });
+ });
+
it('sets the user and clears submitError on a successful login', async () => {
// Stateful on purpose: `onSuccess` writes the user optimistically and then
// invalidates, so /status refetches and is authoritative. A mock that kept
@@ -419,6 +440,32 @@ describe('AuthContext login/register', () => {
});
});
+ it('keeps signingIn up after a sign-in until finishSignIn, for the welcome', async () => {
+ const user = { id: 7, email: '[email protected]', display_name: 'A', is_owner: true };
+ let loggedIn = false;
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {
+ const url = typeof input === 'string' ? input : (input as Request).url;
+ if (url.endsWith('/login')) {
+ loggedIn = true;
+ return json({ success: true, user });
+ }
+ return json({ ...STATUS_BODY, authenticated: loggedIn, user: loggedIn ? user : null });
+ });
+
+ const { latest } = await mountProbe(makeQueryClient());
+ expect(latest().signingIn).toBe(false);
+
+ await act(async () => {
+ await latest().login('[email protected]', 'correct-horse');
+ });
+ await waitFor(() => expect(latest().isAuthenticated).toBe(true));
+ expect(latest().signingIn).toBe(true);
+
+ act(() => latest().finishSignIn());
+ await waitFor(() => expect(latest().signingIn).toBe(false));
+ expect(latest().isAuthenticated).toBe(true);
+ });
+
it('resetAuthErrors clears a stale submit error', async () => {
mockAuthEndpoints((url) =>
url.endsWith('/login') ? json({ detail: 'Invalid email or password' }, 401) : undefined,
diff --git a/client/src/features/home/data/profile.ts b/client/src/features/home/data/profile.ts
index 784d7c73..0292bc4f 100644
--- a/client/src/features/home/data/profile.ts
+++ b/client/src/features/home/data/profile.ts
@@ -37,11 +37,16 @@ export function profileFromSettings(settings: UserSettings | undefined): Profile
};
}
+/** The first word of a full name: "Jordan Lee" is "Jordan". */
+export function firstName(fullName: string): string {
+ return fullName.trim().split(/\s+/)[0] ?? '';
+}
+
/** What agents call the owner: the call name, else the first name. */
export function callName(settings: UserSettings | undefined): string {
const explicit = String(settings?.profile_call_name ?? '').trim();
if (explicit) return explicit;
- return String(settings?.profile_full_name ?? '').trim().split(/\s+/)[0] ?? '';
+ return firstName(String(settings?.profile_full_name ?? ''));
}
export function browserTimezone(): string | null {
diff --git a/docs-internal/authentication.md b/docs-internal/authentication.md
index a63be3dc..7898df76 100644
--- a/docs-internal/authentication.md
+++ b/docs-internal/authentication.md
@@ -150,6 +150,11 @@ interface AuthContextValue {
logout: () => Promise<void>;
/** Check the session again; true when the server answered. */
checkAuth: () => Promise<boolean>;
+ /** A login/register request is in flight, or succeeded and its welcome
+ * is still showing. */
+ signingIn: boolean;
+ /** End the welcome: the requests go back to idle and the app shows. */
+ finishSignIn: () => void;
}
```
@@ -162,11 +167,12 @@ The sign-in gate (onboarding handoff R4), in front of the whole app:
| the server can't be reached (`error`, not signed in) | Connecting (`ConnectingPanel`): a countdown to each check, Try now, "Attempt n", and from the third attempt "Still nothing? Make sure OpenCompany is running." |
| the server answered | "Connected", held `CONNECT_RETRY.CONNECTED_HOLD_MS` (1.5 s, `useHold`) |
| then | sign-in, or the app when the session is good or login is off |
+| a sign-in from the form in flight or just done (`signingIn`) | sign-in, then its welcome (`SignedIn`) until `finishSignIn` |
| signed in, the WebSocket down (`reconnecting` from `useWebSocketActions`) | Connecting over the app (`role="dialog"`, `z-60`); the app stays mounted, `inert` |
-Connecting and sign-in render inside one `ConnectScreen` (the whole window,
-the orb filling it, the logo and the theme button on top), so the orb
-glides from one's slot to the other's. The schedule is `useRetrySchedule`:
+Connecting, sign-in and the welcome render inside one `ConnectScreen` (the
+whole window, the orb filling it, the logo and the theme button on top), so
+the orb glides from one's slot to the other's. The schedule is `useRetrySchedule`:
`CONNECT_RETRY.DELAYS_S` (2, 3, 5, 8, 8 s), each check being `checkAuth`;
over the app the checks are HTTP session checks too, so a session that
expired while the server was away goes to sign-in, and the overlay goes
@@ -175,19 +181,42 @@ base of the chosen family (`shellDialogsStore.connectScreenOpen`, read by
`app/ShellThemeProvider.tsx`).
### Login Page (`client/src/components/auth/LoginPage.tsx`)
+Inside the gate's `ConnectScreen` (onboarding handoff R5): the orb's `login`
+slot above a card that rises in. "Welcome back" or "Create your account", the
+fields ("Your name" when registering, "Email", "Password" with a show/hide
+toggle), Sign in or Create account, and, while `canRegister`, the way to the
+other mode.
- shadcn `Form` composition (react-hook-form + zod), matching `EmailPanel` —
- schema in `components/auth/schemas/login.ts`. `FormControl` supplies
- `aria-invalid` + `aria-describedby` per field; the form is `noValidate` so
- zod is the single validation authority rather than native browser bubbles.
+ schema and the field messages in `components/auth/schemas/login.ts`.
+ `FormControl` supplies `aria-invalid` + `aria-describedby` per field; the
+ form is `noValidate` so zod is the single validation authority rather than
+ native browser bubbles.
- `canRegister` gates the footer link only; the mode itself is local state.
-- **Two error channels, deliberately distinct.** `submitError` is the server's
- own rejection text (wrong password, duplicate email, 429) and takes
- precedence; `error` is a bootstrap-query connectivity failure. Both render in
- a `role="alert"` region.
+- **The card shows one error: what the server said.** `submitError` is the
+ server's own rejection text, shown as it is: `UserAuthService` words it for
+ the owner ("An account with this email already exists.", "This OpenCompany
+ already has its owner. Sign in instead.", a wrong password, a 429). When the
+ request got no answer it is `AUTH_UNREACHABLE` ("Can't reach OpenCompany.
+ Make sure it's running, then try again."). The bootstrap `error` (the server
+ can't be reached at all) is the gate's Connecting screen, so this page never
+ shows it.
- Inputs and the submit button gate on `isSubmitting` (per-request), **not**
`isLoading` (bootstrap query). The latter has always settled by the time this
page renders, so using it disabled nothing and the form accepted unlimited
concurrent submits.
+- The card shakes (`shake` in `lib/motion.ts`) when a field is wrong or the
+ server refuses. The orb follows the form: livelier while a field has focus
+ (`ENERGY.focus`), more with text in it (`ENERGY.typing`), most while the
+ request is out (`ENERGY.generating`).
+- **After signing in** the card gives way to `SignedIn`: "Signed in" or
+ "Account created", "Welcome back, {first name}" (or "Welcome, …" for a new
+ account) and "Opening your team…", and the orb spikes. The gate keeps the
+ screen up while `signingIn` is true, which is the login and register
+ mutations' own state: in flight, or succeeded and not yet finished. The
+ welcome hands over the way a mode switch does (`app/useShellActions.ts`):
+ the screen the app opens on (Home or the editor) loads while the welcome
+ rises in, then `finishSignIn` returns the mutations to idle and the app
+ shows. A session that was already good never sees it.
## Configuration
Environment variables in `.env`:
@@ -381,7 +410,8 @@ useEffect(() => {
| `client/src/config/api.ts` | The backend's base URL (same origin unless `VITE_PYTHON_SERVICE_URL`) |
| `client/src/contexts/AuthContext.tsx` | React auth state: the TanStack Query bootstrap check, `checkAuth` |
| `client/src/lib/connectionConfig.ts` | `CONNECT_RETRY` (the Connecting screen's schedule) and the WebSocket envelope |
-| `client/src/components/auth/LoginPage.tsx` | Login UI |
+| `client/src/components/auth/LoginPage.tsx`, `schemas/login.ts` | Sign in and register, and their messages |
+| `client/src/components/auth/SignedIn.tsx` | The welcome after signing in, until the app is ready |
| `client/src/components/auth/ProtectedRoute.tsx` | The sign-in gate (states above) |
| `client/src/components/auth/ConnectScreen.tsx`, `ConnectingPanel.tsx` | The screen around Connecting and sign-in, and Connecting itself |
| `client/src/components/auth/useRetrySchedule.ts`, `useHold.ts` | The countdown to each check; "Connected" held a moment |
diff --git a/server/services/user_auth.py b/server/services/user_auth.py
index 6271fde5..c7645479 100644
--- a/server/services/user_auth.py
+++ b/server/services/user_auth.py
@@ -30,6 +30,11 @@ logger = logging.getLogger(__name__)
# enumeration oracle on a public, unauthenticated endpoint.
_INVALID_CREDENTIALS = "Invalid email or password"
+# Registration refusals, worded for the owner: the sign-in page shows them as
+# they are.
+_EMAIL_TAKEN = "An account with this email already exists."
+_OWNER_EXISTS = "This OpenCompany already has its owner. Sign in instead."
+
# Compared against when no user matches, so the unknown-email path costs the
# same ~50-300ms of bcrypt as the known-email path. Without it, response time
# alone reveals which addresses are registered.
@@ -124,14 +129,14 @@ class UserAuthService:
await session.execute(select(User).where(User.email == normalized_email))
).scalars().first()
if existing:
- return None, "Email already registered"
+ return None, _EMAIL_TAKEN
user_count = int(
(await session.execute(select(func.count()).select_from(User))).scalar_one()
)
if self.settings.auth_mode != "multi" and user_count > 0:
- return None, "Registration disabled - owner account already exists"
+ return None, _OWNER_EXISTS
is_owner = self.settings.auth_mode == "single" and user_count == 0
@@ -148,7 +153,7 @@ class UserAuthService:
except IntegrityError:
await session.rollback()
logger.info("Registration lost a race on email uniqueness: %s", normalized_email)
- return None, "Email already registered"
+ return None, _EMAIL_TAKEN
await session.refresh(user)
logger.info(f"User registered: {normalized_email} (owner={is_owner})")
diff --git a/server/tests/auth/test_user_auth_service.py b/server/tests/auth/test_user_auth_service.py
index e39cdc65..6b164d3d 100644
--- a/server/tests/auth/test_user_auth_service.py
+++ b/server/tests/auth/test_user_auth_service.py
@@ -34,7 +34,7 @@ class TestRegister:
await _register(user_auth)
user, error = await _register(user_auth, email="[email protected]")
assert user is None
- assert "already exists" in error
+ assert error == "This OpenCompany already has its owner. Sign in instead."
async def test_multi_mode_allows_more_users(self, database):
from services.user_auth import UserAuthService
@@ -58,7 +58,7 @@ class TestRegister:
await _register(user_auth)
user, error = await _register(user_auth, name="Impostor")
assert user is None
- assert error == "Email already registered"
+ assert error == "An account with this email already exists."
async def test_email_is_normalized(self, user_auth):
await _register(user_auth, email=" [email protected] ")