🙌 OpenHands: AI-Driven Development
fix(routes): render unknown URLs as an in-app not-found page (#18023)
Engel Nyst198996a34dca
diff --git a/__tests__/routes/not-found.test.tsx b/__tests__/routes/not-found.test.tsxnew file mode 100644index 0000000000..dced8f3b81--- /dev/null+++ b/__tests__/routes/not-found.test.tsx@@ -0,0 +1,44 @@+import { screen } from "@testing-library/react";+import { describe, expect, it } from "vitest";+import { matchRoutes, type RouteObject } from "react-router";+import routes from "#/routes";+import NotFoundRoute from "#/routes/not-found";+import { renderWithProviders } from "../../test-utils";++function matchedRouteFiles(pathname: string) {+ const matches = matchRoutes(routes as unknown as RouteObject[], pathname);+ return matches?.map((match) => (match.route as { file?: string }).file);+}++describe("unknown URLs", () => {+ it.each(["/this-route-does-not-exist", "/settings/does-not-exist"])(+ "resolves %s to the not-found page inside the app shell",+ (pathname) => {+ expect(matchedRouteFiles(pathname)).toEqual([+ "routes/root-layout.tsx",+ "routes/not-found.tsx",+ ]);+ },+ );++ it("keeps known nested routes on their own pages", () => {+ expect(matchedRouteFiles("/settings/llm")).toEqual([+ "routes/root-layout.tsx",+ "routes/settings.tsx",+ "routes/llm-settings.tsx",+ ]);+ });++ it("renders a not-found message with a link back to home", () => {+ renderWithProviders(<NotFoundRoute />);++ expect(+ screen.getByRole("heading", { name: "NOT_FOUND$TITLE" }),+ ).toBeInTheDocument();+ expect(screen.getByText("NOT_FOUND$MESSAGE")).toBeInTheDocument();+ expect(screen.getByRole("link", { name: "BUTTON$HOME" })).toHaveAttribute(+ "href",+ "/",+ );+ });+});diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex 8ae9147eb1..002d4a977d 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -44470,5 +44470,39 @@"de": "Die Mikrofontaste im Chat-Eingabefeld verwendet die Spracherkennung deines Browsers. Um stattdessen deinen eigenen Transkriptionsdienst zu nutzen, etwa einen lokalen Whisper-Server, gib einen OpenAI-kompatiblen Endpunkt ein. Diese Einstellungen werden nur in diesem Browser gespeichert.","uk": "Кнопка мікрофона в полі чату використовує розпізнавання мовлення вашого браузера. Щоб натомість використовувати власний сервіс транскрибування, наприклад локальний сервер Whisper, введіть OpenAI-сумісну кінцеву точку. Ці налаштування зберігаються лише в цьому браузері.","ca": "El botó del micròfon de l'entrada del xat utilitza el reconeixement de veu del navegador. Per utilitzar el teu propi servei de transcripció, com ara un servidor Whisper local, introdueix un endpoint compatible amb OpenAI. Aquesta configuració només es desa en aquest navegador."+ },+ "NOT_FOUND$TITLE": {+ "en": "Page not found",+ "ja": "ページが見つかりません",+ "zh-CN": "未找到页面",+ "zh-TW": "找不到頁面",+ "ko-KR": "페이지를 찾을 수 없습니다",+ "no": "Fant ikke siden",+ "it": "Pagina non trovata",+ "pt": "Página não encontrada",+ "es": "Página no encontrada",+ "ar": "الصفحة غير موجودة",+ "fr": "Page introuvable",+ "tr": "Sayfa bulunamadı",+ "de": "Seite nicht gefunden",+ "uk": "Сторінку не знайдено",+ "ca": "No s'ha trobat la pàgina"+ },+ "NOT_FOUND$MESSAGE": {+ "en": "This address does not match any page. Check the URL, or go back to the home page.",+ "ja": "このアドレスに一致するページはありません。URL を確認するか、ホームページに戻ってください。",+ "zh-CN": "此地址没有对应的页面。请检查 URL,或返回首页。",+ "zh-TW": "此位址沒有對應的頁面。請檢查 URL,或返回首頁。",+ "ko-KR": "이 주소와 일치하는 페이지가 없습니다. URL을 확인하거나 홈 페이지로 돌아가세요.",+ "no": "Denne adressen samsvarer ikke med noen side. Kontroller URL-en, eller gå tilbake til startsiden.",+ "it": "Questo indirizzo non corrisponde a nessuna pagina. Controlla l'URL o torna alla home page.",+ "pt": "Este endereço não corresponde a nenhuma página. Verifique a URL ou volte para a página inicial.",+ "es": "Esta dirección no coincide con ninguna página. Comprueba la URL o vuelve a la página de inicio.",+ "ar": "لا يطابق هذا العنوان أي صفحة. تحقق من عنوان URL، أو عد إلى الصفحة الرئيسية.",+ "fr": "Cette adresse ne correspond à aucune page. Vérifiez l'URL ou revenez à la page d'accueil.",+ "tr": "Bu adres hiçbir sayfayla eşleşmiyor. URL'yi kontrol edin veya ana sayfaya dönün.",+ "de": "Diese Adresse passt zu keiner Seite. Prüfe die URL oder kehre zur Startseite zurück.",+ "uk": "Ця адреса не відповідає жодній сторінці. Перевірте URL або поверніться на головну сторінку.",+ "ca": "Aquesta adreça no correspon a cap pàgina. Comprova l'URL o torna a la pàgina d'inici."}}diff --git a/src/routes.ts b/src/routes.tsindex aa444409b0..05a28dee45 100644--- a/src/routes.ts+++ b/src/routes.ts@@ -39,6 +39,8 @@ export default [route("automations/templates", "routes/automation-templates.tsx"),route("automations/new/:automationId", "routes/automation-setup-route.tsx"),route("automations/:automationId", "routes/automation-detail.tsx"),+ // Unknown URLs (including /settings/<x>) render inside the app shell.+ route("*", "routes/not-found.tsx"),]),route("shared/conversations/:conversationId",diff --git a/src/routes/not-found.tsx b/src/routes/not-found.tsxnew file mode 100644index 0000000000..2fdeae2cc5--- /dev/null+++ b/src/routes/not-found.tsx@@ -0,0 +1,33 @@+import { useTranslation } from "react-i18next";+import { I18nKey } from "#/i18n/declaration";+import ExclamationCircleIcon from "#/icons/exclamation-circle.svg?react";+import { BackNavButton } from "#/components/shared/buttons/back-nav-button";++/**+ * Catch-all for URLs no route matches. It renders inside the root layout so+ * the sidebar stays usable, instead of React Router's bare document-level 404+ * (which also failed hydration of the prerendered SPA shell).+ */+export default function NotFoundRoute() {+ const { t } = useTranslation("openhands");++ return (+ <div+ data-testid="not-found-screen"+ className="flex h-full flex-col items-center justify-center px-6 py-20 text-center"+ >+ <ExclamationCircleIcon className="size-12 text-muted" aria-hidden />+ <h1 className="mt-4 text-sm font-medium text-content">+ {t(I18nKey.NOT_FOUND$TITLE)}+ </h1>+ <p className="mt-2 text-sm text-muted">{t(I18nKey.NOT_FOUND$MESSAGE)}</p>+ <BackNavButton+ to="/"+ testId="not-found-home-link"+ className="mt-6 self-center"+ >+ {t(I18nKey.BUTTON$HOME)}+ </BackNavButton>+ </div>+ );+}