🙌 OpenHands: AI-Driven Development
feat: show active-backend sync badge on settings pages (#175)
Hiep Le5030a0c9e43a
diff --git a/__tests__/components/features/settings/backend-synced-settings-badge.test.tsx b/__tests__/components/features/settings/backend-synced-settings-badge.test.tsxnew file mode 100644index 0000000000..7d29ac1781--- /dev/null+++ b/__tests__/components/features/settings/backend-synced-settings-badge.test.tsx@@ -0,0 +1,160 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { BackendSyncedSettingsBadge } from "#/components/features/settings/backend-synced-settings-badge";+import { ActiveBackendProvider } from "#/contexts/active-backend-context";+import {+ __resetActiveStoreForTests,+ setActiveSelection,+ setRegisteredBackends,+} from "#/api/backend-registry/active-store";+import * as orgService from "#/api/cloud/organization-service.api";+import type { Backend } from "#/api/backend-registry/types";++// Override the global react-i18next mock for this file. The badge under+// test interpolates `{{name}}` and `{{host}}`, and one regression we+// care about is that the host's `/` characters render literally rather+// than HTML-escaped (`/`). The mock below performs `{{var}}`+// substitution and applies i18next's default HTML escape unless+// `interpolation.escapeValue === false` — exactly what the production+// runtime does — so a missing opt-out would surface as escaped output.+vi.mock("react-i18next", async (importOriginal) => {+ const actual = await importOriginal<typeof import("react-i18next")>();+ const TEMPLATES: Record<string, string> = {+ SETTINGS$BACKEND_SYNCED_BADGE:+ "These settings are synced from {{name}} backend ({{host}})",+ };+ const htmlEscape = (s: string) =>+ s+ .replace(/&/g, "&")+ .replace(/</g, "<")+ .replace(/>/g, ">")+ .replace(/"/g, """)+ .replace(/'/g, "'")+ .replace(/\//g, "/");+ return {+ ...actual,+ useTranslation: () => ({+ t: (key: string, opts?: Record<string, unknown>) => {+ const tpl = TEMPLATES[key] ?? key;+ if (!opts) return tpl;+ const { interpolation } = opts as {+ interpolation?: { escapeValue?: boolean };+ };+ const escape = interpolation?.escapeValue !== false;+ return tpl.replace(/\{\{(\w+)\}\}/g, (_match, name) => {+ if (!(name in opts)) return "";+ const v = String((opts as Record<string, unknown>)[name]);+ return escape ? htmlEscape(v) : v;+ });+ },+ i18n: { language: "en", exists: () => false },+ }),+ };+});++const cloudBackend: Backend = {+ id: "prod",+ name: "Production",+ host: "https://app.all-hands.dev",+ apiKey: "bearer",+ kind: "cloud",+};++function renderBadge() {+ return render(<BackendSyncedSettingsBadge />, {+ wrapper: ({ children }) => (+ <QueryClientProvider+ client={+ new QueryClient({ defaultOptions: { queries: { retry: false } } })+ }+ >+ <ActiveBackendProvider>{children}</ActiveBackendProvider>+ </QueryClientProvider>+ ),+ });+}++describe("BackendSyncedSettingsBadge", () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ window.localStorage.clear();+ __resetActiveStoreForTests();+ });++ afterEach(() => {+ window.localStorage.clear();+ __resetActiveStoreForTests();+ });++ it("renders the bundled local backend label and host URL without HTML-escaping", () => {+ // Arrange — no registered backends; resolved active falls back to bundled.+ // Act+ renderBadge();++ // Assert — the bundled name slot resolves to BACKEND$LOCAL_ROW and the+ // host URL is preserved literally (no `/` from i18next escape).+ const text = screen.getByTestId(+ "backend-synced-settings-badge",+ ).textContent;+ expect(text).toMatch(+ /These settings are synced from BACKEND\$LOCAL_ROW backend \(https?:\/\/.+\)/,+ );+ expect(text).not.toContain("/");+ });++ it("labels a cloud backend's active org as Personal Workspace when it matches the current user id", async () => {+ // Arrange+ setRegisteredBackends([cloudBackend]);+ setActiveSelection({ backendId: cloudBackend.id, orgId: "user-1" });+ vi.spyOn(orgService, "getCurrentCloudApiKey").mockResolvedValue({+ isLegacyKey: false,+ orgId: "user-1",+ } as never);+ vi.spyOn(orgService, "getCloudOrganizations").mockResolvedValue({+ items: [{ id: "user-1", name: "Hiep Le" }],+ } as never);+ vi.spyOn(orgService, "getCloudOrganizationMe").mockResolvedValue({+ orgId: "user-1",+ userId: "user-1",+ } as never);++ // Act+ renderBadge();++ // Assert+ await waitFor(() => {+ expect(+ screen.getByTestId("backend-synced-settings-badge").textContent,+ ).toContain("Production – BACKEND$PERSONAL_WORKSPACE");+ });+ });++ it("labels a cloud backend's active org with the org's display name when the user is not the org owner", async () => {+ // Arrange+ setRegisteredBackends([cloudBackend]);+ setActiveSelection({ backendId: cloudBackend.id, orgId: "team-org" });+ vi.spyOn(orgService, "getCurrentCloudApiKey").mockResolvedValue({+ isLegacyKey: false,+ orgId: "team-org",+ } as never);+ vi.spyOn(orgService, "getCloudOrganizations").mockResolvedValue({+ items: [{ id: "team-org", name: "Acme Team" }],+ } as never);+ vi.spyOn(orgService, "getCloudOrganizationMe").mockResolvedValue({+ orgId: "team-org",+ userId: "user-1",+ } as never);++ // Act+ renderBadge();++ // Assert+ await waitFor(() => {+ expect(+ screen.getByTestId("backend-synced-settings-badge").textContent,+ ).toContain("Production – Acme Team");+ });+ });+});diff --git a/__tests__/routes/mcp-settings.test.tsx b/__tests__/routes/mcp-settings.test.tsxindex dd97e4d65a..ca8dd861bf 100644--- a/__tests__/routes/mcp-settings.test.tsx+++ b/__tests__/routes/mcp-settings.test.tsx@@ -5,6 +5,7 @@ import MCPSettingsScreen from "#/routes/mcp-settings";import SettingsService from "#/api/settings-service/settings-service.api";import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";import { Settings } from "#/types/settings";+import { ActiveBackendProvider } from "#/contexts/active-backend-context";function buildSettings(overrides: Partial<Settings> = {}): Settings {return {@@ -26,7 +27,7 @@ function renderMcpSettingsScreen() {defaultOptions: { queries: { retry: false } },})}>- {children}+ <ActiveBackendProvider>{children}</ActiveBackendProvider></QueryClientProvider>),});diff --git a/__tests__/routes/settings.test.tsx b/__tests__/routes/settings.test.tsxindex 1e8a317230..727cf45b6a 100644--- a/__tests__/routes/settings.test.tsx+++ b/__tests__/routes/settings.test.tsx@@ -12,6 +12,7 @@ import {import type { Backend } from "#/api/backend-registry/types";import { getFirstAvailablePath } from "#/utils/settings-utils";import { OSS_NAV_ITEMS } from "#/constants/settings-nav";+import { ActiveBackendProvider } from "#/contexts/active-backend-context";vi.mock("#/hooks/use-settings-nav-items", () => ({useSettingsNavItems: () => [@@ -114,7 +115,9 @@ describe("settings route", () => {render(<QueryClientProvider client={new QueryClient()}>- <RouterStub initialEntries={["/settings/app"]} />+ <ActiveBackendProvider>+ <RouterStub initialEntries={["/settings/app"]} />+ </ActiveBackendProvider></QueryClientProvider>,);diff --git a/src/components/features/settings/backend-synced-settings-badge.tsx b/src/components/features/settings/backend-synced-settings-badge.tsxnew file mode 100644index 0000000000..b03c69b278--- /dev/null+++ b/src/components/features/settings/backend-synced-settings-badge.tsx@@ -0,0 +1,55 @@+import { useTranslation } from "react-i18next";+import { Typography } from "#/ui/typography";+import { I18nKey } from "#/i18n/declaration";+import InfoCircleIcon from "#/icons/info-circle.svg?react";+import { useActiveBackend } from "#/contexts/active-backend-context";+import { BUNDLED_BACKEND_ID } from "#/api/backend-registry/types";+import { useAllCloudOrganizations } from "#/hooks/query/use-cloud-organizations";+import { useCloudCurrentUserId } from "#/hooks/query/use-cloud-current-user-id";++function useActiveBackendDisplayName(): string {+ const { t } = useTranslation();+ const active = useActiveBackend();+ const cloudOrgs = useAllCloudOrganizations();+ const userIds = useCloudCurrentUserId();++ if (active.backend.id === BUNDLED_BACKEND_ID) {+ return t(I18nKey.BACKEND$LOCAL_ROW);+ }+ if (active.backend.kind !== "cloud" || !active.orgId) {+ return active.backend.name;+ }++ const entry = cloudOrgs[active.backend.id];+ const org = entry?.orgs.find((o) => o.id === active.orgId);+ if (!org) return active.backend.name;++ const userId = userIds[active.backend.id]?.userId ?? null;+ const isPersonal = !!userId && org.id === userId;+ const orgLabel = isPersonal+ ? t(I18nKey.BACKEND$PERSONAL_WORKSPACE)+ : org.name;+ return `${active.backend.name} – ${orgLabel}`;+}++export function BackendSyncedSettingsBadge() {+ const { t } = useTranslation();+ const active = useActiveBackend();+ const name = useActiveBackendDisplayName();++ return (+ <div+ data-testid="backend-synced-settings-badge"+ className="flex items-center gap-2 bg-[rgba(31,31,31,0.4)] border border-[#242424] rounded-full px-2.5 py-1"+ >+ <InfoCircleIcon width={12} height={12} className="text-[#8c8c8c]" />+ <Typography.Text className="text-[11px] font-medium text-[#8c8c8c] leading-5">+ {t(I18nKey.SETTINGS$BACKEND_SYNCED_BADGE, {+ name,+ host: active.backend.host,+ interpolation: { escapeValue: false },+ })}+ </Typography.Text>+ </div>+ );+}diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex ac8d65c680..9d1c35b67d 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -22354,6 +22354,23 @@"uk": "Локальний","ca": "Local"},+ "SETTINGS$BACKEND_SYNCED_BADGE": {+ "en": "These settings are synced from {{name}} backend ({{host}})",+ "ja": "これらの設定は {{name}} バックエンド ({{host}}) と同期されています",+ "zh-CN": "这些设置已与 {{name}} 后端 ({{host}}) 同步",+ "zh-TW": "這些設定已與 {{name}} 後端 ({{host}}) 同步",+ "ko-KR": "이 설정은 {{name}} 백엔드 ({{host}})에서 동기화됩니다",+ "no": "Disse innstillingene er synkronisert fra {{name}}-backend ({{host}})",+ "it": "Queste impostazioni sono sincronizzate dal backend {{name}} ({{host}})",+ "pt": "Estas configurações estão sincronizadas com o backend {{name}} ({{host}})",+ "es": "Estas configuraciones están sincronizadas con el backend {{name}} ({{host}})",+ "ar": "تتم مزامنة هذه الإعدادات من الواجهة الخلفية {{name}} ({{host}})",+ "fr": "Ces paramètres sont synchronisés depuis le backend {{name}} ({{host}})",+ "tr": "Bu ayarlar {{name}} arka uç ({{host}}) ile senkronize edilmiştir",+ "de": "Diese Einstellungen werden mit dem Backend {{name}} ({{host}}) synchronisiert",+ "uk": "Ці налаштування синхронізовано з бекендом {{name}} ({{host}})",+ "ca": "Aquesta configuració està sincronitzada amb el backend {{name}} ({{host}})"+ },"BACKEND$REMOVE": {"en": "Remove","ja": "削除",diff --git a/src/routes/mcp-settings.tsx b/src/routes/mcp-settings.tsxindex 8fb7dd87d3..9f4186ca47 100644--- a/src/routes/mcp-settings.tsx+++ b/src/routes/mcp-settings.tsx@@ -23,6 +23,7 @@ import {import { parseMcpConfig } from "#/utils/mcp-config";import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";import { Typography } from "#/ui/typography";+import { BackendSyncedSettingsBadge } from "#/components/features/settings/backend-synced-settings-badge";export const handle = { hideTitle: true };@@ -193,9 +194,10 @@ export function MCPSettingsScreen() {<div className="h-full flex flex-col gap-6 pb-8"><div className="flex justify-between items-center"><div>- <Typography.H2 className="mb-2">- {t(I18nKey.SETTINGS$MCP_TITLE)}- </Typography.H2>+ <div className="flex flex-col items-start gap-2 mb-2">+ <Typography.H2>{t(I18nKey.SETTINGS$MCP_TITLE)}</Typography.H2>+ <BackendSyncedSettingsBadge />+ </div><Typography.Paragraph className="text-sm text-[#A3A3A3]">{t(I18nKey.SETTINGS$MCP_DESCRIPTION)}</Typography.Paragraph>diff --git a/src/routes/settings.tsx b/src/routes/settings.tsxindex 50860ed4e6..6647f9e45f 100644--- a/src/routes/settings.tsx+++ b/src/routes/settings.tsx@@ -9,6 +9,7 @@ import { SettingsLayout } from "#/components/features/settings";import { WebClientConfig } from "#/api/option-service/option.types";import { QUERY_KEYS, CONFIG_CACHE_OPTIONS } from "#/hooks/query/query-keys";import { Typography } from "#/ui/typography";+import { BackendSyncedSettingsBadge } from "#/components/features/settings/backend-synced-settings-badge";import { useSettingsNavItems } from "#/hooks/use-settings-nav-items";import {getFirstAvailablePath,@@ -75,7 +76,10 @@ function SettingsScreen() {<SettingsLayout navigationItems={navItems}><div className="flex flex-col gap-6 h-full">{!shouldHideTitle && (- <Typography.H2>{t(currentSectionTitle)}</Typography.H2>+ <div className="flex flex-col items-start gap-2">+ <Typography.H2>{t(currentSectionTitle)}</Typography.H2>+ <BackendSyncedSettingsBadge />+ </div>)}<div className="flex-1 overflow-auto custom-scrollbar-always"><Outlet />