From 07ce6f2238e1f2e32af7dcd7055774b03deef17b Mon Sep 17 00:00:00 2001 From: Dongdong Chen Date: Thu, 26 Nov 2026 03:11:46 +0800 Subject: [PATCH] fix(web): polish login, onboarding gate, setup CTA, and dashboard routes --- apps/web/src/app/route-pages.messages.ts | 2 + apps/web/src/app/router.test.tsx | 42 ++++- apps/web/src/app/router.tsx | 35 +++-- .../teamhub-authentication-runtime.test.ts | 43 +++++ .../src/app/teamhub-authentication-runtime.ts | 4 + apps/web/src/app/teamhub-router.test.tsx | 21 ++- apps/web/src/features/auth/auth.messages.ts | 5 +- .../auth/authentication-return-to.test.ts | 10 ++ .../features/auth/authentication-return-to.ts | 9 +- .../features/auth/teamhub-authentication.ts | 7 +- .../features/auth/teamhub-login-page.test.tsx | 59 ++++++- .../src/features/auth/teamhub-login-page.tsx | 53 ++++++- .../computer-app-setup-dialog.tsx | 4 +- .../local-computer/computer-detail.test.tsx | 10 +- .../local-computer/computer-platform.tsx | 82 ++++++++-- .../computer-setup-instructions.test.tsx | 15 +- .../local-computer/computer-setup.messages.ts | 1 - .../local-computer/computers.messages.ts | 7 + .../connect-computer-page.test.tsx | 25 +++ .../local-computer/connect-computer-page.tsx | 46 ++++-- .../local-computer/desktop-computer-setup.tsx | 7 +- .../local-computer-gate.test.tsx | 104 +++++++++++++ .../local-computer/local-computer-gate.tsx | 141 ++++++++++++++--- .../features/rooms/cards/cards.messages.ts | 5 + .../decision-profile-setup-view.test.tsx | 34 +++- .../cards/decision-profile-setup-view.tsx | 88 ++++++++--- apps/web/src/features/rooms/room-shell.tsx | 2 +- .../src/features/rooms/route-layout-key.ts | 2 +- .../src/features/search/search-shortcut.ts | 9 +- apps/web/src/features/teamhub/teamhub-api.ts | 6 +- .../work-items/work-item-detail-drawer.tsx | 27 +++- .../features/work-items/work-item-routes.ts | 6 +- .../work-items/work-items-language.test.tsx | 6 +- .../work-items/work-items-page.test.tsx | 147 ++++++++++++++++-- .../features/work-items/work-items-page.tsx | 144 ++++++++++++----- .../work-items/work-items.messages.ts | 5 + apps/web/src/i18n/locales/zh-CN.json | 17 +- 37 files changed, 1041 insertions(+), 189 deletions(-) diff --git a/apps/web/src/app/route-pages.messages.ts b/apps/web/src/app/route-pages.messages.ts index 2fb3b975a..a0e6a0292 100644 --- a/apps/web/src/app/route-pages.messages.ts +++ b/apps/web/src/app/route-pages.messages.ts @@ -2,8 +2,10 @@ import { defineMessages } from "@/i18n/messages"; /** Pages a route falls back to: the unknown address and the loading error. */ export const routePagesMessages = defineMessages("routePages", { + loadingLinger: "Loading Linger…", notFoundTitle: "Page not found", openMessages: "Open Messages", + goToLogin: "Go to Log in", loadingError: "TeamHub loading error", rooms: "Rooms", roomNavigation: "Room navigation", diff --git a/apps/web/src/app/router.test.tsx b/apps/web/src/app/router.test.tsx index 0b83782cb..aa541b658 100644 --- a/apps/web/src/app/router.test.tsx +++ b/apps/web/src/app/router.test.tsx @@ -76,7 +76,7 @@ describe("Web app route contract", () => { "rooms/:roomId", "chat", "profile", - "dashboard/:workItemId", + "dashboard/:workItemId?", "documents/:documentId", "settings", "account", @@ -87,23 +87,57 @@ describe("Web app route contract", () => { ); }); - it("keeps Work Item links and Room chat reachable", () => { + it("keeps Work Item links, bare Dashboard, and Room chat reachable", () => { const routes = createAppRoutes( new QueryClient(), createTestTeamHubRuntime(), ); expect( matchRoutes(routes, "/t/tenant-a/dashboard")?.at(-1)?.route.path, - ).toBe("*"); + ).toBe("dashboard/:workItemId?"); expect( matchRoutes(routes, "/t/tenant-a/dashboard/work-item-a")?.at(-1)?.route .path, - ).toBe("dashboard/:workItemId"); + ).toBe("dashboard/:workItemId?"); expect( matchRoutes(routes, "/t/tenant-a/rooms/room-a/chat")?.at(-1)?.route.path, ).toBe("chat"); }); + it("redirects /t/:tenantId 401 failures to /login with reason=session-expired and return_to", async () => { + const runtime = createTestTeamHubRuntime(); + runtime.server.on("GET", "/v0/session", () => + teamHubErrorResponse(401, "UNAUTHENTICATED", "Sign in required"), + ); + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + const tenantLoader = createAppRoutes(queryClient, runtime).find( + (route) => route.path === "/t/:tenantId", + )!.loader as LoaderFunction; + let thrown: unknown; + try { + await tenantLoader({ + context: new RouterContextProvider(), + params: { tenantId: "tenant-northstar" }, + pattern: "/t/:tenantId", + request: new Request( + "http://localhost/t/tenant-northstar/dashboard?room=room-all", + ), + url: new URL( + "http://localhost/t/tenant-northstar/dashboard?room=room-all", + ), + }); + } catch (error) { + thrown = error; + } + expect(thrown).toBeInstanceOf(Response); + expect((thrown as Response).headers.get("Location")).toBe( + `/login?reason=session-expired&return_to=${encodeURIComponent("/t/tenant-northstar/dashboard?room=room-all")}`, + ); + queryClient.clear(); + }); + it("mounts My Documents, Shared with me, and Wiki below Library", () => { const tenantRoute = createAppRoutes( new QueryClient({ defaultOptions: { queries: { retry: false } } }), diff --git a/apps/web/src/app/router.tsx b/apps/web/src/app/router.tsx index 506f3a0ac..5b5c85d3d 100644 --- a/apps/web/src/app/router.tsx +++ b/apps/web/src/app/router.tsx @@ -47,7 +47,6 @@ import { type TeamHubClient, } from "@/features/teamhub/teamhub-client"; import type { TeamHubRuntime } from "@/features/teamhub/teamhub-runtime"; -import { commonMessages } from "@/i18n/common.messages"; import { translate } from "@/i18n/language"; import { useT } from "@/i18n/use-translation"; import { @@ -150,8 +149,13 @@ export function createAppRoutes( }), path: "/login", }, - { lazy: loadSharedDocumentPage, path: "/shared-documents" }, { + HydrateFallback: InitialAppLoading, + lazy: loadSharedDocumentPage, + path: "/shared-documents", + }, + { + HydrateFallback: InitialAppLoading, path: "/shared-room-history", lazy: async () => { const { SharedRoomHistoryPage } = @@ -165,6 +169,7 @@ export function createAppRoutes( }, { ErrorBoundary: FullPageRouteErrorSurface, + HydrateFallback: InitialAppLoading, lazy: () => authenticationOperation( new AbortController().signal, @@ -294,7 +299,7 @@ export function createAppRoutes( createWorkItemDashboardRoute( queryClient, client, - "dashboard/:workItemId", + "dashboard/:workItemId?", ), createWorkspaceRoute(), { @@ -337,7 +342,13 @@ export function createAppRoutes( ]); } catch (error) { request.signal.throwIfAborted(); - redirectAuthenticationError(error, queryClient); + const current = new URL(request.url); + const returnTo = `${current.pathname}${current.search}`; + redirectAuthenticationError( + error, + queryClient, + `/login?reason=session-expired&return_to=${encodeURIComponent(returnTo)}`, + ); throw error; } @@ -355,7 +366,7 @@ export function createAppRoutes( function createWorkItemDashboardRoute( queryClient: QueryClient, client: TeamHubClient, - path: "dashboard/:workItemId", + path: "dashboard/:workItemId?", ): RouteObject { return { ErrorBoundary: PanelRouteErrorSurface, @@ -788,11 +799,11 @@ export function InitialAppLoading() { return (
- {t(commonMessages.loadingRoom)} + {t(routePagesMessages.loadingLinger)}
); } @@ -820,10 +831,16 @@ function NotFoundRoute({ inShell = false }: { inShell?: boolean }) {

{t(routePagesMessages.notFoundTitle)}

); diff --git a/apps/web/src/app/teamhub-authentication-runtime.test.ts b/apps/web/src/app/teamhub-authentication-runtime.test.ts index ba703433c..5c2994ef6 100644 --- a/apps/web/src/app/teamhub-authentication-runtime.test.ts +++ b/apps/web/src/app/teamhub-authentication-runtime.test.ts @@ -226,4 +226,47 @@ describe("TeamHub authentication runtime", () => { expect(navigate).toHaveBeenCalledWith("/", { replace: true }); stop(); }); + + it("redirects an unauthenticated root entry to /login without session-expired", () => { + const navigate = vi.fn(); + const signals = createTeamHubAuthenticationSignals({ + channelFactory: () => null, + }); + const stop = startTeamHubAuthenticationRuntime({ + currentLocation: () => ({ pathname: "/", search: "" }), + navigate, + queryClient: new QueryClient(), + signals, + }); + + signals.publish("authentication-required", "session-expired"); + + expect(navigate).toHaveBeenCalledWith("/login", { replace: true }); + stop(); + }); + + it("preserves a Tenant deep link when an authenticated session expires", () => { + const navigate = vi.fn(); + const signals = createTeamHubAuthenticationSignals({ + channelFactory: () => null, + }); + const deepLink = "/t/tenant-northstar/dashboard?room=room-all"; + const stop = startTeamHubAuthenticationRuntime({ + currentLocation: () => ({ + pathname: "/t/tenant-northstar/dashboard", + search: "?room=room-all", + }), + navigate, + queryClient: new QueryClient(), + signals, + }); + + signals.publish("authentication-required", "session-expired"); + + expect(navigate).toHaveBeenCalledWith( + `/login?reason=session-expired&return_to=${encodeURIComponent(deepLink)}`, + { replace: true }, + ); + stop(); + }); }); diff --git a/apps/web/src/app/teamhub-authentication-runtime.ts b/apps/web/src/app/teamhub-authentication-runtime.ts index 5b23c8af5..e0fadefb3 100644 --- a/apps/web/src/app/teamhub-authentication-runtime.ts +++ b/apps/web/src/app/teamhub-authentication-runtime.ts @@ -28,6 +28,10 @@ export function startTeamHubAuthenticationRuntime({ const invalidate = (reason: TeamHubAuthenticationReason) => { clearLocalAuthenticatedState(queryClient); const location = currentLocation?.(); + if (location?.pathname === "/") { + void navigate("/login", { replace: true }); + return; + } const returnTo = location ? safeAuthenticationReturnTo( location.pathname === "/login" diff --git a/apps/web/src/app/teamhub-router.test.tsx b/apps/web/src/app/teamhub-router.test.tsx index 380fad885..9aa95fcb9 100644 --- a/apps/web/src/app/teamhub-router.test.tsx +++ b/apps/web/src/app/teamhub-router.test.tsx @@ -613,7 +613,7 @@ describe("TeamHub routes", () => { expect(screen.getByRole("button", { name: "Open Messages" })).toBeVisible(); }); - it("renders the in-shell not-found page for bare /t/:tenantId/dashboard", async () => { + it("renders the Dashboard page for bare /t/:tenantId/dashboard", async () => { const runtime = createTestTeamHubRuntime(); const queryClient = testQueryClient(); const router = createMemoryRouter(createAppRoutes(queryClient, runtime), { @@ -622,10 +622,27 @@ describe("TeamHub routes", () => { renderApp(queryClient, runtime, router); + expect( + await screen.findByRole("heading", { name: "Fixture Dashboard" }), + ).toBeVisible(); + }); + + it("offers Go to Log in on signed-out unknown paths", async () => { + const runtime = createTestTeamHubRuntime(); + const queryClient = testQueryClient(); + const router = createMemoryRouter(createAppRoutes(queryClient, runtime), { + initialEntries: ["/no-such-page"], + }); + + renderApp(queryClient, runtime, router); + expect( await screen.findByRole("heading", { name: "Page not found" }), ).toBeVisible(); - expect(screen.getByRole("button", { name: "Open Messages" })).toBeVisible(); + expect(screen.getByRole("button", { name: "Go to Log in" })).toBeVisible(); + expect( + screen.queryByRole("button", { name: "Open Messages" }), + ).not.toBeInTheDocument(); }); it("preloads the Room chat chunk from /, /t/:tenantId/rooms, and /t/:tenantId/rooms/:roomId loaders", async () => { diff --git a/apps/web/src/features/auth/auth.messages.ts b/apps/web/src/features/auth/auth.messages.ts index a0d257fdb..7fe9ca68a 100644 --- a/apps/web/src/features/auth/auth.messages.ts +++ b/apps/web/src/features/auth/auth.messages.ts @@ -11,8 +11,9 @@ export const authMessages = defineMessages("auth", { showPassword: "Show password", hidePassword: "Hide password", signIn: "Sign in", - logIn: "Log in", - working: "Working...", + invalidCredentials: + "Incorrect email or password. Check your credentials and try again.", + accessHelp: "Need access or a password reset? Contact your workspace admin.", artTitleFirst: "Your personal AI.", artTitleSecond: "A step ahead.", artLede: diff --git a/apps/web/src/features/auth/authentication-return-to.test.ts b/apps/web/src/features/auth/authentication-return-to.test.ts index 72fdc7f4f..bdb926e88 100644 --- a/apps/web/src/features/auth/authentication-return-to.test.ts +++ b/apps/web/src/features/auth/authentication-return-to.test.ts @@ -5,10 +5,20 @@ const setup = "/connect-computer?code_challenge=challenge&state=state"; it("preserves a same-origin Local Computer setup path after authentication", () => { expect(safeAuthenticationReturnTo(setup)).toBe(setup); }); +it("preserves a same-origin Tenant Space path with query parameters", () => { + expect( + safeAuthenticationReturnTo("/t/tenant-northstar/dashboard?room=room-all"), + ).toBe("/t/tenant-northstar/dashboard?room=room-all"); + expect( + safeAuthenticationReturnTo("/t/tenant-northstar/rooms/room-all/chat"), + ).toBe("/t/tenant-northstar/rooms/room-all/chat"); +}); it.each([ `https://evil.example${setup}`, `//evil.example${setup}`, + "//evil.example/t/tenant-northstar/rooms", `${setup}#token`, + "/t/tenant-northstar/rooms#fragment", "/connect-computer", "/rooms/room_private", ])("rejects unsafe or unsupported return paths: %s", (value) => { diff --git a/apps/web/src/features/auth/authentication-return-to.ts b/apps/web/src/features/auth/authentication-return-to.ts index f7d19f0eb..6e42f590b 100644 --- a/apps/web/src/features/auth/authentication-return-to.ts +++ b/apps/web/src/features/auth/authentication-return-to.ts @@ -1,4 +1,5 @@ -// Destination for signed-in users leaving the login page: only allowlisted local setup paths are accepted; anything else goes to the home page. +// Destination for signed-in users leaving the login page: only allowlisted +// local setup and Space paths are accepted; anything else goes to the home page. export function authenticatedLoginDestination( searchParams: URLSearchParams, ): string { @@ -9,6 +10,7 @@ export function safeAuthenticationReturnTo( value: string | null, ): string | null { if (!value || value.length > 2_048) return null; + if (!value.startsWith("/") || value.startsWith("//")) return null; let target: URL; try { target = new URL(value, "http://localhost"); @@ -18,5 +20,8 @@ export function safeAuthenticationReturnTo( if (target.origin !== "http://localhost" || target.hash !== "") return null; const computerSetup = target.pathname === "/connect-computer" && target.search.length > 1; - return computerSetup ? `${target.pathname}${target.search}` : null; + const tenantSpace = /^\/t\/[^/]+(?:\/.*)?$/u.test(target.pathname); + return computerSetup || tenantSpace + ? `${target.pathname}${target.search}` + : null; } diff --git a/apps/web/src/features/auth/teamhub-authentication.ts b/apps/web/src/features/auth/teamhub-authentication.ts index b70296338..948b77cd2 100644 --- a/apps/web/src/features/auth/teamhub-authentication.ts +++ b/apps/web/src/features/auth/teamhub-authentication.ts @@ -188,6 +188,11 @@ export function useTeamHubAuthentication(input: { } function readAuthenticationError(error: unknown) { - if (error instanceof TeamHubError) return error.message; + if (error instanceof TeamHubError) { + if (error.code === "INVALID_CREDENTIALS") { + return translate(m.invalidCredentials); + } + return error.message; + } return translate(m.teamHubUnreachable); } diff --git a/apps/web/src/features/auth/teamhub-login-page.test.tsx b/apps/web/src/features/auth/teamhub-login-page.test.tsx index eb01929a3..62b72cd5a 100644 --- a/apps/web/src/features/auth/teamhub-login-page.test.tsx +++ b/apps/web/src/features/auth/teamhub-login-page.test.tsx @@ -379,15 +379,70 @@ describe("TeamHubLoginPage", () => { ); }); - it("explains when the current Session expired", () => { + it("explains when the current Session expired and clears it on credential edit or failed submit", async () => { renderAuthenticationPage( - {}, + { + login: () => + teamHubErrorResponse( + 401, + "INVALID_CREDENTIALS", + "email or password is incorrect", + ), + }, { initialEntry: "/login?reason=session-expired" }, ); expect(screen.getByRole("alert")).toHaveTextContent( "Your session has expired. Sign in again to continue.", ); + + // Editing credentials dismisses the expired-session notice so two alerts never stack. + fillSignIn(); + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); + + fireEvent.click(screen.getByRole("button", { name: "Sign in" })); + const alerts = await screen.findAllByRole("alert"); + expect(alerts).toHaveLength(1); + expect(alerts[0]).toHaveTextContent( + "Incorrect email or password. Check your credentials and try again.", + ); + }); + + it("matches submit button visible label to accessible name, focuses email, and shows access help", () => { + renderAuthenticationPage({}); + + const submit = screen.getByRole("button", { name: "Sign in" }); + expect(submit).toHaveTextContent("Sign in"); + expect(submit).not.toHaveAttribute("aria-label"); + expect(screen.getByLabelText("Email")).toHaveFocus(); + expect( + screen.getByText( + "Need access or a password reset? Contact your workspace admin.", + ), + ).toBeVisible(); + }); + + it("returns to a deep-linked Tenant path after signing in", async () => { + const returnTo = "/t/tenant-northstar/dashboard?room=room-all"; + renderAuthenticationPage( + { + login: () => ({ + id: "session-1", + identity: { actors: [{ tenant_id: "tenant-northstar" }] }, + }), + }, + { + initialEntry: `/login?reason=session-expired&return_to=${encodeURIComponent(returnTo)}`, + showLocation: true, + }, + ); + + fillSignIn(); + fireEvent.click(screen.getByRole("button", { name: "Sign in" })); + + await waitFor(() => + expect(screen.getByTestId("location")).toHaveTextContent(returnTo), + ); }); }); diff --git a/apps/web/src/features/auth/teamhub-login-page.tsx b/apps/web/src/features/auth/teamhub-login-page.tsx index 4eb1a9197..a647ec0f5 100644 --- a/apps/web/src/features/auth/teamhub-login-page.tsx +++ b/apps/web/src/features/auth/teamhub-login-page.tsx @@ -4,7 +4,7 @@ import { ViewIcon, ViewOffIcon, } from "@hugeicons/core-free-icons"; -import { useState } from "react"; +import { useEffect, useRef, useState } from "react"; import { useSearchParams } from "react-router"; import { Button } from "@/components/ui/button"; @@ -40,8 +40,15 @@ export function TeamHubLoginPage({ }); const localAccount = useDesktopLocalAccount(); const t = useT(); + const reason = searchParams.get("reason"); + const [dismissedReason, setDismissedReason] = useState(null); + const dismissNotice = () => { + if (reason) setDismissedReason(reason); + }; const authenticationNotice = - searchParams.get("reason") === "session-expired" + reason === "session-expired" && + dismissedReason !== reason && + !authentication.state.error ? t(m.sessionExpired) : null; @@ -56,9 +63,14 @@ export function TeamHubLoginPage({ ) : null} - + ); } @@ -66,9 +78,11 @@ export function TeamHubLoginPage({ function LocalAccountSignIn({ account, authentication, + onAttempt, }: { account: DesktopLocalAccount; authentication: AuthenticationController; + onAttempt: () => void; }) { const t = useT(); return ( @@ -77,6 +91,7 @@ function LocalAccountSignIn({ className="w-full" disabled={authentication.state.isSubmitting} onClick={() => { + onAttempt(); void authentication.signInWithDesktopAccount(account); }} size="large" @@ -97,25 +112,42 @@ function LocalAccountSignIn({ function AuthenticationForm({ authentication, + autoFocusEmail, + onInteract, }: { authentication: AuthenticationController; + autoFocusEmail: boolean; + onInteract: () => void; }) { const { email, error, isSubmitting, password } = authentication.state; const { changeField, handleSubmit } = authentication; + const formRef = useRef(null); const t = useT(); + useEffect(() => { + if (!autoFocusEmail) return; + formRef.current + ?.querySelector('input[type="email"]') + ?.focus(); + }, [autoFocusEmail]); + return (
{ + onInteract(); void handleSubmit(event); }} + ref={formRef} > changeField("email", event.target.value)} + onChange={(event) => { + onInteract(); + changeField("email", event.target.value); + }} placeholder="you@company.com" type="email" value={email} @@ -123,21 +155,26 @@ function AuthenticationForm({ changeField("password", value)} + onChange={(value) => { + onInteract(); + changeField("password", value); + }} value={password} /> {error ? {error} : null} +

+ {t(m.accessHelp)} +

); } diff --git a/apps/web/src/features/local-computer/computer-app-setup-dialog.tsx b/apps/web/src/features/local-computer/computer-app-setup-dialog.tsx index dd3b6e187..acc412770 100644 --- a/apps/web/src/features/local-computer/computer-app-setup-dialog.tsx +++ b/apps/web/src/features/local-computer/computer-app-setup-dialog.tsx @@ -356,11 +356,11 @@ export function CommandLine({ const commandRef = useRef(null); return (
{command} diff --git a/apps/web/src/features/local-computer/computer-detail.test.tsx b/apps/web/src/features/local-computer/computer-detail.test.tsx index f2595e4ed..cfe3d497e 100644 --- a/apps/web/src/features/local-computer/computer-detail.test.tsx +++ b/apps/web/src/features/local-computer/computer-detail.test.tsx @@ -50,11 +50,13 @@ it("uses the target Computer platform for the required update", () => { />, ); fireEvent.click(screen.getAllByRole("button", { name: "Update" })[0]!); - expect(screen.getByRole("combobox")).toHaveValue(""); + const radios = screen.getAllByRole("radio"); + expect(radios).toHaveLength(3); + for (const radio of radios) { + expect(radio).toHaveAttribute("aria-checked", "false"); + } expect(screen.queryByText(/linger-computer.ps1/)).not.toBeInTheDocument(); - fireEvent.change(screen.getByRole("combobox"), { - target: { value: "linux" }, - }); + fireEvent.click(screen.getByRole("radio", { name: "Linux" })); expect(screen.getByText(/curl -fsSL/)).toBeVisible(); }); diff --git a/apps/web/src/features/local-computer/computer-platform.tsx b/apps/web/src/features/local-computer/computer-platform.tsx index 08e402614..321fb582f 100644 --- a/apps/web/src/features/local-computer/computer-platform.tsx +++ b/apps/web/src/features/local-computer/computer-platform.tsx @@ -1,9 +1,19 @@ +import { useId, useRef } from "react"; + import { useT } from "@/i18n/use-translation"; +import { cn } from "@/lib/cn"; import { computerSetupMessages } from "./computer-setup.messages"; export type ComputerPlatform = "darwin" | "linux" | "win32"; +const PLATFORM_OPTIONS: readonly { label: string; value: ComputerPlatform }[] = + [ + { label: "macOS", value: "darwin" }, + { label: "Windows", value: "win32" }, + { label: "Linux", value: "linux" }, + ]; + export function browserComputerPlatform(): ComputerPlatform { const platform = navigator.platform || navigator.userAgent; if (/windows|^win(?:32|64)/i.test(platform)) return "win32"; @@ -59,21 +69,65 @@ export function ComputerPlatformSelector({ onChange: (platform: ComputerPlatform) => void; }) { const t = useT(); + const labelId = useId(); + const buttonRefs = useRef>([]); + const activeIndex = PLATFORM_OPTIONS.findIndex( + (option) => option.value === value, + ); + + function selectIndex(index: number) { + const nextIndex = + (index + PLATFORM_OPTIONS.length) % PLATFORM_OPTIONS.length; + onChange(PLATFORM_OPTIONS[nextIndex]!.value); + buttonRefs.current[nextIndex]?.focus(); + } + return ( - + {PLATFORM_OPTIONS.map((option, index) => { + const checked = value === option.value; + const focusable = checked || (activeIndex < 0 && index === 0); + return ( + + ); + })} +
+ ); } diff --git a/apps/web/src/features/local-computer/computer-setup-instructions.test.tsx b/apps/web/src/features/local-computer/computer-setup-instructions.test.tsx index 2d93280b8..43f03900a 100644 --- a/apps/web/src/features/local-computer/computer-setup-instructions.test.tsx +++ b/apps/web/src/features/local-computer/computer-setup-instructions.test.tsx @@ -22,9 +22,11 @@ describe("CopyValueButton", () => { const writeText = vi.fn().mockResolvedValue(undefined); setClipboard({ writeText }); render(); - fireEvent.change( - screen.getByRole("combobox", { name: "Computer operating system" }), - { target: { value: "win32" } }, + const platformGroup = screen.getByRole("radiogroup", { + name: "Computer operating system", + }); + fireEvent.click( + within(platformGroup).getByRole("radio", { name: "Windows" }), ); expect(screen.getByText(/Run these commands in PowerShell/)).toBeVisible(); fireEvent.click( @@ -41,9 +43,12 @@ describe("CopyValueButton", () => { it("initially selects Windows for a Windows browser", () => { vi.spyOn(navigator, "platform", "get").mockReturnValue("Win32"); render(); + const platformGroup = screen.getByRole("radiogroup", { + name: "Computer operating system", + }); expect( - screen.getByRole("combobox", { name: "Computer operating system" }), - ).toHaveValue("win32"); + within(platformGroup).getByRole("radio", { name: "Windows" }), + ).toHaveAttribute("aria-checked", "true"); expect(screen.getByText(/linger-computer.ps1/)).toBeVisible(); }); diff --git a/apps/web/src/features/local-computer/computer-setup.messages.ts b/apps/web/src/features/local-computer/computer-setup.messages.ts index 6b0dbe8b0..73ca4b325 100644 --- a/apps/web/src/features/local-computer/computer-setup.messages.ts +++ b/apps/web/src/features/local-computer/computer-setup.messages.ts @@ -18,7 +18,6 @@ export const computerSetupMessages = defineMessages("computerSetup", { checkingNew: "Checking for a new Local Computer...", checkingOnline: "Checking for an online Local Computer...", operatingSystem: "Computer operating system", - chooseOperatingSystem: "Choose operating system", copyCommand: "Copy command", commandCopied: "Command copied", commandSelected: "Command selected", diff --git a/apps/web/src/features/local-computer/computers.messages.ts b/apps/web/src/features/local-computer/computers.messages.ts index 9bac854b5..5b125b025 100644 --- a/apps/web/src/features/local-computer/computers.messages.ts +++ b/apps/web/src/features/local-computer/computers.messages.ts @@ -159,12 +159,15 @@ export const computersMessages = defineMessages("computers", { keepCurrentSetup: "Keep current setup", replaceLocalIdentity: "Replace local identity", connectFailed: "The Computer could not be connected. Run setup again.", + connectFailedGuidance: + "Try connecting again below, or return to your terminal and re-run login.", signingOut: "Signing out...", useAnotherAccount: "Use another account", connectingRequest: "Connecting...", reconnectComputer: "Reconnect computer", invalidRequestTitle: "Connection request is invalid", invalidRequestBody: "Return to the terminal and run setup again.", + backToLinger: "Back to Linger", couldNotConnect: "Could not connect", // The gate shown until a Computer can run Another Me. @@ -173,6 +176,10 @@ export const computersMessages = defineMessages("computers", { gateIntro: "Your Agents run on your own computer with Claude Code, Codex or Pi. Connect one to start.", gateReady: "Your computer is ready. Creating your Another Me...", + gateReadySlow: + "Setting up Another Me is taking longer than usual. Retry to check again.", + gateLoadError: + "Couldn't check your computer status right now. Retry to continue.", installTheCli: "Install the CLI", setUpAiApp: "Set up an AI app", availableOnceOnline: "Available once your computer is online.", diff --git a/apps/web/src/features/local-computer/connect-computer-page.test.tsx b/apps/web/src/features/local-computer/connect-computer-page.test.tsx index e2ad00cd0..f6e7b434b 100644 --- a/apps/web/src/features/local-computer/connect-computer-page.test.tsx +++ b/apps/web/src/features/local-computer/connect-computer-page.test.tsx @@ -80,9 +80,34 @@ describe("ConnectComputerPage", () => { name: "Connection request is invalid", }), ).toBeVisible(); + expect( + screen.getByRole("link", { name: "Back to Linger" }), + ).toHaveAttribute("href", "/"); expect(createEnrollment).not.toHaveBeenCalled(); }); + it("shows actionable retry guidance when enrollment fails", async () => { + const runtime = createTestTeamHubRuntime(); + serveEnrollment(runtime, () => + teamHubErrorResponse(500, "INTERNAL_ERROR", "Server failed"), + ); + + renderPage(runtime, vi.fn(), validConnectPath()); + const connectButton = await screen.findByRole("button", { + name: "Connect computer", + }); + await waitFor(() => expect(connectButton).toBeEnabled()); + fireEvent.click(connectButton); + + const alert = await screen.findByRole("alert"); + expect(alert).toHaveTextContent( + "The Computer could not be connected. Run setup again.", + ); + expect(alert).toHaveTextContent( + "Try connecting again below, or return to your terminal and re-run login.", + ); + }); + it("forwards an existing Computer identity for owner-authorized renewal", async () => { const runtime = createTestTeamHubRuntime(); diff --git a/apps/web/src/features/local-computer/connect-computer-page.tsx b/apps/web/src/features/local-computer/connect-computer-page.tsx index c0a705370..7dd2e38d6 100644 --- a/apps/web/src/features/local-computer/connect-computer-page.tsx +++ b/apps/web/src/features/local-computer/connect-computer-page.tsx @@ -7,9 +7,10 @@ import { import { Icon } from "@/components/ui/icon"; import { useMutation, useQuery } from "@tanstack/react-query"; import { useMemo, useState } from "react"; -import { useLocation, useSearchParams } from "react-router"; +import { Link, useLocation, useSearchParams } from "react-router"; -import { Button } from "@/components/ui/button"; +import { BrandMark } from "@/components/ui/brand-mark"; +import { Button, buttonClassName } from "@/components/ui/button"; import { Select, SelectItem } from "@/components/ui/select"; import { authMessages } from "@/features/auth/auth.messages"; import { useLogout } from "@/features/auth/use-logout"; @@ -20,6 +21,7 @@ import { import { teamHubData } from "@/features/teamhub/teamhub-api"; import { TeamHubError } from "@/features/teamhub/teamhub-error"; import { useTeamHubRuntime } from "@/features/teamhub/teamhub-runtime"; +import { translate } from "@/i18n/language"; import { RichMessage, useT } from "@/i18n/use-translation"; import { computerSetupMessages } from "./computer-setup.messages"; @@ -61,7 +63,7 @@ export function ConnectComputerPage({ const enrollment = useMutation({ mutationFn: async () => { if (!request || !selectedTenant) { - throw new Error("Connection request is unavailable."); + throw new Error(translate(computersMessages.invalidRequestTitle)); } return await teamHubData( client.api.POST("/v0/tenants/{tenantId}/local-computer-enrollments", { @@ -246,12 +248,21 @@ export function ConnectComputerPage({ ) : enrollment.error ? ( -

- {t(computersMessages.connectFailed)} -

+

+ {t(computersMessages.connectFailed)} +

+ {enrollment.error instanceof TeamHubError && + enrollment.error.message ? ( +

{enrollment.error.message}

+ ) : null} +

+ {t(computersMessages.connectFailedGuidance)} +

+ ) : null} {switchAccount.error ? ( @@ -304,13 +315,24 @@ const requiresLocalIdentityReplacement = (error: unknown): boolean => function InvalidConnectionRequest() { const t = useT(); return ( -
-
-

{t(computersMessages.invalidRequestTitle)}

-

+

+
+ +

+ {t(computersMessages.invalidRequestTitle)} +

+

{t(computersMessages.invalidRequestBody)}

-
+
+ + {t(computersMessages.backToLinger)} + +
+
); } diff --git a/apps/web/src/features/local-computer/desktop-computer-setup.tsx b/apps/web/src/features/local-computer/desktop-computer-setup.tsx index 7e637e039..6f8002543 100644 --- a/apps/web/src/features/local-computer/desktop-computer-setup.tsx +++ b/apps/web/src/features/local-computer/desktop-computer-setup.tsx @@ -48,9 +48,12 @@ export function DesktopComputerSetup({ const problem = desktopSetupProblem(desktop.status); if (problem) { return ( -

+

{t(problem)} -

+
); } return ( diff --git a/apps/web/src/features/local-computer/local-computer-gate.test.tsx b/apps/web/src/features/local-computer/local-computer-gate.test.tsx index 4c58c6db9..c357acbb9 100644 --- a/apps/web/src/features/local-computer/local-computer-gate.test.tsx +++ b/apps/web/src/features/local-computer/local-computer-gate.test.tsx @@ -24,6 +24,7 @@ import { RoomShell } from "@/features/rooms/room-shell"; import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime"; import type { TeamHubLocalComputerPage } from "@/features/teamhub/teamhub-types"; import { createTestTeamHubRuntime } from "@/test/teamhub-test-runtime"; +import { teamHubErrorResponse } from "@/test/teamhub-test-server"; type LocalComputer = TeamHubLocalComputerPage["items"][number]; @@ -316,6 +317,109 @@ describe("Local Computer gate", () => { within(gate).getAllByText("The npm commands need Node.js."), ).toHaveLength(1); }); + + it("wraps install commands, uses a segmented OS selector, exposes Settings & language, and blocks Cmd+K while gated", async () => { + const fixture = await renderShell(); + + const gate = await screen.findByRole("dialog", { + name: "Connect your computer", + }); + const platformGroup = within(gate).getByRole("radiogroup", { + name: "Computer operating system", + }); + expect( + within(platformGroup).getByRole("radio", { name: "macOS" }), + ).toBeVisible(); + expect( + within(platformGroup).getByRole("radio", { name: "Windows" }), + ).toBeVisible(); + expect( + within(platformGroup).getByRole("radio", { name: "Linux" }), + ).toBeVisible(); + + const installCode = within(gate).getByText(/install\/linger-computer\.sh/); + expect(installCode).toHaveClass("whitespace-pre-wrap", "break-all"); + + fireEvent.click( + within(platformGroup).getByRole("radio", { name: "Windows" }), + ); + expect(within(gate).getByText(/install\/linger-computer\.ps1/)).toHaveClass( + "whitespace-pre-wrap", + "break-all", + ); + + // Global Cmd+K shortcut must not open Search while gated. + fireEvent.keyDown(window, { key: "k", metaKey: true }); + expect(screen.queryByRole("dialog", { name: "Search" })).toBeNull(); + + // Footer includes a Settings escape and language switcher alongside Sign out. + expect( + within(gate).getByRole("button", { name: "Interface language" }), + ).toBeVisible(); + fireEvent.click(within(gate).getByRole("link", { name: "Settings" })); + await waitFor(() => + expect(fixture.router.state.location.pathname).toBe( + "/t/tenant-northstar/settings/account", + ), + ); + }); + + it("shows a retryable alert when computer status fails to load", async () => { + const fixture = await renderShell(); + let fail = true; + fixture.runtime.server.on( + "GET", + "/v0/tenants/{tenantId}/local-computers", + () => + fail + ? teamHubErrorResponse(503, "TEAMHUB_UNAVAILABLE", "Unavailable") + : { items: [] }, + ); + await act(() => + fixture.queryClient.invalidateQueries({ + queryKey: ["teamhub", "local-computers", "tenant-northstar"], + }), + ); + + const gate = await screen.findByRole("dialog", { + name: "Connect your computer", + }); + const alert = await within(gate).findByRole("alert"); + expect(alert).toHaveTextContent( + "Couldn't check your computer status right now. Retry to continue.", + ); + + fail = false; + fireEvent.click(within(alert).getByRole("button", { name: "Retry" })); + await waitFor(() => + expect(within(gate).queryByRole("alert")).not.toBeInTheDocument(), + ); + }); + + it("offers Retry when creating Another Me stalls past 30 seconds", async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + await renderShell({ + ...newMac, + runtimes: [ + { + models: [{ id: "claude-sonnet", label: "Claude Sonnet" }], + status: "ready", + type: "claude", + version: "2.1.0", + }, + ], + }); + expect(await screen.findByText(/Creating your Another Me/)).toBeVisible(); + + await act(() => vi.advanceTimersByTimeAsync(30_100)); + expect( + screen.getByText( + "Setting up Another Me is taking longer than usual. Retry to check again.", + ), + ).toBeVisible(); + fireEvent.click(screen.getByRole("button", { name: "Retry" })); + expect(screen.getByText(/Creating your Another Me/)).toBeVisible(); + }); }); async function renderShell( diff --git a/apps/web/src/features/local-computer/local-computer-gate.tsx b/apps/web/src/features/local-computer/local-computer-gate.tsx index 7c08b6de7..771897290 100644 --- a/apps/web/src/features/local-computer/local-computer-gate.tsx +++ b/apps/web/src/features/local-computer/local-computer-gate.tsx @@ -1,18 +1,27 @@ -import { Tick02Icon } from "@hugeicons/core-free-icons"; +import { + Alert02Icon, + Globe02Icon, + Settings01Icon, + Tick02Icon, +} from "@hugeicons/core-free-icons"; import { useQuery } from "@tanstack/react-query"; -import { type ReactNode, useState } from "react"; +import { type ReactNode, useEffect, useRef, useState } from "react"; import { Link } from "react-router"; import { Button } from "@/components/ui/button"; import { Icon } from "@/components/ui/icon"; +import { ModalDialog } from "@/components/ui/modal-dialog"; import { Spinner } from "@/components/ui/spinner"; import { anotherMeQueryOptions } from "@/features/rooms/room-queries"; +import { settingsMessages } from "@/features/settings/settings.messages"; import { useTeamHubRuntime } from "@/features/teamhub/teamhub-runtime"; import type { TeamHubLocalComputerPage, TeamHubLocalRuntimeType, } from "@/features/teamhub/teamhub-types"; -import { RichMessage, useT } from "@/i18n/use-translation"; +import { commonMessages } from "@/i18n/common.messages"; +import { LANGUAGES, setLanguage } from "@/i18n/language"; +import { RichMessage, useT, useTranslation } from "@/i18n/use-translation"; import { cn } from "@/lib/cn"; import { CommandLine } from "./computer-app-setup-dialog"; @@ -44,6 +53,7 @@ type RuntimeStatus = LocalComputer["runtimes"][number]["status"]; // Runtime installs and sign-ins happen on the Computer and reach the Web only // through the inventory, so the gate polls while it is open. const pollIntervalMs = 3_000; +const readyTimeoutMs = 30_000; /** * Every model call, Another Me's included, runs on the Human's own Computer, @@ -61,11 +71,18 @@ export function LocalComputerGate({ signingOut: boolean; tenantId: string; }) { - const t = useT(); + const { language, t } = useTranslation(); const { client } = useTeamHubRuntime(); const desktop = useDesktopComputer(); const cliInstallAvailable = useCliInstallAvailable(); const [platform, setPlatform] = useState(browserComputerPlatform); + const [readyTimedOut, setReadyTimedOut] = useState(false); + const [readyRetryCount, setReadyRetryCount] = useState(0); + const containerRef = useRef(null); + + useEffect(() => { + containerRef.current?.focus(); + }, []); // The desktop preloads this page hidden so "Open Linger" can reveal a // rendered Room, and the realtime stream is closed while hidden, so the gate // keeps polling in the background or it never sees Another Me arrive. @@ -74,7 +91,7 @@ export function LocalComputerGate({ refetchInterval: pollIntervalMs, refetchIntervalInBackground: true, }); - useQuery({ + const anotherMeQuery = useQuery({ ...anotherMeQueryOptions(client, tenantId), refetchInterval: pollIntervalMs, refetchIntervalInBackground: true, @@ -82,18 +99,45 @@ export function LocalComputerGate({ const computer = gateComputer(computers.data?.items ?? []); const online = computer?.status === "online" && !computer.upgrade_required; const ready = online && hasReadyRuntime(computer); + const queryError = computers.isError || anotherMeQuery.isError; const desktopOnlyStep = Boolean( desktop && (!computer || !cliInstallAvailable), ); const command = computerCommand(); + const nextLanguage = + LANGUAGES.find((entry) => entry.tag !== language) ?? LANGUAGES[0]; + + useEffect(() => { + if (!ready) { + setReadyTimedOut(false); + return; + } + setReadyTimedOut(false); + const timer = window.setTimeout(() => { + setReadyTimedOut(true); + }, readyTimeoutMs); + return () => window.clearTimeout(timer); + }, [ready, readyRetryCount]); + + function retryGateQueries() { + setReadyTimedOut(false); + setReadyRetryCount((count) => count + 1); + void computers.refetch(); + void anotherMeQuery.refetch(); + } return ( -
-
{}} + size="md" + > +

@@ -110,14 +154,51 @@ export function LocalComputerGate({ )}

- {ready ? ( -

- - {t(computersMessages.gateReady)} -

+
+ +

{t(computersMessages.gateLoadError)}

+
+ +
+ ) : null} + + {ready ? ( +
+ {readyTimedOut ? ( + <> +

+ {t(computersMessages.gateReadySlow)} +

+ + + ) : ( +

+ + {t(computersMessages.gateReady)} +

+ )} +
) : (
    {desktopOnlyStep && desktop ? ( @@ -179,7 +260,25 @@ export function LocalComputerGate({
)} -