Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(ui): enforce localized user text at JSX sinks (#2964)

Call White7f36691a7876
diff --git a/docs/plans/ui-localized-text-guard.md b/docs/plans/ui-localized-text-guard.md
new file mode 100644
index 000000000..6dbfd78be
--- /dev/null
+++ b/docs/plans/ui-localized-text-guard.md
@@ -0,0 +1,144 @@
+# Localized user-text lint guard (#2618)
+
+## Change contract
+
+Production `ui/src/**/*.tsx` JSX children and `aria-label`, `title`,
+`placeholder`, and `alt` must not contain literal copy or literal sentence/list
+composition. Locale templates, `Trans` component interpolation, and locale-aware
+formatters own composition. No UI copy or locale resource is changed in this
+rollout.
+
+Use one dependency-free custom ESLint rule with the installed TypeScript AST and
+ESLint lexical scopes. Follow immutable local bindings, TypeScript wrappers,
+conditional display branches, arrays, and inline map/filter result paths into
+these sinks. Calls to translation/formatting functions remain value boundaries;
+this is not whole-program taint analysis. In particular, the original accessible
+label used component props, not inline `t()` calls: literal joins at a sink must
+be diagnosed even when the dynamic values' provenance is unknown.
+
+Keep the rule pinned at error in the shared policy for *every* TS/TSX file; decide
+its narrower production-TSX applicability inside the rule. Preserve domain,
+policy, inline-override and suppression verification without exemptions there.
+
+## Allow/deny boundaries
+
+- Deny ordinary literal JSX copy and punctuation, string templates/`+`/`.join`
+ with literal glue reaching the listed sinks, including local const aliases.
+- Permit dynamic data, translation/formatter results, locale-owned separators,
+ and genuine `react-i18next` `Trans` interpolation. Do not examine class names,
+ protocol props, logging, translation keys, or arbitrary call arguments as copy.
+- Decorative exemptions must be explicit, direct, and glyph-only. Separators
+ such as the original `aria-hidden` middle dot are **not** decorative opt-outs.
+- Technical native markup may display narrowly recognizable machine tokens,
+ structured JSON objects/arrays, or keyboard notation, never arbitrary prose.
+ Complete URL/path literals are data in any sink (not surrounding prose or a
+ separator). Decorative/machine/JSON child exceptions do not apply to
+ accessible-label/title/placeholder/alt attributes or to neighboring prose.
+ No filename/component-name or suppression allowlist.
+
+## Validation plan
+
+1. Behavioral fixtures reproduce the four reviewed #2559 shapes (including the
+ original local `reason`, spread/map cost array, props-based accessible name,
+ and hidden JSX middle dot). Run them against the pre-change config first.
+2. Table-driven positives/negatives exercise every sink, local aliases and scope
+ shadowing, valid localization/formatting/data, and exception containment.
+3. Execute the real gate in a test-owned miniature UI: new file/count fails,
+ localized replacement requires baseline shrink, re-recorded debt passes, and
+ suppression/policy changes cannot bypass enforcement. Retain the existing
+ count-ratchet limitation: same-file/same-rule replacement at equal count is
+ not site-identity enforcement.
+4. Record only measured new-rule debt on unchanged `ui/src`; compare every
+ unrelated violation and suppression allowance to the base byte-for-byte.
+5. Focused lint suites, `npm run lint`, test typechecking, and UI build locally;
+ remaining repository checks in CI. Exact-head Codex review, passing applicable
+ CI, and zero unresolved threads are required. Do not merge or deploy.
+
+## Implemented policy and analysis limits
+
+`avibe/localized-user-text` is an error in `ui/eslint.config.js` and pinned in
+`lintPolicy.mjs`. Applicability is relative to the UI ESLint working directory:
+`src/**/*.tsx`, excluding `*.test.tsx`, `*.spec.tsx`, and `__tests__` directories.
+The rule also treats the explicit `children` prop as a child sink. It reports
+one diagnostic per offending expression/attribute sink or literal JSX text node;
+using the same bad binding in both a title and a child yields two diagnostics.
+
+The analysis follows unmodified, identifier-bound `const` initializers in their
+actual lexical scope (including aliases), TS casts/non-null/satisfies wrappers,
+conditionals, logical output branches, arrays/spreads, final sequence values,
+`join` separators and receivers, `filter` receivers, and `map`/`flatMap` inline
+or const callback return expressions. It ignores conditions and logging inside
+callbacks, and stops at nested functions. Cycles terminate. Literal glue is
+checked even when inputs are component props with unknown provenance.
+
+This deliberately does **not** resolve imports, helper return values, arbitrary
+object properties/destructuring, mutations, state, callback argument flow, or
+cross-component prop flow. Ordinary calls (including `t`, `serverText`, `Intl`
+and the existing `formatNameList`/`formatSentences`/number helpers) are opaque
+output boundaries: their keys and arguments are not assumed to be output copy.
+A helper can therefore hide unlocalized text; this is not proof that every UI
+string is localized. Whitespace-only JSX formatting nodes and empty string
+expressions are ignored; explicit nonempty string expressions/joiners are not.
+No punctuation scan runs outside user-facing sinks.
+
+A named `Trans` import from `react-i18next` (including an import alias) with an
+`i18nKey` owns its fallback JSX text, including component children. Unverified
+same-name components do not. Attributes and composed expression children still
+get checked inside a `Trans` subtree.
+
+Exceptions are content-shaped, not file/component allowlists:
+
+- A direct native `span` with literal true `aria-hidden`, no spread attributes,
+ and exactly one of the rule's small icon glyph set may display that glyph.
+ The original hidden middle dot remains an error. Prose and labels remain errors.
+- Complete whitespace-free HTTP(S)/WS(S) URLs with a hostname and simple explicit
+ absolute/relative/home paths are data, including in titles/placeholders. A lone
+ slash or text around the resource is not exempt. String glue is never exempt.
+- Native `code`/`samp` may display recognizable compound identifiers/flags;
+ `code`/`samp`/`pre` may display a complete parsed JSON object/array. `kbd` may
+ display narrowly recognized keyboard notation. These do not exempt attributes,
+ descendants, or arbitrary prose, and are not a general programming-language
+ parser. Other existing technical display may conservatively remain baselined;
+ do not translate a protocol command merely to silence it. A future exception
+ needs a bounded content contract plus positive and escape-hatch tests.
+
+## Initial measured baseline
+
+Measured against unchanged `ui/src` at base
+`055870279641fd86a5f501e6c67310ccde28194a`:
+
+| Ledger | Before | After | Delta |
+| --- | ---: | ---: | ---: |
+| New localized-user-text diagnostics | 0 | 322 across 102 files | +322, initial rollout only |
+| All unrelated error allowances | 471 | 471 | 0 |
+| All inline-suppression allowances | 44 | 44 | 0 |
+| Measured TS/TSX domain | 1111 | 1111 | 0 |
+
+Every per-file new-rule count is in `ui/eslint-baseline.json`; it is the only
+ledger, not duplicated here. All unrelated per-file/rule counts, suppressions,
+and rationales compare equal to the base. No source or locale files changed.
+The initial diagnostics include real sentence/accessible-name composition,
+ordinary copy, and conservative technical/glyph display; this is not a claim
+that every diagnostic should become translated prose.
+
+The gate still freezes counts, not site identities. Replacing one violation with
+another of this same rule in this same file at equal count can pass. New pairs,
+increased counts, newly suppressed messages, and stale allowances cannot. This
+accepted residual is tested explicitly rather than obscured by a second ledger.
+
+## Validation evidence
+
+- Before enabling the rule, all four historical fixture tests failed because the
+ real config returned zero localized-text errors; afterward all four pass.
+- `localizedUserText.test.mjs` executes the real ESLint config for the historical
+ forms, all sinks, local indirection, valid locale/formatter/data paths and
+ narrow exception containment. Existing convention/policy/baseline tests remain.
+- `localizedUserTextGate.test.mjs` runs real `npm run lint` in test-owned miniature
+ UI trees: new files/counts fail; localized replacements force shrink; re-recorded
+ shrink passes; equal-count replacement retains the documented residual;
+ suppressions, inline overrides and severity demotion cannot bypass the gate.
+- `npm run lint`, `npm run typecheck:tests`, and `npm run build` pass locally.
+ Build retains its pre-existing browser-crypto/chunk-size warnings. No Incus
+ update, service change, runtime deployment or manual UI-copy rewrite is needed
+ for this lint-only change.
+
diff --git a/ui/README.md b/ui/README.md
index 8cef778b8..6398039ab 100644
--- a/ui/README.md
+++ b/ui/README.md
@@ -12,6 +12,15 @@ records the paired tool upgrade and its one-time, unchanged-source baseline
remeasurement. This development requirement does not change the separately
packaged Show Runtime's Node contract.
+Production TSX also enforces `avibe/localized-user-text`: put visible copy and
+sentence/list composition in locale keys, `Trans`, or locale-aware formatters,
+not literal JSX text, templates, `+`, or `.join` glue. JSX children and
+`aria-label`, `title`, `placeholder`, and `alt` are checked, including immutable
+local aliases. The [localized-text guard contract](../docs/plans/ui-localized-text-guard.md)
+documents narrow decorative/technical exceptions, the initial measured debt,
+and the bounded analysis/count-ratchet limitations. Existing debt is not a budget
+for new copy; record reductions with `npm run lint:baseline`.
+
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
diff --git a/ui/eslint-baseline.json b/ui/eslint-baseline.json
index b783c78ee..b6018f39f 100644
--- a/ui/eslint-baseline.json
+++ b/ui/eslint-baseline.json
@@ -1,6 +1,7 @@
{
"$comment": "Explicit ledger of existing lint debt, remeasured on unchanged source during the ESLint 10 migration (docs/maintenance/eslint-10-migration.md). `npm run lint` fails on anything not recorded here, on a recorded entry that grows, and on a recorded entry that shrinks without being re-recorded. See scripts/lint-baseline.mjs. Regenerate with `npm run lint:baseline`; raising a count needs a reviewer to agree in the PR.",
"rationale": {
+ "avibe/localized-user-text": "Initial #2618 measurement on unchanged production TSX. Existing literal JSX copy, sentence/list glue and conservative technical-display diagnostics are recorded per file, not fixed by a whole-UI rewrite. New or increased counts fail; paying down debt must shrink this allowance. Review technical diagnostics against the narrow content policy rather than translating protocol data. See docs/plans/ui-localized-text-guard.md for boundaries, measured totals and the count-ratchet residual.",
"@typescript-eslint/no-explicit-any": "The untyped edge of the Python API. Each one is a response body, an SSE event payload or a third-party callback that reaches the UI as `any`. Typing them is a per-endpoint contract change against the backend, not a lint fix, and doing it as one sweep would produce a diff nobody can review. The ratchet's job here is to stop a NEW endpoint from landing untyped; the recorded ones come down endpoint by endpoint.",
"react-hooks/set-state-in-effect": "Legitimate-looking `reset derived state when the subject changes` and prop-mirroring effects in components with no test coverage. Each rewrite changes when a render happens, so each needs its own regression test first; batching them behind a lint deadline is how a subtle render-order bug ships.",
"react-hooks/preserve-manual-memoization": "Advice for adopting the React Compiler, not a defect. `babel-plugin-react-compiler` is not in this project's Vite plugin list, so no shipped behaviour depends on these; they become actionable in the change that turns the compiler on.",
@@ -21,20 +22,33 @@
"no-useless-assignment": 1
},
"src/App.tsx": {
+ "avibe/localized-user-text": 1,
"react-hooks/set-state-in-effect": 1
},
+ "src/apps/LibraryApp.tsx": {
+ "avibe/localized-user-text": 1
+ },
"src/components/AppShell.tsx": {
"@typescript-eslint/no-explicit-any": 2,
+ "avibe/localized-user-text": 2,
"react-hooks/set-state-in-effect": 1
},
"src/components/InstallHint.tsx": {
"react-hooks/set-state-in-effect": 1
},
"src/components/RemoteAccess.tsx": {
+ "avibe/localized-user-text": 7,
"react-hooks/purity": 1,
"react-hooks/set-state-in-effect": 2
},
+ "src/components/ShowPagesPage.tsx": {
+ "avibe/localized-user-text": 3
+ },
+ "src/components/ThemeToggle.tsx": {
+ "avibe/localized-user-text": 1
+ },
"src/components/VersionBadge.tsx": {
+ "avibe/localized-user-text": 4,
"react-hooks/immutability": 2
},
"src/components/Wizard.tsx": {
@@ -44,16 +58,33 @@
"src/components/apps/AppWindow.tsx": {
"react-hooks/set-state-in-effect": 1
},
+ "src/components/apps/Dock.tsx": {
+ "avibe/localized-user-text": 1
+ },
"src/components/apps/windowChords.ts": {
"no-useless-assignment": 1
},
"src/components/onboarding/BackendConnectionDialog.tsx": {
+ "avibe/localized-user-text": 2,
"react-hooks/set-state-in-effect": 1
},
+ "src/components/onboarding/providers/AddSourceDialog.tsx": {
+ "avibe/localized-user-text": 2
+ },
+ "src/components/onboarding/providers/ProviderCard.tsx": {
+ "avibe/localized-user-text": 2
+ },
+ "src/components/onboarding/providers/ProvidersScreen.tsx": {
+ "avibe/localized-user-text": 1
+ },
"src/components/settings/BackendLifecycleChip.tsx": {
+ "avibe/localized-user-text": 1,
"react-hooks/refs": 2,
"react-hooks/set-state-in-effect": 2
},
+ "src/components/settings/BackendOAuthPanel.tsx": {
+ "avibe/localized-user-text": 1
+ },
"src/components/settings/OpencodeProviderTestPanel.tsx": {
"react-hooks/set-state-in-effect": 1
},
@@ -61,8 +92,15 @@
"@typescript-eslint/no-explicit-any": 1,
"react-hooks/set-state-in-effect": 1
},
+ "src/components/settings/SettingsComputerUsePage.tsx": {
+ "avibe/localized-user-text": 1
+ },
+ "src/components/settings/SettingsLayout.tsx": {
+ "avibe/localized-user-text": 2
+ },
"src/components/settings/SettingsMessagingPage.tsx": {
"@typescript-eslint/no-explicit-any": 2,
+ "avibe/localized-user-text": 1,
"react-hooks/set-state-in-effect": 1
},
"src/components/settings/SettingsPlatformsPage.tsx": {
@@ -71,6 +109,9 @@
"src/components/settings/SettingsServicePage.tsx": {
"@typescript-eslint/no-explicit-any": 4
},
+ "src/components/settings/models/AgentCard.tsx": {
+ "avibe/localized-user-text": 5
+ },
"src/components/settings/models/BackendModelCatalogDialog.tsx": {
"react-hooks/refs": 1,
"react-hooks/set-state-in-effect": 2
@@ -84,21 +125,39 @@
"src/components/settings/models/BackendSupplyModeCard.tsx": {
"react-hooks/set-state-in-effect": 1
},
+ "src/components/settings/models/GatewayModule.tsx": {
+ "avibe/localized-user-text": 1
+ },
+ "src/components/settings/models/GuardImpact.tsx": {
+ "avibe/localized-user-text": 2
+ },
"src/components/settings/models/MigrationDialog.tsx": {
+ "avibe/localized-user-text": 1,
"react-hooks/set-state-in-effect": 2
},
"src/components/settings/models/OAuthConnectDialog.tsx": {
+ "avibe/localized-user-text": 2,
"react-hooks/purity": 1,
"react-hooks/refs": 3,
"react-hooks/set-state-in-effect": 2
},
+ "src/components/settings/models/QuotaTab.tsx": {
+ "avibe/localized-user-text": 10
+ },
"src/components/settings/models/RouteCandidatePopover.tsx": {
"react-hooks/set-state-in-effect": 1
},
"src/components/settings/models/RouteChainDialog.tsx": {
+ "avibe/localized-user-text": 2,
"react-hooks/refs": 35,
"react-hooks/set-state-in-effect": 2
},
+ "src/components/settings/models/RouteRecordedTurn.tsx": {
+ "avibe/localized-user-text": 6
+ },
+ "src/components/settings/models/SearchServiceParts.tsx": {
+ "avibe/localized-user-text": 1
+ },
"src/components/settings/models/SettingsModelsPage.tsx": {
"react-hooks/preserve-manual-memoization": 4,
"react-hooks/refs": 9,
@@ -107,15 +166,30 @@
"src/components/settings/models/SourceDetailPanel.test.tsx": {
"react-hooks/refs": 1
},
+ "src/components/settings/models/SourceDetailPanel.tsx": {
+ "avibe/localized-user-text": 6
+ },
"src/components/settings/models/SourceOrderDrawer.tsx": {
+ "avibe/localized-user-text": 2,
"react-hooks/set-state-in-effect": 1
},
"src/components/settings/models/SourceTestDialog.tsx": {
+ "avibe/localized-user-text": 2,
"react-hooks/set-state-in-effect": 1
},
+ "src/components/settings/models/TimeHint.tsx": {
+ "avibe/localized-user-text": 1
+ },
+ "src/components/settings/models/ToolsTab.tsx": {
+ "avibe/localized-user-text": 2
+ },
"src/components/settings/models/UsageTab.tsx": {
+ "avibe/localized-user-text": 5,
"react-hooks/set-state-in-effect": 5
},
+ "src/components/settings/models/WebFetchOrder.tsx": {
+ "avibe/localized-user-text": 2
+ },
"src/components/settings/models/modelsApi.ts": {
"no-useless-assignment": 1
},
@@ -127,10 +201,12 @@
"react-hooks/refs": 1
},
"src/components/settings/providers/BackendConnectionForm.tsx": {
+ "avibe/localized-user-text": 4,
"react-hooks/refs": 3,
"react-hooks/set-state-in-effect": 1
},
"src/components/settings/providers/OpencodeProviderConfig.tsx": {
+ "avibe/localized-user-text": 4,
"react-hooks/set-state-in-effect": 1
},
"src/components/settings/shared/useBackendRuntime.ts": {
@@ -138,6 +214,9 @@
"preserve-caught-error": 1,
"react-hooks/refs": 3
},
+ "src/components/shared/ProxyUrlField.tsx": {
+ "avibe/localized-user-text": 1
+ },
"src/components/shared/RoutingConfigPanel.tsx": {
"@typescript-eslint/no-explicit-any": 2,
"react-hooks/set-state-in-effect": 1
@@ -147,23 +226,28 @@
},
"src/components/steps/ChannelList.tsx": {
"@typescript-eslint/no-explicit-any": 28,
+ "avibe/localized-user-text": 3,
"react-hooks/immutability": 1,
"react-hooks/set-state-in-effect": 3,
"react-hooks/static-components": 1
},
"src/components/steps/DiscordConfig.tsx": {
"@typescript-eslint/no-explicit-any": 6,
+ "avibe/localized-user-text": 3,
"react-hooks/set-state-in-effect": 3
},
"src/components/steps/DoctorPanel.tsx": {
"@typescript-eslint/no-explicit-any": 4,
+ "avibe/localized-user-text": 2,
"react-hooks/set-state-in-effect": 1
},
"src/components/steps/LarkConfig.tsx": {
"@typescript-eslint/no-explicit-any": 6,
+ "avibe/localized-user-text": 6,
"react-hooks/set-state-in-effect": 3
},
"src/components/steps/LogsPanel.tsx": {
+ "avibe/localized-user-text": 11,
"react-hooks/set-state-in-effect": 1
},
"src/components/steps/ModeSelection.tsx": {
@@ -176,47 +260,83 @@
},
"src/components/steps/SlackConfig.tsx": {
"@typescript-eslint/no-explicit-any": 4,
+ "avibe/localized-user-text": 9,
"react-hooks/immutability": 1,
"react-hooks/set-state-in-effect": 2
},
"src/components/steps/Summary.tsx": {
- "@typescript-eslint/no-explicit-any": 5
+ "@typescript-eslint/no-explicit-any": 5,
+ "avibe/localized-user-text": 2
},
"src/components/steps/TelegramConfig.tsx": {
"@typescript-eslint/no-explicit-any": 4,
+ "avibe/localized-user-text": 5,
"react-hooks/set-state-in-effect": 2
},
"src/components/steps/UserList.tsx": {
"@typescript-eslint/no-explicit-any": 2,
+ "avibe/localized-user-text": 5,
"react-hooks/set-state-in-effect": 2
},
"src/components/steps/WeChatConfig.tsx": {
"@typescript-eslint/no-explicit-any": 4,
+ "avibe/localized-user-text": 2,
"react-hooks/immutability": 1,
"react-hooks/set-state-in-effect": 1
},
"src/components/steps/Welcome.tsx": {
"react-hooks/immutability": 1
},
+ "src/components/ui/combobox.tsx": {
+ "avibe/localized-user-text": 3
+ },
"src/components/ui/confirm-dialog.tsx": {
+ "avibe/localized-user-text": 1,
"react-hooks/set-state-in-effect": 1
},
"src/components/ui/editor-dialog.tsx": {
"react-hooks/set-state-in-effect": 1
},
+ "src/components/ui/file-card.tsx": {
+ "avibe/localized-user-text": 3
+ },
"src/components/ui/file-preview.tsx": {
+ "avibe/localized-user-text": 4,
"no-useless-assignment": 1,
"react-hooks/set-state-in-effect": 6
},
+ "src/components/ui/file-viewer-modal.tsx": {
+ "avibe/localized-user-text": 1
+ },
+ "src/components/ui/folder-browser.tsx": {
+ "avibe/localized-user-text": 5
+ },
+ "src/components/ui/image-viewer.tsx": {
+ "avibe/localized-user-text": 1
+ },
+ "src/components/ui/markdown.tsx": {
+ "avibe/localized-user-text": 5
+ },
"src/components/ui/secret-request-card.tsx": {
+ "avibe/localized-user-text": 3,
"react-hooks/set-state-in-effect": 1
},
"src/components/ui/vault-approval-card.tsx": {
+ "avibe/localized-user-text": 1,
"react-hooks/set-state-in-effect": 1
},
"src/components/ui/vault-chat-requests.tsx": {
"react-hooks/set-state-in-effect": 1
},
+ "src/components/ui/vault-field-list.tsx": {
+ "avibe/localized-user-text": 2
+ },
+ "src/components/ui/vault-lock-indicator.tsx": {
+ "avibe/localized-user-text": 1
+ },
+ "src/components/ui/vault-request-card.tsx": {
+ "avibe/localized-user-text": 1
+ },
"src/components/ui/vault-secret-form.tsx": {
"react-hooks/refs": 1,
"react-hooks/set-state-in-effect": 4
@@ -224,22 +344,53 @@
"src/components/ui/vault-settings-dialog.tsx": {
"react-hooks/set-state-in-effect": 1
},
+ "src/components/visual/BrandLogo.tsx": {
+ "avibe/localized-user-text": 1
+ },
+ "src/components/visual/EmbeddedConfigShell.tsx": {
+ "avibe/localized-user-text": 1
+ },
+ "src/components/visual/WizardChrome.tsx": {
+ "avibe/localized-user-text": 1
+ },
+ "src/components/workbench/AgentActivityGroup.tsx": {
+ "avibe/localized-user-text": 7
+ },
+ "src/components/workbench/AgentGraphCanvas.tsx": {
+ "avibe/localized-user-text": 1
+ },
"src/components/workbench/AgentGraphDetail.tsx": {
+ "avibe/localized-user-text": 6,
"react-hooks/refs": 2,
"react-hooks/set-state-in-effect": 1
},
+ "src/components/workbench/AgentGraphMobileList.tsx": {
+ "avibe/localized-user-text": 1
+ },
+ "src/components/workbench/AgentGraphNodeCard.tsx": {
+ "avibe/localized-user-text": 1
+ },
+ "src/components/workbench/AgentGraphOrphanStrip.tsx": {
+ "avibe/localized-user-text": 1
+ },
"src/components/workbench/AgentGraphTab.tsx": {
"react-hooks/preserve-manual-memoization": 1,
"react-hooks/set-state-in-effect": 3
},
+ "src/components/workbench/AgentGraphTriggerChip.tsx": {
+ "avibe/localized-user-text": 2
+ },
"src/components/workbench/AgentGraphTriggerDetail.tsx": {
+ "avibe/localized-user-text": 4,
"react-hooks/refs": 2,
"react-hooks/set-state-in-effect": 1
},
"src/components/workbench/AgentRoutePicker.tsx": {
+ "avibe/localized-user-text": 2,
"react-hooks/set-state-in-effect": 2
},
"src/components/workbench/AgentsPage.tsx": {
+ "avibe/localized-user-text": 8,
"no-useless-assignment": 1,
"react-hooks/immutability": 1,
"react-hooks/preserve-manual-memoization": 1,
@@ -247,6 +398,7 @@
"react-hooks/set-state-in-effect": 4
},
"src/components/workbench/AppsFileBrowserPage.tsx": {
+ "avibe/localized-user-text": 4,
"no-useless-assignment": 1,
"react-hooks/immutability": 1,
"react-hooks/preserve-manual-memoization": 9,
@@ -257,23 +409,31 @@
},
"src/components/workbench/ChatPage.tsx": {
"@typescript-eslint/no-explicit-any": 1,
+ "avibe/localized-user-text": 11,
"react-hooks/immutability": 1,
"react-hooks/preserve-manual-memoization": 7,
"react-hooks/refs": 6,
"react-hooks/set-state-in-effect": 11
},
"src/components/workbench/Composer.tsx": {
+ "avibe/localized-user-text": 1,
"react-hooks/set-state-in-effect": 3
},
"src/components/workbench/EditorApp.tsx": {
+ "avibe/localized-user-text": 2,
"react-hooks/immutability": 1,
"react-hooks/preserve-manual-memoization": 1,
"react-hooks/set-state-in-effect": 2
},
+ "src/components/workbench/EditorFontSizePopover.tsx": {
+ "avibe/localized-user-text": 3
+ },
"src/components/workbench/EditorSearchView.tsx": {
+ "avibe/localized-user-text": 1,
"react-hooks/set-state-in-effect": 2
},
"src/components/workbench/FailureDetails.tsx": {
+ "avibe/localized-user-text": 11,
"react-hooks/set-state-in-effect": 1
},
"src/components/workbench/FileEditorPane.tsx": {
@@ -284,27 +444,45 @@
"react-hooks/set-state-in-effect": 2
},
"src/components/workbench/FileTree.tsx": {
+ "avibe/localized-user-text": 2,
"react-hooks/refs": 1,
"react-hooks/set-state-in-effect": 3
},
"src/components/workbench/GlobalPromptsDialog.tsx": {
+ "avibe/localized-user-text": 1,
"react-hooks/set-state-in-effect": 1
},
"src/components/workbench/HarnessPage.tsx": {
+ "avibe/localized-user-text": 20,
"react-hooks/set-state-in-effect": 7
},
+ "src/components/workbench/HostedToolRow.tsx": {
+ "avibe/localized-user-text": 14
+ },
+ "src/components/workbench/InboxPage.tsx": {
+ "avibe/localized-user-text": 4
+ },
"src/components/workbench/NewAgentDialog.tsx": {
"react-hooks/set-state-in-effect": 3
},
+ "src/components/workbench/NewProjectDialog.tsx": {
+ "avibe/localized-user-text": 2
+ },
"src/components/workbench/ProjectAgentsMdDialog.tsx": {
"react-hooks/set-state-in-effect": 1
},
+ "src/components/workbench/ProjectsPage.tsx": {
+ "avibe/localized-user-text": 3
+ },
"src/components/workbench/QueuedAttachments.tsx": {
"react-hooks/set-state-in-effect": 1
},
"src/components/workbench/QuickReplies.tsx": {
"react-hooks/set-state-in-effect": 1
},
+ "src/components/workbench/SenderHead.tsx": {
+ "avibe/localized-user-text": 1
+ },
"src/components/workbench/ShowPageShareControl.tsx": {
"no-useless-assignment": 1,
"react-hooks/set-state-in-effect": 1
@@ -314,24 +492,49 @@
"react-hooks/set-state-in-effect": 1
},
"src/components/workbench/SkillsPage.tsx": {
+ "avibe/localized-user-text": 1,
"react-hooks/set-state-in-effect": 2
},
"src/components/workbench/TerminalView.tsx": {
+ "avibe/localized-user-text": 2,
"react-hooks/set-state-in-effect": 1
},
+ "src/components/workbench/VaultListTags.tsx": {
+ "avibe/localized-user-text": 1
+ },
"src/components/workbench/VaultsPage.tsx": {
+ "avibe/localized-user-text": 8,
"react-hooks/immutability": 1,
"react-hooks/set-state-in-effect": 4
},
"src/components/workbench/WebPushControl.tsx": {
"react-hooks/set-state-in-effect": 1
},
+ "src/components/workbench/WorkbenchSidebar.tsx": {
+ "avibe/localized-user-text": 5
+ },
"src/components/workbench/harnessLifecycle.test.ts": {
"@typescript-eslint/no-explicit-any": 1
},
+ "src/components/workbench/search/SearchResultGroup.tsx": {
+ "avibe/localized-user-text": 2
+ },
+ "src/components/workbench/skills/AddSkillDialog.tsx": {
+ "avibe/localized-user-text": 1
+ },
"src/components/workbench/skills/BrowseRegistryDialog.tsx": {
+ "avibe/localized-user-text": 1,
"react-hooks/set-state-in-effect": 1
},
+ "src/components/workbench/skills/QualityMeter.tsx": {
+ "avibe/localized-user-text": 1
+ },
+ "src/components/workbench/skills/SkillDetailPanel.tsx": {
+ "avibe/localized-user-text": 1
+ },
+ "src/components/workbench/skills/SkillRow.tsx": {
+ "avibe/localized-user-text": 2
+ },
"src/components/workbench/useSessionActions.tsx": {
"react-hooks/refs": 5,
"react-hooks/set-state-in-effect": 1
@@ -347,6 +550,9 @@
"@typescript-eslint/no-explicit-any": 1,
"no-useless-assignment": 1
},
+ "src/context/ToastProvider.tsx": {
+ "avibe/localized-user-text": 1
+ },
"src/context/WorkbenchInboxProvider.tsx": {
"react-hooks/refs": 8
},
@@ -357,6 +563,7 @@
"@typescript-eslint/no-explicit-any": 1
},
"src/features/permissions/PermissionsPage.tsx": {
+ "avibe/localized-user-text": 5,
"react-hooks/refs": 2
},
"src/features/permissions/api.ts": {
@@ -375,7 +582,11 @@
"react-hooks/refs": 1,
"react-hooks/set-state-in-effect": 1
},
+ "src/pet/PetAvatar.tsx": {
+ "avibe/localized-user-text": 1
+ },
"src/pet/PetPage.tsx": {
+ "avibe/localized-user-text": 3,
"react-hooks/preserve-manual-memoization": 2,
"react-hooks/set-state-in-effect": 6
}
diff --git a/ui/eslint.config.js b/ui/eslint.config.js
index d045ed3c9..af80988ca 100644
--- a/ui/eslint.config.js
+++ b/ui/eslint.config.js
@@ -4,6 +4,7 @@ import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
+import localizedUserText from './scripts/localizedUserText.mjs'
export default defineConfig([
globalIgnores(['dist']),
@@ -19,7 +20,9 @@ export default defineConfig([
ecmaVersion: 2020,
globals: globals.browser,
},
+ plugins: { avibe: { rules: { 'localized-user-text': localizedUserText } } },
rules: {
+ 'avibe/localized-user-text': 'error',
// The codebase already marks a binding as deliberately unused by naming it
// `_something` — an argument kept for signature shape, a destructured slot
// being skipped, a caught error that is intentionally swallowed. Opt the
diff --git a/ui/scripts/lintPolicy.mjs b/ui/scripts/lintPolicy.mjs
index fad36d51c..da05ffa22 100644
--- a/ui/scripts/lintPolicy.mjs
+++ b/ui/scripts/lintPolicy.mjs
@@ -78,6 +78,7 @@ export const EXPECTED_RULES = {
'@typescript-eslint/prefer-as-const': [2],
'@typescript-eslint/prefer-namespace-keyword': [2],
'@typescript-eslint/triple-slash-reference': [2],
+ 'avibe/localized-user-text': [2],
'constructor-super': [0],
'for-direction': [2],
'getter-return': [0, { allowImplicit: false }],
@@ -192,7 +193,7 @@ export const EXPECTED_POLICY = {
sourceType: 'module',
parserOptions: {},
processor: null,
- plugins: ['@', '@typescript-eslint', 'react-hooks', 'react-refresh'],
+ plugins: ['@', '@typescript-eslint', 'avibe', 'react-hooks', 'react-refresh'],
linterOptions: { reportUnusedDisableDirectives: 1 },
globals: EXPECTED_BROWSER_GLOBALS,
};
diff --git a/ui/scripts/localizedUserText.mjs b/ui/scripts/localizedUserText.mjs
new file mode 100644
index 000000000..aec2534b8
--- /dev/null
+++ b/ui/scripts/localizedUserText.mjs
@@ -0,0 +1,225 @@
+// Sink-local analysis, not a translation taint engine. See
+// docs/plans/ui-localized-text-guard.md for the rollout and analysis boundary.
+import path from 'node:path';
+
+const USER_PROPS = new Set(['aria-label', 'title', 'placeholder', 'alt', 'children']);
+const WRAPPERS = new Set(['TSAsExpression', 'TSTypeAssertion', 'TSNonNullExpression', 'TSSatisfiesExpression', 'ChainExpression']);
+// Deliberately excludes sentence/list punctuation (including ·). aria-hidden
+// alone never proves that a glyph is decorative: #2559's separator had it too.
+const DECORATIVE_GLYPHS = new Set(['×', '✓', '✔', '✕', '✖', '←', '→', '↑', '↓', '↗', '↙', '⌘', '⌥', '⇧']);
+
+function unwrap(node) {
+ while (node && WRAPPERS.has(node.type)) node = node.expression;
+ return node;
+}
+
+function tagOf(element) {
+ const name = element?.openingElement?.name;
+ return name?.type === 'JSXIdentifier' ? name.name : null;
+}
+
+function attribute(element, name) {
+ return element?.openingElement?.attributes.find((attr) => attr.type === 'JSXAttribute' && attr.name.name === name);
+}
+
+function literalAttribute(attr) {
+ return attr?.value?.type === 'JSXExpressionContainer' ? unwrap(attr.value.expression) : attr?.value;
+}
+
+function hidden(element) {
+ const attr = attribute(element, 'aria-hidden');
+ const value = literalAttribute(attr);
+ return Boolean(attr && !element.openingElement.attributes.some((entry) => entry.type === 'JSXSpreadAttribute')
+ && (!attr.value || value?.value === true || value?.value === 'true'));
+}
+
+// Recognizable machine syntax only, never a whole <code>/<samp> subtree or
+// arbitrary words. These are content classifiers, not a parser for source code.
+function resourceLiteral(text) {
+ if (/\s/u.test(text)) return false;
+ if (/^(?:https?:\/\/|wss?:\/\/)/u.test(text)) {
+ try { return Boolean(new URL(text).hostname); } catch { return false; }
+ }
+ return /^(?:\.{0,2}\/|~\/)[\w./@+-]*[\w][\w./@+-]*$/u.test(text);
+}
+
+function machineToken(text) {
+ return /^--[a-z][a-z0-9-]*(?:=[\w./:-]+)?$/u.test(text)
+ || /^[a-zA-Z_$][\w$]*(?:[._-][\w$]+)+$/u.test(text);
+}
+
+function structuredJson(text) {
+ if (!/^[\s]*[\[{]/u.test(text)) return false;
+ try { return typeof JSON.parse(text) === 'object'; } catch { return false; }
+}
+
+function keyboardToken(text) {
+ return /^(?:(?:Ctrl|Alt|Shift|Meta|Cmd|⌘|⌥|⇧)\+)*(?:[A-Z0-9]|F(?:[1-9]|1[0-2])|Enter|Escape|Tab|Space|Backspace|Delete|Home|End|Arrow(?:Up|Down|Left|Right)|[⌘⌥⇧←→↑↓])$/u.test(text);
+}
+
+export default {
+ meta: {
+ type: 'problem',
+ docs: { description: 'Keep user-visible text and sentence/list composition in locale resources.' },
+ schema: [],
+ messages: {
+ literal: 'Localize this user-facing text with a locale key or Trans; literal copy and separators do not belong in JSX.',
+ composition: 'Let a locale template, Trans, or locale-aware formatter compose this text instead of literal string glue.',
+ },
+ },
+ create(context) {
+ // The rule stays configured identically for ALL TS/TSX, preserving the
+ // effective-policy invariant. Only this rule's behavior is production-TSX.
+ const relative = path.relative(context.cwd, context.filename).split(path.sep).join('/');
+ if (!relative.startsWith('src/') || !relative.endsWith('.tsx')
+ || /\.(?:test|spec)\.tsx$/u.test(relative) || relative.split('/').includes('__tests__')) return {};
+
+ const source = context.sourceCode;
+ function variable(node, name = node.name) {
+ for (let scope = source.getScope(node); scope; scope = scope.upper) {
+ if (scope.set.has(name)) return scope.set.get(name);
+ }
+ return null;
+ }
+ function initializer(node) {
+ const binding = variable(node);
+ const def = binding?.defs[0];
+ if (binding?.defs.length !== 1 || def?.type !== 'Variable' || def.parent.kind !== 'const'
+ || def.node.id.type !== 'Identifier' || binding.references.some((ref) => ref.isWrite() && !ref.init)) return null;
+ return def.node.init;
+ }
+ function isTrans(element) {
+ const name = element?.openingElement?.name;
+ if (name?.type !== 'JSXIdentifier') return false;
+ const binding = variable(name);
+ const def = binding?.defs[0];
+ const key = literalAttribute(attribute(element, 'i18nKey'));
+ return def?.type === 'ImportBinding' && def.parent.source.value === 'react-i18next'
+ && def.node.type === 'ImportSpecifier' && def.node.imported.name === 'Trans'
+ && key && !(key.type === 'Literal' && !key.value);
+ }
+ function translatedChild(node) {
+ for (let parent = node.parent; parent; parent = parent.parent) {
+ // A JSX attribute is a separate sink even inside a translated subtree.
+ if (parent.type === 'JSXAttribute') return false;
+ if (parent.type === 'JSXElement' && isTrans(parent)) return true;
+ }
+ return false;
+ }
+ function exemptText(text, element) {
+ // A complete URL/path is data even in a title or placeholder, unlike a
+ // surrounding sentence. Never apply this exception to string glue.
+ if (resourceLiteral(text)) return true;
+ if (tagOf(element) === 'span' && hidden(element) && DECORATIVE_GLYPHS.has(text)) return true;
+ if (['code', 'samp'].includes(tagOf(element)) && machineToken(text)) return true;
+ if (['code', 'samp', 'pre'].includes(tagOf(element)) && structuredJson(text)) return true;
+ return tagOf(element) === 'kbd' && keyboardToken(text);
+ }
+
+ // Collect only actual return expressions, never conditions, logging,
+ // declarations or a nested function's return. Lexical bindings used by a
+ // returned expression are followed separately through ESLint's scope graph.
+ function returns(fn) {
+ fn = unwrap(fn);
+ if (fn?.type === 'Identifier') fn = unwrap(initializer(fn));
+ if (!['ArrowFunctionExpression', 'FunctionExpression'].includes(fn?.type)) return [];
+ if (fn.body.type !== 'BlockStatement') return [fn.body];
+ const found = [];
+ function visit(node) {
+ if (!node || /Function/u.test(node.type)) return;
+ if (node.type === 'ReturnStatement') { if (node.argument) found.push(node.argument); return; }
+ for (const key of source.visitorKeys[node.type] ?? []) {
+ const value = node[key];
+ if (Array.isArray(value)) value.forEach(visit);
+ else visit(value);
+ }
+ }
+ visit(fn.body);
+ return found;
+ }
+
+ function inspect(root, element) {
+ const active = new Set();
+ const memo = [new Map(), new Map()];
+ function check(raw, allowExemption = true) {
+ const node = unwrap(raw);
+ if (!node || active.has(node)) return null;
+ const cache = memo[Number(allowExemption)];
+ if (cache.has(node)) return cache.get(node);
+ active.add(node);
+ const result = analyze(node, allowExemption);
+ active.delete(node);
+ cache.set(node, result);
+ return result;
+ }
+ function any(nodes, allowExemption = true) { return nodes.map((node) => check(node, allowExemption)).find(Boolean) ?? null; }
+ function analyze(node, allowExemption) {
+ const allowed = (text) => allowExemption && exemptText(text, element);
+ switch (node.type) {
+ case 'Literal':
+ return typeof node.value === 'string' && node.value !== '' && !allowed(node.value) ? 'literal' : null;
+ case 'Identifier': return check(initializer(node), allowExemption);
+ case 'TemplateLiteral':
+ if (node.quasis.some((part) => part.value.cooked !== '')) {
+ if (node.expressions.length === 0) return allowed(node.quasis[0].value.cooked) ? null : 'literal';
+ return 'composition';
+ }
+ return any(node.expressions, allowExemption);
+ case 'BinaryExpression':
+ return node.operator === '+' && any([node.left, node.right], false) ? 'composition' : null;
+ case 'ConditionalExpression': return any([node.consequent, node.alternate], allowExemption);
+ // &&'s left side is a condition, not the displayed string. || and ??
+ // may display their left value, so both alternatives are examined.
+ case 'LogicalExpression': return node.operator === '&&' ? check(node.right, allowExemption) : any([node.left, node.right], allowExemption);
+ case 'ArrayExpression': return any(node.elements, allowExemption);
+ case 'SpreadElement': return check(node.argument, allowExemption);
+ case 'SequenceExpression': return check(node.expressions.at(-1), allowExemption);
+ case 'CallExpression': {
+ const callee = unwrap(node.callee);
+ if (callee?.type !== 'MemberExpression') return null;
+ const method = callee.computed ? callee.property.value : callee.property.name;
+ if (method === 'join') {
+ // Omitted/undefined separator is a literal comma too. Dynamic or
+ // translated separators are opaque unless a local const exposes it.
+ const separator = unwrap(node.arguments[0]);
+ if (!separator || (separator.type === 'Identifier' && separator.name === 'undefined' && !variable(separator)?.defs.length)) return 'composition';
+ if (check(separator, false)) return 'composition';
+ return check(callee.object, allowExemption);
+ }
+ if (method === 'filter') return check(callee.object, allowExemption);
+ if (method === 'map' || method === 'flatMap') return any(returns(node.arguments[0]), allowExemption);
+ // t(), Intl format(), formatNameList(), and other helpers own their
+ // output. Their keys, options and inputs are not returned copy.
+ return null;
+ }
+ default: return null;
+ }
+ }
+ return check(root);
+ }
+ function report(node, expression, element = null) {
+ const messageId = inspect(expression, element);
+ if (messageId) context.report({ node, messageId });
+ }
+ return {
+ JSXText(node) {
+ const text = node.value.trim();
+ if (text && !translatedChild(node) && !exemptText(text, node.parent)) {
+ context.report({ node, messageId: 'literal' });
+ }
+ },
+ JSXExpressionContainer(node) {
+ if (['JSXElement', 'JSXFragment'].includes(node.parent.type)) {
+ report(node, node.expression, node.parent);
+ }
+ },
+ JSXAttribute(node) {
+ if (!USER_PROPS.has(node.name.name) || !node.value) return;
+ const expression = literalAttribute(node);
+ // children= has the same content policy as actual children, except that
+ // attributes never inherit a surrounding Trans exemption.
+ report(node, expression, node.name.name === 'children' ? node.parent.parent : null);
+ },
+ };
+ },
+};
diff --git a/ui/scripts/localizedUserText.test.mjs b/ui/scripts/localizedUserText.test.mjs
new file mode 100644
index 000000000..c80c6cfeb
--- /dev/null
+++ b/ui/scripts/localizedUserText.test.mjs
@@ -0,0 +1,199 @@
+import { beforeAll, describe, expect, it } from 'vitest';
+import { ESLint } from 'eslint';
+
+const RULE = 'avibe/localized-user-text';
+const FILE = 'src/__probe__/LocalizedText.tsx';
+let eslint;
+beforeAll(() => { eslint = new ESLint(); });
+
+async function errors(code, filePath = FILE) {
+ const [result] = await eslint.lintText(code, { filePath });
+ expect(result.fatalErrorCount).toBe(0);
+ return result.messages.filter((message) => message.ruleId === RULE && message.severity === 2);
+}
+
+// Reduced from the four actual review hunks in #2559, not just inline t() calls.
+// These fixtures protect the sink contract that existing lint presets never saw.
+const originalRegressions = [
+ ['probe reason through a local binding', `
+ export function Reason({ result, outcomes, index, t }) {
+ const failure = serverText(t, result?.call.error);
+ const reason = outcomes[index] === 'verified' || outcomes[index] === 'unsupported'
+ ? null : outcomes[index] === 'inconclusive' && !failure
+ ? t('reason.inconclusive')
+ : \`\${t('reason.transient')}\${failure ? \` (\${failure})\` : ''}\`;
+ return <p>{reason}</p>;
+ }`],
+ ['cost array with spread/map and literal joiner', `
+ export function Cost({ price, t }) {
+ const perUnit = (usd, unit) => t('cost.perUnit', { usd, unit }) as string;
+ return <span>{[t('cost.listNote'), ...price.extra.map((extra) =>
+ \`+ \${perUnit(extra.usd_per_1k, extra.unit)}\`)].join(' · ')}</span>;
+ }`],
+ ['accessible name from props rather than inline translations', `
+ export function Chip({ label, explanation, facts }) {
+ return <button aria-label={[label, explanation, ...facts.map((fact) => fact.value)].join('. ')} />;
+ }`],
+ ['aria-hidden middle dot between translated phrases', `
+ export function Summary({ upgraded, aged, t }) {
+ return <p>
+ {upgraded > 0 && <span>{t('upgraded', { count: upgraded })}</span>}
+ {upgraded > 0 && aged > 0 && <span aria-hidden>·</span>}
+ {aged > 0 && <span>{t('aged', { count: aged })}</span>}
+ </p>;
+ }`],
+];
+
+describe('#2618: the original localized-copy regressions cannot return unnoticed', () => {
+ it.each(originalRegressions)('errors on %s', async (_name, code) => {
+ expect((await errors(code)).length).toBeGreaterThan(0);
+ });
+});
+
+const component = (jsx, setup = '') => `
+ import { useTranslation, Trans as LocaleText } from 'react-i18next';
+ import { formatNameList, formatSentences, formatSmallUsd } from '@/components/settings/models/format';
+ export function Probe({ user, values, ready, label, explanation, locale, n }) {
+ const { t } = useTranslation();
+ ${setup}
+ return (${jsx});
+ }
+`;
+
+// Each case names a credible escape from the sink-local contract. The four
+// historical fixtures alone miss other props, aliases, control-flow and syntax.
+describe('all user-facing sinks enforce literal-copy and composition boundaries', () => {
+ it.each(['aria-label', 'title', 'placeholder', 'alt', 'children'])('checks literals and local composition in %s', async (prop) => {
+ for (const jsx of [
+ `<Widget ${prop}="Save" />`,
+ `<Widget ${prop}={'Save'} />`,
+ `<Widget ${prop}={sentence} />`,
+ `<Widget ${prop}={joined} />`,
+ `<Widget ${prop}={added} />`,
+ ]) {
+ const setup = "const reason = t('reason'); const sentence = `${reason} (${explanation})`; const joined = [reason, explanation].join('. '); const added = reason + ': ' + explanation;";
+ expect(await errors(component(jsx, setup))).toHaveLength(1);
+ }
+ });
+
+ it.each([
+ ['ordinary JSX copy', '<button>Save</button>'],
+ ['non-English copy', '<button>保存</button>'],
+ ['literal JSX punctuation', '<p>{label} / {explanation}</p>'],
+ ['explicit space between phrases', "<p>{label}{' '}{explanation}</p>"],
+ ['string addition', "<p>{t('reason') + ': ' + user.name}</p>"],
+ ['template with unknown data', '<p>{`Hello ${user.name}`}</p>'],
+ ['literal conditional alternative', "<p>{ready ? t('ready') : 'Pending'}</p>"],
+ ['literal fallback', "<p>{user.name || 'Anonymous'}</p>"],
+ ['literal left fallback', "<p>{'Anonymous' ?? user.name}</p>"],
+ ['conditional child', "<p>{ready && 'Pending'}</p>"],
+ ['implicit comma joiner', '<p>{values.join()}</p>'],
+ ['explicit undefined comma joiner', '<p>{values.join(undefined)}</p>'],
+ ['computed join method', "<p>{values['join'](' / ')}</p>"],
+ ['optional join call', "<p>{values?.join(' / ')}</p>"],
+ ['array content with localized joiner', "<p>{['Save', t('cancel')].join(t('separator'))}</p>"],
+ ['map expression result', '<p>{values.map(value => `Hello ${value}`)}</p>'],
+ ['map block return result', "<p>{values.map(value => { if (ready) return value; return 'Unknown'; })}</p>"],
+ ])('rejects %s', async (_name, jsx) => {
+ expect((await errors(component(jsx))).length).toBeGreaterThan(0);
+ });
+
+ it.each([
+ ["const text = 'Save'; const alias = text as string;", '<p>{alias}</p>'],
+ ["const reason = t('reason'); const failure = t('failure'); const text = `${reason} (${failure})`; const alias = text!;", '<p>{alias}</p>'],
+ ["const parts = [t('a'), t('b')]; const separator = ' · '; const text = parts.filter(Boolean).join(separator);", '<p>{text}</p>'],
+ ["const text = [label, explanation].join('. '); const alias = text satisfies string;", '<button aria-label={alias} />'],
+ ["const callback = (value) => { const text = `Hello ${value}`; return text; }; const text = values.map(callback);", '<p>{text}</p>'],
+ ])('follows immutable lexical output bindings: %s', async (setup, jsx) => {
+ expect(await errors(component(jsx, setup))).toHaveLength(1);
+ });
+
+ it('does not confuse a shadowed parameter with an outer literal binding', async () => {
+ const code = "const text = 'not displayed'; export function Probe({ text }) { return <p>{text}</p>; }";
+ expect(await errors(code)).toEqual([]);
+ });
+
+ it('terminates on cyclic bindings instead of crashing the gate', async () => {
+ expect(await errors(component('<p>{a}</p>', "const a = b; const b = a + 'Suffix';"))).toHaveLength(1);
+ });
+});
+
+describe('legitimate localization, dynamic data and non-copy values stay usable', () => {
+ it.each([
+ ['locale interpolation', "<p>{t('reasonWithFailure', { reason: t('reason'), failure: user.error })}</p>"],
+ ['locale-owned cost list', "<p>{t('cost.noteWithExtras', { extras: values.map(value => t('cost.extra', { value })).join(t('cost.separator')) })}</p>"],
+ ['locale-owned accessible sentence list', '<button aria-label={formatSentences([label, explanation], locale)} />'],
+ ['locale-owned styled summary', '<LocaleText i18nKey="summary" values={{ upgraded: n, aged: n }} components={{ upgraded: <strong /> }} />'],
+ ['locale-owned separator', "<p>{[label, explanation].filter(Boolean).join(t('separator'))}</p>"],
+ ['Trans component interpolation', '<LocaleText i18nKey="pair" values={{ name: user.name }} components={{ strong: <strong /> }} />'],
+ ['Trans fallback interpolation', '<LocaleText i18nKey="pair">Hello <strong>{{ name: user.name }}</strong></LocaleText>'],
+ ['existing locale-aware lists', '<p>{formatNameList(values, locale)}{formatSentences(values, locale)}</p>'],
+ ['existing number formatter', '<p>{formatSmallUsd(n)}</p>'],
+ ['Intl formatting', '<p>{new Intl.ListFormat(locale).format(values)}{new Intl.NumberFormat(locale).format(n)}</p>'],
+ ['dynamic data in every surface', '<img aria-label={label} title={user.path} placeholder={user.example} alt={user.name} />'],
+ ['dynamic children and numeric arithmetic', '<p>{user.name}{n + 1}{ready && n}</p>'],
+ ['non-copy attributes', '<input className="hello-world" id="field" name="field" type="text" data-label="Save" value="internal-id" />'],
+ ['conditional predicate is not copy', "<p>{user.kind === 'admin' ? user.name : t('guest')}</p>"],
+ ['map logging is not copy', "<p>{values.map(value => { console.log('Loaded item', value); return value; })}</p>"],
+ ['empty strings', "<p>{ready ? label : ''}{values.join('')}</p>"],
+ ])('allows %s', async (_name, jsx) => {
+ expect(await errors(component(jsx))).toEqual([]);
+ });
+
+ it('does not inspect a composition used only for protocol data or logging', async () => {
+ const setup = "const text = `${user.path}/${user.id}`; console.log('Loaded: ' + text);";
+ expect(await errors(component('<p data-path={text}>{user.name}</p>', setup))).toEqual([]);
+ });
+});
+
+describe('exemptions are narrow content contracts, not subtree escape hatches', () => {
+ it.each([
+ '<span aria-hidden>×</span>', '<span aria-hidden="true">→</span>',
+ "<span aria-hidden={true}>{'✓'}</span>",
+ '<code>model_id</code>', '<samp>https://example.com/v1</samp>',
+ '<code>./config.json</code>', '<code>--verbose</code>', '<kbd>Ctrl+K</kbd>',
+ '<code>{user.command}</code>',
+ '<input placeholder="https://example.com/v1" />', '<span>~/.avibe/config.json</span>',
+ '<pre>{\'{"scopes":["read"]}\'}</pre>',
+ ])('allows explicit decorative/technical display: %s', async (jsx) => {
+ expect(await errors(component(jsx))).toEqual([]);
+ });
+
+ it.each([
+ '<span>×</span>', '<span aria-hidden="false">×</span>',
+ '<span aria-hidden={ready}>×</span>', '<span aria-hidden {...user}>×</span>', '<span aria-hidden>·</span>',
+ '<span aria-hidden>Save</span>', '<span aria-hidden>✓ Save</span>',
+ '<span aria-hidden><b>×</b></span>', '<span aria-hidden>✓<b>Save</b></span>',
+ "<span aria-hidden>{'✓' + t('save')}</span>",
+ '<span aria-hidden title="Close">×</span>', '<span aria-hidden aria-label="Close">×</span>',
+ '<code>Save changes</code>', '<code>Save</code>', '<code><b>Save changes</b></code>',
+ '<code title="model_id">model_id</code>', '<code aria-label="model_id">model_id</code>',
+ '<kbd>Save changes</kbd>', '<p><code>model_id</code> is required</p>',
+ '<pre>Save changes</pre>', '<code>{\'"Save"\'}</code>',
+ '<input placeholder="Open https://example.com" />', '<p>/</p>',
+ '<pre aria-label={\'{"scopes":["read"]}\'} />',
+ '<LocaleText>Save</LocaleText>', '<Trans i18nKey="save">Save</Trans>',
+ '<LocaleText i18nKey="save"><button title="Save">Save</button></LocaleText>',
+ "<LocaleText i18nKey=\"save\">{label + ' Save'}</LocaleText>",
+ '<><LocaleText i18nKey="save" />Save changes</>',
+ ])('does not exempt prose, labels, or neighbors: %s', async (jsx) => {
+ expect((await errors(component(jsx))).length).toBeGreaterThan(0);
+ });
+
+ it('does not trust a component named Trans from another package', async () => {
+ expect(await errors('import { Trans } from "other"; export const Probe = () => <Trans i18nKey="save">Save</Trans>;')).toHaveLength(1);
+ });
+});
+
+describe('applicability is narrower than, but does not change, the globally pinned policy', () => {
+ it.each(['src/Probe.test.tsx', 'src/Probe.spec.tsx', 'src/__tests__/Probe.tsx', 'e2e/Probe.tsx'])('does not lint test/non-source copy in %s', async (file) => {
+ expect(await errors('export const Probe = () => <button>Save</button>;', file)).toEqual([]);
+ expect((await eslint.calculateConfigForFile(file)).rules[RULE]).toEqual([2]);
+ });
+
+ it('does not inspect literal values in non-TSX modules, while still resolving the policy', async () => {
+ expect(await errors('export const text = "Save";', 'src/copy.ts')).toEqual([]);
+ expect((await eslint.calculateConfigForFile('src/copy.ts')).rules[RULE]).toEqual([2]);
+ });
+});
+
diff --git a/ui/scripts/localizedUserTextGate.test.mjs b/ui/scripts/localizedUserTextGate.test.mjs
new file mode 100644
index 000000000..c708fef36
--- /dev/null
+++ b/ui/scripts/localizedUserTextGate.test.mjs
@@ -0,0 +1,96 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { spawnSync } from 'node:child_process';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+const UI_ROOT = fileURLToPath(new URL('../', import.meta.url));
+const RULE = 'avibe/localized-user-text';
+let root;
+
+// Test-owned mini UI under this worktree's dependency directory: normal Node
+// resolution reuses installed dependencies, but no source/config/build output
+// is shared or mutated. The outer gate excludes node_modules by contract.
+beforeEach(() => {
+ root = fs.mkdtempSync(path.join(UI_ROOT, 'node_modules/.localized-lint-'));
+ fs.mkdirSync(path.join(root, 'scripts'));
+ fs.mkdirSync(path.join(root, 'src'));
+ fs.copyFileSync(path.join(UI_ROOT, 'eslint.config.js'), path.join(root, 'eslint.config.js'));
+ for (const name of ['lint-baseline.mjs', 'lintPolicy.mjs', 'browserGlobals.mjs', 'localizedUserText.mjs']) {
+ fs.copyFileSync(path.join(UI_ROOT, 'scripts', name), path.join(root, 'scripts', name));
+ }
+ write('package.json', JSON.stringify({ type: 'module', scripts: { lint: 'node scripts/lint-baseline.mjs' } }));
+ write('eslint-baseline.json', JSON.stringify({ rationale: { [RULE]: 'Test-owned legacy copy.' }, violations: {}, suppressions: {} }));
+});
+afterEach(() => fs.rmSync(root, { recursive: true, force: true }));
+const write = (name, value) => fs.writeFileSync(path.join(root, name), value);
+const baseline = () => JSON.parse(fs.readFileSync(path.join(root, 'eslint-baseline.json'), 'utf8'));
+function gate(...args) {
+ const result = spawnSync('npm', ['run', 'lint', '--silent', '--', ...args], { cwd: root, encoding: 'utf8', timeout: 30000 });
+ if (result.error) throw result.error;
+ return { status: result.status, output: `${result.stdout}\n${result.stderr}` };
+}
+const COPY = 'export const Probe = () => <button>Save</button>;\n';
+const LOCALIZED = `import { useTranslation } from 'react-i18next';
+export function Probe() { const { t } = useTranslation(); return <button>{t('save')}</button>; }\n`;
+
+describe('the real npm lint gate ratchets localized-copy debt without a second ledger', () => {
+ it('rejects new files and increased counts; requires paid-down debt to be re-recorded', () => {
+ write('src/Legacy.tsx', COPY);
+ expect(gate().output).toContain('NEW src/Legacy.tsx avibe/localized-user-text 1');
+ expect(gate('--update').status).toBe(0);
+ expect(baseline().violations).toEqual({ 'src/Legacy.tsx': { [RULE]: 1 } });
+ expect(gate().status).toBe(0);
+
+ write('src/New.tsx', COPY);
+ let result = gate();
+ expect(result.status).toBe(1);
+ expect(result.output).toContain('NEW src/New.tsx');
+ fs.rmSync(path.join(root, 'src/New.tsx'));
+
+ write('src/Legacy.tsx', 'export const Probe = () => <><button>Save</button><button>Cancel</button></>;');
+ result = gate();
+ expect(result.status).toBe(1);
+ expect(result.output).toContain('EXPANDED src/Legacy.tsx');
+
+ write('src/Legacy.tsx', LOCALIZED);
+ result = gate();
+ expect(result.status).toBe(1);
+ expect(result.output).toContain('STALE src/Legacy.tsx');
+ expect(gate('--update').status).toBe(0);
+ expect(baseline().violations).toEqual({});
+ expect(gate().status).toBe(0);
+
+ write('src/Legacy.tsx', COPY);
+ expect(gate().status).toBe(1);
+ }, 60000);
+
+ it('keeps the documented same-file/same-rule equal-count replacement limitation explicit', () => {
+ write('src/Legacy.tsx', COPY);
+ expect(gate('--update').status).toBe(0);
+ write('src/Legacy.tsx', 'export const Probe = () => <img alt="Different unlocalized text" />;');
+ expect(gate().status).toBe(0);
+ }, 20000);
+
+ it('does not turn disable comments, inline overrides or config demotion into unmeasured slack', () => {
+ write('src/New.tsx', `// eslint-disable-next-line ${RULE}\n${COPY}`);
+ let result = gate();
+ expect(result.status).toBe(1);
+ expect(result.output).toContain('1 suppressed messages (not in the baseline)');
+
+ write('src/New.tsx', `/* eslint ${RULE}: "off" */\n${COPY}`);
+ result = gate();
+ expect(result.status).toBe(1);
+ expect(result.output).toContain('INLINE');
+
+ write('src/New.tsx', LOCALIZED);
+ const config = fs.readFileSync(path.join(root, 'eslint.config.js'), 'utf8');
+ write('eslint.config.js', config.replace("'avibe/localized-user-text': 'error'", "'avibe/localized-user-text': 'warn'"));
+ const before = fs.readFileSync(path.join(root, 'eslint-baseline.json'), 'utf8');
+ result = gate('--update');
+ expect(result.status).toBe(1);
+ expect(result.output).toContain('POLICY');
+ expect(result.output).toContain('avibe/localized-user-text: expected [2], resolved [1]');
+ expect(fs.readFileSync(path.join(root, 'eslint-baseline.json'), 'utf8')).toBe(before);
+ }, 30000);
+});