diff --git a/web/bun.lock b/web/bun.lock index 2927d138..e49acd34 100644 --- a/web/bun.lock +++ b/web/bun.lock @@ -43,6 +43,8 @@ "formik": "^2.2.9", "highlight.js": "^11.11.1", "highlightjs-sap-abap": "^0.3.0", + "i18next": "^26.3.4", + "i18next-browser-languagedetector": "^8.2.1", "js-cookie": "^3.0.5", "katex": "^0.17.0", "linguist-languages": "^9.3.1", @@ -59,6 +61,7 @@ "react-day-picker": "^9.13.0", "react-dom": "19.2.4", "react-dropzone": "^14.2.3", + "react-i18next": "^17.0.8", "react-icons": "^4.8.0", "react-markdown": "^9.0.1", "recharts": "^3.9.2", @@ -1667,6 +1670,8 @@ "html-escaper": ["html-escaper@2.0.2", "", {}, "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg=="], + "html-parse-stringify": ["html-parse-stringify@3.0.1", "", { "dependencies": { "void-elements": "3.1.0" } }, "sha512-KknJ50kTInJ7qIScF3jeaFRpMpE8/lfiTdzf/twXyPBLAGrLRTmkz3AdTnKeh40X8k9L2fdYwEp/42WGXIRGcg=="], + "html-url-attributes": ["html-url-attributes@3.0.1", "", {}, "sha512-ol6UPyBWqsrO6EJySPz2O7ZSr856WDrEzM5zMqp+FJJLGMW35cLYmmZnl0vztAZxRUoNZJFTCohfjuIJ8I4QBQ=="], "html-void-elements": ["html-void-elements@3.0.0", "", {}, "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg=="], @@ -1679,6 +1684,10 @@ "hyperdyperid": ["hyperdyperid@1.2.0", "", {}, "sha512-Y93lCzHYgGWdrJ66yIktxiaGULYc6oGiABxhcO5AufBeOyoIdZF7bIfLaOrbM0iGIOXQQgxxRrFEnb+Y6w1n4A=="], + "i18next": ["i18next@26.3.4", "", { "peerDependencies": { "typescript": "^5 || ^6" }, "optionalPeers": ["typescript"] }, "sha512-pa7m0d7pBDqGHZxljT+WPFeyFgQ7P7SciPPo1tTqYuO0z4sqADYhwnBESmmGp/wEof1inwdls/k8ZgTg8rxFHA=="], + + "i18next-browser-languagedetector": ["i18next-browser-languagedetector@8.2.1", "", { "dependencies": { "@babel/runtime": "^7.23.2" } }, "sha512-bZg8+4bdmaOiApD7N7BPT9W8MLZG+nPTOFlLiJiT8uzKXFjhxw4v2ierCXOwB5sFDMtuA5G4kgYZ0AznZxQ/cw=="], + "iconv-lite": ["iconv-lite@0.6.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="], "identity-obj-proxy": ["identity-obj-proxy@3.0.0", "", { "dependencies": { "harmony-reflect": "^1.4.6" } }, "sha512-00n6YnVHKrinT9t0d9+5yZC6UBNJANpYEQvL2LlX6Ab9lnmxzIRcEmTPuyGScvl1+jKuCICX1Z0Ab1pPKKdikA=="], @@ -2193,6 +2202,8 @@ "react-fast-compare": ["react-fast-compare@2.0.4", "", {}, "sha512-suNP+J1VU1MWFKcyt7RtjiSWUjvidmQSlqu+eHslq+342xCbGTYmC0mEhPCOHxlW0CywylOC1u2DFAT+bv4dBw=="], + "react-i18next": ["react-i18next@17.0.8", "", { "dependencies": { "@babel/runtime": "^7.29.2", "html-parse-stringify": "^3.0.1", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "i18next": ">= 26.2.0", "react": ">= 16.8.0", "typescript": "^5 || ^6" }, "optionalPeers": ["typescript"] }, "sha512-0ooKbGLU8JXhe1zwpQUWIeXSgLPOfwJmgheWRIUpcoA0CpyabpGhayjdG+/eA5esC1AQ8h2jWpXjJfzQzeDOCw=="], + "react-icons": ["react-icons@4.12.0", "", { "peerDependencies": { "react": "*" } }, "sha512-IBaDuHiShdZqmfc/TwHu6+d6k2ltNCf3AszxNmjJc1KUfXdEeRJOKyNvLmAHaarhzGmTSVygNdyu8/opXv2gaw=="], "react-is": ["react-is@19.2.7", "", {}, "sha512-kZFnouyVv7eP/Phmrlo9FK+zcAdriZJvzxXHF1Sl1P377WSGe2G/JxVolhTrB/jeV47lKImhNUsijjHAAbcl/A=="], @@ -2499,6 +2510,8 @@ "vite": ["vite@6.4.3", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", "picomatch": "^4.0.2", "postcss": "^8.5.3", "rollup": "^4.34.9", "tinyglobby": "^0.2.13" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "jiti": ">=1.21.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A=="], + "void-elements": ["void-elements@3.1.0", "", {}, "sha512-Dhxzh5HZuiHQhbvTW9AMetFfBHDMYpo23Uo9btPXgdYP+3T5S+p+jgNy7spra+veYhBP2dCSgxR/i2Y02h5/6w=="], + "w3c-xmlserializer": ["w3c-xmlserializer@5.0.0", "", { "dependencies": { "xml-name-validator": "^5.0.0" } }, "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA=="], "walker": ["walker@1.0.8", "", { "dependencies": { "makeerror": "1.0.12" } }, "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ=="], diff --git a/web/lib/opal/src/components/inputs/password-input-type-in/components.tsx b/web/lib/opal/src/components/inputs/password-input-type-in/components.tsx index 23fa6d67..fbe48141 100644 --- a/web/lib/opal/src/components/inputs/password-input-type-in/components.tsx +++ b/web/lib/opal/src/components/inputs/password-input-type-in/components.tsx @@ -9,6 +9,7 @@ import { } from "@opal/components"; import { cn } from "@opal/utils"; import { SvgEye, SvgEyeClosed } from "@opal/icons"; +import { useTranslation } from "react-i18next"; // Backend placeholder pattern - indicates a stored value that can't be revealed const BACKEND_PLACEHOLDER_PATTERN = /^•+$/; // All bullet characters (U+2022) @@ -108,11 +109,14 @@ function PasswordInputTypeIn({ const showToggleButton = hasValue || isFocused; const isRevealed = isPasswordVisible && !effectiveNonRevealable; + const { t } = useTranslation(); const toggleLabel = effectiveNonRevealable - ? "Value cannot be revealed" + ? t("auth.value_cannot_be_revealed", { + defaultValue: "Value cannot be revealed", + }) : isPasswordVisible - ? "Hide password" - : "Show password"; + ? t("auth.hide_password", { defaultValue: "Hide password" }) + : t("auth.show_password", { defaultValue: "Show password" }); const isNativeMask = mask === "native"; // The ✱ presentation only draws while idle. Focus anywhere in the field diff --git a/web/lib/opal/src/layouts/settings/components.tsx b/web/lib/opal/src/layouts/settings/components.tsx index 9ccfc31a..029d4a9d 100644 --- a/web/lib/opal/src/layouts/settings/components.tsx +++ b/web/lib/opal/src/layouts/settings/components.tsx @@ -1,6 +1,6 @@ -"use client"; +"use client"; -import { useRouter } from "next/navigation"; +import { useRouter, usePathname } from "next/navigation"; import { cn } from "@opal/utils"; import { Divider, Button, Spacer } from "@opal/components"; import type { @@ -12,6 +12,7 @@ import type { import { HtmlHTMLAttributes, useEffect, useRef, useState } from "react"; import { Content } from "@opal/layouts"; import { SvgArrowLeft } from "@opal/icons"; +import { useTranslation } from "react-i18next"; // --------------------------------------------------------------------------- // Root @@ -36,7 +37,7 @@ interface SettingsRootProps extends WithoutStyles< /** * Wrapper for settings pages. Creates a centered, scrollable container. * The `id="page-wrapper-scroll-container"` is referenced by `Header` for - * scroll-shadow detection — do not remove it. + * scroll-shadow detection ÔÇö do not remove it. */ function SettingsRoot({ width = "md", ...props }: SettingsRootProps) { return ( @@ -69,7 +70,7 @@ export interface SettingsHeaderProps { * Sticky header for settings pages. Shows a scroll shadow when the page * has scrolled. Headers with `rightChildren` are always sticky; others are not. * - * Back button: set `backButton` to show a "← Back" button. Supply a function + * Back button: set `backButton` to show a "ÔåÉ Back" button. Supply a function * to override the default `router.back()` behavior. */ function SettingsHeader({ @@ -82,6 +83,8 @@ function SettingsHeader({ divider, }: SettingsHeaderProps) { const router = useRouter(); + const pathname = usePathname(); + const { t } = useTranslation(); const [showShadow, setShowShadow] = useState(false); const headerRef = useRef(null); @@ -90,6 +93,31 @@ function SettingsHeader({ const onBack = typeof backButton === "function" ? backButton : () => router.back(); + let displayTitle = title; + let displayDescription = description; + + if ( + pathname && + (pathname.startsWith("/admin/") || pathname.startsWith("/ee/admin/")) + ) { + const key = pathname.replace(/^\/(ee\/)?admin\//, "").replace(/[/-]/g, "_"); + if (typeof title === "string") { + displayTitle = t( + `admin.page_titles.${key}`, + t(`admin.sidebar.routes.${key}`, title) + ); + } + if (typeof description === "string") { + displayDescription = t( + `admin.${key}.desc`, + t( + `admin.${key}.description`, + t(`admin.${key}.page_description`, description) + ) + ); + } + } + useEffect(() => { if (!isSticky) return; @@ -132,8 +160,8 @@ function SettingsHeader({
diff --git a/web/lib/opal/src/layouts/sidebar/components.tsx b/web/lib/opal/src/layouts/sidebar/components.tsx index b2f9d111..6465ad0c 100644 --- a/web/lib/opal/src/layouts/sidebar/components.tsx +++ b/web/lib/opal/src/layouts/sidebar/components.tsx @@ -1,6 +1,7 @@ "use client"; import "@opal/layouts/sidebar/styles.css"; +import { useTranslation } from "react-i18next"; import { createContext, useCallback, @@ -135,6 +136,7 @@ function SidebarHeader({ showLogoWhenFolded = true, children, }: SidebarHeaderProps) { + const { t } = useTranslation(); const foldable = useContext(SidebarFoldableContext); const { folded, setFolded } = useSidebarState(); const toggleFolded = useCallback( @@ -147,7 +149,7 @@ function SidebarHeader({ +
@@ -132,6 +134,7 @@ const HumanMessage = React.memo(function HumanMessage({ stopGenerating = () => null, disableSwitchingForStreaming = false, }: HumanMessageProps) { + const { t } = useTranslation(); // TODO (@raunakab): // // This is some duplicated state that is patching a memoization issue with `HumanMessage`. @@ -177,20 +180,21 @@ const HumanMessage = React.memo(function HumanMessage({ content} prominence="tertiary" + tooltip={t("chat.copy")} data-testid="HumanMessage/copy-button" /> {onEdit && ( + ); }; @@ -35,13 +37,14 @@ export const ErrorBanner = ({ stackTrace?: string | null; resubmit?: () => void; }) => { + const { t } = useTranslation(); const [isStackTraceExpanded, setIsStackTraceExpanded] = useState(false); return (
{getErrorIcon(errorCode)} - {getErrorTitle(errorCode)} + {t(getErrorTitle(errorCode))} {error} {details?.model && ( @@ -63,7 +66,7 @@ export const ErrorBanner = ({ icon={isStackTraceExpanded ? SvgChevronDown : SvgChevronRight} onClick={() => setIsStackTraceExpanded(!isStackTraceExpanded)} > - Stack trace + {t("chat.stack_trace")} (null); const finalAnswerRef = useRef(null); @@ -355,7 +357,7 @@ const AgentMessage = React.memo(function AgentMessage({ {pacedDisplayGroups.length === 0 && stopReason === StopReason.USER_CANCELLED && ( - User has stopped generation + {t("chat.user_stopped_generation")} )}
diff --git a/web/src/app/app/message/messageComponents/MessageToolbar.tsx b/web/src/app/app/message/messageComponents/MessageToolbar.tsx index f60f4b58..a61bc2be 100644 --- a/web/src/app/app/message/messageComponents/MessageToolbar.tsx +++ b/web/src/app/app/message/messageComponents/MessageToolbar.tsx @@ -1,6 +1,7 @@ "use client"; import React, { RefObject, useState, useCallback, useMemo } from "react"; +import { useTranslation } from "react-i18next"; import { Packet, StreamingCitation } from "@/app/app/services/streamingModels"; import { FeedbackType, Message } from "@/app/app/interfaces"; import { OnyxDocument } from "@/lib/search/interfaces"; @@ -52,6 +53,7 @@ const SourcesTagWrapper = React.memo(function SourcesTagWrapper({ updateCurrentDocumentSidebarVisible, updateCurrentSelectedNodeForDocDisplay, }: SouurcesTagWrapperProps) { + const { t } = useTranslation(); // Convert citations to SourceInfo array const sources = useMemo( () => citationsToSourceInfoArray(citations, documentMap), @@ -80,7 +82,7 @@ const SourcesTagWrapper = React.memo(function SourcesTagWrapper({ return ( @@ -284,8 +289,8 @@ export default function MessageToolbar({ state={isFeedbackTransient("dislike") ? "selected" : "empty"} tooltip={ currentFeedback === "dislike" - ? "Remove Dislike" - : "Bad Response" + ? t("chat.remove_dislike") + : t("chat.bad_response") } data-testid="AgentMessage/dislike-button" /> diff --git a/web/src/app/app/message/messageComponents/timeline/headers/CompletedHeader.tsx b/web/src/app/app/message/messageComponents/timeline/headers/CompletedHeader.tsx index 78e152c3..ea5cd57a 100644 --- a/web/src/app/app/message/messageComponents/timeline/headers/CompletedHeader.tsx +++ b/web/src/app/app/message/messageComponents/timeline/headers/CompletedHeader.tsx @@ -1,6 +1,7 @@ "use client"; import React from "react"; +import { useTranslation } from "react-i18next"; import { SvgFold, SvgExpand, SvgAddLines, SvgMaximize2 } from "@opal/icons"; import { Button } from "@opal/components"; import Tag from "@/refresh-components/buttons/Tag"; @@ -30,10 +31,13 @@ function MemoryTagWithTooltip({ memoryId, memoryIndex, }: MemoryTagWithTooltipProps) { + const { t } = useTranslation(); const memoriesModal = useCreateModal(); const operationLabel = - memoryOperation === "add" ? "Added to memories" : "Updated memory"; + memoryOperation === "add" + ? t("chat.added_to_memories") + : t("chat.updated_memory"); const tag = ; @@ -128,6 +132,8 @@ export const CompletedHeader = React.memo(function CompletedHeader({ memoryId = null, memoryIndex = null, }: CompletedHeaderProps) { + const { t } = useTranslation(); + if (isMemoryOnly) { return (
@@ -148,7 +154,9 @@ export const CompletedHeader = React.memo(function CompletedHeader({ aria-label="Expand timeline" aria-expanded={isExpanded} > - {`${totalSteps} ${totalSteps === 1 ? "step" : "steps"}`} + {totalSteps === 1 + ? t("chat.step_count_single") + : t("chat.step_count_plural", { count: totalSteps })} )}
@@ -156,14 +164,16 @@ export const CompletedHeader = React.memo(function CompletedHeader({ } const durationText = processingDurationSeconds - ? `Thought for ${formatDurationSeconds(processingDurationSeconds)}` - : "Thought for some time"; + ? t("chat.thought_for", { + duration: formatDurationSeconds(processingDurationSeconds), + }) + : t("chat.thought_for_some_time"); const imageText = generatedImageCount > 0 - ? `Generated ${generatedImageCount} ${ - generatedImageCount === 1 ? "image" : "images" - }` + ? generatedImageCount === 1 + ? t("chat.generated_image_single") + : t("chat.generated_image_plural", { count: generatedImageCount }) : null; return ( @@ -195,7 +205,9 @@ export const CompletedHeader = React.memo(function CompletedHeader({ aria-label="Expand timeline" aria-expanded={isExpanded} > - {`${totalSteps} ${totalSteps === 1 ? "step" : "steps"}`} + {totalSteps === 1 + ? t("chat.step_count_single") + : t("chat.step_count_plural", { count: totalSteps })} )} diff --git a/web/src/app/app/message/messageComponents/timeline/headers/StoppedHeader.tsx b/web/src/app/app/message/messageComponents/timeline/headers/StoppedHeader.tsx index 64dfae54..f45c92cc 100644 --- a/web/src/app/app/message/messageComponents/timeline/headers/StoppedHeader.tsx +++ b/web/src/app/app/message/messageComponents/timeline/headers/StoppedHeader.tsx @@ -1,4 +1,5 @@ import React from "react"; +import { useTranslation } from "react-i18next"; import { SvgFold, SvgExpand } from "@opal/icons"; import { Button } from "@opal/components"; import Text from "@/refresh-components/texts/Text"; @@ -19,6 +20,7 @@ export const StoppedHeader = React.memo(function StoppedHeader({ isExpanded, onToggle, }: StoppedHeaderProps) { + const { t } = useTranslation(); const isInteractive = collapsible && totalSteps > 0; return ( @@ -33,7 +35,7 @@ export const StoppedHeader = React.memo(function StoppedHeader({ >
- Interrupted Thinking + {t("chat.interrupted_thinking")}
@@ -43,10 +45,16 @@ export const StoppedHeader = React.memo(function StoppedHeader({ size="md" onClick={noProp(onToggle)} rightIcon={isExpanded ? SvgFold : SvgExpand} - aria-label={isExpanded ? "Collapse timeline" : "Expand timeline"} + aria-label={ + isExpanded + ? t("chat.collapse_timeline", "Collapse timeline") + : t("chat.expand_timeline", "Expand timeline") + } aria-expanded={isExpanded} > - {`${totalSteps} ${totalSteps === 1 ? "step" : "steps"}`} + {totalSteps === 1 + ? t("chat.step_count_single") + : t("chat.step_count_plural", { count: totalSteps })} )} diff --git a/web/src/app/app/message/messageComponents/toolDisplayHelpers.tsx b/web/src/app/app/message/messageComponents/toolDisplayHelpers.tsx index e877f6c7..186d0111 100644 --- a/web/src/app/app/message/messageComponents/toolDisplayHelpers.tsx +++ b/web/src/app/app/message/messageComponents/toolDisplayHelpers.tsx @@ -5,6 +5,7 @@ import { SearchToolPacket, } from "@/app/app/services/streamingModels"; import { constructCurrentSearchState } from "./timeline/renderers/search/searchStateUtils"; +import i18n from "@/lib/i18n"; import { SvgGlobe, SvgSearchMenu, @@ -89,38 +90,41 @@ export function parseToolKey(key: string): { export function getToolName(packets: Packet[]): string { const firstPacket = packets[0]; - if (!firstPacket) return "Tool"; + if (!firstPacket) return i18n.t("chat.tool_display.tool"); switch (firstPacket.obj.type) { case PacketType.SEARCH_TOOL_START: { const searchState = constructCurrentSearchState( packets as SearchToolPacket[] ); - return searchState.isInternetSearch ? "Web Search" : "Internal Search"; + return searchState.isInternetSearch + ? i18n.t("admin.chat_preferences.tool_web_search") + : i18n.t("admin.chat_preferences.tool_internal_search"); } case PacketType.PYTHON_TOOL_START: - return "Code Interpreter"; + return i18n.t("admin.chat_preferences.tool_code_interpreter"); case PacketType.FETCH_TOOL_START: - return "Open URLs"; + return i18n.t("admin.chat_preferences.tool_open_url"); case PacketType.CUSTOM_TOOL_START: return ( - (firstPacket.obj as { tool_name?: string }).tool_name || "Custom Tool" + (firstPacket.obj as { tool_name?: string }).tool_name || + i18n.t("chat.tool_display.custom_tool") ); case PacketType.IMAGE_GENERATION_TOOL_START: - return "Generate Image"; + return i18n.t("admin.chat_preferences.tool_image_gen"); case PacketType.DEEP_RESEARCH_PLAN_START: - return "Generate plan"; + return i18n.t("chat.tool_display.generate_plan"); case PacketType.RESEARCH_AGENT_START: - return "Research agent"; + return i18n.t("chat.tool_display.research_agent"); case PacketType.CODING_AGENT_START: - return "Coding agent"; + return i18n.t("admin.chat_preferences.tool_coding_agent"); case PacketType.REASONING_START: - return "Thinking"; + return i18n.t("chat.tool_display.thinking"); case PacketType.MEMORY_TOOL_START: case PacketType.MEMORY_TOOL_NO_ACCESS: - return "Memory"; + return i18n.t("chat.tool_display.memory"); default: - return "Tool"; + return i18n.t("chat.tool_display.tool"); } } diff --git a/web/src/app/app/settings/layout.tsx b/web/src/app/app/settings/layout.tsx index c5c96174..199b3f7a 100644 --- a/web/src/app/app/settings/layout.tsx +++ b/web/src/app/app/settings/layout.tsx @@ -1,6 +1,7 @@ "use client"; import { usePathname, useRouter } from "next/navigation"; +import { useTranslation } from "react-i18next"; import type { Route } from "next"; import { SettingsLayouts } from "@opal/layouts"; import { SidebarTab, Text } from "@opal/components"; @@ -20,6 +21,7 @@ interface SettingsTab { } export default function Layout({ children }: LayoutProps) { + const { t } = useTranslation(); const pathname = usePathname(); const router = useRouter(); const { user } = useUser(); @@ -30,12 +32,12 @@ export default function Layout({ children }: LayoutProps) { const showAccountsAccessTab = showPasswordSection || showTokensSection; const tabs: SettingsTab[] = [ - { href: "/app/settings/general", label: "General" }, - { href: "/app/settings/chat-preferences", label: "Chat Preferences" }, + { href: "/app/settings/general", label: t("settings.tabs.general", "General") }, + { href: "/app/settings/chat-preferences", label: t("settings.tabs.chat_preferences", "Chat Preferences") }, ...(showAccountsAccessTab - ? [{ href: "/app/settings/accounts-access", label: "Accounts & Access" }] + ? [{ href: "/app/settings/accounts-access", label: t("settings.tabs.accounts_access", "Accounts & Access") }] : []), - { href: "/app/settings/connectors", label: "Connectors" }, + { href: "/app/settings/connectors", label: t("settings.tabs.connectors", "Connectors") }, ]; // Derive the trigger label from the pathname directly. InputSelect normally @@ -46,7 +48,7 @@ export default function Layout({ children }: LayoutProps) { return ( - +
- Welcome to {appName} + {t("auth.welcome_to")} {appName} - Your open source AI platform for work + {t("auth.tagline")} ); diff --git a/web/src/app/auth/signup/SignupText.tsx b/web/src/app/auth/signup/SignupText.tsx new file mode 100644 index 00000000..9857f634 --- /dev/null +++ b/web/src/app/auth/signup/SignupText.tsx @@ -0,0 +1,19 @@ +"use client"; + +import React from "react"; +import { useTranslation } from "react-i18next"; +import Text from "@/refresh-components/texts/Text"; + +export default function SignupText({ cloud }: { cloud?: boolean }) { + const { t } = useTranslation(); + return ( +
+ + {cloud ? t("auth.complete_signup") : t("auth.create_account")} + + + {t("auth.get_started")} + +
+ ); +} diff --git a/web/src/components/auth/AuthFlowContainer.tsx b/web/src/components/auth/AuthFlowContainer.tsx index 505057e9..339b68ba 100644 --- a/web/src/components/auth/AuthFlowContainer.tsx +++ b/web/src/components/auth/AuthFlowContainer.tsx @@ -1,5 +1,9 @@ +"use client"; + import Link from "next/link"; import { SvgOnyxLogo } from "@opal/logos"; +import { useTranslation } from "react-i18next"; +import { useSettings } from "@/lib/settings/hooks"; export default function AuthFlowContainer({ children, @@ -10,9 +14,12 @@ export default function AuthFlowContainer({ authState?: "signup" | "login" | "join"; footerContent?: React.ReactNode; }) { + const { t } = useTranslation(); + const { appName } = useSettings(); + return (
-
+
{children}
@@ -20,12 +27,12 @@ export default function AuthFlowContainer({
{footerContent ?? ( <> - New to Onyx?{" "} + {t("auth.new_to_onyx", { appName })}{" "} - Create an Account + {t("auth.create_account")} )} @@ -33,12 +40,12 @@ export default function AuthFlowContainer({ )} {authState === "signup" && (
- Already have an account?{" "} + {t("auth.already_have_account")}{" "} - Sign In + {t("auth.sign_in")}
)} diff --git a/web/src/components/errorPages/ErrorPage.tsx b/web/src/components/errorPages/ErrorPage.tsx index 28d376ef..4df8a551 100644 --- a/web/src/components/errorPages/ErrorPage.tsx +++ b/web/src/components/errorPages/ErrorPage.tsx @@ -2,47 +2,54 @@ import ErrorPageLayout from "@/components/errorPages/ErrorPageLayout"; import Text from "@/refresh-components/texts/Text"; import { DOCS_BASE_URL } from "@/lib/constants"; import { SvgAlertCircle } from "@opal/icons"; +import { useTranslation, Trans } from "react-i18next"; export default function Error() { + const { t } = useTranslation(); + return (
- We encountered an issue + {t("error_page.title")}
- It seems there was a problem loading your Onyx settings. This could be - due to a configuration issue or incomplete setup. + {t("error_page.onyx_settings_error")} - If you're an admin, please review our{" "} - - documentation - {" "} - for proper configuration steps. If you're a user, please contact - your admin for assistance. + + ), + }} + /> - Need help? Join our{" "} - - Discord community - {" "} - for support. + + ), + }} + />
); diff --git a/web/src/layouts/chromes/AppChrome.tsx b/web/src/layouts/chromes/AppChrome.tsx index 2ecb033e..72c56150 100644 --- a/web/src/layouts/chromes/AppChrome.tsx +++ b/web/src/layouts/chromes/AppChrome.tsx @@ -9,6 +9,7 @@ import { type ReactNode, } from "react"; import { RootLayout, RootLayoutRightPanelSlotContext } from "@opal/layouts"; +import { useTranslation } from "react-i18next"; import { cn, markdown } from "@opal/utils"; import { INTERACTIVE_SELECTOR, noProp } from "@/lib/utils"; import { useAppBackground } from "@/providers/AppBackgroundProvider"; @@ -74,6 +75,7 @@ import { useFullWidthChat } from "@/providers/FullWidthChatProvider"; // --------------------------------------------------------------------------- function Header() { + const { t } = useTranslation(); const appFocus = useAppFocus(); const businessTier = useTierAtLeast(Tier.BUSINESS); const { state, setAppMode } = useQueryController(); @@ -294,7 +296,7 @@ function Header() { rounding="sm" color="danger" icon={SvgTrash} - title="Delete" + title={t("settings.danger_zone.delete_btn", "Delete")} onClick={noProp(() => setDeleteConfirmationModalOpen(true))} />, ]; @@ -344,7 +346,7 @@ function Header() { onClose={() => setDeleteModalOpen(false)} submit={ } > @@ -391,7 +393,7 @@ function Header() { : SvgBubbleText } > - {effectiveMode === "search" ? "Search" : "Chat"} + {effectiveMode === "search" ? "Search" : t("settings.chats.mode_chat", "Chat")} @@ -403,7 +405,7 @@ function Header() { state={ effectiveMode === "search" ? "selected" : "empty" } - title="Search" + title={t("settings.chats.mode_search", "Search")} description="Quick search for documents" onClick={noProp(() => { setAppMode("search"); @@ -417,7 +419,7 @@ function Header() { state={ effectiveMode === "chat" ? "selected" : "empty" } - title="Chat" + title={t("settings.chats.mode_chat", "Chat")} description="Conversation and research" onClick={noProp(() => { setAppMode("chat"); diff --git a/web/src/lib/i18n.ts b/web/src/lib/i18n.ts new file mode 100644 index 00000000..23029a41 --- /dev/null +++ b/web/src/lib/i18n.ts @@ -0,0 +1,52 @@ +import i18n from "i18next"; +import { initReactI18next } from "react-i18next"; +import LanguageDetector from "i18next-browser-languagedetector"; + +import enCommon from "../../public/locales/en/common.json"; +import esCommon from "../../public/locales/es/common.json"; +import ptCommon from "../../public/locales/pt/common.json"; +import frCommon from "../../public/locales/fr/common.json"; +import deCommon from "../../public/locales/de/common.json"; + +/** + * Initialize the shared i18next instance. + * + * Intentionally an explicit factory rather than an import-time side effect: + * importing this module (e.g. for the default `i18n` export used by non-React + * helpers) must NOT trigger initialization, cookie/localStorage reads, etc. + * Call this once at app startup (see `AppProvider`). + * + * Idempotent — the underlying `init()` only runs the first time. + */ +export function initI18n() { + if (!i18n.isInitialized) { + i18n + .use(LanguageDetector) + .use(initReactI18next) + .init({ + resources: { + en: { common: enCommon }, + es: { common: esCommon }, + pt: { common: ptCommon }, + fr: { common: frCommon }, + de: { common: deCommon }, + }, + fallbackLng: "en", + ns: ["common"], + defaultNS: "common", + interpolation: { + escapeValue: false, // React already safes from XSS + }, + detection: { + order: ["cookie", "localStorage", "navigator", "htmlTag"], + caches: ["cookie", "localStorage"], + lookupCookie: "i18next", + lookupLocalStorage: "i18nextLng", + }, + }); + } + + return i18n; +} + +export default i18n; diff --git a/web/src/lib/tool-i18n.ts b/web/src/lib/tool-i18n.ts new file mode 100644 index 00000000..0a5d2cd8 --- /dev/null +++ b/web/src/lib/tool-i18n.ts @@ -0,0 +1,30 @@ +import type { TFunction } from "i18next"; +import { + CODING_AGENT_TOOL_ID, + IMAGE_GENERATION_TOOL_ID, + OPEN_URL_TOOL_ID, + PYTHON_TOOL_ID, + SEARCH_TOOL_ID, + WEB_SEARCH_TOOL_ID, +} from "@/app/app/components/tools/constants"; +import type { ToolSnapshot } from "@/lib/tools/interfaces"; + +const TOOL_LABEL_KEYS: Record = { + [SEARCH_TOOL_ID]: "tools.internal_search", + [IMAGE_GENERATION_TOOL_ID]: "tools.image_gen", + [WEB_SEARCH_TOOL_ID]: "tools.web_search", + [PYTHON_TOOL_ID]: "tools.code_interpreter", + [CODING_AGENT_TOOL_ID]: "tools.coding_agent", + [OPEN_URL_TOOL_ID]: "tools.open_url", +}; + +export function getLocalizedToolLabel( + tool: Pick, + t: TFunction +): string { + const toolKey = tool.in_code_tool_id || tool.name; + if (toolKey && TOOL_LABEL_KEYS[toolKey]) { + return t(TOOL_LABEL_KEYS[toolKey]); + } + return tool.display_name || tool.name; +} diff --git a/web/src/lib/types.ts b/web/src/lib/types.ts index 73a6b008..fe7a496b 100644 --- a/web/src/lib/types.ts +++ b/web/src/lib/types.ts @@ -30,6 +30,7 @@ interface UserPreferences { shortcut_enabled: boolean; temperature_override_enabled: boolean; theme_preference: ThemePreference | null; + language?: string | null; chat_background: string | null; default_app_mode: "AUTO" | "CHAT" | "SEARCH"; // Input preferences diff --git a/web/src/providers/AppProvider.tsx b/web/src/providers/AppProvider.tsx index f61e27f0..8af9350d 100644 --- a/web/src/providers/AppProvider.tsx +++ b/web/src/providers/AppProvider.tsx @@ -26,6 +26,8 @@ import { useState } from "react"; import Cookies from "js-cookie"; +import { I18nextProvider } from "react-i18next"; +import i18n, { initI18n } from "@/lib/i18n"; import { UserProvider } from "@/providers/UserProvider"; import { ProviderContextProvider } from "@/components/chat/ProviderContext"; import { SettingsProvider } from "@/providers/SettingsProvider"; @@ -73,33 +75,43 @@ interface AppProviderProps { } export default function AppProvider({ children }: AppProviderProps) { + // Initialize i18next once at app startup. `initI18n` is idempotent and + // synchronous (resources are bundled), so the instance is ready before the + // provider renders. A lazy `useState` initializer guarantees it runs exactly + // once during render (even under Strict Mode's double-render) without leaking + // a side effect into the render body. Done here rather than as an import-time + // side effect. + useState(() => initI18n()); + return ( - - - - - - - - - - - {children} - - - - - - - - - - + + + + + + + + + + + + {children} + + + + + + + + + + + ); } diff --git a/web/src/providers/UserProvider.tsx b/web/src/providers/UserProvider.tsx index 2950afe4..e20a049c 100644 --- a/web/src/providers/UserProvider.tsx +++ b/web/src/providers/UserProvider.tsx @@ -25,6 +25,7 @@ import { setUserDefaultModel, } from "@/lib/users/svc"; import { useTheme } from "next-themes"; +import { useTranslation } from "react-i18next"; interface UserContextType { user: User | null; @@ -48,6 +49,7 @@ interface UserContextType { updateUserThemePreference: ( themePreference: ThemePreference ) => Promise; + updateUserLanguagePreference: (language: string) => Promise; updateUserChatBackground: (chatBackground: string | null) => Promise; updateUserDefaultModel: (defaultModel: string | null) => Promise; updateUserDefaultAppMode: (mode: "CHAT" | "SEARCH") => Promise; @@ -62,6 +64,7 @@ const UserContext = createContext(undefined); export function UserProvider({ children }: { children: React.ReactNode }) { const { user: fetchedUser, mutateUser } = useCurrentUser(); + const { i18n } = useTranslation(); const { authTypeMetadata, isLoading: authTypeMetadataLoading } = useAuthTypeMetadata(); const updatedSettingsData = useSettings(); @@ -150,6 +153,27 @@ export function UserProvider({ children }: { children: React.ReactNode }) { setTheme, ]); + // Sync user's language preference from DB to i18next on load + const hasSyncedLanguageRef = useRef(false); + + useEffect(() => { + // Only sync once per session + if (hasSyncedLanguageRef.current) return; + + // Wait for user data to load + if (!upToDateUser?.id) return; + + // Only sync if user has a saved preference + const savedLanguage = upToDateUser?.preferences?.language; + if (!savedLanguage) return; + + i18n.changeLanguage(savedLanguage); + if (typeof document !== "undefined") { + document.documentElement.lang = savedLanguage; + } + hasSyncedLanguageRef.current = true; + }, [upToDateUser?.id, upToDateUser?.preferences?.language, i18n]); + const updateUserTemperatureOverrideEnabled = async (enabled: boolean) => { try { setUpToDateUser((prevUser) => { @@ -394,6 +418,54 @@ export function UserProvider({ children }: { children: React.ReactNode }) { } }; + const updateUserLanguagePreference = async (language: string) => { + // Snapshot the current language so we can roll back the optimistic + // i18n change if the request fails. + const previousLanguage = i18n.language; + try { + setUpToDateUser((prevUser) => { + if (prevUser) { + return { + ...prevUser, + preferences: { + ...prevUser.preferences, + language, + }, + }; + } + return prevUser; + }); + + // Change local language immediately (optimistic) + i18n.changeLanguage(language); + if (typeof document !== "undefined") { + document.documentElement.lang = language; + } + + const response = await fetch(`/api/user/language`, { + method: "PATCH", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ language }), + }); + + if (!response.ok) { + throw new Error("Failed to update language preference"); + } + } catch (error) { + // Roll back the optimistic UI language change so the live UI stays in + // sync with the persisted preference. + i18n.changeLanguage(previousLanguage); + if (typeof document !== "undefined") { + document.documentElement.lang = previousLanguage; + } + await refreshUser(); + console.error("Error updating language preference:", error); + throw error; + } + }; + const updateUserChatBackground = async (chatBackground: string | null) => { try { setUpToDateUser((prevUser) => { @@ -547,6 +619,7 @@ export function UserProvider({ children }: { children: React.ReactNode }) { updateUserTemperatureOverrideEnabled, updateUserPersonalization, updateUserThemePreference, + updateUserLanguagePreference, updateUserChatBackground, updateUserDefaultModel, updateUserDefaultAppMode, diff --git a/web/src/refresh-components/modals/MemoriesModal.tsx b/web/src/refresh-components/modals/MemoriesModal.tsx index 8def9724..6ee00137 100644 --- a/web/src/refresh-components/modals/MemoriesModal.tsx +++ b/web/src/refresh-components/modals/MemoriesModal.tsx @@ -11,6 +11,7 @@ import TextSeparator from "@/refresh-components/TextSeparator"; import { toast } from "@opal/layouts"; import { useModalClose } from "@opal/components"; import { SvgAddLines, SvgMinusCircle, SvgPlusCircle } from "@opal/icons"; +import { useTranslation } from "react-i18next"; import { useMemoryManager, MAX_MEMORY_LENGTH, @@ -49,6 +50,7 @@ function MemoryItem({ const [isHighlighting, setIsHighlighting] = useState(false); const textareaRef = useRef(null); const wrapperRef = useRef(null); + const { t } = useTranslation(); useEffect(() => { if (shouldFocus && textareaRef.current) { @@ -90,7 +92,10 @@ function MemoryItem({
onUpdate(originalIndex, e.target.value)} onFocus={() => setIsFocused(true)} @@ -119,8 +124,8 @@ function MemoryItem({ prominence="tertiary" icon={SvgMinusCircle} onClick={() => void onRemove(originalIndex)} - aria-label="Remove Line" - tooltip="Remove Line" + aria-label={t("settings.memory.remove_line_aria", "Remove Line")} + tooltip={t("settings.memory.remove_line_tooltip", "Remove Line")} />
(null); + const { t } = useTranslation(); // Self-fetching: when no props provided, fetch from UserProvider const { user, refreshUser, updateUserPersonalization } = useUser(); @@ -177,8 +183,14 @@ export default function MemoriesModal({ user, updateUserPersonalization, { - onSuccess: () => toast.success("Preferences saved"), - onError: () => toast.error("Failed to save preferences"), + onSuccess: () => + toast.success( + t("settings.chats.toast_prefs_saved", "Preferences saved") + ), + onError: () => + toast.error( + t("settings.chats.toast_prefs_failed", "Failed to save preferences") + ), } ); @@ -237,7 +249,22 @@ export default function MemoriesModal({ } = useMemoryManager({ memories: effectiveMemories, onSaveMemories: effectiveSave, - onNotify: (message, type) => toast[type](message), + onNotify: (message, type) => { + let translated = message; + if (message === "Memory saved") { + translated = t("settings.memory.saved_success", "Memory saved"); + } else if (message === "Failed to save memory") { + translated = t("settings.memory.saved_failed", "Failed to save memory"); + } else if (message === "Memory deleted") { + translated = t("settings.memory.deleted_success", "Memory deleted"); + } else if (message === "Failed to delete memory") { + translated = t( + "settings.memory.deleted_failed", + "Failed to delete memory" + ); + } + toast[type](translated); + }, }); // Always start with an empty card; optionally focus it (View/Add button) @@ -265,13 +292,16 @@ export default function MemoriesModal({
setSearchQuery(e.target.value)} searchIcon @@ -283,11 +313,14 @@ export default function MemoriesModal({ rightIcon={SvgPlusCircle} title={ !canAddMemory - ? `Maximum of ${MAX_MEMORY_COUNT} memories reached` + ? t("settings.memory.max_reached", { + defaultValue: `Maximum of ${MAX_MEMORY_COUNT} memories reached`, + count: MAX_MEMORY_COUNT, + }) : undefined } > - Add Line + {t("settings.memory.add_line", "Add Line")}
@@ -297,8 +330,14 @@ export default function MemoriesModal({
{searchQuery.trim() - ? "No memories match your search." - : 'No memories yet. Click "Add Line" to get started.'} + ? t( + "settings.memory.no_matches", + "No memories match your search." + ) + : t( + "settings.memory.no_memories_yet", + 'No memories yet. Click "Add Line" to get started.' + )}
) : ( @@ -327,7 +366,11 @@ export default function MemoriesModal({ )}
diff --git a/web/src/refresh-components/popovers/ActionsPopover/ActionLineItem.tsx b/web/src/refresh-components/popovers/ActionsPopover/ActionLineItem.tsx index ec3163e2..e2b8dc10 100644 --- a/web/src/refresh-components/popovers/ActionsPopover/ActionLineItem.tsx +++ b/web/src/refresh-components/popovers/ActionsPopover/ActionLineItem.tsx @@ -18,6 +18,8 @@ import { useRouter } from "next/navigation"; import type { Route } from "next"; import EnabledCount from "@/refresh-components/EnabledCount"; import { Section } from "@/layouts/general-layouts"; +import { useTranslation } from "react-i18next"; +import { getLocalizedToolLabel } from "@/lib/tool-i18n"; export interface ActionItemProps { tool?: ToolSnapshot; @@ -63,13 +65,14 @@ export default function ActionLineItem({ }: ActionItemProps) { const router = useRouter(); const { currentProjectId } = useProjectsContext(); + const { t } = useTranslation(); const Icon = tool ? getIconForAction(tool) : ProvidedIcon!; const toolName = tool?.name || providedLabel || ""; - let label = tool ? tool.display_name || tool.name : providedLabel!; + let label = tool ? getLocalizedToolLabel(tool, t) : providedLabel!; if (!!currentProjectId && tool?.in_code_tool_id === SEARCH_TOOL_ID) { - label = "Project Search"; + label = t("chat.actions.project_search", "Project Search"); } const isSearchToolWithNoConnectors = @@ -185,8 +188,11 @@ export default function ActionLineItem({
diff --git a/web/src/refresh-components/popovers/FilePickerPopover.tsx b/web/src/refresh-components/popovers/FilePickerPopover.tsx index ab8a8b33..2f588d05 100644 --- a/web/src/refresh-components/popovers/FilePickerPopover.tsx +++ b/web/src/refresh-components/popovers/FilePickerPopover.tsx @@ -1,6 +1,7 @@ "use client"; import React, { useEffect, useMemo, useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; import { Popover, PopoverMenu } from "@opal/components"; import { noProp } from "@/lib/utils"; import { cn } from "@opal/utils"; @@ -111,7 +112,8 @@ function FilePickerPopoverContents({ triggerUploadPicker, openRecentFilesModal, }: FilePickerPopoverContentsProps) { - // These are the "quick" files that we show. Essentially "speed dial", but for files. + const { t } = useTranslation(); + // These are the "quick" files that we show. // The rest of the files will be hidden behind the "All Recent Files" button, should there be more files left to show! const hasFiles = recentFiles.length > 0; const shouldShowMoreFilesButton = recentFiles.length > MAX_FILES_TO_SHOW; @@ -124,10 +126,10 @@ function FilePickerPopoverContents({ - Upload Files + {t("admin.files.upload_files")} , // Separator diff --git a/web/src/sections/agents/AgentsFilters.tsx b/web/src/sections/agents/AgentsFilters.tsx index a508c392..92e4d9dd 100644 --- a/web/src/sections/agents/AgentsFilters.tsx +++ b/web/src/sections/agents/AgentsFilters.tsx @@ -27,6 +27,7 @@ */ import { useMemo, useState } from "react"; +import { useTranslation } from "react-i18next"; import { FilterButton, LineItemButton } from "@opal/components"; import { SvgActions, SvgUser } from "@opal/icons"; import { Popover, PopoverMenu } from "@opal/components"; @@ -93,6 +94,7 @@ interface UseAgentsFiltersReturn { export function useAgentsFilters( agents: T[] ): UseAgentsFiltersReturn { + const { t } = useTranslation(); const { user } = useUser(); const { mcpData } = useMcpServers(); const { tools: allTools } = useAvailableTools(); @@ -226,24 +228,31 @@ export function useAgentsFilters( // -- Filter button labels -------------------------------------------------- const creatorFilterButtonText = useMemo(() => { - if (selectedCreatorIds.size === 0) return "Everyone"; + if (selectedCreatorIds.size === 0) return t("admin.agents.filter_everyone"); if (selectedCreatorIds.size === 1) { const selectedId = Array.from(selectedCreatorIds)[0]; const creator = uniqueCreators.find((c) => c.id === selectedId); - return creator ? `By ${creator.email}` : "Everyone"; + return creator + ? t("admin.agents.filter_by_email", { email: creator.email }) + : t("admin.agents.filter_everyone"); } - return `${selectedCreatorIds.size} people`; - }, [selectedCreatorIds, uniqueCreators]); + return t("admin.agents.filter_people_count", { + count: selectedCreatorIds.size, + }); + }, [selectedCreatorIds, uniqueCreators, t]); const actionsFilterButtonText = useMemo(() => { - if (selectedActionKeys.size === 0) return "All Actions"; + if (selectedActionKeys.size === 0) + return t("admin.agents.filter_all_actions"); if (selectedActionKeys.size === 1) { const key = Array.from(selectedActionKeys)[0]; const item = uniqueActions.find((a) => actionFilterKey(a) === key); - return item?.name ?? "All Actions"; + return item?.name ?? t("admin.agents.filter_all_actions"); } - return `${selectedActionKeys.size} selected`; - }, [selectedActionKeys, uniqueActions]); + return t("admin.agents.filter_selected_count", { + count: selectedActionKeys.size, + }); + }, [selectedActionKeys, uniqueActions, t]); // -- Filtered agents ------------------------------------------------------- @@ -297,7 +306,7 @@ export function useAgentsFilters( {[ ( selectVariant="select-heavy" icon={SvgUser} title={creator.email} - description={isCurrentUser ? "Me" : undefined} + description={ + isCurrentUser ? t("admin.agents.filter_me") : undefined + } state={isSelected ? "selected" : "empty"} onClick={() => { setSelectedCreatorIds((prev) => { @@ -352,7 +363,7 @@ export function useAgentsFilters( {[
@@ -56,7 +58,7 @@ function Header({ children, onClose }: HeaderProps) { icon={SvgX} prominence="tertiary" onClick={onClose} - tooltip="Close Sidebar" + tooltip={t("chat.sidebar.close_sidebar", "Close Sidebar")} />
@@ -92,6 +94,7 @@ const DocumentsSidebar = memo( selectedDocuments, setPresentingDocument, }: DocumentsSidebarProps) => { + const { t } = useTranslation(); const idOfMessageToDisplay = useSelectedNodeForDocDisplay(); const currentMessageTree = useCurrentMessageTree(); @@ -166,7 +169,9 @@ const DocumentsSidebar = memo(
{hasCited && (
-
Cited Sources
+
+ {t("chat.sidebar.cited_sources", "Cited Sources")} +
{citedDocuments.map((document) => (
- {citedDocuments.length > 0 ? "More" : "Found Sources"} + {citedDocuments.length > 0 + ? t("chat.sidebar.more", "More") + : t("chat.sidebar.found_sources", "Found Sources")}
{otherDocuments.map((document) => ( @@ -206,7 +213,9 @@ const DocumentsSidebar = memo( {humanFileDescriptors && humanFileDescriptors.length > 0 && (
-
User Files
+
+ {t("chat.sidebar.user_files", "User Files")} +
{humanFileDescriptors.map((file) => ( { + const { t } = useTranslation(); const [isRecording, setIsRecording] = useState(false); const [recordingCycleCount, setRecordingCycleCount] = useState(0); const [isMuted, setIsMuted] = useState(false); @@ -203,55 +204,6 @@ const AppInputBar = React.memo( const isSearchMode = (isNewSession && appMode === "search") || isSearchActive; - // Keyed by chat session id, or "new" until the session is created. - const chatSessionId = appFocus.isChat() ? appFocus.getId() : null; - const chatDraftStorageKey = draftKey("chat", chatSessionId ?? "new"); - const { - draft: chatDraft, - loaded: chatDraftLoaded, - save: saveChatDraft, - clear: clearChatDraft, - } = useDraft({ key: chatDraftStorageKey }); - const draftSeededRef = useRef(false); - const skipNextDraftSaveRef = useRef(false); - const prevDraftKeyRef = useRef(chatDraftStorageKey); - // Snapshot of message, read non-reactively in the restore effect so seeding - // doesn't re-run on every keystroke. - const messageRef = useRef(message); - messageRef.current = message; - - useEffect(() => { - draftSeededRef.current = false; - // Clear the previous session's leftover text instead of leaking it into - // this one. - if (prevDraftKeyRef.current !== chatDraftStorageKey) { - prevDraftKeyRef.current = chatDraftStorageKey; - clearMessage(); - } - }, [chatDraftStorageKey, clearMessage]); - - // Restore once read: a URL prompt wins and a non-empty input is never - // clobbered. - useEffect(() => { - if (!chatDraftLoaded || draftSeededRef.current) return; - draftSeededRef.current = true; - if (chatDraft && !initialMessage && !messageRef.current) { - // Skip the save effect's next run; it would fire with the stale empty - // message and wipe what we just seeded. - skipNextDraftSaveRef.current = true; - setMessage(chatDraft); - } - }, [chatDraftLoaded, chatDraft, initialMessage, setMessage]); - - useEffect(() => { - if (!chatDraftLoaded || !draftSeededRef.current) return; - if (skipNextDraftSaveRef.current) { - skipNextDraftSaveRef.current = false; - return; - } - saveChatDraft(message); - }, [message, chatDraftLoaded, saveChatDraft]); - const handleRecordingChange = useCallback((nextIsRecording: boolean) => { setIsRecording((prevIsRecording) => { if (!prevIsRecording && nextIsRecording) { @@ -275,9 +227,8 @@ const AppInputBar = React.memo( return; } handleSubmit(text); - clearChatDraft(); }, - [handleSubmit, clearChatDraft] + [handleSubmit] ); // Expose reset and focus methods to parent via ref @@ -285,7 +236,6 @@ const AppInputBar = React.memo( reset: () => { if (!isAutoSending.current) { clearMessage(); - clearChatDraft(); } }, focus: () => { @@ -632,7 +582,7 @@ const AppInputBar = React.memo( diff --git a/web/src/sections/modals/ShareChatSessionModal.tsx b/web/src/sections/modals/ShareChatSessionModal.tsx index 66a7a6b1..bc7f79d6 100644 --- a/web/src/sections/modals/ShareChatSessionModal.tsx +++ b/web/src/sections/modals/ShareChatSessionModal.tsx @@ -1,6 +1,7 @@ "use client"; import { useState } from "react"; +import { useTranslation } from "react-i18next"; import { ChatSession, ChatSessionSharedStatus } from "@/app/app/interfaces"; import { useChatSessionStore } from "@/app/app/stores/useChatSessionStore"; import { copyAll } from "@/app/app/message/copyingUtils"; @@ -96,6 +97,7 @@ export default function ShareChatSessionModal({ chatSession, onClose, }: ShareChatSessionModalProps) { + const { t } = useTranslation(); const isCurrentlyPublic = chatSession.shared_status === ChatSessionSharedStatus.Public; @@ -117,11 +119,11 @@ export default function ShareChatSessionModal({ let submitButtonText: string; if (isShared) { - submitButtonText = "Copy Link"; + submitButtonText = t("chat.share.copy_link"); } else if (isCurrentlyPublic && !wantsPublic) { - submitButtonText = "Make Private"; + submitButtonText = t("chat.share.make_private"); } else { - submitButtonText = "Create Share Link"; + submitButtonText = t("chat.share.create_share_link"); } const submitDisabled = isLoading || (!isCurrentlyPublic && !wantsPublic); @@ -136,9 +138,9 @@ export default function ShareChatSessionModal({ updateCurrentChatSessionSharedStatus(ChatSessionSharedStatus.Public); await refreshChatSessions(); copyAll(link); - toast.success("Share link copied to clipboard!"); + toast.success(t("chat.share.toast_copied")); } else { - toast.error("Failed to generate share link"); + toast.error(t("chat.share.toast_generate_failed")); } } else if (!wantsPublic && isCurrentlyPublic) { const success = await deleteShareLink(chatSession.id); @@ -146,20 +148,20 @@ export default function ShareChatSessionModal({ setShareLink(""); updateCurrentChatSessionSharedStatus(ChatSessionSharedStatus.Private); await refreshChatSessions(); - toast.success("Chat is now private"); + toast.success(t("chat.share.toast_now_private")); onClose(); } else { - toast.error("Failed to make chat private"); + toast.error(t("chat.share.toast_private_failed")); } } else if (wantsPublic && shareLink) { copyAll(shareLink); - toast.success("Share link copied to clipboard!"); + toast.success(t("chat.share.toast_copied")); } else { onClose(); } } catch (e) { console.error(e); - toast.error("An error occurred"); + toast.error(t("chat.share.toast_error")); } finally { setIsLoading(false); } @@ -170,8 +172,10 @@ export default function ShareChatSessionModal({ @@ -183,16 +187,16 @@ export default function ShareChatSessionModal({ > setSelectedPrivacy("private")} ariaLabel="share-modal-option-private" /> setSelectedPrivacy("public")} ariaLabel="share-modal-option-public" @@ -207,7 +211,7 @@ export default function ShareChatSessionModal({ rightChildren={ shareLink} - tooltip="Copy link" + tooltip={t("chat.share.copy_link_tooltip")} size="sm" aria-label="share-modal-copy-link" /> @@ -222,7 +226,7 @@ export default function ShareChatSessionModal({ onClick={onClose} aria-label="share-modal-cancel" > - Cancel + {t("general.cancel")} )}
@@ -123,7 +125,7 @@ export default function NonAdminStep() {
{ @@ -149,7 +151,7 @@ export default function NonAdminStep() {
{/* TODO(@raunakab): migrate to opal Button once className/iconClassName is resolved */} - +
diff --git a/web/src/sections/onboarding/components/OnboardingHeader.tsx b/web/src/sections/onboarding/components/OnboardingHeader.tsx index 6bf2691e..7a01ea51 100644 --- a/web/src/sections/onboarding/components/OnboardingHeader.tsx +++ b/web/src/sections/onboarding/components/OnboardingHeader.tsx @@ -11,6 +11,7 @@ import { SvgProgressCircle, SvgX } from "@opal/icons"; import { Card } from "@/refresh-components/cards"; import { Section } from "@/layouts/general-layouts"; import { ContentAction } from "@opal/layouts"; +import { useTranslation } from "react-i18next"; interface OnboardingHeaderProps { state: OnboardingState; @@ -25,9 +26,44 @@ const OnboardingHeader = React.memo( handleHideOnboarding, handleFinishOnboarding, }: OnboardingHeaderProps) => { + const { t } = useTranslation(); const iconPercentage = STEP_CONFIG[onboardingState.currentStep].iconPercentage; - const stepButtonText = STEP_CONFIG[onboardingState.currentStep].buttonText; + const rawTitle = STEP_CONFIG[onboardingState.currentStep].title; + const rawButtonText = STEP_CONFIG[onboardingState.currentStep].buttonText; + + let title = rawTitle; + if (rawTitle === "Let's take a moment to get you set up.") { + title = t( + "onboarding.setup_title", + "Let's take a moment to get you set up." + ); + } else if ( + rawTitle === "Almost there! Connect your models to start chatting." + ) { + title = t( + "onboarding.connect_models_title", + "Almost there! Connect your models to start chatting." + ); + } else if ( + rawTitle === + "You're all set, review the optional settings or click Finish Setup" + ) { + title = t( + "onboarding.complete_title", + "You're all set, review the optional settings or click Finish Setup" + ); + } + + let stepButtonText = rawButtonText; + if (rawButtonText === "Let's Go") { + stepButtonText = t("onboarding.btn_lets_go", "Let's Go"); + } else if (rawButtonText === "Next") { + stepButtonText = t("onboarding.btn_next", "Next"); + } else if (rawButtonText === "Finish Setup") { + stepButtonText = t("onboarding.btn_finish_setup", "Finish Setup"); + } + const isWelcomeStep = onboardingState.currentStep === OnboardingStep.Welcome; const isCompleteStep = @@ -44,7 +80,7 @@ const OnboardingHeader = React.memo( icon={(props) => ( )} - title={STEP_CONFIG[onboardingState.currentStep].title} + title={title} sizePreset="main-ui" variant="body" color="muted" @@ -54,8 +90,11 @@ const OnboardingHeader = React.memo(
{!isWelcomeStep && ( - Step {onboardingState.stepIndex} of{" "} - {onboardingState.totalSteps} + {t("onboarding.step_indicator", { + defaultValue: "Step {{current}} of {{total}}", + current: onboardingState.stepIndex, + total: onboardingState.totalSteps, + })} )} } diff --git a/web/src/sections/onboarding/steps/LLMStep.tsx b/web/src/sections/onboarding/steps/LLMStep.tsx index ed33003b..2a8df2cc 100644 --- a/web/src/sections/onboarding/steps/LLMStep.tsx +++ b/web/src/sections/onboarding/steps/LLMStep.tsx @@ -1,6 +1,7 @@ "use client"; import { memo, useState, useCallback } from "react"; +import { useTranslation } from "react-i18next"; import Text from "@/refresh-components/texts/Text"; import { Button, Divider } from "@opal/components"; import LLMProviderCard from "@/sections/onboarding/components/LLMProviderCard"; @@ -90,6 +91,7 @@ const LLMStep = memo( actions: onboardingActions, disabled, }: LLMStepProps) => { + const { t } = useTranslation(); const { llmProviderOptions, isLoading } = useLLMProviderOptions(); const llmDescriptors = llmProviderOptions ?? []; @@ -143,7 +145,7 @@ const LLMStep = memo( rightIcon={SvgExternalLink} href="/admin/configuration/language-models" > - View in Admin Panel + {t("onboarding.llm.btn_view_admin", "View in Admin Panel")} } /> @@ -235,7 +237,7 @@ const LLMStep = memo( onboardingActions.setButtonActive(true); onboardingActions.goToStep(OnboardingStep.LlmSetup); }} - aria-label="Edit LLM providers" + aria-label={t("onboarding.llm.edit_providers", "Edit LLM providers")} >
diff --git a/web/src/sections/onboarding/steps/NameStep.tsx b/web/src/sections/onboarding/steps/NameStep.tsx index dbd41f2c..d4e5c45e 100644 --- a/web/src/sections/onboarding/steps/NameStep.tsx +++ b/web/src/sections/onboarding/steps/NameStep.tsx @@ -1,6 +1,7 @@ "use client"; import React, { useRef } from "react"; +import { useTranslation } from "react-i18next"; import Text from "@/refresh-components/texts/Text"; import { InputTypeIn } from "@opal/components"; import { @@ -22,6 +23,7 @@ export interface NameStepProps { const NameStep = React.memo( ({ state: onboardingState, actions: onboardingActions }: NameStepProps) => { + const { t } = useTranslation(); const { userName } = onboardingState.data; const { updateName, goToStep, setButtonActive, nextStep } = onboardingActions; @@ -49,7 +51,7 @@ const NameStep = React.memo( @@ -93,7 +95,7 @@ const NameStep = React.memo(
{/* TODO(@raunakab): migrate to opal Button once className/iconClassName is resolved */} - + p.id === currentProjectId); - const projectName = currentProject?.name || "Loading project..."; + const projectName = currentProject?.name || t("projects.loading_project"); if (!currentProjectId) return null; // no selection yet @@ -110,8 +112,8 @@ export default function ProjectContextPanel({ addInstructionModal.toggle(true)} interaction={addInstructionModal.isOpen ? "active" : undefined} > - Set Instructions + {t("projects.set_instructions")} } /> @@ -168,8 +170,8 @@ export default function ProjectContextPanel({ - Add Files + {t("projects.add_files")} )} onFileClick={handleOnView} @@ -215,8 +217,10 @@ export default function ProjectContextPanel({ projectFilesModal.toggle(true)} @@ -242,8 +246,10 @@ export default function ProjectContextPanel({ } @@ -257,9 +263,7 @@ export default function ProjectContextPanel({ {projectTokenCount > availableContextTokens && ( - This project exceeds the model's context limits. Sessions - will automatically search for relevant files first before - generating response. + {t("projects.context_limit_warning")} )} @@ -274,8 +278,8 @@ export default function ProjectContextPanel({ > {isDragActive - ? "Drop files here to add to this project" - : "Add documents, texts, or images to use in the project. Drag & drop supported."} + ? t("projects.dropzone_active") + : t("projects.dropzone_desc")}
)} diff --git a/web/src/sections/settings/Memories.tsx b/web/src/sections/settings/Memories.tsx index b33fcf06..6ec891a0 100644 --- a/web/src/sections/settings/Memories.tsx +++ b/web/src/sections/settings/Memories.tsx @@ -9,6 +9,7 @@ import LineItem from "@/refresh-components/buttons/LineItem"; import { Button } from "@opal/components"; import { useCreateModal } from "@opal/components"; import { MemoryItem } from "@/lib/types"; +import { useTranslation } from "react-i18next"; interface MemoriesProps { memories: MemoryItem[]; @@ -18,13 +19,17 @@ interface MemoriesProps { export default function Memories({ memories, onSaveMemories }: MemoriesProps) { const memoriesModal = useCreateModal(); const [targetMemoryId, setTargetMemoryId] = useState(null); + const { t } = useTranslation(); return ( <> {memories.length === 0 ? ( { setTargetMemoryId(null); memoriesModal.toggle(true); @@ -55,8 +60,8 @@ export default function Memories({ memories, onSaveMemories }: MemoriesProps) { ))}
{ setTargetMemoryId(null); diff --git a/web/src/sections/sidebar/AccountPopover.tsx b/web/src/sections/sidebar/AccountPopover.tsx index 317781d7..0c76859c 100644 --- a/web/src/sections/sidebar/AccountPopover.tsx +++ b/web/src/sections/sidebar/AccountPopover.tsx @@ -1,6 +1,7 @@ "use client"; import { useState } from "react"; +import { useTranslation } from "react-i18next"; import { LOGOUT_DISABLED } from "@/lib/constants"; import { preload } from "swr"; import { errorHandlingFetcher } from "@/lib/fetcher"; @@ -44,6 +45,7 @@ function SettingsPopover({ onOpenNotifications, undismissedCount, }: SettingsPopoverProps) { + const { t } = useTranslation(); const { user } = useUser(); const settings = useSettings(); const enterpriseSettings = settings.enterprise; @@ -67,7 +69,7 @@ function SettingsPopover({ logout() .then((response) => { if (!response?.ok) { - alert("Failed to logout"); + alert(t("account.logout_failed")); return; } @@ -81,7 +83,7 @@ function SettingsPopover({ }) .catch(() => { - toast.error("Failed to logout"); + toast.error(t("account.logout_failed")); }); }; @@ -98,7 +100,7 @@ function SettingsPopover({ variant="section" rounding="sm" icon={SvgSliders} - title="Settings" + title={t("general.settings")} href="/app/settings" onClick={onUserSettingsClick} /> @@ -109,7 +111,7 @@ function SettingsPopover({ variant="section" rounding="sm" icon={SvgBell} - title="Notifications" + title={t("account.notifications")} onClick={onOpenNotifications} rightChildren={ undismissedCount ? ( @@ -123,7 +125,7 @@ function SettingsPopover({ variant="section" rounding="sm" icon={SvgHelpCircle} - title="Help & FAQ" + title={t("account.help_faq")} href="https://docs.onyx.app" target="_blank" />, @@ -149,7 +151,7 @@ function SettingsPopover({ variant="section" rounding="sm" icon={SvgUser} - title="Log in" + title={t("account.log_in")} onClick={handleLogin} /> ), @@ -161,7 +163,7 @@ function SettingsPopover({ color="danger" rounding="sm" icon={SvgLogOut} - title="Log Out" + title={t("general.logout")} onClick={handleLogout} /> ), diff --git a/web/src/sections/sidebar/AppSidebar.tsx b/web/src/sections/sidebar/AppSidebar.tsx index ba15f518..67dbc2db 100644 --- a/web/src/sections/sidebar/AppSidebar.tsx +++ b/web/src/sections/sidebar/AppSidebar.tsx @@ -1,6 +1,7 @@ "use client"; import { useCallback, useMemo, useState, useEffect, useRef } from "react"; +import { useTranslation } from "react-i18next"; import useNotifications from "@/hooks/useNotifications"; import { useRouter } from "next/navigation"; import { useSettings } from "@/lib/settings/hooks"; @@ -120,6 +121,7 @@ function RecentsSection({ isLoadingMore, onLoadMore, }: RecentsSectionProps) { + const { t } = useTranslation(); const { setNodeRef, isOver } = useDroppable({ id: DRAG_TYPES.RECENTS, data: { @@ -162,7 +164,7 @@ function RecentsSection({ isOver && "bg-background-tint-03" )} > - + {chatSessions.length === 0 ? ( Try sending a message! Your chat history will appear here. @@ -197,6 +199,7 @@ function RecentsSection({ } export default function AppSidebar() { + const { t } = useTranslation(); const { folded } = useSidebarState(); const router = useRouter(); const combinedSettingsData = useSettings(); @@ -493,7 +496,7 @@ export default function AppSidebar() { reset(); }} > - New Session + {t("sidebar.new_session", "New Session")}
); @@ -526,7 +529,7 @@ export default function AppSidebar() { - Search Chats + {t("sidebar.search_chats", "Search Chats")} } /> @@ -547,7 +550,9 @@ export default function AppSidebar() { selected={activeSidebarTab.isMoreAgents()} variant={folded ? "sidebar-heavy" : "sidebar-light"} > - {visibleAgents.length === 0 ? "Explore Agents" : "More Agents"} + {visibleAgents.length === 0 + ? t("sidebar.explore_agents", "Explore Agents") + : t("sidebar.more_agents", "More Agents")}
), @@ -681,7 +686,7 @@ export default function AppSidebar() { collisionDetection={closestCenter} onDragEnd={handleAgentDragEnd} > - + {/* Projects */} createProjectModal.toggle(true)} /> } diff --git a/web/src/sections/sidebar/ChatButton.tsx b/web/src/sections/sidebar/ChatButton.tsx index 1574dbdd..95a62ed9 100644 --- a/web/src/sections/sidebar/ChatButton.tsx +++ b/web/src/sections/sidebar/ChatButton.tsx @@ -1,6 +1,7 @@ "use client"; import React, { useState, memo, useMemo, useEffect } from "react"; +import { useTranslation } from "react-i18next"; import { useDraggable } from "@dnd-kit/core"; import useChatSessions from "@/hooks/useChatSessions"; import { deleteChatSession, renameChatSession } from "@/app/app/services/lib"; @@ -10,11 +11,11 @@ import { noProp } from "@/lib/utils"; import { cn } from "@opal/utils"; import { Popover, PopoverMenu } from "@opal/components"; import { useAppRouter } from "@/hooks/appNavigation"; -import type { Project } from "@/lib/projects/types"; import { removeChatSessionFromProject, createProject as createProjectService, } from "@/lib/projects/svc"; +import type { Project } from "@/lib/projects/types"; import { useProjectsContext } from "@/providers/ProjectsContext"; import MoveCustomAgentChatModal from "@/sections/modals/MoveCustomAgentChatModal"; import { UNNAMED_CHAT } from "@/lib/constants"; @@ -52,6 +53,7 @@ export function PopoverSearchInput({ setShowMoveOptions, onSearch, }: PopoverSearchInputProps) { + const { t } = useTranslation(); const [searchTerm, setSearchTerm] = useState(""); const handleChange = (e: React.ChangeEvent) => { @@ -84,7 +86,7 @@ export function PopoverSearchInput({ value={searchTerm} onChange={handleChange} onKeyDown={handleKeyDown} - placeholder="Search Projects" + placeholder={t("projects.search_projects")} onClick={noProp()} variant="internal" autoFocus @@ -101,6 +103,7 @@ export interface ChatButtonProps { const ChatButton = memo( ({ chatSession, project, draggable = false }: ChatButtonProps) => { + const { t } = useTranslation(); const route = useAppRouter(); const activeSidebarTab = useAppFocus(); const active = useMemo( @@ -193,7 +196,7 @@ const ChatButton = memo( sizePreset="main-ui" rounding="sm" icon={SvgShare} - title="Share" + title={t("projects.share")} onClick={noProp(() => setShowShareModal(true))} />, setRenaming(true))} />, setShowMoveOptions(true))} />, project && ( @@ -218,7 +221,7 @@ const ChatButton = memo( sizePreset="main-ui" rounding="sm" icon={SvgFolder} - title={`Remove from ${project.name}`} + title={t("projects.remove_from_project", { name: project.name })} onClick={noProp(() => handleRemoveFromProject())} /> ), @@ -229,7 +232,7 @@ const ChatButton = memo( rounding="sm" color="danger" icon={SvgTrash} - title="Delete" + title={t("projects.delete")} onClick={noProp(() => setDeleteConfirmationModalOpen(true))} />, ]; @@ -264,7 +267,9 @@ const ChatButton = memo( sizePreset="main-ui" rounding="sm" icon={SvgFolderPlus} - title={`Create ${searchTerm.trim()}`} + title={t("projects.create_with_name", { + name: searchTerm.trim(), + })} onClick={noProp(() => handleCreateProjectAndMove(searchTerm.trim()) )} @@ -285,6 +290,7 @@ const ChatButton = memo( chatSession.id, searchTerm, createProject, + t, ]); // Pin the chat's agent when clicking on the conversation @@ -457,7 +463,7 @@ const ChatButton = memo( <> {deleteConfirmationModalOpen && ( setDeleteConfirmationModalOpen(false)} submit={ @@ -468,12 +474,11 @@ const ChatButton = memo( handleChatDelete(); }} > - Delete + {t("projects.delete")} } > - Are you sure you want to delete this chat? This action cannot be - undone. + {t("projects.delete_chat_confirm")} )} diff --git a/web/src/sections/sidebar/ChatSearchCommandMenu.tsx b/web/src/sections/sidebar/ChatSearchCommandMenu.tsx index 0fc795d7..1697cb84 100644 --- a/web/src/sections/sidebar/ChatSearchCommandMenu.tsx +++ b/web/src/sections/sidebar/ChatSearchCommandMenu.tsx @@ -1,6 +1,7 @@ "use client"; import React, { useState, useMemo, useCallback } from "react"; +import { useTranslation } from "react-i18next"; import { useRouter } from "next/navigation"; import type { Route } from "next"; import CommandMenu, { @@ -29,16 +30,23 @@ import TextSeparator from "@/refresh-components/TextSeparator"; * Dynamic footer that shows contextual action labels based on highlighted item type */ function DynamicFooter() { + const { t } = useTranslation(); const { highlightedItemType } = useCommandMenuContext(); // "Show all" for filters, "Open" for everything else (items, actions, or no highlight) - const actionLabel = highlightedItemType === "filter" ? "Show all" : "Open"; + const actionLabel = + highlightedItemType === "filter" + ? t("sidebar.search.show_all", "Show all") + : t("sidebar.search.open", "Open"); return ( - + } @@ -60,6 +68,7 @@ interface FilterableProject { export default function ChatSearchCommandMenu({ trigger, }: ChatSearchCommandMenuProps) { + const { t } = useTranslation(); const [open, setOpen] = useState(false); const [searchValue, setSearchValue] = useState(""); const [activeFilter, setActiveFilter] = useState< @@ -135,13 +144,13 @@ export default function ChatSearchCommandMenu({ // Header filters for showing active filter as a chip const headerFilters = useMemo(() => { if (activeFilter === "chats") { - return [{ id: "chats", label: "Sessions" }]; + return [{ id: "chats", label: t("sidebar.search.sessions", "Sessions") }]; } if (activeFilter === "projects") { - return [{ id: "projects", label: "Projects" }]; + return [{ id: "projects", label: t("sidebar.projects", "Projects") }]; } return []; - }, [activeFilter]); + }, [activeFilter, t]); const handleFilterRemove = useCallback(() => { setActiveFilter("all"); @@ -211,7 +220,10 @@ export default function ChatSearchCommandMenu({ - New Session + {t("sidebar.new_session", "New Session")} )} @@ -250,7 +262,9 @@ export default function ChatSearchCommandMenu({ filteredChats.length <= PREVIEW_CHATS_LIMIT } > - {activeFilter === "chats" ? "Recent" : "Recent Sessions"} + {activeFilter === "chats" + ? t("sidebar.search.recent", "Recent") + : t("sidebar.search.recent_sessions", "Recent Sessions")} )} {displayedChats.map((chat) => ( @@ -302,7 +316,7 @@ export default function ChatSearchCommandMenu({ filteredProjects.length <= PREVIEW_PROJECTS_LIMIT } > - Projects + {t("sidebar.projects", "Projects")} {/* New Project action - shown after Projects filter when no search term */} {!hasSearchValue && activeFilter === "all" && ( @@ -311,7 +325,7 @@ export default function ChatSearchCommandMenu({ icon={SvgFolderPlus} onSelect={() => handleNewProject()} > - New Project + {t("sidebar.new_project", "New Project")} )} {displayedProjects.map((project) => ( diff --git a/web/src/sections/sidebar/ProjectFolderButton.tsx b/web/src/sections/sidebar/ProjectFolderButton.tsx index 0a8b2597..24140167 100644 --- a/web/src/sections/sidebar/ProjectFolderButton.tsx +++ b/web/src/sections/sidebar/ProjectFolderButton.tsx @@ -1,6 +1,7 @@ "use client"; import React, { useState, memo } from "react"; +import { useTranslation } from "react-i18next"; import { Project, useProjectsContext } from "@/providers/ProjectsContext"; import { useDroppable } from "@dnd-kit/core"; import { Button, LineItemButton, SidebarTab } from "@opal/components"; @@ -30,6 +31,7 @@ export interface ProjectFolderButtonProps { } const ProjectFolderButton = memo(({ project }: ProjectFolderButtonProps) => { + const { t } = useTranslation(); const route = useAppRouter(); const [open, setOpen] = useState(false); const [deleteConfirmationModalOpen, setDeleteConfirmationModalOpen] = @@ -88,7 +90,7 @@ const ProjectFolderButton = memo(({ project }: ProjectFolderButtonProps) => { sizePreset="main-ui" rounding="sm" icon={SvgEdit} - title="Rename Project" + title={t("projects.rename_project")} onClick={noProp(() => setIsEditing(true))} />, null, @@ -98,7 +100,7 @@ const ProjectFolderButton = memo(({ project }: ProjectFolderButtonProps) => { rounding="sm" color="danger" icon={SvgTrash} - title="Delete Project" + title={t("projects.delete_project")} onClick={noProp(() => setDeleteConfirmationModalOpen(true))} />, ]; @@ -114,7 +116,7 @@ const ProjectFolderButton = memo(({ project }: ProjectFolderButtonProps) => { {/* Confirmation Modal (only for deletion) */} {deleteConfirmationModalOpen && ( setDeleteConfirmationModalOpen(false)} submit={ @@ -125,12 +127,11 @@ const ProjectFolderButton = memo(({ project }: ProjectFolderButtonProps) => { deleteProject(project.id); }} > - Delete + {t("projects.delete")} } > - Are you sure you want to delete this project? This action cannot be - undone. + {t("projects.delete_project_confirm")} )} diff --git a/web/src/views/AgentEditorPage.tsx b/web/src/views/AgentEditorPage.tsx index 9325a2e0..22e03b5e 100644 --- a/web/src/views/AgentEditorPage.tsx +++ b/web/src/views/AgentEditorPage.tsx @@ -1,6 +1,7 @@ "use client"; import { useState, useRef, useEffect, useCallback } from "react"; +import { useTranslation } from "react-i18next"; import { useRouter } from "next/navigation"; import { SettingsLayouts, toast } from "@opal/layouts"; import * as GeneralLayouts from "@/layouts/general-layouts"; @@ -128,6 +129,7 @@ function FormWarningsEffect() { } function AgentIconEditor({ existingAgent }: AgentIconEditorProps) { + const { t } = useTranslation(); const { values, setFieldValue } = useFormikContext<{ name: string; icon_name: string | null; @@ -248,7 +250,7 @@ function AgentIconEditor({ existingAgent }: AgentIconEditorProps) { onClick={() => fileInputRef.current?.click()} emphasized > - Upload Image + {t("agents.upload_image")} , null,
@@ -547,6 +549,7 @@ export default function AgentEditorPage({ agent: existingAgent, refreshAgent, }: AgentEditorPageProps) { + const { t } = useTranslation(); const router = useRouter(); const appRouter = useAppRouter(); const { refresh: refreshAgents } = useAgents(); @@ -1224,7 +1227,7 @@ export default function AgentEditorPage({ { @@ -1296,7 +1299,7 @@ export default function AgentEditorPage({ {deleteAgentModal.isOpen && ( Delete Agent @@ -1352,7 +1355,9 @@ export default function AgentEditorPage({ } type="submit" > - {existingAgent ? "Save" : "Create"} + {existingAgent + ? t("admin.agents.editor_save") + : t("admin.agents.editor_create")}
@@ -1377,21 +1382,28 @@ export default function AgentEditorPage({ alignItems="start" > - + @@ -1399,7 +1411,7 @@ export default function AgentEditorPage({ @@ -1414,8 +1426,8 @@ export default function AgentEditorPage({ @@ -1496,14 +1508,14 @@ export default function AgentEditorPage({ height="auto" > @@ -1519,7 +1531,7 @@ export default function AgentEditorPage({ <> @@ -1587,8 +1599,8 @@ export default function AgentEditorPage({ @@ -1740,8 +1772,10 @@ export default function AgentEditorPage({ @@ -1783,8 +1817,8 @@ export default function AgentEditorPage({ )} diff --git a/web/src/views/AgentsNavigationPage.tsx b/web/src/views/AgentsNavigationPage.tsx index c0ba4db2..ee97e896 100644 --- a/web/src/views/AgentsNavigationPage.tsx +++ b/web/src/views/AgentsNavigationPage.tsx @@ -44,7 +44,10 @@ function AgentsSection({ title, description, agents }: AgentsSectionProps) { ); } +import { useTranslation } from "react-i18next"; + export default function AgentsNavigationPage() { + const { t } = useTranslation(); const { agents } = useAgents(); const { user } = useUser(); const [searchQuery, setSearchQuery] = useState(""); @@ -95,15 +98,15 @@ export default function AgentsNavigationPage() { > - New Agent + {t("agents.new_agent")} } > @@ -112,7 +115,7 @@ export default function AgentsNavigationPage() {
setSearchQuery(event.target.value)} searchIcon @@ -124,8 +127,12 @@ export default function AgentsNavigationPage() { onValueChange={(value) => setActiveTab(value as "all" | "your")} > - All Agents - Your Agents + + {t("agents.all_agents")} + + + {t("agents.your_agents")} +
@@ -142,19 +149,23 @@ export default function AgentsNavigationPage() { className="w-full h-full flex flex-col items-center justify-center py-12" text03 > - No Agents found + {t("agents.no_agents")} ) : ( <> - + )} diff --git a/web/src/views/AppPage.tsx b/web/src/views/AppPage.tsx index a051002d..535af1b5 100644 --- a/web/src/views/AppPage.tsx +++ b/web/src/views/AppPage.tsx @@ -1,6 +1,7 @@ "use client"; import { redirect, useRouter, useSearchParams } from "next/navigation"; +import { useTranslation } from "react-i18next"; import { personaIncludesRetrieval } from "@/app/app/services/lib"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { SEARCH_PARAM_NAMES } from "@/app/app/services/searchParams"; @@ -111,6 +112,7 @@ export interface ChatPageProps { } export default function AppPage({ firstMessage }: ChatPageProps) { + const { t } = useTranslation(); // Performance tracking // Keeping this here in case we need to track down slow renders in the future // const renderCount = useRef(0); @@ -742,7 +744,7 @@ export default function AppPage({ firstMessage }: ChatPageProps) { updateCurrentDocumentSidebarVisible(false)} /> diff --git a/web/src/views/SettingsPage.tsx b/web/src/views/SettingsPage.tsx index f1638662..de08d7ca 100644 --- a/web/src/views/SettingsPage.tsx +++ b/web/src/views/SettingsPage.tsx @@ -33,6 +33,7 @@ import InputSelect from "@/refresh-components/inputs/InputSelect"; import { Switch } from "@opal/components"; import { useUser } from "@/providers/UserProvider"; import { useTheme } from "next-themes"; +import { useTranslation } from "react-i18next"; import { MemoryItem, ThemePreference } from "@/lib/types"; import useUserPersonalization from "@/hooks/useUserPersonalization"; import ModelSelector from "@/sections/model-selector/ModelSelector"; @@ -122,6 +123,7 @@ function ScopeSelector({ scopesError, disabled, }: ScopeSelectorProps) { + const { t } = useTranslation(); const groups = useMemo(() => { const byLabel = new Map(); for (const option of scopeOptions) { @@ -141,14 +143,17 @@ function ScopeSelector({ if (scopesError) { return ( - Couldn't load permissions. + {t( + "settings.accounts.err_could_not_load_pats", + "Couldn't load permissions." + )} ); } if (scopeOptions.length === 0) { return ( - Loading permissions... + {t("settings.accounts.loading_permissions", "Loading permissions...")} ); } @@ -181,7 +186,11 @@ function ScopeSelector({
{locked - ? `${option.label} (included with ${lockReason})` + ? t("settings.accounts.scope_included_with", { + defaultValue: `${option.label} (included with ${lockReason})`, + label: option.label, + reason: lockReason, + }) : option.label} {/* Fixed 2-line slot so every row is the same height. */} @@ -233,15 +242,19 @@ function PATModal({ onCreate, createdToken, }: PATModalProps) { + const { t } = useTranslation(); if (createdToken?.token) { return ( !open && onClose()}> {createdToken.token} @@ -253,7 +266,7 @@ function PATModal({ getCopyText={() => createdToken.token} prominence="primary" > - Copy Token + {t("settings.accounts.btn_copy_token", "Copy Token")} } /> @@ -266,8 +279,11 @@ function PATModal({ return ( - {isCreating ? "Creating Token..." : "Create Token"} + {isCreating + ? t("settings.accounts.creating_token", "Creating Token...") + : t("settings.accounts.create_token", "Create Token")} } >
- + setNewTokenName(e.target.value)} variant={isCreating ? "disabled" : undefined} @@ -293,7 +317,7 @@ function PATModal({ /> - + - 7 days - 30 days - 365 days - No expiration + + {t("settings.accounts.days_7", "7 days")} + + + {t("settings.accounts.days_30", "30 days")} + + + {t("settings.accounts.days_365", "365 days")} + + + {t("settings.accounts.no_expiration", "No expiration")} + @@ -339,11 +387,18 @@ function PATModal({ onValueChange={(value) => setAccessMode(value as AccessMode)} disabled={isCreating} > - + - Full access + + {t("settings.accounts.full_access", "Full access")} + - Limited access + {t("settings.accounts.permissions_limited", "Limited access")} @@ -367,9 +422,11 @@ function GeneralSettings() { user, updateUserPersonalization, updateUserThemePreference, + updateUserLanguagePreference, updateUserChatBackground, } = useUser(); const { theme, setTheme, systemTheme } = useTheme(); + const { t, i18n } = useTranslation(); const applyBackground = useCallback( async (bg: (typeof CHAT_BACKGROUND_OPTIONS)[number]) => { @@ -399,8 +456,20 @@ function GeneralSettings() { updatePersonalizationField, handleSavePersonalization, } = useUserPersonalization(user, updateUserPersonalization, { - onSuccess: () => toast.success("Personalization updated successfully"), - onError: () => toast.error("Failed to update personalization"), + onSuccess: () => + toast.success( + t( + "settings.danger_zone.toast_update_personalization_success", + "Personalization updated successfully" + ) + ), + onError: () => + toast.error( + t( + "settings.danger_zone.toast_update_personalization_failed", + "Failed to update personalization" + ) + ), }); // Track initial values to detect changes @@ -418,25 +487,35 @@ function GeneralSettings() { try { const response = await deleteAllChatSessions(); if (response.ok) { - toast.success("All your chat sessions have been deleted."); + toast.success( + t( + "settings.danger_zone.toast_success", + "All your chat sessions have been deleted." + ) + ); await refreshChatSessions(); setShowDeleteConfirmation(false); } else { throw new Error("Failed to delete all chat sessions"); } } catch (error) { - toast.error("Failed to delete all chat sessions"); + toast.error( + t( + "settings.danger_zone.toast_failed", + "Failed to delete all chat sessions" + ) + ); } finally { setIsDeleting(false); } - }, [pathname, router, refreshChatSessions]); + }, [pathname, router, refreshChatSessions, t]); return ( <> {showDeleteConfirmation && ( setShowDeleteConfirmation(false)} submit={ } >
- All your chat sessions and history will be permanently deleted. - Deletion cannot be undone. + {t( + "settings.danger_zone.confirm_desc_1", + "All your chat sessions and history will be permanently deleted. Deletion cannot be undone." + )} - Are you sure you want to delete all chats? + {t( + "settings.danger_zone.confirm_desc_2", + "Are you sure you want to delete all chats?" + )}
@@ -465,21 +551,27 @@ function GeneralSettings() {
updatePersonalizationField("name", e.target.value) @@ -499,14 +591,20 @@ function GeneralSettings() { /> updatePersonalizationField("role", e.target.value) @@ -530,15 +628,18 @@ function GeneralSettings() {
@@ -566,25 +667,52 @@ function GeneralSettings() { : undefined } > - Auto + {t("settings.appearance.mode_auto", "Auto")} } > - Light + {t("settings.appearance.mode_light", "Light")} } > - Dark + {t("settings.appearance.mode_dark", "Dark")} - + + { + updateUserLanguagePreference(value); + }} + > + + + English + Español + Français + Português + Deutsch + + + +
{CHAT_BACKGROUND_OPTIONS.map((bg) => { const currentBackgroundId = @@ -604,7 +732,9 @@ function GeneralSettings() { > {isNone ? (
- None + + {t("settings.appearance.bg_none", "None")} +
) : (
@@ -673,6 +809,7 @@ function PromptShortcuts() { const { promptShortcuts, isLoading, error, refresh } = usePromptShortcuts(); const [shortcuts, setShortcuts] = useState([]); const [isInitialLoad, setIsInitialLoad] = useState(true); + const { t } = useTranslation(); // Initialize shortcuts when input prompts are loaded useEffect(() => { @@ -705,8 +842,10 @@ function PromptShortcuts() { // Show error popup if fetch fails useEffect(() => { if (!error) return; - toast.error("Failed to load shortcuts"); - }, [error]); + toast.error( + t("settings.shortcuts.toast_load_failed", "Failed to load shortcuts") + ); + }, [error, t]); const handleUpdateShortcut = useCallback( (index: number, field: "prompt" | "content", value: string) => { @@ -778,22 +917,34 @@ function PromptShortcuts() { if (response.ok) { setShortcuts((prev) => prev.filter((_, i) => i !== index)); await refresh(); - toast.success("Shortcut deleted"); + toast.success( + t("settings.shortcuts.toast_deleted", "Shortcut deleted") + ); } else { throw new Error("Failed to delete shortcut"); } } catch (error) { - toast.error("Failed to delete shortcut"); + toast.error( + t( + "settings.shortcuts.toast_delete_failed", + "Failed to delete shortcut" + ) + ); } }, - [shortcuts, refresh] + [shortcuts, refresh, t] ); const handleSaveShortcut = useCallback( async (index: number) => { const shortcut = shortcuts[index]; if (!shortcut || !shortcut.prompt.trim() || !shortcut.content.trim()) { - toast.error("Both shortcut and expansion are required"); + toast.error( + t( + "settings.shortcuts.err_both_required", + "Both shortcut and expansion are required" + ) + ); return; } @@ -813,7 +964,9 @@ function PromptShortcuts() { if (response.ok) { await refresh(); - toast.success("Shortcut created"); + toast.success( + t("settings.shortcuts.toast_created", "Shortcut created") + ); } else { throw new Error("Failed to create shortcut"); } @@ -832,16 +985,20 @@ function PromptShortcuts() { if (response.ok) { await refresh(); - toast.success("Shortcut updated"); + toast.success( + t("settings.shortcuts.toast_updated", "Shortcut updated") + ); } else { throw new Error("Failed to update shortcut"); } } } catch (error) { - toast.error("Failed to save shortcut"); + toast.error( + t("settings.shortcuts.toast_save_failed", "Failed to save shortcut") + ); } }, - [shortcuts, refresh] + [shortcuts, refresh, t] ); const handleBlurShortcut = useCallback( @@ -884,7 +1041,10 @@ function PromptShortcuts() { > handleUpdateShortcut(index, "prompt", e.target.value) @@ -908,16 +1068,25 @@ function PromptShortcuts() { icon={SvgMinusCircle} onClick={() => void handleRemoveShortcut(index)} prominence="tertiary" - aria-label="Remove shortcut" + aria-label={t( + "settings.shortcuts.remove_aria", + "Remove shortcut" + )} tooltip={ shortcut.is_public - ? "Cannot delete public prompt-shortcuts." + ? t( + "settings.shortcuts.cannot_delete_public", + "Cannot delete public prompt-shortcuts." + ) : undefined } />
handleUpdateShortcut(index, "content", e.target.value) @@ -964,6 +1133,7 @@ function ChatPreferencesSettings() { enabled: smoothStreamingEnabled, setEnabled: setSmoothStreamingEnabled, } = useSmoothStreaming(); + const { t } = useTranslation(); const { personalizationValues, @@ -972,8 +1142,12 @@ function ChatPreferencesSettings() { updateUserPreferences, handleSavePersonalization, } = useUserPersonalization(user, updateUserPersonalization, { - onSuccess: () => toast.success("Preferences saved"), - onError: () => toast.error("Failed to save preferences"), + onSuccess: () => + toast.success(t("settings.chats.toast_prefs_saved", "Preferences saved")), + onError: () => + toast.error( + t("settings.chats.toast_prefs_failed", "Failed to save preferences") + ), }); const [draftVoicePlaybackSpeed, setDraftVoicePlaybackSpeed] = useState( user?.preferences.voice_playback_speed ?? 1 @@ -991,12 +1165,16 @@ function ChatPreferencesSettings() { }) => { try { await updateUserVoiceSettings(settings); - toast.success("Preferences saved"); + toast.success( + t("settings.chats.toast_prefs_saved", "Preferences saved") + ); } catch { - toast.error("Failed to save preferences"); + toast.error( + t("settings.chats.toast_prefs_failed", "Failed to save preferences") + ); } }, - [updateUserVoiceSettings] + [updateUserVoiceSettings, t] ); const commitVoicePlaybackSpeed = useCallback(() => { @@ -1029,15 +1207,18 @@ function ChatPreferencesSettings() {
- Chat - Search + + {t("settings.chats.mode_chat", "Chat")} + + + {t("settings.chats.mode_search", "Search")} + @@ -1150,12 +1350,21 @@ function ChatPreferencesSettings() {
updateUserPreferences(e.target.value)} onBlur={() => void handleSavePersonalization()} @@ -1170,15 +1379,21 @@ function ChatPreferencesSettings() { />
@@ -1314,21 +1547,42 @@ function AccountsAccessSettings() { const { user, authTypeMetadata } = useUser(); const isMultiTenant = useIsMultiTenant(); const [showPasswordModal, setShowPasswordModal] = useState(false); + const { t } = useTranslation(); // TODO(auth-refresh): only passwordMinLength is enforced here; the remaining // constraints (max length, uppercase, lowercase, digit, special char) will be // wired up when this form is refreshed as part of auth-refresh. const passwordValidationSchema = Yup.object().shape({ - currentPassword: Yup.string().required("Current password is required"), + currentPassword: Yup.string().required( + t( + "settings.accounts.current_password_required", + "Current password is required" + ) + ), newPassword: Yup.string() .min( authTypeMetadata?.passwordMinLength ?? 0, - `Password must be at least ${authTypeMetadata?.passwordMinLength ?? 0} characters` + t("settings.accounts.new_password_min_length", { + defaultValue: `Password must be at least ${ + authTypeMetadata?.passwordMinLength ?? 0 + } characters`, + count: authTypeMetadata?.passwordMinLength ?? 0, + }) ) - .required("New password is required"), + .required( + t("settings.accounts.new_password_required", "New password is required") + ), confirmPassword: Yup.string() - .oneOf([Yup.ref("newPassword")], "Passwords do not match") - .required("Please confirm your new password"), + .oneOf( + [Yup.ref("newPassword")], + t("settings.accounts.passwords_do_not_match", "Passwords do not match") + ) + .required( + t( + "settings.accounts.confirm_password_required", + "Please confirm your new password" + ) + ), }); // PAT state @@ -1398,19 +1652,28 @@ function AccountsAccessSettings() { // Show error popup if SWR fetch fails useEffect(() => { if (error) { - toast.error("Failed to load tokens"); + toast.error( + t("settings.accounts.toast_load_failed", "Failed to load tokens") + ); } - }, [error]); + }, [error, t]); useEffect(() => { if (scopeOptionsError) { - toast.error("Failed to load permission options"); + toast.error( + t( + "settings.accounts.toast_load_scopes_failed", + "Failed to load permission options" + ) + ); } - }, [scopeOptionsError]); + }, [scopeOptionsError, t]); const createPAT = useCallback(async () => { if (!newTokenName.trim()) { - toast.error("Token name is required"); + toast.error( + t("settings.accounts.err_name_required", "Token name is required") + ); return; } @@ -1435,19 +1698,32 @@ function AccountsAccessSettings() { token: data.token, name: newTokenName, }); - toast.success("Token created successfully"); + toast.success( + t( + "settings.accounts.toast_create_success", + "Token created successfully" + ) + ); // Revalidate the token list await mutate(); } else { const errorData = await response.json(); - toast.error(errorData.detail || "Failed to create token"); + toast.error( + errorData.detail || + t("settings.accounts.toast_create_failed", "Failed to create token") + ); } } catch (error) { - toast.error("Network error creating token"); + toast.error( + t( + "settings.accounts.toast_create_network_error", + "Network error creating token" + ) + ); } finally { setIsCreating(false); } - }, [newTokenName, expirationDays, accessMode, selectedScopes, mutate]); + }, [newTokenName, expirationDays, accessMode, selectedScopes, mutate, t]); const deletePAT = useCallback( async (patId: number) => { @@ -1462,16 +1738,28 @@ function AccountsAccessSettings() { setNewlyCreatedToken(null); } await mutate(); - toast.success("Token deleted successfully"); + toast.success( + t( + "settings.accounts.toast_delete_success", + "Token deleted successfully" + ) + ); setTokenToDelete(null); } else { - toast.error("Failed to delete token"); + toast.error( + t("settings.accounts.toast_delete_failed", "Failed to delete token") + ); } } catch (error) { - toast.error("Network error deleting token"); + toast.error( + t( + "settings.accounts.toast_delete_network_error", + "Network error deleting token" + ) + ); } }, - [newlyCreatedToken, mutate] + [newlyCreatedToken, mutate, t] ); const handleChangePassword = useCallback( @@ -1493,17 +1781,30 @@ function AccountsAccessSettings() { }); if (response.ok) { - toast.success("Password updated successfully"); + toast.success( + t( + "settings.accounts.toast_success", + "Password updated successfully" + ) + ); setShowPasswordModal(false); } else { const errorData = await response.json(); - toast.error(errorData.detail || "Failed to change password"); + toast.error( + errorData.detail || + t("settings.accounts.toast_failed", "Failed to change password") + ); } } catch (error) { - toast.error("An error occurred while changing the password"); + toast.error( + t( + "settings.accounts.toast_error_occurred", + "An error occurred while changing the password" + ) + ); } }, - [] + [t] ); return ( @@ -1537,23 +1838,33 @@ function AccountsAccessSettings() { {tokenToDelete && ( setTokenToDelete(null)} submit={ } >
- {`Any application using the token ${tokenToDelete.name} (${tokenToDelete.token_display}) will lose access to Onyx. This action cannot be undone.`} + {t("settings.accounts.revoke_desc_1", { + defaultValue: `Any application using the token ${tokenToDelete.name} (${tokenToDelete.token_display}) will lose access to Onyx. This action cannot be undone.`, + name: tokenToDelete.name, + display: tokenToDelete.token_display, + })} - Are you sure you want to revoke this token? + {t( + "settings.accounts.revoke_desc_2", + "Are you sure you want to revoke this token?" + )}
@@ -1585,7 +1896,10 @@ function AccountsAccessSettings() {
- {isSubmitting ? "Updating..." : "Update"} + {isSubmitting + ? t("settings.accounts.updating", "Updating...") + : t("settings.accounts.btn_update", "Update")} } onClose={() => { @@ -1609,7 +1925,10 @@ function AccountsAccessSettings() {
- +
{user?.email ?? "anonymous"} @@ -1675,8 +2006,11 @@ function AccountsAccessSettings() { {showPasswordSection && ( )} @@ -1695,7 +2029,7 @@ function AccountsAccessSettings() { {showTokensSection && (
{isLoading - ? "Loading tokens..." - : "No access tokens created."} + ? t( + "settings.accounts.loading_tokens", + "Loading tokens..." + ) + : t( + "settings.accounts.no_tokens", + "No access tokens created." + )}
) : ( setQuery(e.target.value)} searchIcon @@ -1732,7 +2075,10 @@ function AccountsAccessSettings() { interaction={showCreateModal ? "active" : "rest"} onClick={() => setShowCreateModal(true)} > - New Access Token + {t( + "settings.accounts.new_access_token", + "New Access Token" + )}
@@ -1746,31 +2092,50 @@ function AccountsAccessSettings() { (1000 * 60 * 60 * 24) ); - let expiryText = "Never expires"; + let expiryText = t( + "settings.accounts.never_expires", + "Never expires" + ); if (pat.expires_at) { const expiresDate = new Date(pat.expires_at); const daysUntilExpiry = Math.ceil( (expiresDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24) ); - expiryText = `Expires in ${daysUntilExpiry} day${ - daysUntilExpiry === 1 ? "" : "s" - }`; + expiryText = + daysUntilExpiry === 1 + ? t( + "settings.accounts.expires_in_day", + "Expires in 1 day" + ) + : t("settings.accounts.expires_in_days", { + defaultValue: `Expires in ${daysUntilExpiry} days`, + days: daysUntilExpiry, + }); } const scopeText = pat.scopes === null - ? "Full access" + ? t("settings.accounts.full_access", "Full access") : pat.scopes .map((scope) => scopeLabels.get(scope) ?? scope) .join(", "); const createdText = daysSinceCreation === 0 - ? "Created today" - : `Created ${daysSinceCreation} day${ - daysSinceCreation === 1 ? "" : "s" - } ago`; + ? t( + "settings.accounts.created_today", + "Created today" + ) + : daysSinceCreation === 1 + ? t( + "settings.accounts.created_day_ago", + "Created 1 day ago" + ) + : t("settings.accounts.created_days_ago", { + defaultValue: `Created ${daysSinceCreation} days ago`, + days: daysSinceCreation, + }); const middleText = `${createdText} - ${expiryText} - ${scopeText}`; @@ -1792,7 +2157,14 @@ function AccountsAccessSettings() { onClick={() => setTokenToDelete(pat)} prominence="tertiary" size="sm" - aria-label={`Delete token ${pat.name}`} + aria-label={ + t( + "settings.accounts.modal_revoke_title", + "Revoke Access Token" + ) + + " " + + pat.name + } /> } /> @@ -1807,10 +2179,13 @@ function AccountsAccessSettings() {
- Access tokens require an active paid subscription. + {t( + "settings.accounts.paid_subscription_required", + "Access tokens require an active paid subscription." + )}
@@ -1829,13 +2204,18 @@ interface IndexedConnectorCardProps { function IndexedConnectorCard({ source, isActive }: IndexedConnectorCardProps) { const sourceMetadata = getSourceMetadata(source); + const { t } = useTranslation(); return ( @@ -1856,6 +2236,7 @@ function FederatedConnectorCard({ const [showDisconnectConfirmation, setShowDisconnectConfirmation] = useState(false); const sourceMetadata = getSourceMetadata(connector.source as ValidSources); + const { t } = useTranslation(); const handleDisconnect = useCallback(async () => { setIsDisconnecting(true); @@ -1866,25 +2247,37 @@ function FederatedConnectorCard({ ); if (response.ok) { - toast.success("Disconnected successfully"); + toast.success( + t( + "settings.connectors.toast_disconnect_success", + "Disconnected successfully" + ) + ); setShowDisconnectConfirmation(false); onDisconnectSuccess(); } else { throw new Error("Failed to disconnect"); } } catch (error) { - toast.error("Failed to disconnect"); + toast.error( + t("settings.connectors.toast_disconnect_failed", "Failed to disconnect") + ); } finally { setIsDisconnecting(false); } - }, [connector.federated_connector_id, onDisconnectSuccess]); + }, [connector.federated_connector_id, onDisconnectSuccess, t]); return ( <> {showDisconnectConfirmation && ( setShowDisconnectConfirmation(false)} submit={ } >
- {`Onyx will no longer be able to access or search content from your ${sourceMetadata.displayName} account.`} + {t("settings.connectors.disconnect_desc_1", { + defaultValue: `Onyx will no longer be able to access or search content from your ${sourceMetadata.displayName} account.`, + name: sourceMetadata.displayName, + })} - {`You can still continue existing sessions referencing ${sourceMetadata.displayName} content.`} + {t("settings.connectors.disconnect_desc_2", { + defaultValue: `You can still continue existing sessions referencing ${sourceMetadata.displayName} content.`, + name: sourceMetadata.displayName, + })}
@@ -1912,7 +2313,9 @@ function FederatedConnectorCard({ icon={sourceMetadata.icon} title={sourceMetadata.displayName} description={ - connector.has_oauth_token ? "Connected" : "Not connected" + connector.has_oauth_token + ? t("settings.connectors.connected", "Connected") + : t("settings.connectors.not_connected", "Not connected") } sizePreset="main-content" variant="section" @@ -1933,7 +2336,7 @@ function FederatedConnectorCard({ target="_blank" rightIcon={SvgArrowExchange} > - Connect + {t("settings.connectors.btn_connect", "Connect")} ) : undefined } @@ -1949,6 +2352,7 @@ function ConnectorsSettings() { refetch: refetchFederatedConnectors, } = useFederatedOAuthStatus(); const { ccPairs } = useCCPairs(); + const { t } = useTranslation(); const ACTIVE_STATUSES: ConnectorCredentialPairStatus[] = [ ConnectorCredentialPairStatus.ACTIVE, @@ -1986,7 +2390,7 @@ function ConnectorsSettings() {
)}
diff --git a/web/tests/setup/jest.setup.ts b/web/tests/setup/jest.setup.ts index c6c98c4c..eacdae7c 100644 --- a/web/tests/setup/jest.setup.ts +++ b/web/tests/setup/jest.setup.ts @@ -89,3 +89,45 @@ console.error = (...args: any[]) => { } originalError.call(console, ...args); }; + +// Global mock for react-i18next to resolve keys using the English locale JSON +jest.mock("react-i18next", () => { + const enCommon = require("../../public/locales/en/common.json"); + + const getNestedValue = (obj: any, path: string): string => { + return path.split(".").reduce((acc, part) => acc && acc[part], obj) || path; + }; + + return { + useTranslation: () => ({ + t: (key: string, options?: any) => { + const fallback = options?.defaultValue; + const val = getNestedValue(enCommon, key); + if (val === key && fallback !== undefined) { + return fallback; + } + // Handle interpolations like {{count}} or {{date}} + if (typeof val === "string" && options) { + let interpolated = val; + for (const k of Object.keys(options)) { + interpolated = interpolated.replace( + new RegExp(`{{${k}}}`, "g"), + options[k] + ); + } + return interpolated; + } + return val; + }, + i18n: { + changeLanguage: () => Promise.resolve(), + language: "en", + }, + }), + I18nextProvider: ({ children }: any) => children, + initReactI18next: { + type: "3rdParty", + init: () => {}, + }, + }; +});