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(i18n): type translation keys and resource consumers (#2029)

Max4019b704c99a
diff --git a/docs/plans/issue-1967-translation-key-types.md b/docs/plans/issue-1967-translation-key-types.md
new file mode 100644
index 000000000..390a88abf
--- /dev/null
+++ b/docs/plans/issue-1967-translation-key-types.md
@@ -0,0 +1,127 @@
+# Translation keys as a compiler-checked consumption contract
+
+## Goal and starting evidence
+
+Implement issue #1967 on master `06a864947556406062fe2e585c2e27784fcbaf58`, after #1969/#2016. Make locally authored translation names and their consumed value shapes a compiler-checked contract. Preserve runtime translation semantics and existing coverage guards.
+
+The source currently has no i18next resource augmentation or bundle-derived TranslationKey. Carriers such as ProxyUrlField, SettingsLayout, app registry, agentGraph, sourceStatePresentation and error-key helpers widen keys to string. MemorySettingsPanel asserts returnObjects results as string[] before mapping. The app tsconfig excludes tests, and typecheck:tests only includes Model Hub tests. Installed i18next 25.x already has resource typing, ParseKeys, plural resolution and returnObjects-dependent returns; prefer these existing mechanisms over a second translation API or generated duplicate bundle.
+
+## Contract
+
+1. The canonical bundled resource shape owns locally authored translation keys. Text-carrying props/data/functions accept keys that resolve to text, not arbitrary strings or object prefixes. Lists and intentional prefixes have their own accurately derived types where consumed. Inventory actual producers/consumers, not the historical estimate of 18 prop names.
+2. Type checks connect every local key carrier to the actual typed translation consumer. Valid literal and finite-union keys retain inference through data tables and component props. Existing plural families and intentional key prefixes remain valid with their appropriate options; a subtree cannot silently become a plain rendered label.
+3. returnObjects list consumption gets its list element shape from resources. Remove the MemorySettingsPanel `as string[]` escape. An object-valued resource or a string at that call must cause a real consumer compile error. Do not claim TypeScript can outlaw deliberate double assertions/any; the implementation must not add them to evade this contract.
+4. A key may be deliberately absent when the existing caller supplies a fallback. Preserve this behavior explicitly without making every static carrier a free string again. Existing backend/server-chosen dynamic key surfaces remain open at the transport boundary: validate/resolve them at a small existing ownership boundary, preserving fallback behavior. Do not cast arbitrary runtime input to TranslationKey and call it validated. Document and test whatever dynamic boundary is selected.
+5. The guard and the compiler-contract witnesses belong to a maintained tsc project invoked by CI. `tsc --listFilesOnly` proves membership. Fixture i18next instances with synthetic resources must stay usable without pretending their keys belong to the app resource contract; isolate this test boundary honestly.
+6. Keep #1969's presence/validity distinction and existing existence/parity/residue/blank/plural checks. Typechecking does not prove nonblank copy or equal locale content. No orphan pin, no wholesale scanner removal, no claims that genuinely dynamic inputs are now statically exhaustive.
+
+## Scope
+
+One isolated implementation lane owns this plan; ui/src/i18n type definitions and focused fixtures; genuine translation carrier props/data/return annotations across ui/src; the MemorySettingsPanel list consumer; existing dynamic-translation boundary helpers and necessary focused tests; minimal ui tsconfig/package script integration. This is semantic typing, not visual design; preserve displayed copy, layout and behavior. Inventory exact files in the plan before broad migration. No Python, desktop, service, deployment, #1968 or #1976 work. No dependencies or lockfile changes unless independently justified to PM first. Bundle edits are not a shortcut to silence types: report any real product-copy defect separately before editing bundles. Keep unrelated Model Hub/security work out of this PR.
+
+## Approach and decisions
+
+Start with a small compiler experiment against the installed i18next declarations to choose augmentation and exported carrier types. Native resource typing is the preferred direction, not a mandate to force a particular flag. Report the selected static/fallback/dynamic boundary with representative compiler evidence to PM before mass edits; proceed on the smallest contract-preserving design. If a change needs a parallel translation framework, broad caller rewrite, or altered fallback policy, stop and have PM diagnose scope first. Ordinary annotation/inference repairs within this contract do not need per-file approval.
+
+## Acceptance evidence
+
+- Real consuming negative controls: typo in a component carrier; typo in a data-table field; deletion/rename of a referenced key in the canonical bundle; object/list key given to a text carrier; wrong resource shape at MemorySettingsPanel list consumption. Compiler exits nonzero and names the consumer. Restore mutations afterward.
+- Positive controls: valid carrier/data keys; finite template unions; plural counts; proper list returns; legitimate missing-key fallback; known and unknown server-provided keys with the existing honest fallback outcome.
+- Type-level fixture uses consumed @ts-expect-error or equivalent existing tools, so widening the contract makes the fixture fail. Include representative real carrier types instead of testing only an unused helper type.
+- Existing keyCoverage guard passes, including meaningful M21/M22/presence-vs-shape checks. Focused affected component/boundary tests pass. Run typecheck:tests, required UI build, lint, and appropriate broader UI validation; let GitHub run full CI.
+- Non-draft PR to master, exact-head Codex PASS, all expected CI green, full paginated zero unresolved threads, CLEAN. PM independently verifies a diff and consuming tests each findings round. Same root-cause class on two reviewed heads or three findings-bearing heads after a rewrite pauses patching for PM diagnosis.
+
+## Delivery
+
+PM session sesg43e4mnngm. Owner authorized this issue's implementation and reviewable PR, not its merge; the earlier merge instruction named only #2014/#2016. Lane does not merge or close the issue. Maintain one durable combined PR/CI Watch with separate lane cursor, --forever and --timeout 0 on supervisor and waiter, unchanged across heads; no push over pending review. Deliver final report to PM before removing the Watch, then quiesce. PM owns independent gate Watch and final handback.
+
+## Implementation ledger
+
+Base and PM decisions were verified against the actual code and compiler throughout implementation. The final contract and evidence follow the producer inventory.
+
+### Native typing experiment and inventory (before migration)
+
+On base `06a864947556406062fe2e585c2e27784fcbaf58`, i18next's resource augmentation, `ParseKeys`, and native `defaultValue` overload passed a small compiler witness: text literals accepted; typo/object/list text carriers rejected; list inference accepted; string/object `.map` rejected; open strings require explicit fallback. Keep `strictKeyChecks` at its native false default to preserve intentional missing-key defaults. No custom t overload.
+
+The synthetic-resource scanner gets its own tsc project without app augmentation; the app contract witnesses get augmentation and actual component/data types. TypeScript's overload diagnostic crashes on the old `(key: string) => string` helper call in FilePicker; fix the producer signature, not TypeScript or dependencies.
+
+Exact producer inventory (consumer errors downstream do not necessarily require editing those files):
+
+Text carrier props/data:
+- `ui/src/components/ui/signing-address-list.tsx`
+- `ui/src/components/settings/SettingsPlaceholderPage.tsx`
+- `ui/src/components/settings/SettingsLayout.tsx`
+- `ui/src/components/settings/memory/useMemoryResource.ts`
+- `ui/src/components/settings/models/GuardGapList.tsx`
+- `ui/src/components/settings/models/UsageTab.tsx`
+- `ui/src/components/settings/models/sourceStatePresentation.ts`
+- `ui/src/components/shared/ProxyUrlField.tsx`
+- `ui/src/components/shared/RoutingConfigPanel.tsx` (message types are open server values; inheritsFromKey is a config key, not a translation)
+- `ui/src/components/steps/DoctorPanel.tsx`
+- `ui/src/components/steps/LogsPanel.tsx`
+- `ui/src/components/workbench/AgentGraphDetail.tsx`
+- `ui/src/components/workbench/TerminalView.tsx`
+- `ui/src/components/workbench/ShowPageAnnotateControl.tsx`
+- `ui/src/components/workbench/AgentActivityGroup.tsx`
+- `ui/src/components/workbench/AgentGraphOrphanStrip.tsx`
+- `ui/src/components/workbench/HarnessPage.tsx`
+- `ui/src/components/workbench/WorkbenchSidebar.tsx`
+- `ui/src/lib/agentGraph.ts`
+- `ui/src/apps/registry.tsx`
+
+Translation function signatures:
+- `ui/src/components/settings/SettingsMessagingPage.tsx`
+- `ui/src/components/settings/memory/MemoryProfilePanel.tsx`
+- `ui/src/components/steps/UserList.tsx`
+- `ui/src/components/workbench/AgentGraphCanvas.tsx`
+- `ui/src/components/workbench/AgentActivityGroup.tsx`
+- `ui/src/components/workbench/harnessRuns.ts`
+- `ui/src/components/workbench/HarnessPage.tsx`
+- `ui/src/components/workbench/harnessLifecycle.ts`
+- `ui/src/lib/filesApi.ts`
+- `ui/src/lib/agentGraph.ts`
+
+Other local key producers and finite unions:
+- `ui/src/components/settings/models/{addApiKeyState,manage,repair,serverCopy,sourcePresentation,sourceStatePresentation}.ts`
+- `ui/src/components/settings/models/{AddApiKeyDialog,BackendModelCatalogDialog,BackendModelEditorDialog,MigrationDialog,RouteChainDialog,SourceMutationReport,SupplyGraph,SourcesCard,UsageTab}.tsx`
+- `ui/src/lib/{actionShortcuts,agentBackends,annotationView,backgroundActivity,chatTrigger,workbenchUpload}.ts`
+- `ui/src/components/{RemoteAccess,Workbench}.tsx`
+- `ui/src/components/onboarding/AccessTiles.tsx`
+- `ui/src/components/steps/LarkConfig.tsx`
+- `ui/src/components/workbench/{AgentsPage,Composer,TerminalView,WorkbenchModulePlaceholder}.tsx`
+- `ui/src/components/settings/{BackendTestPanel,OpencodeProviderTestPanel}.tsx`
+- `ui/src/components/settings/memory/{MemorySettingsPanel,MemoryProcessingRecordPanel,memoryStatusPresentation}.tsx` (presentation is `.ts`)
+- `ui/src/components/ui/directory-browser.tsx`
+
+Open runtime boundary consumers: existing `serverText` and `fileBrowserErrorMessage`; backend platform titles/descriptions in `PlatformSelection`, `ChannelList`, `UserList`, `SettingsPlatformsPage`; dependency ids in `SettingsDependenciesPage`; source names in Memory processing records; message types in RoutingConfigPanel. These remain open with existing key/raw/generic fallback outcomes. Closed server vocabularies remain compiler checked. No transport schema narrowing to the installed UI bundle.
+
+### Final representation and boundaries
+
+- Native i18next `CustomTypeOptions.resources` derives solely from `en.json` through `TranslationPaths<T>`. The bundle contains 21 literal dotted keys mixed with nested resources, including `vendor` alongside `vendor.search`; native recursive return typing otherwise walks JavaScript String methods. The adapter enumerates full paths, retains real objects/arrays, and looks up nested paths before literal dotted fallbacks. String methods are never traversed. No runtime resources, translations, dependencies or resolver behavior change.
+- Type-only `keySeparator: never` treats the expanded paths atomically in native i18next types. Runtime keeps its default dot separator. Native `keyPrefix` is unsupported by this adapter and has no current source consumer; the existing Workbench placeholder uses a finite, bundle-derived full-path prefix. Arrays retain their element shape; this adapter does not expose indexed translation paths because no app consumer needs them.
+- `TranslationKey` filters native `ParseKeys` to actual text available without count, excluding plural-only family bases. Counted `t` calls still use native plural typing. Concrete plural suffix text remains a valid plain key. This avoids claiming a generic label can resolve a family that requires count.
+- Local props, data tables, callback signatures and key-producing functions keep type information through to native `t`. Finite template producers retain literal inference. Memory disclosure maps the inferred string array without an assertion.
+- Deliberate missing-key fallback remains native `defaultValue`. That overload also admits arbitrary strings and even known malformed shapes: it is an explicit API escape boundary, not a universal static guarantee. The existing presence/validity guard remains required. A server restore-preview `manual` origin, for which the bundle has no copy, retains its existing key-string fallback explicitly rather than inventing copy.
+- Open server keys remain strings. `serverText` resolves raw values and returns only text or its existing generic/null fallback. Its immutable options object is an opaque shape-inspection boundary to the source scanner, which cannot infer list consumption there; real i18next runtime tests prove text/missing/object/array behavior. `fileBrowserErrorMessage` keeps raw-error fallback. The existing platform catalog owner now resolves open title/description keys with the existing key-string fallback. Neither boundary casts arbitrary data to TranslationKey.
+- The coverage guard has its own maintained tsc project, without app augmentation, so its synthetic resources remain honestly untyped. App/compiler witnesses and Model Hub tests include augmentation explicitly. All three projects run under CI's existing `typecheck:tests` invocation. No new test framework or workflow needed.
+- Scanner preservation: only type nodes are omitted from runtime literal collection. Runtime literals inside assertions, satisfies expressions, JSX, enums, calls and plain data remain covered. Exactly six old residual pins disappear because OAuth full-key selection and ShowPage equality narrowing remove unreachable template products. No new pin, presence/shape weakening, or dynamic/orphan completeness claim.
+
+### Validation evidence
+
+- Normal app tsc and all three `typecheck:tests` projects pass. `--listFilesOnly` proves guard/witness membership and the synthetic guard's exclusion of application augmentation.
+- Eight temporary real-source negative controls each exit 2 and name the expected consumer: Telegram prop typo, app registry typo, object as registry title, list as Telegram label, deletion of Telegram's resource key, and Memory disclosure changed to object, string, or object array. Each mutation was restored in `finally`; canonical bundles are unchanged.
+- Maintained expect-error witnesses cover actual ProxyUrlField, app registry, SourceStatePresentation and placeholder prop types; typo, prefix/list text misuse, plural-family-without-count, list `.map`, phantom descendant and String.search/String.sub callability errors. Positive witnesses cover text, finite prefixes, plural count, list elements and explicit missing defaults. Runtime coverage checks every actual dotted resource key in both locales and nested-vs-literal collision precedence.
+- Initial focused run: 83 tests pass across keyCoverage, translationContract, serverCopy and MemorySettingsPanel. Subsequent guard fixture strengthening passes all 20 guard tests, including existing M21/M22 and presence/shape controls. Final local verification: all 305 UI test files / 4,149 tests pass, all three test typecheck projects pass, lint baseline passes (204 remaining legacy violations), and production build passes. Existing chunk-size/dependency annotation warnings remain. PR gates follow below when terminal.
+- Lint baseline only decreases: replacing permissive translation callbacks removes seven existing any violations. No new debt is added.
+
+### Delivery state
+
+No Codex findings-bearing heads yet. No merge/deployment/runtime restart authorized. UI runtime verification is unit/render and build-based; cross-platform manual/Incus verification is not required for this type-contract change and has not been performed.
+
+### Integration with the security dependency update
+
+PR #2029 was opened at `ef31a1bf27d4b48a603ad1c42f7f42cce8743ed4` while master advanced. Integrated merged #2026 (`9852e25f464659fc63acebf0447a8047906d2d99`) locally using a non-destructive merge, producing `7c8dbabca284e3b8c7575a742bf8decf29081edd`. The new remote head is held until the initial Codex review is terminal.
+
+Installed the merged lockfile with `npm ci`; its SHA-256 is `f406596208e6bc5cf7b69c829dae9f14f3b4fab55dec6fe65b8316a6d74a5a6a`. With these exact dependencies, test typechecking, lint and production build pass; all 308 UI test files / 4,173 tests pass, including #2026's added security/script tests. Rechecked tsc file membership. Final diff against this master still contains no dependency/lockfile/bundle changes.
+
+The remote has a restricted fetch refspec: explicit `refs/heads/master:refs/remotes/origin/master` was used to update the tracking ref before integration. No shared config or primary checkout changed. Open #2028 overlaps only the package script location and the platform-array const annotation; #2027 had no code overlap at inspection. Neither open peer was cherry-picked.
diff --git a/ui/eslint-baseline.json b/ui/eslint-baseline.json
index 991b48d1c..964246b50 100644
--- a/ui/eslint-baseline.json
+++ b/ui/eslint-baseline.json
@@ -79,7 +79,7 @@
"@typescript-eslint/no-explicit-any": 4
},
"src/components/steps/UserList.tsx": {
- "@typescript-eslint/no-explicit-any": 3
+ "@typescript-eslint/no-explicit-any": 2
},
"src/components/steps/WeChatConfig.tsx": {
"@typescript-eslint/no-explicit-any": 4
@@ -97,9 +97,6 @@
"src/components/workbench/FileTree.tsx": {
"react-hooks/set-state-in-effect": 2
},
- "src/components/workbench/HarnessPage.tsx": {
- "@typescript-eslint/no-explicit-any": 1
- },
"src/components/workbench/TerminalView.tsx": {
"react-hooks/set-state-in-effect": 1
},
@@ -109,9 +106,6 @@
"src/components/workbench/harnessLifecycle.test.ts": {
"@typescript-eslint/no-explicit-any": 1
},
- "src/components/workbench/harnessLifecycle.ts": {
- "@typescript-eslint/no-explicit-any": 5
- },
"src/context/ApiContext.tsx": {
"@typescript-eslint/no-explicit-any": 49,
"react-refresh/only-export-components": 1
diff --git a/ui/package.json b/ui/package.json
index 43f65be41..6ce973e21 100644
--- a/ui/package.json
+++ b/ui/package.json
@@ -15,7 +15,7 @@
"lint:baseline": "node scripts/lint-baseline.mjs --update",
"preview": "vite preview",
"test": "vitest run",
- "typecheck:tests": "tsc -p src/components/settings/models/tsconfig.tests.json --noEmit",
+ "typecheck:tests": "tsc -p src/components/settings/models/tsconfig.tests.json --noEmit && tsc -p tsconfig.i18n-tests.json --noEmit && tsc -p src/i18n/tsconfig.guard.json --noEmit",
"test:crypto": "vitest run src/lib/vaultCrypto.test.ts",
"e2e": "playwright test",
"e2e:headed": "playwright test --headed",
diff --git a/ui/src/apps/registry.tsx b/ui/src/apps/registry.tsx
index 674e1cb15..bb36046b1 100644
--- a/ui/src/apps/registry.tsx
+++ b/ui/src/apps/registry.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import { Suspense, lazy } from 'react';
import { CodeXml, Eye, Folder, LayoutGrid, MonitorPlay, SquareTerminal } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
@@ -16,7 +17,7 @@ export type AppId = 'files' | 'terminal' | 'editor' | 'preview' | 'showpage' | '
export interface AppDefinition {
id: AppId;
/** i18n key for the window title / Dock label. */
- titleKey: string;
+ titleKey: TranslationKey;
icon: LucideIcon;
/** Tint for the Dock tile + window title icon — a CSS var token name. */
accent: string;
diff --git a/ui/src/components/RemoteAccess.tsx b/ui/src/components/RemoteAccess.tsx
index a55f581b0..ea1815694 100644
--- a/ui/src/components/RemoteAccess.tsx
+++ b/ui/src/components/RemoteAccess.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import React, { useCallback, useEffect, useState } from 'react';
import {
Activity,
@@ -298,7 +299,12 @@ export const RemoteAccess: React.FC = () => {
: qualityGrade === 'critical' || qualityGrade === 'degraded'
? 'destructive'
: 'secondary';
- const qualityLabel = t(`remoteAccess.quality${qualityGrade.charAt(0).toUpperCase()}${qualityGrade.slice(1)}`);
+ const qualityKeys = {
+ good: 'remoteAccess.qualityGood', fair: 'remoteAccess.qualityFair', poor: 'remoteAccess.qualityPoor',
+ critical: 'remoteAccess.qualityCritical', unknown: 'remoteAccess.qualityUnknown',
+ degraded: 'remoteAccess.qualityDegraded', recovering: 'remoteAccess.qualityRecovering',
+ } as const satisfies Record<typeof qualityGrade, TranslationKey>;
+ const qualityLabel = t(qualityKeys[qualityGrade]);
const requestPath = quality?.request_path;
const requestPathDisplayState = getTunnelRequestPathDisplayState(requestPath);
const requestPathUnavailable = requestPathDisplayState === 'unavailable';
diff --git a/ui/src/components/Workbench.tsx b/ui/src/components/Workbench.tsx
index c8dba17f7..303e5389a 100644
--- a/ui/src/components/Workbench.tsx
+++ b/ui/src/components/Workbench.tsx
@@ -50,13 +50,13 @@ export const Workbench: React.FC = () => {
// Quick chips under the hero — three of the most common first moves.
const suggestions = [
...(canCreateProject
- ? [{ key: 'newProject', icon: FolderPlus, onClick: () => setNewProjectOpen(true) }]
+ ? [{ key: 'newProject' as const, icon: FolderPlus, onClick: () => setNewProjectOpen(true) }]
: []),
...(capabilities.can_manage_agents
- ? [{ key: 'openAgents', icon: Bot, onClick: () => navigate('/agents') }]
+ ? [{ key: 'openAgents' as const, icon: Bot, onClick: () => navigate('/agents') }]
: []),
...(capabilities.can_manage_instance
- ? [{ key: 'openHarness', icon: Activity, onClick: () => navigate('/harness') }]
+ ? [{ key: 'openHarness' as const, icon: Activity, onClick: () => navigate('/harness') }]
: []),
];
diff --git a/ui/src/components/onboarding/AccessTiles.tsx b/ui/src/components/onboarding/AccessTiles.tsx
index b37b7a317..5a71c9064 100644
--- a/ui/src/components/onboarding/AccessTiles.tsx
+++ b/ui/src/components/onboarding/AccessTiles.tsx
@@ -3,7 +3,7 @@ import { useTranslation } from 'react-i18next';
import { PlatformIcon } from '../visual';
import { useOnboardingMotion } from './motion';
-const PLATFORMS = ['avibe', 'slack', 'discord', 'telegram', 'lark', 'wechat'];
+const PLATFORMS = ['avibe', 'slack', 'discord', 'telegram', 'lark', 'wechat'] as const;
export function AccessTiles() {
const { t } = useTranslation();
diff --git a/ui/src/components/settings/BackendTestPanel.tsx b/ui/src/components/settings/BackendTestPanel.tsx
index be32f8cb5..bb4f4a3b2 100644
--- a/ui/src/components/settings/BackendTestPanel.tsx
+++ b/ui/src/components/settings/BackendTestPanel.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Play, Zap } from 'lucide-react';
@@ -64,7 +65,7 @@ export const BackendTestPanel: React.FC<BackendTestPanelProps> = ({ backend }) =
const failureSentence = (result: BackendAuthTestResult): string => {
const detail = (result.detail || '').trim();
const code = (result.error || '').trim();
- const map: Record<string, string> = {
+ const map: Record<string, TranslationKey> = {
invalid_credentials: 'settings.backends.testFailureInvalidCredentials',
forbidden: 'settings.backends.testFailureForbidden',
model_not_found: 'settings.backends.testFailureModelNotFound',
diff --git a/ui/src/components/settings/OpencodeProviderTestPanel.tsx b/ui/src/components/settings/OpencodeProviderTestPanel.tsx
index 9f17e08dc..4c556ab3c 100644
--- a/ui/src/components/settings/OpencodeProviderTestPanel.tsx
+++ b/ui/src/components/settings/OpencodeProviderTestPanel.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import React, { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Play, Zap } from 'lucide-react';
@@ -49,7 +50,7 @@ export const OpencodeProviderTestPanel: React.FC<OpencodeProviderTestPanelProps>
const failureSentence = (result: BackendAuthTestResult): string => {
const detail = (result.detail || '').trim();
const code = (result.error || '').trim();
- const map: Record<string, string> = {
+ const map: Record<string, TranslationKey> = {
invalid_credentials: 'settings.backends.testFailureInvalidCredentials',
forbidden: 'settings.backends.testFailureForbidden',
model_not_found: 'settings.backends.testFailureModelNotFound',
diff --git a/ui/src/components/settings/SettingsDependenciesPage.tsx b/ui/src/components/settings/SettingsDependenciesPage.tsx
index a67d13b35..89f447601 100644
--- a/ui/src/components/settings/SettingsDependenciesPage.tsx
+++ b/ui/src/components/settings/SettingsDependenciesPage.tsx
@@ -122,7 +122,7 @@ export const SettingsDependenciesPage: React.FC = () => {
const res = await api.installDependency(dep.id);
showToast(
res.ok
- ? t('settings.dependencies.installed', { name: t(`settings.dependencies.items.${displayId}.label`) })
+ ? t('settings.dependencies.installed', { name: t(`settings.dependencies.items.${displayId}.label`, { defaultValue: `settings.dependencies.items.${displayId}.label` }) })
: localizedFailure(res),
res.ok ? 'success' : 'error'
);
@@ -228,8 +228,8 @@ export const SettingsDependenciesPage: React.FC = () => {
icon={meta.icon}
tileClassName={meta.tileCls}
iconClassName={meta.iconCls}
- title={t(`settings.dependencies.items.${id}.label`)}
- detail={t(`settings.dependencies.items.${id}.detail`)}
+ title={t(`settings.dependencies.items.${id}.label`, { defaultValue: `settings.dependencies.items.${id}.label` })}
+ detail={t(`settings.dependencies.items.${id}.detail`, { defaultValue: `settings.dependencies.items.${id}.detail` })}
actions={
<>
{checkProgress}
@@ -265,7 +265,7 @@ export const SettingsDependenciesPage: React.FC = () => {
icon={meta.icon}
tileClassName={meta.tileCls}
iconClassName={meta.iconCls}
- title={t(`settings.dependencies.items.${id}.label`)}
+ title={t(`settings.dependencies.items.${id}.label`, { defaultValue: `settings.dependencies.items.${id}.label` })}
badges={
d.required && (
<Badge variant="secondary" className="font-mono uppercase tracking-[0.08em]">
@@ -275,7 +275,7 @@ export const SettingsDependenciesPage: React.FC = () => {
}
detail={
<>
- {t(`settings.dependencies.items.${id}.detail`)}
+ {t(`settings.dependencies.items.${id}.detail`, { defaultValue: `settings.dependencies.items.${id}.detail` })}
{d.id === 'model-hub-engine' && d.latest_version && (
<span className="mt-1 block font-mono text-[11px]">
{t('settings.dependencies.targetVersion', {
diff --git a/ui/src/components/settings/SettingsLayout.tsx b/ui/src/components/settings/SettingsLayout.tsx
index 939a2b241..1872d76ed 100644
--- a/ui/src/components/settings/SettingsLayout.tsx
+++ b/ui/src/components/settings/SettingsLayout.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import React, { useEffect, useMemo, useState } from 'react';
import { NavLink, Outlet, useLocation, useNavigate } from 'react-router-dom';
import {
@@ -40,7 +41,7 @@ import { modelHubEnabledFromConfig } from './models/featureFlags';
type SettingsItem = {
path: string;
- labelKey: string;
+ labelKey: TranslationKey;
icon: React.ComponentType<{ className?: string }>;
ownerOnly?: boolean;
feature?: 'models' | 'memory' | 'channels';
@@ -50,7 +51,7 @@ type SettingsItem = {
};
type SettingsGroup = {
- labelKey: string;
+ labelKey: TranslationKey;
items: SettingsItem[];
};
diff --git a/ui/src/components/settings/SettingsMessagingPage.tsx b/ui/src/components/settings/SettingsMessagingPage.tsx
index a230005e9..dedb1bd0d 100644
--- a/ui/src/components/settings/SettingsMessagingPage.tsx
+++ b/ui/src/components/settings/SettingsMessagingPage.tsx
@@ -1,3 +1,4 @@
+import type { TFunction } from 'i18next';
import React, { useEffect, useMemo, useState } from 'react';
import { ArrowRight, Bot, HelpCircle, MessageSquare, Radio, Send, Sparkles, Type } from 'lucide-react';
import { Link } from 'react-router-dom';
@@ -27,7 +28,7 @@ import {
} from '@/lib/chatDisplay';
import { configChanges } from '@/lib/configMutations';
-function formatSavedAt(value: number | null, t: (key: string) => string) {
+function formatSavedAt(value: number | null, t: TFunction) {
if (!value) return t('settings.messagingStatusIdle');
const deltaSec = Math.max(0, Math.round((Date.now() - value) / 1000));
return deltaSec <= 1
diff --git a/ui/src/components/settings/SettingsPlaceholderPage.tsx b/ui/src/components/settings/SettingsPlaceholderPage.tsx
index 619a879b9..329a6ec18 100644
--- a/ui/src/components/settings/SettingsPlaceholderPage.tsx
+++ b/ui/src/components/settings/SettingsPlaceholderPage.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import React from 'react';
import { Link } from 'react-router-dom';
import { ArrowRight, Sparkles } from 'lucide-react';
@@ -7,8 +8,8 @@ import { SettingsPageShell } from './SettingsPageShell';
export const SettingsPlaceholderPage: React.FC<{
tab: 'platforms' | 'backends' | 'messaging';
- titleKey: string;
- subtitleKey: string;
+ titleKey: TranslationKey;
+ subtitleKey: TranslationKey;
}> = ({ tab, titleKey, subtitleKey }) => {
const { t } = useTranslation();
diff --git a/ui/src/components/settings/SettingsPlatformsPage.tsx b/ui/src/components/settings/SettingsPlatformsPage.tsx
index 487481661..971ec8a7c 100644
--- a/ui/src/components/settings/SettingsPlatformsPage.tsx
+++ b/ui/src/components/settings/SettingsPlatformsPage.tsx
@@ -1,3 +1,4 @@
+import { platformText } from '@/lib/platforms';
import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';
import React, { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -340,7 +341,7 @@ export const SettingsPlatformsPage: React.FC = () => {
active ? 'font-bold text-foreground' : 'font-medium text-muted'
)}
>
- {t(platform.title_key || `platform.${id}.title`)}
+ {platformText(t, id, 'title', platform.title_key)}
</span>
</button>
);
@@ -352,8 +353,8 @@ export const SettingsPlatformsPage: React.FC = () => {
with no credentials only appear here after the user checks them. */}
{cardPlatforms.map((id) => {
const descriptor = platformCatalog.find((p) => p.id === id);
- const label = t(descriptor?.title_key || `platform.${id}.title`);
- const description = t(descriptor?.description_key || `platform.${id}.desc`);
+ const label = platformText(t, id, 'title', descriptor?.title_key);
+ const description = platformText(t, id, 'desc', descriptor?.description_key);
const tile = tileStyle(id);
const runnable = platformHasRunnableConfig(config, id);
const enabled = enabledPlatforms.includes(id);
@@ -421,10 +422,7 @@ export const SettingsPlatformsPage: React.FC = () => {
<DialogDescription>
{t('platform.disableConfirmBody', {
name: confirmDisableId
- ? t(
- platformCatalog.find((p) => p.id === confirmDisableId)?.title_key ||
- `platform.${confirmDisableId}.title`
- )
+ ? platformText(t, confirmDisableId, 'title', platformCatalog.find((p) => p.id === confirmDisableId)?.title_key)
: '',
})}
</DialogDescription>
diff --git a/ui/src/components/settings/memory/MemoryProcessingRecordPanel.tsx b/ui/src/components/settings/memory/MemoryProcessingRecordPanel.tsx
index 448b85ec8..b67858a77 100644
--- a/ui/src/components/settings/memory/MemoryProcessingRecordPanel.tsx
+++ b/ui/src/components/settings/memory/MemoryProcessingRecordPanel.tsx
@@ -55,7 +55,7 @@ const SourceNotices: React.FC<{ sources: MemoryProcessingRecordSources }> = ({ s
{unavailable.map(([name, source]) => (
<div key={name} className="rounded-md border border-border bg-surface px-3 py-2 text-[11.5px] text-muted">
{t('memory.processingRecord.records.sourceNotice', {
- section: t(`memory.processingRecord.source.${name}`),
+ section: t(`memory.processingRecord.source.${name}`, { defaultValue: `memory.processingRecord.source.${name}` }),
state: t(`memory.processingRecord.sourceState.${source.status}`),
reason: reasonLabel(t, source.reason),
})}
diff --git a/ui/src/components/settings/memory/MemoryProfilePanel.tsx b/ui/src/components/settings/memory/MemoryProfilePanel.tsx
index 78dae57aa..83c05709b 100644
--- a/ui/src/components/settings/memory/MemoryProfilePanel.tsx
+++ b/ui/src/components/settings/memory/MemoryProfilePanel.tsx
@@ -1,3 +1,4 @@
+import type { TFunction } from 'i18next';
import { useEffect, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { ChevronDown, Loader2, RefreshCw } from 'lucide-react';
@@ -11,7 +12,6 @@ import { useMemoryResource } from './useMemoryResource';
import { memoryOriginLabelKey } from './memoryOrigin';
type MemoryItemsOk = Extract<MemoryItemsResult, { status: 'ok' }>;
-type Translate = (key: string, options?: Record<string, unknown>) => string;
const DISCLOSURE_TRIGGER_CLASSES =
'flex min-w-0 items-center gap-1.5 rounded text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring';
@@ -83,13 +83,13 @@ const ProfileEntry: React.FC<{
};
/** A blank/whitespace-only category or trait still needs a discoverable, deterministic label. */
-const resolveEntryLabel = (t: Translate, raw: string | null, index: number): string => {
+const resolveEntryLabel = (t: TFunction, raw: string | null, index: number): string => {
const trimmed = raw?.trim();
return trimmed ? trimmed : t('memory.profile.entryFallback', { number: index + 1 });
};
/** Render provider values as inert text nodes, never as Markdown or HTML. */
-export const StructuredMemoryProfile: React.FC<{ profile: MemoryProfile; t: Translate }> = ({ profile, t }) => (
+export const StructuredMemoryProfile: React.FC<{ profile: MemoryProfile; t: TFunction }> = ({ profile, t }) => (
<div className="flex flex-col gap-4">
{profile.summary ? (
<section>
@@ -134,7 +134,7 @@ export const StructuredMemoryProfile: React.FC<{ profile: MemoryProfile; t: Tran
</div>
);
-export const MemoryProfileItemBlock: React.FC<{ item: MemoryItem; t: Translate }> = ({ item, t }) => (
+export const MemoryProfileItemBlock: React.FC<{ item: MemoryItem; t: TFunction }> = ({ item, t }) => (
<div className="rounded-xl border border-border bg-surface px-4 py-3">
<div className="mb-3 flex items-center gap-2">
<Badge variant="secondary">{t(`memory.kind.${item.kind}`)}</Badge>
diff --git a/ui/src/components/settings/memory/MemorySettingsPanel.tsx b/ui/src/components/settings/memory/MemorySettingsPanel.tsx
index d5640da18..43828b562 100644
--- a/ui/src/components/settings/memory/MemorySettingsPanel.tsx
+++ b/ui/src/components/settings/memory/MemorySettingsPanel.tsx
@@ -606,10 +606,10 @@ export const MemorySettingsPanel: React.FC<{
<div className="rounded-xl border border-border bg-surface p-4">
<h3 className="mb-2 text-[13px] font-semibold text-foreground">{t('memory.settings.disclosureTitle')}</h3>
<ul className="flex flex-col gap-1.5">
- {(t(
+ {t(
customMode ? 'memory.settings.disclosure' : 'memory.settings.cloudDisclosure',
{ returnObjects: true },
- ) as string[]).map((line, idx) => (
+ ).map((line, idx) => (
<li key={idx} className="flex gap-2 text-[11.5px] leading-snug text-muted">
<span className="mt-1 size-1 shrink-0 rounded-full bg-muted" />
{line}
diff --git a/ui/src/components/settings/memory/memoryOrigin.ts b/ui/src/components/settings/memory/memoryOrigin.ts
index 492469623..5d1cd76bb 100644
--- a/ui/src/components/settings/memory/memoryOrigin.ts
+++ b/ui/src/components/settings/memory/memoryOrigin.ts
@@ -1,4 +1,5 @@
+import type { TranslationKey } from '@/i18n/types';
import type { MemoryItem } from '../../../context/ApiContext';
-export const memoryOriginLabelKey = (origin: MemoryItem['origin']): string | null =>
+export const memoryOriginLabelKey = (origin: MemoryItem['origin']): TranslationKey | null =>
origin ? `memory.origin.${origin}` : null;
diff --git a/ui/src/components/settings/memory/memoryStatusPresentation.ts b/ui/src/components/settings/memory/memoryStatusPresentation.ts
index 6905ac6dc..1bbec0770 100644
--- a/ui/src/components/settings/memory/memoryStatusPresentation.ts
+++ b/ui/src/components/settings/memory/memoryStatusPresentation.ts
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import type { TFunction } from 'i18next';
import type { MemoryProcessingSourceStatus, MemoryStatus } from '../../../context/ApiContext';
@@ -98,7 +99,7 @@ const PROCESSING_REASON_LABEL_KEYS = {
unknown: 'memory.processingRecord.reason.unknown',
} as const;
-const knownLabel = (t: TFunction, keys: Record<string, string>, value: string): string => {
+const knownLabel = (t: TFunction, keys: Record<string, TranslationKey>, value: string): string => {
const key = Object.prototype.hasOwnProperty.call(keys, value) ? keys[value] : undefined;
return key ? t(key) : value;
};
@@ -128,7 +129,7 @@ export const memoryStatusAnomalyLabel = (
t: TFunction,
group: AnomalyLabelGroup,
value: string,
-): string => knownLabel(t, ANOMALY_LABEL_KEYS[group] as Record<string, string>, value);
+): string => knownLabel(t, ANOMALY_LABEL_KEYS[group], value);
export const memoryStatusHealthLabel = (t: TFunction, value: string): string => (
knownLabel(t, HEALTH_STATUS_LABEL_KEYS, value)
@@ -161,7 +162,7 @@ export const memoryStatusRuntimeFactLabel = (
t: TFunction,
group: RuntimeFactGroup,
value: string,
-): string => knownLabel(t, RUNTIME_FACT_LABEL_KEYS[group] as Record<string, string>, value);
+): string => knownLabel(t, RUNTIME_FACT_LABEL_KEYS[group], value);
export const formatMemoryStatusRuntimeFact = (
t: TFunction,
diff --git a/ui/src/components/settings/memory/useMemoryResource.ts b/ui/src/components/settings/memory/useMemoryResource.ts
index f4f022c2f..9ef033f3a 100644
--- a/ui/src/components/settings/memory/useMemoryResource.ts
+++ b/ui/src/components/settings/memory/useMemoryResource.ts
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import { useCallback, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -34,7 +35,7 @@ export type UseMemoryResourceOptions<A extends unknown[]> = {
/** Compatibility success predicate; current Memory routes use the default `status: 'ok'` envelope. */
accept?: (value: unknown) => boolean;
/** i18n key used when the request itself throws, so there is no closed code. */
- failureMessageKey: string;
+ failureMessageKey: TranslationKey;
/** When false, `reload` is a no-op — Memory being off is not a failure. */
enabled?: boolean;
} & Partial<MemoryRetryPolicy>;
diff --git a/ui/src/components/settings/models/AddApiKeyDialog.tsx b/ui/src/components/settings/models/AddApiKeyDialog.tsx
index 385b769de..1b935c989 100644
--- a/ui/src/components/settings/models/AddApiKeyDialog.tsx
+++ b/ui/src/components/settings/models/AddApiKeyDialog.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import * as React from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import {
@@ -166,7 +167,7 @@ const sourceClientNonce = (): string => {
const failureMessageKey = (failure: ReturnType<typeof apiFailure>): string | null =>
failure?.detail ?? failure?.code ?? null;
-const REPLACE_FAILURE_KEY: Record<ModelHubFailureClass, string> = {
+const REPLACE_FAILURE_KEY: Record<ModelHubFailureClass, TranslationKey> = {
'authoritative-terminal': 'settings.models.repair.replaceFailed',
inconclusive: 'settings.models.repair.replaceFailed',
'retryable-provider': 'settings.models.repair.replaceFailed',
diff --git a/ui/src/components/settings/models/AgentCard.tsx b/ui/src/components/settings/models/AgentCard.tsx
index 842c3806f..a6ef48f18 100644
--- a/ui/src/components/settings/models/AgentCard.tsx
+++ b/ui/src/components/settings/models/AgentCard.tsx
@@ -145,6 +145,7 @@ const AgentSupplyIssues: React.FC<{ agent: AgentSupply }> = ({ agent }) => {
const reason = named.effective_model_id === null ? 'modelMissing'
: named.route_reason === 'route_unconfigured' ? 'routeMissing'
: named.supply_status;
+ if (reason === null || reason === 'ok') return null;
return (
<li key={named.name} className="min-w-0 text-[11px] leading-4" data-agent-supply-issue>
<p className="min-w-0 font-semibold text-foreground [overflow-wrap:anywhere]">{named.name}</p>
diff --git a/ui/src/components/settings/models/BackendModelCatalogDialog.tsx b/ui/src/components/settings/models/BackendModelCatalogDialog.tsx
index bb63af27b..51ee5d823 100644
--- a/ui/src/components/settings/models/BackendModelCatalogDialog.tsx
+++ b/ui/src/components/settings/models/BackendModelCatalogDialog.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
// One model-catalog dialog for every backend.
//
// It replaces OpenCodeMenuDialog, which existed because OpenCode was the only
@@ -207,7 +208,7 @@ export const BackendModelCatalogDialog: React.FC<{
const [draft, setDraft] = React.useState<BackendModel[]>([]);
const draftRef = React.useRef<BackendModel[]>([]);
const [query, setQuery] = React.useState('');
- const [saveFailedKey, setSaveFailedKey] = React.useState<string | null>(null);
+ const [saveFailedKey, setSaveFailedKey] = React.useState<TranslationKey | null>(null);
const [editing, setEditing] = React.useState<{ model: BackendModel | null; seedId?: string } | null>(null);
const [picking, setPicking] = React.useState<{ seed: ReadonlySet<string> } | null>(null);
const [removing, setRemoving] = React.useState<RemovalQuestion | null>(null);
diff --git a/ui/src/components/settings/models/BackendModelEditorDialog.tsx b/ui/src/components/settings/models/BackendModelEditorDialog.tsx
index 120c457b1..421ef0c88 100644
--- a/ui/src/components/settings/models/BackendModelEditorDialog.tsx
+++ b/ui/src/components/settings/models/BackendModelEditorDialog.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
// One editor for every backend catalog row, add and edit alike.
//
// It writes nothing. The row it commits goes back into the catalog dialog's
@@ -141,7 +142,7 @@ export const BackendModelEditorDialog: React.FC<{
const [fillState, setFillState] = React.useState<FillState>('idle');
/** Which sentence `fillState === 'error'` shows, resolved while the server's
* own answer is still in hand. */
- const [fillFailedKey, setFillFailedKey] = React.useState('settings.models.gateway.modelEditor.fillFailed');
+ const [fillFailedKey, setFillFailedKey] = React.useState<TranslationKey>('settings.models.gateway.modelEditor.fillFailed');
const [matches, setMatches] = React.useState<ModelsDevMatch[]>([]);
/** The query the typeahead is answering; empty closes it. Held apart from
* `draft.id` because choosing a suggestion writes the id, and a list keyed on
diff --git a/ui/src/components/settings/models/GuardGapList.tsx b/ui/src/components/settings/models/GuardGapList.tsx
index fce004d0b..c8b11e73d 100644
--- a/ui/src/components/settings/models/GuardGapList.tsx
+++ b/ui/src/components/settings/models/GuardGapList.tsx
@@ -1,9 +1,10 @@
+import type { TranslationKey } from '@/i18n/types';
import * as React from "react";
import { useTranslation } from "react-i18next";
import type { SupplyGap } from "./types";
-export const GuardGapList: React.FC<{ gaps: SupplyGap[]; labelKey?: string }> = ({
+export const GuardGapList: React.FC<{ gaps: SupplyGap[]; labelKey?: TranslationKey }> = ({
gaps,
labelKey = "settings.models.guard.gap.label",
}) => {
diff --git a/ui/src/components/settings/models/GuardImpact.test.tsx b/ui/src/components/settings/models/GuardImpact.test.tsx
index f29537295..2ef81bf42 100644
--- a/ui/src/components/settings/models/GuardImpact.test.tsx
+++ b/ui/src/components/settings/models/GuardImpact.test.tsx
@@ -76,14 +76,14 @@ describe('GuardImpact', () => {
it('distinguishes a stated absence of gaps from nobody having stated one', () => {
// Every claim this body can make about interruption, read off the keys
// rather than copied, so a reworded claim is caught by the same assertion.
- const claims = [
+ const claims = ([
'settings.models.guard.hint.safe',
'settings.models.guard.hint.interrupt',
'settings.models.guard.result.hint.safe',
'settings.models.guard.result.hint.interrupt',
'settings.models.guard.gap.label',
'settings.models.guard.result.gapLabel',
- ].map((key) => i18n.t(key));
+ ] as const).map((key) => i18n.t(key));
// `[]` is the guard saying so, and it is entitled to: it can see the supply.
const stated = renderImpact({ hops: [hop()], gaps: [] });
diff --git a/ui/src/components/settings/models/MigrationDialog.tsx b/ui/src/components/settings/models/MigrationDialog.tsx
index d16ef9aa5..ddcdfb482 100644
--- a/ui/src/components/settings/models/MigrationDialog.tsx
+++ b/ui/src/components/settings/models/MigrationDialog.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
// 迁移对话框 · 接入模型中枢 (frame 03). Non-destructive: a per-backend checklist of
// detected native configs. Actions follow migration-scan.schema (spec v1.1,
// Option 1): API keys / base URLs → import; subscription OAuth → keep_native.
@@ -38,7 +39,7 @@ function migrationVisual(item: MigrationItem): { Icon: React.ComponentType<{ siz
const ActionBadge: React.FC<{ action: MigrationAction }> = ({ action }) => {
const { t } = useTranslation();
- const map: Record<MigrationAction, { variant: 'success' | 'warning' | 'secondary'; key: string }> = {
+ const map: Record<MigrationAction, { variant: 'success' | 'warning' | 'secondary'; key: TranslationKey }> = {
import: { variant: 'success', key: 'settings.models.migration.action.import' },
controlled_import: { variant: 'warning', key: 'settings.models.migration.action.controlledImport' },
keep_native: { variant: 'secondary', key: 'settings.models.migration.action.keepNative' },
diff --git a/ui/src/components/settings/models/OAuthConnectDialog.tsx b/ui/src/components/settings/models/OAuthConnectDialog.tsx
index 2276f2457..e630a5cfe 100644
--- a/ui/src/components/settings/models/OAuthConnectDialog.tsx
+++ b/ui/src/components/settings/models/OAuthConnectDialog.tsx
@@ -813,12 +813,12 @@ export const OAuthConnectDialog: React.FC<{
const disabled = isNative && nativeSlotTaken;
const selected = channel === candidate;
const badgeKey = disabled
- ? 'added'
+ ? 'settings.models.addSub.opt.added'
: candidate === recommended
- ? 'recommended'
+ ? 'settings.models.addSub.badge.recommended'
: vendorCopy === 'claude'
- ? 'secondary'
- : 'supportedNotRecommended';
+ ? 'settings.models.addSub.badge.secondary'
+ : 'settings.models.addSub.badge.supportedNotRecommended';
const optionKey = isNative ? 'native' : 'hub';
return (
<button
@@ -866,7 +866,7 @@ export const OAuthConnectDialog: React.FC<{
{t(`settings.models.addSub.opt.${optionKey}.label`)}
</span>
<span className="model-hub-accent-pill--mint model-hub-add-sub-badge rounded-full border font-semibold">
- {t(`settings.models.addSub.${disabled ? 'opt' : 'badge'}.${badgeKey}`)}
+ {t(badgeKey)}
</span>
</span>
<span className="model-hub-add-sub-description block text-muted">
diff --git a/ui/src/components/settings/models/RouteChainDialog.tsx b/ui/src/components/settings/models/RouteChainDialog.tsx
index 46cd8cc1f..4c8fce986 100644
--- a/ui/src/components/settings/models/RouteChainDialog.tsx
+++ b/ui/src/components/settings/models/RouteChainDialog.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import {
@@ -161,7 +162,7 @@ export const RouteChainDialog: React.FC<{
const [unknownSourceCurrent, setUnknownSourceCurrent] = React.useState(false);
const [selectorEpoch, setSelectorEpoch] = React.useState(0);
const [announcement, setAnnouncement] = React.useState<{
- key: string;
+ key: TranslationKey;
params?: Record<string, unknown>;
} | null>(null);
const gripRefs = React.useRef<Array<HTMLButtonElement | null>>([]);
@@ -229,7 +230,7 @@ export const RouteChainDialog: React.FC<{
const dirty = manualDraft ? savedOverride === null || !sameRouteDraft(savedOverride.hops, draft) : savedOverride !== null;
const canDiscardDraft = (phase === "ready" || phase === "rejected") && (dirty || restoring);
const draftOrigin = manualDraft ? (draft.length ? 'manual' : null) : (preview ?? chain)?.route_origin ?? null;
- const announce = (key: string, params?: Record<string, unknown>) =>
+ const announce = (key: TranslationKey, params?: Record<string, unknown>) =>
setAnnouncement({ key, params });
const focusAfterRender = (ref: React.RefObject<HTMLElement | null>) => {
requestAnimationFrame(() => ref.current?.focus());
@@ -1099,7 +1100,7 @@ export const RouteChainDialog: React.FC<{
<span>{t('settings.models.routing.restorePending')}</span>
</div>}
{preview && <div className="model-hub-route-preview" data-origin={preview.route_origin ?? 'unconfigured'} role="status">
- <strong>{t(`settings.models.routing.preview.${preview.route_origin ?? 'unconfigured'}`)}</strong>
+ <strong>{t(`settings.models.routing.preview.${preview.route_origin ?? 'unconfigured'}`, { defaultValue: `settings.models.routing.preview.${preview.route_origin ?? 'unconfigured'}` })}</strong>
<span>{t('settings.models.routing.restorePending')}</span>
</div>}
{!unresolvedPreview && <><h3 className="model-hub-route-label font-bold">
diff --git a/ui/src/components/settings/models/SourceMutationReport.tsx b/ui/src/components/settings/models/SourceMutationReport.tsx
index 7fc250e17..346fc38e9 100644
--- a/ui/src/components/settings/models/SourceMutationReport.tsx
+++ b/ui/src/components/settings/models/SourceMutationReport.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import * as React from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { Loader2, X } from 'lucide-react';
@@ -17,13 +18,13 @@ export const SourceMutationReport: React.FC<{
const impact = report?.commit.impact ?? null;
const action = report?.commit.action ?? 'edit';
const copyKind = action === 'edit' ? 'edit' : 'remove';
- const titleKey = impact
+ const titleKey: TranslationKey = impact
? `settings.models.sourceDetail.${copyKind}.impact.title`
: `settings.models.sourceDetail.${copyKind}.settlement.title`;
- const detailKey = impact
+ const detailKey: TranslationKey = impact
? `settings.models.sourceDetail.${copyKind}.impact.detail`
: 'settings.models.sourceDetail.impact.refreshFail';
- const actionKey = report?.landingFailed
+ const actionKey: TranslationKey = report?.landingFailed
? 'settings.models.sourceDetail.retry'
: `settings.models.sourceDetail.${copyKind}.impact.done`;
diff --git a/ui/src/components/settings/models/SourceOrderDrawer.test.tsx b/ui/src/components/settings/models/SourceOrderDrawer.test.tsx
index 26a469a19..6fa90df0f 100644
--- a/ui/src/components/settings/models/SourceOrderDrawer.test.tsx
+++ b/ui/src/components/settings/models/SourceOrderDrawer.test.tsx
@@ -103,7 +103,7 @@ describe('SourceOrderDrawer keyboard ordering', () => {
expect(rows[index].classList.contains(index < 2 ? 'model-hub-order-row--ordered' : 'model-hub-order-row--held')).toBe(true);
expect(rows[index].querySelector('.model-hub-order-row-actions')).not.toBeNull();
});
- for (const kind of ['ordered', 'heldOut']) {
+ for (const kind of ['ordered', 'heldOut'] as const) {
const note = screen.getByText(locale.t(`settings.models.order.section.${kind}.note`));
expect(note.classList.contains('model-hub-order-section-explanation')).toBe(true);
expect(note.parentElement?.classList.contains('model-hub-order-section-head')).toBe(true);
diff --git a/ui/src/components/settings/models/SourcesCard.tsx b/ui/src/components/settings/models/SourcesCard.tsx
index 03b867b4c..5a123af8e 100644
--- a/ui/src/components/settings/models/SourcesCard.tsx
+++ b/ui/src/components/settings/models/SourcesCard.tsx
@@ -27,8 +27,8 @@ export const SourcesCard: React.FC<{
degraded: (staleData) => staleData,
});
const groups = [
- { id: 'native', sources: (sources ?? []).filter((source) => source.supply_channel === 'native_cli') },
- { id: 'hub', sources: (sources ?? []).filter((source) => source.supply_channel === 'hub') },
+ { id: 'native' as const, sources: (sources ?? []).filter((source) => source.supply_channel === 'native_cli') },
+ { id: 'hub' as const, sources: (sources ?? []).filter((source) => source.supply_channel === 'hub') },
].filter((group) => group.sources.length > 0);
// The settings route pane owns vertical scrolling. This card grows with its
// sources so users never have to coordinate a second scroll area here.
diff --git a/ui/src/components/settings/models/SupplyGraph.tsx b/ui/src/components/settings/models/SupplyGraph.tsx
index 4d7a44054..14c9853bd 100644
--- a/ui/src/components/settings/models/SupplyGraph.tsx
+++ b/ui/src/components/settings/models/SupplyGraph.tsx
@@ -1,3 +1,4 @@
+import type { TranslationSuffix } from '@/i18n/types';
import * as React from 'react';
import { useTranslation } from 'react-i18next';
@@ -130,7 +131,7 @@ export const SupplyGraph: React.FC<{
};
const LEGEND_ORDER: SupplyRelationKind[] = ['native', 'gateway', 'passthrough', 'connected_unused', 'takeover', 'unavailable'];
-const LEGEND_COPY: Record<SupplyRelationKind, string> = {
+const LEGEND_COPY: Record<SupplyRelationKind, TranslationSuffix<'settings.models.legend'>> = {
native: 'native',
gateway: 'viaGateway',
passthrough: 'passthrough',
diff --git a/ui/src/components/settings/models/UsageTab.tsx b/ui/src/components/settings/models/UsageTab.tsx
index 20cfc6331..c4a8e00b5 100644
--- a/ui/src/components/settings/models/UsageTab.tsx
+++ b/ui/src/components/settings/models/UsageTab.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
// 用量 — the metered-token report over a trailing local-day window
// (`usage-summary.schema.json`).
//
@@ -95,7 +96,7 @@ const TokenFigure: React.FC<{ counters: TokenCoverage; value: number }> = ({ cou
* identity at all once its label is gone — its ledger key is a digest — so the
* row says so in words instead of printing the key.
*/
-const RowIdentity: React.FC<{ identity: UsageIdentity; goneKey: string }> = ({ identity, goneKey }) => {
+const RowIdentity: React.FC<{ identity: UsageIdentity; goneKey: TranslationKey }> = ({ identity, goneKey }) => {
const { t } = useTranslation();
if (identity.kind === 'label') return <span className="truncate" title={identity.text}>{identity.text}</span>;
return (
@@ -116,7 +117,7 @@ const SOURCE_COLUMNS = ['source', 'tokens', 'requests', 'cached', 'lastMetered']
type SourceColumn = (typeof SOURCE_COLUMNS)[number];
-const columnLabel = (column: SourceColumn) => `settings.models.usage.bySource.col.${column}`;
+const columnLabel = (column: SourceColumn): TranslationKey => `settings.models.usage.bySource.col.${column}`;
/**
* One measured cell, told which column it answers.
diff --git a/ui/src/components/settings/models/addApiKeyState.ts b/ui/src/components/settings/models/addApiKeyState.ts
index 54947de20..0b6b77e26 100644
--- a/ui/src/components/settings/models/addApiKeyState.ts
+++ b/ui/src/components/settings/models/addApiKeyState.ts
@@ -1,6 +1,7 @@
+import type { TranslationKey } from '@/i18n/types';
import type { SourceProtocol } from './types';
-export const PROTOCOL_COPY_KEYS: Record<SourceProtocol, string> = {
+export const PROTOCOL_COPY_KEYS: Record<SourceProtocol, TranslationKey> = {
anthropic: 'settings.models.addKey.protocol.anthropicMessages',
openai_responses: 'settings.models.addKey.protocol.openaiResponses',
openai_chat: 'settings.models.addKey.protocol.openaiChatCompletions',
diff --git a/ui/src/components/settings/models/manage.ts b/ui/src/components/settings/models/manage.ts
index 4a7852869..43d494ddf 100644
--- a/ui/src/components/settings/models/manage.ts
+++ b/ui/src/components/settings/models/manage.ts
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import type { Source, SourcePatch } from './types';
import { SOURCE_DISPLAY_NAME_MAX_LENGTH } from './types';
import {
@@ -17,7 +18,7 @@ export const MANAGE_DESTINATION: Record<ManageKind, ManageDestination> = {
delete_source: 'delete_source_guard',
};
-export const MANAGE_LABEL_KEY: Record<ManageKind, string> = {
+export const MANAGE_LABEL_KEY: Record<ManageKind, TranslationKey> = {
edit_source: 'settings.models.sourceDetail.manage.edit',
delete_source: 'settings.models.sourceDetail.manage.remove',
};
@@ -267,7 +268,7 @@ export type SourceEditInvalidReason =
| 'displayNameCredential'
| 'baseUrlCredential';
-export const SOURCE_EDIT_REASON_KEY: Record<SourceEditInvalidReason, string> = {
+export const SOURCE_EDIT_REASON_KEY: Record<SourceEditInvalidReason, TranslationKey> = {
displayNameRequired: 'settings.models.sourceDetail.edit.validation.displayNameRequired',
displayNameTooLong: 'settings.models.sourceDetail.edit.validation.displayNameTooLong',
displayNameCredential: 'settings.models.sourceDetail.edit.validation.displayNameCredential',
diff --git a/ui/src/components/settings/models/repair.ts b/ui/src/components/settings/models/repair.ts
index 01e242d96..bc0696ff4 100644
--- a/ui/src/components/settings/models/repair.ts
+++ b/ui/src/components/settings/models/repair.ts
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
// The supply JOURNEYS' decisions — which remedy a stopped source actually has,
// what the server's answer to a repair means, and whether 试跑 has anything real
// to run. Same shape and same reason as `supply.ts` / `sufficiency.ts`: each of
@@ -126,7 +127,7 @@ export function repairAction(source: Source): RepairKind | null {
* a Record the compiler refuses a new RepairKind that has no label, and
* `repair.test.ts` proves each one is translated in both locales.
*/
-export const REPAIR_LABEL_KEY: Record<RepairKind, string> = {
+export const REPAIR_LABEL_KEY: Record<RepairKind, TranslationKey> = {
reauth: 'settings.models.repair.reauth',
replace_key: 'settings.models.repair.replaceKey',
retest: 'settings.models.repair.retest',
@@ -179,13 +180,13 @@ export type ReauthCost = 'immediate' | 'on_failure';
export const reauthCost = (source: Source): ReauthCost =>
source.supply_channel === 'native_cli' ? 'immediate' : 'on_failure';
-const REAUTH_BODY_KEY: Record<ReauthCost, string> = {
+const REAUTH_BODY_KEY: Record<ReauthCost, TranslationKey> = {
immediate: 'settings.models.repair.reauthBody.immediate',
on_failure: 'settings.models.repair.reauthBody.onFailure',
};
/** The confirm body that is TRUE for this source. */
-export const reauthBodyKey = (source: Source): string => REAUTH_BODY_KEY[reauthCost(source)];
+export const reauthBodyKey = (source: Source): TranslationKey => REAUTH_BODY_KEY[reauthCost(source)];
// ── What the server's repair answer MEANS ────────────────────────────────
@@ -255,7 +256,7 @@ export const repairSettles = (outcome: RepairOutcome): boolean =>
*/
export type RepairLine = Exclude<RepairOutcome['kind'], 'gaps'>;
-export const REPAIR_LINE_KEY: Record<RepairLine, string> = {
+export const REPAIR_LINE_KEY: Record<RepairLine, TranslationKey> = {
repaired: 'settings.models.repair.repaired',
refreshed: 'settings.models.repair.refreshed',
unresolved: 'settings.models.repair.unresolved',
@@ -275,7 +276,7 @@ export const REPAIR_LINE_KEY: Record<RepairLine, string> = {
* that happens to render it, and a Record over the full union makes the next
* verdict added answer for its own tone instead of inheriting green.
*/
-export const REPAIR_TOAST: Record<RepairOutcome['kind'], { key: string; tone: 'success' | 'warning' }> = {
+export const REPAIR_TOAST: Record<RepairOutcome['kind'], { key: TranslationKey; tone: 'success' | 'warning' }> = {
repaired: { key: REPAIR_LINE_KEY.repaired, tone: 'success' },
refreshed: { key: REPAIR_LINE_KEY.refreshed, tone: 'success' },
// The call succeeded and the source is still stopped: this page's gold 需处理
diff --git a/ui/src/components/settings/models/serverCopy.test.ts b/ui/src/components/settings/models/serverCopy.test.ts
index 001de3f8a..9c3c4671f 100644
--- a/ui/src/components/settings/models/serverCopy.test.ts
+++ b/ui/src/components/settings/models/serverCopy.test.ts
@@ -53,6 +53,13 @@ describe('serverText', () => {
expect(text).not.toContain('models.oauth.some.future');
});
+ it.each(['en', 'zh'] as const)('rejects existing objects and arrays as server text in %s', (lng) => {
+ for (const key of ['common', 'memory.settings.disclosure']) {
+ expect(serverText(t(lng), key)).toBeNull();
+ expect(serverText(t(lng), key, 'settings.models.oauth.error.generic')).toBe(t(lng)('settings.models.oauth.error.generic'));
+ }
+ });
+
it('renders nothing for optional copy whose key is unknown', () => {
// A migration row's secondary line has no generic substitute — dropping the
// line is honest, printing the key is not.
diff --git a/ui/src/components/settings/models/serverCopy.ts b/ui/src/components/settings/models/serverCopy.ts
index 917c90450..5bddef3c3 100644
--- a/ui/src/components/settings/models/serverCopy.ts
+++ b/ui/src/components/settings/models/serverCopy.ts
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
// Rendering an i18n key the SERVER chose, safely.
//
// Two kinds of key reach this page from the backend. Closed vocabularies —
@@ -26,18 +27,20 @@ import type { TFunction } from 'i18next';
export const serverText = (
t: TFunction,
key: string | null | undefined,
- fallbackKey?: string,
+ fallbackKey?: TranslationKey,
): string | null => {
+ // Resolve the value for inspection; returnObjects here is not a list consumer.
+ const textResolutionOptions = { defaultValue: '', returnObjects: true } as const;
if (key) {
// `defaultValue: ''` rather than the fallback text itself: i18next returns
// the default for a missing key, and an empty one lets us tell "missing" from
// "translated to something" without string-comparing against the key.
- const translated = t(key, { defaultValue: '' }) as string;
- if (translated) return translated;
+ const translated = t(key, textResolutionOptions);
+ if (typeof translated === 'string' && translated) return translated;
}
if (!fallbackKey) return null;
- const generic = t(fallbackKey, { defaultValue: '' }) as string;
- return generic || null;
+ const generic = t(fallbackKey, textResolutionOptions);
+ return typeof generic === 'string' && generic ? generic : null;
};
/**
@@ -80,7 +83,7 @@ const MATERIALIZE_CODES = ['discovery_failed', 'migration_item_conflict'];
* that user their source could not be CREATED names the wrong object and hides the
* thing that just happened to the one they have.
*/
-export const oauthFailureKey = (code: string | undefined, journey: OAuthJourney): string =>
+export const oauthFailureKey = (code: string | undefined, journey: OAuthJourney): TranslationKey =>
code && MATERIALIZE_CODES.includes(code)
? journey === 'reauth'
? 'settings.models.oauth.error.finalizeReauth'
@@ -91,7 +94,7 @@ export const oauthFailureKey = (code: string | undefined, journey: OAuthJourney)
export const NATIVE_SUBSCRIPTION_EXISTS_FAILURE = 'modelHub.errors.native_subscription_exists';
export const NATIVE_LOGIN_IN_PROGRESS_FAILURE = 'modelHub.errors.native_login_in_progress';
-export const oauthStartFailureKey = (code: string | undefined): string =>
+export const oauthStartFailureKey = (code: string | undefined): TranslationKey =>
code === NATIVE_SUBSCRIPTION_EXISTS_FAILURE
? 'settings.models.addSub.error.alreadyBound'
: code === NATIVE_LOGIN_IN_PROGRESS_FAILURE
@@ -110,7 +113,7 @@ export const oauthStartFailureKey = (code: string | undefined): string =>
* because a `modelHub.errors.*` key lives in the backend bundle and would
* otherwise render to the user as a machine string.
*/
-const CATALOG_SAVE_FAILURE_COPY: Readonly<Record<string, string>> = {
+const CATALOG_SAVE_FAILURE_COPY: Readonly<Record<string, TranslationKey>> = {
// authority-consumer: catalog.guard.error backend_model_in_route
// authority-consumer: candidate.error candidate_suppliers_changed
'modelHub.errors.backend_model_in_route': 'settings.models.gateway.catalog.saveRouted',
@@ -123,7 +126,7 @@ const CATALOG_SAVE_FAILURE_COPY: Readonly<Record<string, string>> = {
'modelHub.errors.backend_model_catalog_invalid': 'settings.models.gateway.catalog.saveInvalid',
};
-export const catalogSaveFailureKey = (detail: string | undefined): string =>
+export const catalogSaveFailureKey = (detail: string | undefined): TranslationKey =>
CATALOG_SAVE_FAILURE_COPY[detail ?? ''] ?? 'settings.models.gateway.catalog.saveFailed';
/**
@@ -175,7 +178,7 @@ export const tierEditRefusedAsManaged = (
* way forward is to stop retrying and type the fields in — every one of them is
* editable whether or not a fill ever succeeds.
*/
-export const modelsDevFillFailureKey = (detail: string | undefined): string =>
+export const modelsDevFillFailureKey = (detail: string | undefined): TranslationKey =>
detail === 'modelHub.errors.models_dev_unavailable'
? 'settings.models.gateway.modelEditor.fillUnavailable'
: 'settings.models.gateway.modelEditor.fillFailed';
diff --git a/ui/src/components/settings/models/sourcePresentation.ts b/ui/src/components/settings/models/sourcePresentation.ts
index 34fd5c912..c03ec76df 100644
--- a/ui/src/components/settings/models/sourcePresentation.ts
+++ b/ui/src/components/settings/models/sourcePresentation.ts
@@ -1,7 +1,8 @@
+import type { TranslationKey } from '@/i18n/types';
import type { Source } from './types';
import { officialVendorForEndpoint } from './vendorMeta';
-export const SOURCE_PROVIDER_COPY_KEYS: Partial<Record<string, string>> = {
+export const SOURCE_PROVIDER_COPY_KEYS: Partial<Record<string, TranslationKey>> = {
anthropic: 'settings.models.upstream.vendor.anthropic',
openai: 'settings.models.upstream.vendor.openai',
};
diff --git a/ui/src/components/settings/models/sourceStatePresentation.ts b/ui/src/components/settings/models/sourceStatePresentation.ts
index abe275da2..9dd51dec3 100644
--- a/ui/src/components/settings/models/sourceStatePresentation.ts
+++ b/ui/src/components/settings/models/sourceStatePresentation.ts
@@ -1,9 +1,10 @@
+import type { TranslationKey } from '@/i18n/types';
import type { AgentBackend, AdoptedBy, NeedsActionDetailKey, SourceState, SourceStatus } from './types';
export type SourceStateSurface = 'card' | 'detail';
export type SourceStatePresentation = {
- key: string | null;
+ key: TranslationKey | null;
values?: Record<string, string>;
/**
* Copy that explains the label in place, for a reading whose plain meaning is
@@ -12,7 +13,7 @@ export type SourceStatePresentation = {
* and the label is what it is called, and neither is a string a consumer may
* invent at the keyboard.
*/
- hint?: { labelKey: string; bodyKey: string };
+ hint?: { labelKey: TranslationKey; bodyKey: TranslationKey };
textClass: string;
dotClass: string;
};
@@ -47,7 +48,7 @@ const STANDBY: SourceStatePresentation = {
dotClass: 'bg-muted',
};
-const NEEDS_ACTION_KEY: Readonly<Record<NeedsActionDetailKey, string>> = {
+const NEEDS_ACTION_KEY: Readonly<Record<NeedsActionDetailKey, TranslationKey>> = {
'models.source.needs_action.oauth_expired': 'settings.models.sourceDetail.status.needsAction.oauthExpired',
'models.source.needs_action.balance_exhausted': 'settings.models.sourceDetail.status.needsAction.balanceExhausted',
'models.source.needs_action.credential_revoked': 'settings.models.sourceDetail.status.needsAction.credentialRevoked',
diff --git a/ui/src/components/settings/models/tsconfig.tests.json b/ui/src/components/settings/models/tsconfig.tests.json
index 721948207..d474ba89e 100644
--- a/ui/src/components/settings/models/tsconfig.tests.json
+++ b/ui/src/components/settings/models/tsconfig.tests.json
@@ -5,6 +5,6 @@
"noEmit": true,
"tsBuildInfoFile": "../../../../node_modules/.tmp/model-hub-tests.tsbuildinfo"
},
- "include": ["./**/*.ts", "./**/*.tsx"],
+ "include": ["./**/*.ts", "./**/*.tsx", "../../../i18n/i18next.d.ts"],
"exclude": []
}
diff --git a/ui/src/components/shared/ProxyUrlField.tsx b/ui/src/components/shared/ProxyUrlField.tsx
index ea808813c..9e1f93770 100644
--- a/ui/src/components/shared/ProxyUrlField.tsx
+++ b/ui/src/components/shared/ProxyUrlField.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import { useState } from 'react';
import { ChevronDown, SplitSquareVertical } from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -11,14 +12,14 @@ interface ProxyUrlFieldProps {
* i18n key for the label. Defaults to `common.proxyUrl`. Telegram passes
* `telegramConfig.proxyUrl` so its label can stay platform-flavored.
*/
- labelKey?: string;
+ labelKey?: TranslationKey;
/**
* i18n key for the long hint shown below the input when expanded. Defaults
* to `common.proxyUrlHint`. Telegram passes `telegramConfig.proxyUrlHint`
* and Lark passes `larkConfig.proxyUrlLarkLimitation` so the SDK warning
* stays where users see it.
*/
- hintKey?: string;
+ hintKey?: TranslationKey;
}
export function ProxyUrlField({
diff --git a/ui/src/components/shared/RoutingConfigPanel.tsx b/ui/src/components/shared/RoutingConfigPanel.tsx
index 270cb314e..393fab041 100644
--- a/ui/src/components/shared/RoutingConfigPanel.tsx
+++ b/ui/src/components/shared/RoutingConfigPanel.tsx
@@ -256,7 +256,7 @@ export const RoutingConfigPanel: React.FC<RoutingConfigPanelProps> = ({
<div className="flex flex-wrap gap-2 text-sm">
{availableMessageTypes.map((msgType) => {
const checked = (value.show_message_types || []).includes(msgType);
- const label = t(`channelList.messageType.${msgType}`);
+ const label = t(`channelList.messageType.${msgType}`, { defaultValue: `channelList.messageType.${msgType}` });
return (
<button
key={msgType}
diff --git a/ui/src/components/steps/ChannelList.tsx b/ui/src/components/steps/ChannelList.tsx
index d0690977d..f2e4e11db 100644
--- a/ui/src/components/steps/ChannelList.tsx
+++ b/ui/src/components/steps/ChannelList.tsx
@@ -1,3 +1,4 @@
+import { platformText } from '@/lib/platforms';
import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import {
@@ -1226,7 +1227,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
)}
>
<PlatformIcon platform={p} size={16} />
- <span>{t(`platform.${p}.title`)}</span>
+ <span>{platformText(t, p, 'title')}</span>
<span
className={clsx(
'rounded-full px-1.5 py-0.5 font-mono text-[10px]',
@@ -1382,7 +1383,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
{pageTab === 'all'
? t('channelList.headerSummary', { active: summary.active, discovered: summary.total })
: t('channelList.headerSummaryPlatform', {
- platform: t(`platform.${pageTab}.title`),
+ platform: platformText(t, pageTab, 'title'),
active: summary.active,
discovered: summary.total,
})}
@@ -1709,7 +1710,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
</span>
<span>{t('dashboard.metricGroupsHint', { count: channels.length })}</span>
<span className="hidden h-1 w-1 rounded-full bg-border md:inline-block" />
- <span className="font-mono text-xs uppercase tracking-[0.18em]">{t(`platform.${platform}.title`)}</span>
+ <span className="font-mono text-xs uppercase tracking-[0.18em]">{platformText(t, platform, 'title')}</span>
</div>
)}
</div>
@@ -1728,7 +1729,7 @@ export const ChannelList: React.FC<ChannelListProps> = ({ data = {}, onNext, onB
: 'border-border bg-foreground/[0.04] text-foreground hover:border-border-strong'
)}
>
- {t(`platform.${candidate}.title`)}
+ {platformText(t, candidate, 'title')}
</button>
))}
</div>
diff --git a/ui/src/components/steps/DoctorPanel.tsx b/ui/src/components/steps/DoctorPanel.tsx
index 2deceb191..81b35150a 100644
--- a/ui/src/components/steps/DoctorPanel.tsx
+++ b/ui/src/components/steps/DoctorPanel.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import React, { useEffect, useState } from 'react';
import {
Activity,
@@ -20,7 +21,7 @@ import { Button } from '../ui/button';
interface DoctorPanelProps {
isPage?: boolean;
logsPath?: string;
- titleKey?: string;
+ titleKey?: TranslationKey;
}
type CheckStatus = 'pass' | 'warn' | 'fail';
diff --git a/ui/src/components/steps/LarkConfig.tsx b/ui/src/components/steps/LarkConfig.tsx
index 8a392c326..dd2729e79 100644
--- a/ui/src/components/steps/LarkConfig.tsx
+++ b/ui/src/components/steps/LarkConfig.tsx
@@ -429,7 +429,7 @@ export const LarkConfig: React.FC<LarkConfigProps> = ({ data, onNext, onBack, em
{t('larkConfig.step3ManualList')}
</summary>
<ul className="mt-2 space-y-1.5 pl-1">
- {[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14].map((i) => (
+ {([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] as const).map((i) => (
<li key={i} className="flex items-start gap-2">
<code className="shrink-0 rounded bg-foreground/[0.06] px-1.5 py-0.5 font-mono text-[11px] text-foreground">
{i}
diff --git a/ui/src/components/steps/LogsPanel.tsx b/ui/src/components/steps/LogsPanel.tsx
index f89e76d79..8058618c3 100644
--- a/ui/src/components/steps/LogsPanel.tsx
+++ b/ui/src/components/steps/LogsPanel.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import {
ArrowDown,
@@ -32,7 +33,7 @@ const parseLogMessage = (message: string): { location?: string; content: string
};
interface LogsPanelProps {
- titleKey?: string;
+ titleKey?: TranslationKey;
compactHeader?: boolean;
}
diff --git a/ui/src/components/steps/PlatformSelection.tsx b/ui/src/components/steps/PlatformSelection.tsx
index 4684873a1..e4f7e5931 100644
--- a/ui/src/components/steps/PlatformSelection.tsx
+++ b/ui/src/components/steps/PlatformSelection.tsx
@@ -1,3 +1,4 @@
+import { platformText } from '@/lib/platforms';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
@@ -161,7 +162,7 @@ export const PlatformSelection: React.FC<PlatformSelectionProps> = ({ data, onNe
};
const activeDescriptor = platformCatalog.find((item) => item.id === activeCredentialPlatform) || platformCatalog[0];
- const activePlatformLabel = t(activeDescriptor?.title_key || `platform.${activeCredentialPlatform}.title`);
+ const activePlatformLabel = platformText(t, activeCredentialPlatform, 'title', activeDescriptor?.title_key);
const activeCredential = credentialDraft[activeCredentialPlatform] || {};
const currentValidationState = validationState[activeCredentialPlatform] || 'idle';
@@ -340,7 +341,7 @@ export const PlatformSelection: React.FC<PlatformSelectionProps> = ({ data, onNe
const option = platform.id;
const active = selected.includes(option);
const focused = activeCredentialPlatform === option;
- const label = t(platform.title_key || `platform.${option}.title`);
+ const label = platformText(t, option, 'title', platform.title_key);
return (
<button
key={option}
@@ -411,7 +412,7 @@ export const PlatformSelection: React.FC<PlatformSelectionProps> = ({ data, onNe
: 'border-border bg-surface-3 text-muted hover:border-border-strong'
)}
>
- {t(descriptor?.title_key || `platform.${platform}.title`)}
+ {platformText(t, platform, 'title', descriptor?.title_key)}
</button>
);
})}
@@ -596,7 +597,7 @@ export const PlatformSelection: React.FC<PlatformSelectionProps> = ({ data, onNe
active ? 'font-bold text-foreground' : 'font-medium text-muted'
)}
>
- {t(platform.title_key || `platform.${option}.title`)}
+ {platformText(t, option, 'title', platform.title_key)}
</span>
{/* Selection indicator on the phone row only; on sm+ the
mint border carries the selected state (design.pen). */}
diff --git a/ui/src/components/steps/UserList.tsx b/ui/src/components/steps/UserList.tsx
index f3d30e972..c60acf8b4 100644
--- a/ui/src/components/steps/UserList.tsx
+++ b/ui/src/components/steps/UserList.tsx
@@ -1,3 +1,5 @@
+import { platformText } from '@/lib/platforms';
+import type { TFunction } from 'i18next';
import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';
import React, { useEffect, useMemo, useState } from 'react';
import {
@@ -385,7 +387,7 @@ const ActiveCodeBox: React.FC<{
code: BindCodeItem;
onCopy: () => void;
copied: boolean;
- t: (k: string, opts?: any) => string;
+ t: TFunction;
}> = ({ code, onCopy, copied, t }) => {
const expiryLabel = code.type === 'expiring' && code.expires_at
? t('bindCode.expiresIn', { time: formatExpiry(code.expires_at) })
@@ -763,7 +765,7 @@ export const UserList: React.FC = () => {
</span>
<span
className="absolute -bottom-1 -right-1 flex size-[20px] items-center justify-center rounded-full border border-border bg-background shadow-[0_0_0_2px_var(--color-background)]"
- title={t(`platform.${u.platform}.title`)}
+ title={platformText(t, u.platform, 'title')}
>
<PlatformIcon platform={u.platform} size={13} />
</span>
diff --git a/ui/src/components/ui/directory-browser.tsx b/ui/src/components/ui/directory-browser.tsx
index a88859caf..ed207c150 100644
--- a/ui/src/components/ui/directory-browser.tsx
+++ b/ui/src/components/ui/directory-browser.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import React, { useEffect, useState, useCallback, useRef } from 'react';
import {
Check,
@@ -39,7 +40,7 @@ interface DirectoryBrowserProps {
// and verifies each path exists). Well-known shortcuts get a localized label;
// OS roots like /tmp, /data or a Windows drive are shown by their path. Both
// label and icon are keyed off the backend's stable ``key``.
-const FAVORITE_I18N: Record<string, string> = {
+const FAVORITE_I18N: Record<string, TranslationKey> = {
home: 'directoryBrowser.favoritesHome',
desktop: 'directoryBrowser.favoritesDesktop',
documents: 'directoryBrowser.favoritesDocuments',
diff --git a/ui/src/components/ui/signing-address-list.tsx b/ui/src/components/ui/signing-address-list.tsx
index 23dfc2d61..f96418df8 100644
--- a/ui/src/components/ui/signing-address-list.tsx
+++ b/ui/src/components/ui/signing-address-list.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import { useState } from 'react';
import { Check, Copy } from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -7,7 +8,7 @@ import { cn, copyTextToClipboard } from '@/lib/utils';
// Display order: ETH first, then BTC modern → legacy. Each entry maps a backend
// signing_addresses key to a short label; missing entries are skipped.
-const ROWS: ReadonlyArray<{ key: keyof SigningAddresses; labelKey: string }> = [
+const ROWS: ReadonlyArray<{ key: keyof SigningAddresses; labelKey: TranslationKey }> = [
{ key: 'eth', labelKey: 'vaults.addresses.eth' },
{ key: 'btc_segwit', labelKey: 'vaults.addresses.btcSegwit' },
{ key: 'btc_taproot', labelKey: 'vaults.addresses.btcTaproot' },
diff --git a/ui/src/components/workbench/AgentActivityGroup.tsx b/ui/src/components/workbench/AgentActivityGroup.tsx
index b5a6ac3e0..2b82bdf3c 100644
--- a/ui/src/components/workbench/AgentActivityGroup.tsx
+++ b/ui/src/components/workbench/AgentActivityGroup.tsx
@@ -1,3 +1,5 @@
+import type { TFunction } from 'i18next';
+import type { TranslationKey } from '@/i18n/types';
import { lazy, memo, Suspense, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
@@ -78,13 +80,13 @@ const TOOL_ICON: Record<ToolIconKind, LucideIcon> = {
};
// File operation → badge glyph + i18n key (the mint-soft "+ 新增" style chip in A).
-const FILE_OP_META: Record<FileOp, { glyph: string; i18nKey: string; className: string }> = {
+const FILE_OP_META: Record<FileOp, { glyph: string; i18nKey: TranslationKey; className: string }> = {
create: { glyph: '+', i18nKey: 'chat.agentActivity.opCreate', className: 'border-mint/30 bg-mint/[0.08] text-mint-ink' },
modify: { glyph: '~', i18nKey: 'chat.agentActivity.opModify', className: 'border-cyan/30 bg-cyan/[0.08] text-cyan-ink' },
delete: { glyph: '−', i18nKey: 'chat.agentActivity.opDelete', className: 'border-gold/30 bg-gold/[0.08] text-gold-ink' },
};
-const stepLabel = (t: (k: string, o?: Record<string, unknown>) => string, count: number): string =>
+const stepLabel = (t: TFunction, count: number): string =>
t(count === 1 ? 'chat.agentActivity.step' : 'chat.agentActivity.steps', { count });
// ----- B: tool-row visibility pill (eye / eye-off + "Tools"). Global, config-backed
diff --git a/ui/src/components/workbench/AgentGraphCanvas.tsx b/ui/src/components/workbench/AgentGraphCanvas.tsx
index 4bfbdabdb..4abad8b09 100644
--- a/ui/src/components/workbench/AgentGraphCanvas.tsx
+++ b/ui/src/components/workbench/AgentGraphCanvas.tsx
@@ -1,3 +1,4 @@
+import type { TFunction } from 'i18next';
import { createContext, useContext, useEffect, useMemo, useRef, useState } from 'react';
import {
Background,
@@ -414,7 +415,7 @@ const Flow: React.FC<AgentGraphCanvasProps> = ({
};
const Legend: React.FC<{
- t: (k: string) => string;
+ t: TFunction;
showDisabled: boolean;
onToggleDisabled: (next: boolean) => void;
}> = ({ t, showDisabled, onToggleDisabled }) => (
diff --git a/ui/src/components/workbench/AgentGraphDetail.tsx b/ui/src/components/workbench/AgentGraphDetail.tsx
index 8414eb172..b1cec29ca 100644
--- a/ui/src/components/workbench/AgentGraphDetail.tsx
+++ b/ui/src/components/workbench/AgentGraphDetail.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
@@ -352,7 +353,7 @@ export const AgentGraphDetail: React.FC<AgentGraphDetailProps> = ({
// Per-state end action, matching the old running list. Idle disconnect is
// non-destructive (no confirm); active Stop and orphan Kill require a 2nd click.
type EndState = 'active' | 'idle' | 'orphan';
-const END_META: Record<EndState, { labelKey: string; Icon: typeof Square; needsConfirm: boolean }> = {
+const END_META: Record<EndState, { labelKey: TranslationKey; Icon: typeof Square; needsConfirm: boolean }> = {
active: { labelKey: 'agents.running.endActive', Icon: Square, needsConfirm: true },
idle: { labelKey: 'agents.running.endIdle', Icon: Power, needsConfirm: false },
orphan: { labelKey: 'agents.running.endOrphan', Icon: Trash2, needsConfirm: true },
diff --git a/ui/src/components/workbench/AgentGraphOrphanStrip.tsx b/ui/src/components/workbench/AgentGraphOrphanStrip.tsx
index 10643ace7..a00cfd811 100644
--- a/ui/src/components/workbench/AgentGraphOrphanStrip.tsx
+++ b/ui/src/components/workbench/AgentGraphOrphanStrip.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { AlertTriangle, Loader2, Power, Square, Trash2 } from 'lucide-react';
@@ -21,7 +22,7 @@ import { formatElapsed } from '../../lib/agentGraph';
type LiveState = 'active' | 'idle' | 'orphan';
const STATE_META: Record<
LiveState,
- { dotClass: string; stateKey: string; endKey: string; Icon: typeof Square; needsConfirm: boolean }
+ { dotClass: string; stateKey: TranslationKey; endKey: TranslationKey; Icon: typeof Square; needsConfirm: boolean }
> = {
active: { dotClass: 'bg-mint', stateKey: 'agents.running.stateActive', endKey: 'agents.running.endActive', Icon: Square, needsConfirm: true },
idle: { dotClass: 'bg-muted', stateKey: 'agents.running.stateIdle', endKey: 'agents.running.endIdle', Icon: Power, needsConfirm: false },
diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsx
index dfdaa2ad3..a97b62de6 100644
--- a/ui/src/components/workbench/Composer.tsx
+++ b/ui/src/components/workbench/Composer.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import {
forwardRef,
useCallback,
@@ -231,7 +232,7 @@ const retryStoredVoiceSession = (session: VoiceRecordingSession): Promise<void>
return session.finalization;
};
-const voiceErrorTranslationKey = (error: unknown): string => {
+const voiceErrorTranslationKey = (error: unknown): TranslationKey => {
if (!(error instanceof VoiceTranscriptionError)) return 'chat.compose.voiceFailed';
if (error.code === 'too_large') return 'chat.compose.voiceTooLarge';
if (error.code === 'timeout') return 'chat.compose.voiceTimedOut';
diff --git a/ui/src/components/workbench/HarnessPage.tsx b/ui/src/components/workbench/HarnessPage.tsx
index d040501ce..684d67e03 100644
--- a/ui/src/components/workbench/HarnessPage.tsx
+++ b/ui/src/components/workbench/HarnessPage.tsx
@@ -1,3 +1,5 @@
+import type { TFunction } from 'i18next';
+import type { TranslationKey } from '@/i18n/types';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
@@ -99,7 +101,7 @@ import { errorMessage } from '@/lib/errorMessage';
// Detail-panel schedule, in words. The literal it was derived from is printed
// beside it by the caller — humanizing must never be the only copy of a value
// an operator may need to paste back into a CLI.
-function formatSchedule(task: HarnessTask, t: (k: string, opts?: any) => string): string {
+function formatSchedule(task: HarnessTask, t: TFunction): string {
if (task.cron) return humanizeCron(task.cron, t);
// A one-shot's ``run_at`` is stored as the user typed it, which is usually a
// wall-clock reading in ``task.timezone`` with no offset. The scheduler has
@@ -121,7 +123,7 @@ function formatSchedule(task: HarnessTask, t: (k: string, opts?: any) => string)
// marked as the default rather than left out.
function formatTimeout(
task: HarnessTask,
- t: (k: string, opts?: Record<string, unknown>) => string,
+ t: TFunction,
): string {
const { seconds, isDefault } = taskTimeout(task);
if (seconds <= 0) return t('harness.detail.timeoutNone');
@@ -562,9 +564,10 @@ export const HarnessPage: React.FC = () => {
const isRunsTab = tab === 'runs';
// One filter row, three tabs. Runs swap in outcome statuses and add a type
// selector; everything else (search, the shown/total hint) is shared.
- const statusOptions: readonly string[] = isRunsTab ? RUN_STATUS_FILTERS : DEFINITION_STATUS_FILTERS;
+ const statusOptions = isRunsTab
+ ? RUN_STATUS_FILTERS.map((value) => ({ value, labelKey: `harness.runStatus.${value}` as const }))
+ : DEFINITION_STATUS_FILTERS.map((value) => ({ value, labelKey: `harness.statusFilter.${value}` as const }));
const activeStatus: string = isRunsTab ? runStatusFilter : statusFilter;
- const statusLabelPrefix = isRunsTab ? 'harness.runStatus' : 'harness.statusFilter';
const queryDefinitionCounts = tab === 'tasks' ? queryTaskCounts : queryWatchCounts;
const totalForTab = isRunsTab ? queryRunCounts.all : queryDefinitionCounts.total;
// How many rows a chip stands for. A definition chip is a *set* of lifecycle
@@ -697,7 +700,7 @@ export const HarnessPage: React.FC = () => {
/>
</div>
<div className="flex rounded-md border border-border-strong bg-surface p-0.5">
- {statusOptions.map((opt) => (
+ {statusOptions.map(({ value: opt, labelKey }) => (
<button
key={opt}
type="button"
@@ -709,7 +712,7 @@ export const HarnessPage: React.FC = () => {
: 'text-muted hover:text-foreground',
)}
>
- {t(`${statusLabelPrefix}.${opt}`)}
+ {t(labelKey)}
<span
className={clsx(
'ml-1 tabular-nums',
@@ -1260,7 +1263,7 @@ const RowActions: React.FC<RowActionsProps> = ({ enabled, pending, onToggle, onD
* one whose Session row is gone (the same ``deleted`` state the Session field prints
* two rows up) -- it drops that term instead of contradicting itself.
*/
-function commandCwdFallbackKey(task: HarnessTask): string {
+function commandCwdFallbackKey(task: HarnessTask): TranslationKey {
const state = harnessSessionState(task, task.session_id);
return state === 'none' || state === 'deleted'
? 'harness.detail.cwdRuntimeDefault'
@@ -2017,13 +2020,13 @@ const LifecyclePill: React.FC<{ row: HarnessTask | HarnessWatch }> = ({ row }) =
);
};
-function sessionPolicyLabel(policy: string | null | undefined, t: (k: string) => string): string {
+function sessionPolicyLabel(policy: string | null | undefined, t: TFunction): string {
if (policy === 'create_per_run') return t('harness.sessionPolicy.createPerRun');
if (policy === 'create_once') return t('harness.sessionPolicy.createOnce');
return t('harness.sessionPolicy.existing');
}
-function deliveryLabel(postTo: string | null | undefined, t: (k: string) => string): string {
+function deliveryLabel(postTo: string | null | undefined, t: TFunction): string {
if (postTo === 'channel') return t('harness.delivery.channel');
if (postTo === 'thread') return t('harness.delivery.thread');
return t('harness.delivery.session');
@@ -2201,7 +2204,7 @@ const FailureDetails: React.FC<{
);
};
-const EmptyState: React.FC<{ i18nKey: string }> = ({ i18nKey }) => {
+const EmptyState: React.FC<{ i18nKey: TranslationKey }> = ({ i18nKey }) => {
const { t } = useTranslation();
return (
<div className="flex flex-col items-center gap-2 rounded-xl border border-dashed border-border bg-surface px-6 py-12 text-center">
diff --git a/ui/src/components/workbench/ShowPageAnnotateControl.tsx b/ui/src/components/workbench/ShowPageAnnotateControl.tsx
index 42ff9dc49..2438cd381 100644
--- a/ui/src/components/workbench/ShowPageAnnotateControl.tsx
+++ b/ui/src/components/workbench/ShowPageAnnotateControl.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
@@ -27,8 +28,8 @@ import type { AnnotationMode, AnnotationState } from './useShowPageAnnotation';
interface ModeDef {
id: AnnotationMode;
icon: LucideIcon;
- labelKey: string;
- descKey: string;
+ labelKey: TranslationKey;
+ descKey: TranslationKey;
}
const MODES: readonly ModeDef[] = [
diff --git a/ui/src/components/workbench/ShowPageSharingSettings.tsx b/ui/src/components/workbench/ShowPageSharingSettings.tsx
index b19ae04bc..166dde76b 100644
--- a/ui/src/components/workbench/ShowPageSharingSettings.tsx
+++ b/ui/src/components/workbench/ShowPageSharingSettings.tsx
@@ -849,7 +849,7 @@ export function ShowPageSharingSettings({
) : null}
</section>
- {['conflict', 'invalid', 'error'].includes(gate) ? (
+ {(gate === 'conflict' || gate === 'invalid' || gate === 'error') ? (
<div className="flex items-center justify-between gap-2 border-t border-border pt-2">
<span className="text-[11px] leading-snug text-destructive-ink">
{t(`chat.showPage.sharingErrors.${gate}`)}
diff --git a/ui/src/components/workbench/TerminalView.tsx b/ui/src/components/workbench/TerminalView.tsx
index b657facd5..b58b04172 100644
--- a/ui/src/components/workbench/TerminalView.tsx
+++ b/ui/src/components/workbench/TerminalView.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Terminal } from '@xterm/xterm';
@@ -67,7 +68,7 @@ const SEARCH_DECORATIONS = {
// Accessory key bar for phones (their soft keyboards lack these). Each button sends the raw
// byte sequence the PTY expects; Ctrl is a sticky modifier. Labels go through i18n (the
// control sequences stay here).
-const KEYS: { labelKey: string; seq?: string; ctrl?: boolean }[] = [
+const KEYS: { labelKey: TranslationKey; seq?: string; ctrl?: boolean }[] = [
{ labelKey: 'apps.terminal.keys.esc', seq: '\x1b' },
{ labelKey: 'apps.terminal.keys.tab', seq: '\t' },
{ labelKey: 'apps.terminal.keys.ctrl', ctrl: true },
diff --git a/ui/src/components/workbench/WorkbenchModulePlaceholder.tsx b/ui/src/components/workbench/WorkbenchModulePlaceholder.tsx
index 0d5a39109..46b122136 100644
--- a/ui/src/components/workbench/WorkbenchModulePlaceholder.tsx
+++ b/ui/src/components/workbench/WorkbenchModulePlaceholder.tsx
@@ -1,3 +1,4 @@
+import type { TranslationPrefix } from '@/i18n/types';
import type { ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
@@ -6,7 +7,7 @@ interface WorkbenchModulePlaceholderProps {
/** i18n key prefix (e.g. `workbench.modules.agents`). The component reads
* `${prefix}.title` and `${prefix}.description` plus the shared
* `workbench.modules.comingSoon` hint. */
- i18nPrefix: string;
+ i18nPrefix: Extract<TranslationPrefix<'title'> & TranslationPrefix<'description'>, `workbench.modules.${string}`>;
}
// Shared placeholder used by all four capability modules and the inbox
diff --git a/ui/src/components/workbench/WorkbenchSidebar.tsx b/ui/src/components/workbench/WorkbenchSidebar.tsx
index 5abb64c30..9186f3ee6 100644
--- a/ui/src/components/workbench/WorkbenchSidebar.tsx
+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { NavLink, useLocation, useNavigate } from 'react-router-dom';
@@ -49,7 +50,7 @@ import { SortableProjectList, type ProjectDragHandle } from './SortableProjectLi
interface CapabilityNavItem {
to: string;
- i18nKey: string;
+ i18nKey: TranslationKey;
icon: LucideIcon;
}
diff --git a/ui/src/components/workbench/harnessLifecycle.ts b/ui/src/components/workbench/harnessLifecycle.ts
index 80807f6f1..b9d8d7ccd 100644
--- a/ui/src/components/workbench/harnessLifecycle.ts
+++ b/ui/src/components/workbench/harnessLifecycle.ts
@@ -1,3 +1,4 @@
+import type { TFunction } from 'i18next';
import { formatElapsed } from '../../lib/agentGraph';
// Pure mappers behind the Harness task/watch rows (plan §4.1–§4.3). Like
@@ -99,16 +100,16 @@ export function definitionSurvivesToggle(
export function lifecycleLabel(
state: string | null | undefined,
detail: string | null | undefined,
- t: (k: string) => string,
+ t: TFunction,
): string {
- if (state === 'finished') return t(`harness.lifecycle.${detail && DETAILS.has(detail) ? detail : 'finished'}`);
- if (state && STATES.has(state)) return t(`harness.lifecycle.${state}`);
+ if (state === 'finished') return t(`harness.lifecycle.${LIFECYCLE_DETAILS.find((value) => value === detail) ?? 'finished'}`);
+ const known = STATES.find((value) => value === state);
+ if (known) return t(`harness.lifecycle.${known}`);
return t('harness.lifecycle.unknown');
}
-const STATES = new Set<string>(['running', 'waiting', 'paused', 'finished']);
+const STATES = ['running', 'waiting', 'paused', 'finished'] as const;
export const LIFECYCLE_DETAILS = ['normal', 'timeout', 'error', 'missed', 'canceled'] as const;
-const DETAILS = new Set<string>(LIFECYCLE_DETAILS);
// ---------------------------------------------------------------------------
// Time, never printed raw (§4.2)
@@ -131,7 +132,7 @@ function calendarDayDelta(target: Date, now: Date): number {
// full timestamp.
export function humanizeTime(
iso: string | null | undefined,
- t: (k: string, opts?: any) => string,
+ t: TFunction,
now: number = Date.now(),
): string {
if (!iso) return '—';
@@ -157,7 +158,7 @@ export function humanizeTime(
export function humanizeGap(
iso: string | null | undefined,
now: number,
- t: (key: string) => string,
+ t: TFunction,
): string | null {
if (!iso) return null;
const at = Date.parse(iso);
@@ -182,7 +183,7 @@ export function isWallClockTimestamp(iso: string | null | undefined): boolean {
export function formatWallTime(
iso: string | null | undefined,
timezone: string | null | undefined,
- t: (k: string, opts?: any) => string,
+ t: TFunction,
): string {
if (!iso) return '—';
const raw = iso.trim();
@@ -209,7 +210,7 @@ export function formatWallTime(
// Pinned to APScheduler's own ``WEEKDAYS`` constant by a test in
// ``tests/test_harness_definition_lifecycle.py`` — upgrade the library's
// numbering and that test fails rather than the rows quietly shifting a day.
-const WEEKDAY_NAMES = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'];
+const WEEKDAY_NAMES = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] as const;
const WEEKDAY_INDEX: Record<string, number> = WEEKDAY_NAMES.reduce(
(map, name, index) => ({ ...map, [name]: index }),
{},
@@ -267,7 +268,7 @@ function clockTime(hour: string, minute: string): string | null {
// unchanged — a wrong plain-English schedule is worse than a raw one, and the
// detail panel prints the expression either way. Deliberately not a dependency:
// the whole grammar we need is four cases.
-export function humanizeCron(expr: string | null | undefined, t: (k: string, opts?: any) => string): string {
+export function humanizeCron(expr: string | null | undefined, t: TFunction): string {
const raw = (expr ?? '').trim();
if (!raw) return '';
const fields = raw.split(/\s+/);
@@ -667,7 +668,7 @@ export function waiterExpectedAlive(row: HarnessDefinitionFacts): boolean {
export function definitionChipLabel(
row: HarnessDefinitionFacts,
kind: HarnessDefinitionKind,
- t: (k: string, opts?: any) => string,
+ t: TFunction,
): string {
if (kind === 'watch') {
return t(row.mode === 'forever' ? 'harness.row.modeForever' : 'harness.row.modeOnce');
@@ -693,7 +694,7 @@ export type HarnessDefinitionLine = {
function livenessLabel(
row: HarnessDefinitionFacts,
- t: (k: string) => string,
+ t: TFunction,
): string | null {
if (row.process_alive === true) return t('harness.row.processAlive');
// Report an exit only where an exit is unexpected. A retired waiter did stop,
@@ -713,7 +714,7 @@ function livenessLabel(
export function definitionRowLine(
row: HarnessDefinitionFacts,
kind: HarnessDefinitionKind,
- t: (k: string, opts?: any) => string,
+ t: TFunction,
now: number = Date.now(),
): HarnessDefinitionLine {
const state = row.lifecycle_state;
diff --git a/ui/src/components/workbench/harnessRuns.ts b/ui/src/components/workbench/harnessRuns.ts
index dcc98f121..7e4fcabb1 100644
--- a/ui/src/components/workbench/harnessRuns.ts
+++ b/ui/src/components/workbench/harnessRuns.ts
@@ -1,3 +1,4 @@
+import type { TFunction } from 'i18next';
import type { HarnessRun, HarnessSessionSummary } from '../../context/ApiContext';
// Pure mappers behind the Harness run rows (plan §4.1/§4.2). They take ``t``
@@ -37,18 +38,20 @@ export function runTypeOptions(present: readonly string[] | undefined): string[]
// Human words for an internal run_type. Same map feeds the row chip and the
// type selector, so the two can never disagree.
-export function runTypeLabel(runType: string | null | undefined, t: (k: string) => string): string {
+export function runTypeLabel(runType: string | null | undefined, t: TFunction): string {
if (!runType) return t('harness.runType.unknown');
- return KNOWN_RUN_TYPES.has(runType) ? t(`harness.runType.${runType}`) : runType;
+ const known = RUN_TYPES.find((type) => type === runType);
+ return known ? t(`harness.runType.${known}`) : runType;
}
-const RUN_STATUSES = ['queued', 'running', 'succeeded', 'failed', 'canceled'];
+const RUN_STATUSES = ['queued', 'running', 'succeeded', 'failed', 'canceled'] as const;
// Human words for a run status. Same map feeds the detail pill and the status
// segments; an unrecognised status still prints rather than blanking out.
-export function runStatusLabel(status: string | null | undefined, t: (k: string) => string): string {
+export function runStatusLabel(status: string | null | undefined, t: TFunction): string {
if (!status) return '—';
- return RUN_STATUSES.includes(status) ? t(`harness.runStatus.${status}`) : status;
+ const known = RUN_STATUSES.find((value) => value === status);
+ return known ? t(`harness.runStatus.${known}`) : status;
}
const WHITESPACE_RUN = /\s+/g;
diff --git a/ui/src/components/workbench/harnessTabs.ts b/ui/src/components/workbench/harnessTabs.ts
index 83b94d355..aa66dc2c5 100644
--- a/ui/src/components/workbench/harnessTabs.ts
+++ b/ui/src/components/workbench/harnessTabs.ts
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
// Which Harness tab is on screen, and what an empty one says. The tab set and
// the ``?tab=`` mapping live together so removing a tab later cannot strand its
// old links, and the copy keys are asserted without rendering the page
@@ -19,7 +20,7 @@ export function harnessTabFromParam(param: string | null | undefined): TabKey {
return (TAB_ORDER as string[]).includes(param ?? '') ? (param as TabKey) : DEFAULT_TAB;
}
-export function harnessEmptyStateKey(kind: TabKey, hasStoredRows: boolean): string {
+export function harnessEmptyStateKey(kind: TabKey, hasStoredRows: boolean): TranslationKey {
if (!hasStoredRows) {
return kind === 'tasks' ? 'harness.emptyTasks' : kind === 'watches' ? 'harness.emptyWatches' : 'harness.emptyRuns';
}
diff --git a/ui/src/i18n/i18next.d.ts b/ui/src/i18n/i18next.d.ts
new file mode 100644
index 000000000..8fcf8840f
--- /dev/null
+++ b/ui/src/i18n/i18next.d.ts
@@ -0,0 +1,13 @@
+import type en from './en.json';
+import type { TranslationPaths } from './resourceTypes';
+import 'i18next';
+
+declare module 'i18next' {
+ interface CustomTypeOptions {
+ resources: { translation: TranslationPaths<typeof en> };
+ // Paths are already expanded in the TYPE representation. The runtime retains
+ // its default '.' separator and the original JSON. Native keyPrefix is not
+ // supported by this adapter; consumers compose full, finite paths instead.
+ keySeparator: never;
+ }
+}
diff --git a/ui/src/i18n/keyCoverage.test.ts b/ui/src/i18n/keyCoverage.test.ts
index 2ca425dda..90c046f43 100644
--- a/ui/src/i18n/keyCoverage.test.ts
+++ b/ui/src/i18n/keyCoverage.test.ts
@@ -537,6 +537,7 @@ export const collectDottedLiterals = (source: string, fileName = 'fixture.tsx'):
);
const found = new Set<string>();
const visit = (node: ts.Node) => {
+ if (ts.isTypeNode(node)) return;
if (ts.isStringLiteralLike(node) && DOTTED.test(node.text)) found.add(node.text);
ts.forEachChild(node, visit);
};
@@ -914,27 +915,6 @@ const NON_KEY_LITERALS = [
// true of this guard. Deleting product code is out of scope for this PR.
'workbench.createDialog.kindTask',
'workbench.createDialog.kindWatch',
-
- // Combinations a template's types allow and the app cannot reach. A union is
- // an upper bound on what arrives at a call site, never the exact set, so
- // expanding one names keys alongside the real ones — and the two are told
- // apart the same way every other name here is: by the bundles. These have
- // copy in neither locale because nothing ever asks for them.
- //
- // `OAuthConnectDialog` picks the prefix and the leaf from the SAME condition
- // (`disabled ? 'opt' : 'badge'` beside `badgeKey = disabled ? 'added' : …`),
- // so only 4 of the 8 products exist; the other 4 are these. Correlation
- // between spans is real dataflow, and no expansion of independent parts can
- // see it.
- 'settings.models.addSub.badge.added',
- 'settings.models.addSub.opt.recommended',
- 'settings.models.addSub.opt.secondary',
- 'settings.models.addSub.opt.supportedNotRecommended',
- // `ShowPageSharingSettings` renders this behind
- // `['conflict', 'invalid', 'error'].includes(gate)`, which narrows nothing
- // for the compiler, so the other two members of `Gate` expand too.
- 'chat.showPage.sharingErrors.ready',
- 'chat.showPage.sharingErrors.share_id_taken',
];
/** Every dotted literal the app carries, wherever it sits, sorted. */
@@ -1656,17 +1636,31 @@ describe('app i18n key coverage', () => {
const sentence = 'Read the fixture.docs page for more';
const single = 'undotted';
const templated = \`fixture.\${dynamic}\`;
+ type Prefix = TranslationSuffix<'fixture.typeOnly'>;
+ interface Carrier { key: 'fixture.interfaceOnly' }
+ const alias = 'fixture.castValue' as 'fixture.castType';
+ const checked = 'fixture.satisfiesValue' satisfies 'fixture.satisfiesType';
+ const jsx = <Thing title={'fixture.jsxValue' as const} />;
+ enum State { Ready = 'fixture.enumValue' }
+ const typed = 'fixture.runtime' satisfies TranslationKey;
+ const asserted = 'fixture.asserted' as TranslationKey;
`;
expect(collectDottedLiterals(fixture)).toEqual([
'avibe.editor.fontSize.v1',
'editor.background',
+ 'fixture.asserted',
'fixture.attrHint',
'fixture.attrLabel',
'fixture.braced',
'fixture.called',
+ 'fixture.castValue',
+ 'fixture.enumValue',
'fixture.held',
'fixture.inArray',
'fixture.invented',
+ 'fixture.jsxValue',
+ 'fixture.runtime',
+ 'fixture.satisfiesValue',
'fixture.tableBody',
'fixture.tableLabel',
]);
diff --git a/ui/src/i18n/resourceTypes.ts b/ui/src/i18n/resourceTypes.ts
new file mode 100644
index 000000000..9df49f90e
--- /dev/null
+++ b/ui/src/i18n/resourceTypes.ts
@@ -0,0 +1,19 @@
+/** All actual resource paths, retaining containers for returnObjects consumers. */
+type ResourcePaths<T> = {
+ [K in keyof T & string]: T[K] extends readonly unknown[] ? K
+ : T[K] extends object ? K | `${K}.${ResourcePaths<T[K]>}` : K;
+}[keyof T & string];
+
+type NestedValue<T, P extends string> = P extends `${infer Head}.${infer Tail}`
+ ? Head extends keyof T ? ResourceValue<T[Head], Tail> : never
+ : never;
+
+/** i18next traverses objects first, then tries a literal dotted key. Never walk String methods. */
+type ResourceValue<T, P extends string> = T extends object
+ ? [NestedValue<T, P>] extends [never]
+ ? P extends keyof T ? T[P] : never
+ : NestedValue<T, P>
+ : never;
+
+/** Type-only adapter for nested resources mixed with literal dotted siblings. */
+export type TranslationPaths<T> = { [P in ResourcePaths<T>]: ResourceValue<T, P> };
diff --git a/ui/src/i18n/translationContract.test.ts b/ui/src/i18n/translationContract.test.ts
new file mode 100644
index 000000000..1e0f971ce
--- /dev/null
+++ b/ui/src/i18n/translationContract.test.ts
@@ -0,0 +1,132 @@
+import type { ComponentProps } from 'react';
+import type { TFunction } from 'i18next';
+import { createInstance } from 'i18next';
+import { describe, expect, it } from 'vitest';
+import type { ProxyUrlField } from '../components/shared/ProxyUrlField';
+import type { WorkbenchModulePlaceholder } from '../components/workbench/WorkbenchModulePlaceholder';
+import type { AppDefinition } from '../apps/registry';
+import type { SourceStatePresentation } from '../components/settings/models/sourceStatePresentation';
+import { FilesApiError, fileBrowserErrorMessage } from '../lib/filesApi';
+import { platformText } from '../lib/platforms';
+import type { TranslationKey } from './types';
+import type { TranslationPaths } from './resourceTypes';
+import en from './en.json';
+import zh from './zh.json';
+
+// Compiled by typecheck:tests, not executed. These are real consuming prop/data
+// types: broadening a carrier or t makes an expect-error unused and fails CI.
+function compilerContract(t: TFunction, key: TranslationKey, custom: boolean) {
+ const proxy: ComponentProps<typeof ProxyUrlField> = {
+ value: '', onChange: () => {}, labelKey: 'common.proxyUrl', hintKey: 'common.proxyUrlHint',
+ };
+ // @ts-expect-error typo in an actual component carrier
+ proxy.labelKey = 'common.proxyUrll';
+ // @ts-expect-error object prefixes cannot be rendered labels
+ proxy.labelKey = 'common';
+ // @ts-expect-error a list cannot be rendered as a text label
+ proxy.hintKey = 'memory.settings.disclosure';
+ const app: Pick<AppDefinition, 'titleKey'> = { titleKey: 'apps.fileBrowser.label' };
+ // @ts-expect-error typo in the app registry data contract
+ app.titleKey = 'apps.fileBrowser.lable';
+ const state: Pick<SourceStatePresentation, 'key'> = { key: 'settings.models.upstream.state.standby' };
+ // @ts-expect-error a source label must be a text leaf
+ state.key = 'settings.models';
+ const module: ComponentProps<typeof WorkbenchModulePlaceholder> = { icon: null, i18nPrefix: 'workbench.modules.skills' };
+ // @ts-expect-error prefix lacks both required text children
+ module.i18nPrefix = 'common';
+ // @ts-expect-error a plural-only family requires count, so is not a plain label
+ proxy.labelKey = 'settings.models.gateway.agentIssues.summary';
+ proxy.labelKey = 'settings.models.gateway.agentIssues.summary_one';
+ const text: string = t(key);
+ const title: string = t(`${module.i18nPrefix}.title`);
+ const plural: string = t('settings.models.gateway.agentIssues.summary', { count: 2 });
+ const list = t(custom ? 'memory.settings.disclosure' : 'memory.settings.cloudDisclosure', { returnObjects: true });
+ const lengths: number[] = list.map((line) => line.length);
+ // @ts-expect-error string resource cannot satisfy the real list consumption
+ t('common.save', { returnObjects: true }).map((line: string) => line);
+ // @ts-expect-error object resource cannot satisfy the real list consumption
+ t('common', { returnObjects: true }).map((line: string) => line);
+ // @ts-expect-error unknown direct name needs an explicit fallback
+ t('common.svae');
+ const fallback: string = t('deliberately.absent', { defaultValue: 'Fallback' });
+ const parent: string = t('settings.models.addKey.field.vendor');
+ const child: string = t('settings.models.addKey.field.vendor.search');
+ const sub: string = t('settings.models.direct.card.current.sub');
+ // @ts-expect-error dotted copy is a string, never String.search
+ t('settings.models.addKey.field.vendor.search')('query');
+ // @ts-expect-error dotted copy must not acquire String.search's callable signature
+ const method: (query: string | RegExp) => number = t('settings.models.addKey.field.vendor.search');
+ // @ts-expect-error dotted copy must not acquire String.sub's callable signature
+ const subMethod: () => string = t('settings.models.direct.card.current.sub');
+ // @ts-expect-error no phantom string-method descendants
+ t('settings.models.addKey.field.vendor.toUpperCase');
+ // @ts-expect-error no phantom descendants under a literal dotted key
+ t('settings.models.addKey.field.vendor.search.typo');
+ return [proxy, app, state, text, title, plural, lengths, fallback, parent, child, sub, method, subMethod];
+}
+void compilerContract;
+
+const collision = { leaf: { title: 'Nested' }, 'leaf.title': ['Literal'] };
+function collisionContract(value: TranslationPaths<typeof collision>['leaf.title']) {
+ const text: string = value;
+ // @ts-expect-error nested path wins: the literal sibling cannot make this an array
+ value.map((line: string) => line);
+ return text;
+}
+void collisionContract;
+
+const translator = (lng: 'en' | 'zh') => {
+ const instance = createInstance();
+ void instance.init({ lng, fallbackLng: false, resources: { en: { translation: en }, zh: { translation: zh } } });
+ return instance;
+};
+
+const dottedEntries = (resource: object, prefix = ''): [string, unknown][] =>
+ Object.entries(resource).flatMap(([key, value]) => [
+ ...(key.includes('.') ? [[`${prefix}${key}`, value] as [string, unknown]] : []),
+ ...(value && typeof value === 'object' && !Array.isArray(value) ? dottedEntries(value, `${prefix}${key}.`) : []),
+ ]);
+
+describe('resource type representation and dynamic boundaries', () => {
+ it.each(['en', 'zh'] as const)('resolves every literal dotted sibling in %s', (lng) => {
+ const instance = translator(lng);
+ const entries = dottedEntries(lng === 'en' ? en : zh);
+ expect(entries.length).toBeGreaterThan(0);
+ for (const [key, value] of entries) {
+ expect(instance.t(key, { defaultValue: '', returnObjects: true }), key).toEqual(value);
+ }
+ expect(instance.t('settings.models.addKey.field.vendor')).toEqual((lng === 'en' ? en : zh).settings.models.addKey.field.vendor);
+ expect(instance.t('memory.settings.disclosure', { returnObjects: true })).toEqual((lng === 'en' ? en : zh).memory.settings.disclosure);
+ expect(instance.t('common', { returnObjects: true }).save).toEqual((lng === 'en' ? en : zh).common.save);
+ });
+
+ it('matches nested-before-literal collision precedence', () => {
+ const instance = createInstance();
+ void instance.init({ lng: 'en', resources: { en: { translation: { collision } } } });
+ expect(instance.t('collision.leaf.title', { defaultValue: '', returnObjects: true })).toBe('Nested');
+ });
+
+ it('keeps absent-key defaults explicit', () => {
+ expect(translator('en').t('deliberately.absent', { defaultValue: 'Fallback' })).toBe('Fallback');
+ });
+
+ it.each(['en', 'zh'] as const)('resolves file errors and preserves unknown/error-shape fallback in %s', (lng) => {
+ const instance = translator(lng);
+ expect(fileBrowserErrorMessage(new FilesApiError('not_found', 'raw'), instance.t, 'fallback')).toBe(instance.t('apps.fileBrowser.errors.not_found'));
+ expect(fileBrowserErrorMessage(new FilesApiError('future', 'raw'), instance.t, 'fallback')).toBe('raw');
+ expect(fileBrowserErrorMessage(new Error('ordinary'), instance.t, 'fallback')).toBe('ordinary');
+ expect(fileBrowserErrorMessage(null, instance.t, 'fallback')).toBe('fallback');
+ instance.addResourceBundle(lng, 'translation', { apps: { fileBrowser: { errors: { object: { title: 'Object' }, list: ['Array'] } } } }, true, true);
+ for (const code of ['object', 'list']) expect(fileBrowserErrorMessage(new FilesApiError(code, 'raw'), instance.t, 'fallback')).toBe('raw');
+ });
+
+ it('resolves open platform keys and retains the established key fallback', () => {
+ const instance = translator('en');
+ expect(platformText(instance.t, 'slack', 'title')).toBe(instance.t('platform.slack.title'));
+ expect(platformText(instance.t, 'future', 'title')).toBe('platform.future.title');
+ expect(platformText(instance.t, 'slack', 'title', '')).toBe(instance.t('platform.slack.title'));
+ expect(platformText(instance.t, 'slack', 'title', 'future.key')).toBe('future.key');
+ expect(platformText(instance.t, 'slack', 'title', 'common')).toBe('common');
+ expect(platformText(instance.t, 'slack', 'title', 'memory.settings.disclosure')).toBe('memory.settings.disclosure');
+ });
+});
diff --git a/ui/src/i18n/tsconfig.guard.json b/ui/src/i18n/tsconfig.guard.json
new file mode 100644
index 000000000..568e96f07
--- /dev/null
+++ b/ui/src/i18n/tsconfig.guard.json
@@ -0,0 +1,6 @@
+{
+ "extends": "../../tsconfig.app.json",
+ "compilerOptions": { "types": ["node"] },
+ "include": ["keyCoverage.test.ts"],
+ "exclude": []
+}
diff --git a/ui/src/i18n/types.ts b/ui/src/i18n/types.ts
new file mode 100644
index 000000000..ee36a0208
--- /dev/null
+++ b/ui/src/i18n/types.ts
@@ -0,0 +1,14 @@
+import type { ParseKeys, TFunctionReturn } from 'i18next';
+
+/** Text leaves that resolve without count. Native t also accepts plural families with count. */
+type TextKey<K extends ParseKeys> = K extends unknown
+ ? [TFunctionReturn<'translation', K, { returnObjects: false }>] extends [never] ? never
+ : TFunctionReturn<'translation', K, { returnObjects: false }> extends string ? K : never
+ : never;
+export type TranslationKey = TextKey<ParseKeys>;
+
+/** Finite suffixes/prefixes for consumers that intentionally compose a path. */
+export type TranslationSuffix<Prefix extends string> =
+ Extract<TranslationKey, `${Prefix}.${string}`> extends `${Prefix}.${infer Suffix}` ? Suffix : never;
+export type TranslationPrefix<Suffix extends string> =
+ Extract<TranslationKey, `${string}.${Suffix}`> extends `${infer Prefix}.${Suffix}` ? Prefix : never;
diff --git a/ui/src/lib/actionShortcuts.ts b/ui/src/lib/actionShortcuts.ts
index 6a12b154b..aab176528 100644
--- a/ui/src/lib/actionShortcuts.ts
+++ b/ui/src/lib/actionShortcuts.ts
@@ -1,3 +1,4 @@
+import type { TranslationSuffix } from '@/i18n/types';
import { useMemo, useSyncExternalStore } from 'react';
import { useTranslation } from 'react-i18next';
import type { TFunction } from 'i18next';
@@ -212,7 +213,7 @@ const SYMBOL_KEY_LABELS: Readonly<Record<string, string>> = {
Slash: '/',
};
-const TRANSLATED_KEY_LABELS: Readonly<Record<string, string>> = {
+const TRANSLATED_KEY_LABELS: Readonly<Record<string, TranslationSuffix<'settings.shortcuts.keyLabels'>>> = {
Backspace: 'backspace',
CapsLock: 'capsLock',
ContextMenu: 'contextMenu',
diff --git a/ui/src/lib/agentBackends.ts b/ui/src/lib/agentBackends.ts
index bdf5770de..0cf0a130f 100644
--- a/ui/src/lib/agentBackends.ts
+++ b/ui/src/lib/agentBackends.ts
@@ -17,7 +17,7 @@ export type BackendUiMeta = {
iconCls: string;
};
-export const AGENT_BACKENDS: BackendUiMeta[] = [
+export const AGENT_BACKENDS = [
{
id: 'opencode',
label: 'OpenCode',
@@ -57,7 +57,7 @@ export const AGENT_BACKENDS: BackendUiMeta[] = [
tileCls: 'bg-gold',
iconCls: 'text-gold-foreground',
},
-];
+] as const satisfies readonly BackendUiMeta[];
export const DEFAULT_BACKEND_ID = 'opencode';
diff --git a/ui/src/lib/agentGraph.ts b/ui/src/lib/agentGraph.ts
index d705b4d65..60272d74a 100644
--- a/ui/src/lib/agentGraph.ts
+++ b/ui/src/lib/agentGraph.ts
@@ -1,3 +1,5 @@
+import type { TFunction } from 'i18next';
+import type { TranslationKey } from '@/i18n/types';
// Shared types + pure helpers for the Agents · 运行图 (run graph).
//
// The wire shape is the frozen contract in
@@ -182,7 +184,7 @@ export type StatusTone = 'mint' | 'gold' | 'cyan' | 'muted' | 'destructive';
export type StatusMeta = {
tone: StatusTone;
dotClass: string;
- labelKey: string;
+ labelKey: TranslationKey;
dim: boolean;
// Which glyph the node header shows: a colored dot, a check, or a cross.
glyph: 'dot' | 'check' | 'cross';
@@ -219,7 +221,7 @@ export function isBackground(node: Pick<AgentGraphNode, 'visibility'>): boolean
// ``t`` is required rather than optional because the unit is user-visible text:
// an optional translator would leave a path that silently prints English into a
// Chinese UI, which is how "等待 3h" shipped in the first place.
-export function formatElapsed(seconds: number | null | undefined, t: (key: string) => string): string {
+export function formatElapsed(seconds: number | null | undefined, t: TFunction): string {
if (seconds == null) return '—';
const s = Math.max(0, seconds);
if (s < 60) return `${Math.round(s)}${t('common.duration.seconds')}`;
diff --git a/ui/src/lib/annotationView.ts b/ui/src/lib/annotationView.ts
index 2db12efc3..18d0753cd 100644
--- a/ui/src/lib/annotationView.ts
+++ b/ui/src/lib/annotationView.ts
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
// What a Show Page annotation draws in chat, distilled from ``content.annotation``.
// Design: design.pen m31JWV (states) + TxFKk (anatomy and rules); the rule
// numbers cited below are that frame's.
@@ -39,7 +40,7 @@ export function readAnnotationView(content: unknown): AnnotationView | null {
// resolved agent mark is still titled "Agent 批注"; the marker below the body is
// what says it is done. The direction is data on the row; the words are frontend
// i18n, so switching UI language re-labels existing rows instead of rewriting them.
-export const annotationTitleKey = (direction: AnnotationView['direction']): string =>
+export const annotationTitleKey = (direction: AnnotationView['direction']): TranslationKey =>
direction === 'user' ? 'chat.annotation.titleUser' : 'chat.annotation.titleAgent';
// What names a queued annotation on the strip's single line when its author
diff --git a/ui/src/lib/backendAccent.ts b/ui/src/lib/backendAccent.ts
index 22e74dde2..8e8bdf2c3 100644
--- a/ui/src/lib/backendAccent.ts
+++ b/ui/src/lib/backendAccent.ts
@@ -7,11 +7,11 @@
export const BACKEND_ORDER = ['claude', 'opencode', 'codex'] as const;
export type Backend = (typeof BACKEND_ORDER)[number];
-export const BACKEND_LABEL: Record<Backend, string> = {
+export const BACKEND_LABEL = {
claude: 'Claude',
opencode: 'OpenCode',
codex: 'Codex',
-};
+} as const satisfies Record<Backend, string>;
// Text / icon accent — e.g. <Icon className={BACKEND_TEXT[b]} />.
export const BACKEND_TEXT: Record<Backend, string> = {
diff --git a/ui/src/lib/backgroundActivity.ts b/ui/src/lib/backgroundActivity.ts
index 1a1571732..e9d7967a3 100644
--- a/ui/src/lib/backgroundActivity.ts
+++ b/ui/src/lib/backgroundActivity.ts
@@ -37,7 +37,7 @@ export function isQueuedRun(
// run" reads as still-executing and misled users about unfinished work.
export function activityKindI18nKey(
item: Pick<SessionActivityState, 'item_kind' | 'schedule_type' | 'status'>,
-): string {
+) {
const kind = activityItemKind(item);
if (kind === 'task') {
if (item.schedule_type === 'at') return 'taskOneShot';
diff --git a/ui/src/lib/chatTrigger.ts b/ui/src/lib/chatTrigger.ts
index 492951372..16916f740 100644
--- a/ui/src/lib/chatTrigger.ts
+++ b/ui/src/lib/chatTrigger.ts
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
// Provenance click-through for a harness trigger message in Chat (contract
// A9a/A9b). A pure mapper so the branching is unit-tested without the component.
//
@@ -57,7 +58,7 @@ type TriggerFields = Pick<
| 'source_session_agent_name'
> & { metadata?: Record<string, unknown> };
-const VAULT_CALLBACK_STATUS_KEYS: Record<string, string> = {
+const VAULT_CALLBACK_STATUS_KEYS: Record<string, TranslationKey> = {
'provision:fulfilled': 'chat.source.vaultProvided',
'access:approved': 'chat.source.vaultAccessApproved',
'sign:approved': 'chat.source.vaultSigned',
@@ -89,7 +90,7 @@ export function isVaultCallback(message: TriggerFields): boolean {
return sourceActor.startsWith('vault:');
}
-export function vaultCallbackStatusKey(message: TriggerFields): string | null {
+export function vaultCallbackStatusKey(message: TriggerFields): TranslationKey | null {
const metadata = vaultCallbackMetadata(message);
if (!metadata) return null;
return VAULT_CALLBACK_STATUS_KEYS[`${metadata.requestType}:${metadata.status}`] ?? null;
@@ -132,7 +133,7 @@ export function chatTriggerLink(message: TriggerFields, agentFallback: string):
// never the mechanism-flavored "Automated" that read as system-triggered.
// - Task / Watch / Webhook keep their own self-contained labels.
// Pure so the branch is unit-tested alongside chatTriggerLink.
-export function harnessChipLabelKey(message: TriggerFields): string {
+export function harnessChipLabelKey(message: TriggerFields): TranslationKey {
if (message.source === 'harness' && message.source_session_id) return 'chat.source.from';
if (isVaultCallback(message)) return 'chat.source.vault';
const kind = message.author_name;
diff --git a/ui/src/lib/filesApi.ts b/ui/src/lib/filesApi.ts
index 649bda481..12f2a30b0 100644
--- a/ui/src/lib/filesApi.ts
+++ b/ui/src/lib/filesApi.ts
@@ -1,3 +1,4 @@
+import type { TFunction } from 'i18next';
// Client for the whole-machine File Browser backend (`/api/files/*`). Reuses the
// shared `apiFetch`, which attaches the CSRF header to mutating verbs and routes
// remote-auth-expiry redirects. Backend contract: `core/file_browser_service.py`.
@@ -56,14 +57,14 @@ export class FilesApiError extends Error {
}
}
-export function fileBrowserErrorMessage(error: unknown, t: (key: string) => string, fallback: string): string {
+export function fileBrowserErrorMessage(error: unknown, t: TFunction, fallback: string): string {
if (error instanceof FilesApiError) {
// Every error code (backend not_found/permission_denied/... and the client-side
// file_not_utf8) maps 1:1 to apps.fileBrowser.errors.<code>; fall back to the raw
// message when no localized string exists.
const key = `apps.fileBrowser.errors.${error.code}`;
- const translated = t(key);
- return translated === key ? error.message : translated;
+ const translated = t(key, { defaultValue: key, returnObjects: true });
+ return typeof translated === 'string' && translated !== key ? translated : error.message;
}
return error instanceof Error ? error.message : fallback;
}
diff --git a/ui/src/lib/platforms.ts b/ui/src/lib/platforms.ts
index 14d7dfdce..eb0862cb2 100644
--- a/ui/src/lib/platforms.ts
+++ b/ui/src/lib/platforms.ts
@@ -1,3 +1,6 @@
+import type { TFunction } from 'i18next';
+import type { TranslationKey } from '@/i18n/types';
+
export type PlatformName = string;
export type PlatformCapabilities = {
@@ -41,7 +44,7 @@ export const WORKBENCH_PLATFORM_ID = 'avibe';
export const isWorkbenchPlatform = (platform: string): boolean =>
platform === WORKBENCH_PLATFORM_ID;
-const LEGACY_FALLBACK_CATALOG: PlatformDescriptor[] = [
+const LEGACY_FALLBACK_CATALOG: (PlatformDescriptor & { title_key: TranslationKey; description_key: TranslationKey })[] = [
{
id: 'slack',
config_key: 'slack',
@@ -211,3 +214,10 @@ export const platformHasRunnableConfig = (data: any, platform: string): boolean
export const hasConfiguredPlatformCredentials = (data: any): boolean =>
getEnabledPlatforms(data).some((platform) => platformHasRunnableConfig(data, platform));
+
+/** Catalog labels are server-selected; unknown names retain i18next's key fallback. */
+export function platformText(t: TFunction, id: string, field: 'title' | 'desc', key?: string): string {
+ const name = key || `platform.${id}.${field}`;
+ const value = t(name, { defaultValue: name, returnObjects: true });
+ return typeof value === 'string' ? value : name;
+}
diff --git a/ui/src/lib/workbenchUpload.ts b/ui/src/lib/workbenchUpload.ts
index 7fb9e37e4..4163c2bf2 100644
--- a/ui/src/lib/workbenchUpload.ts
+++ b/ui/src/lib/workbenchUpload.ts
@@ -1,3 +1,4 @@
+import type { TranslationKey } from '@/i18n/types';
import { apiFetch } from './apiFetch';
// Product safety limit, enforced again by core/workbench_media.py. This is an
@@ -93,7 +94,7 @@ export async function uploadWorkbenchAttachment(
return payload;
}
-export function workbenchUploadErrorTranslationKey(error: unknown): string {
+export function workbenchUploadErrorTranslationKey(error: unknown): TranslationKey {
if (!(error instanceof WorkbenchUploadError)) return 'chat.compose.attachmentFailed';
if (error.code === 'too_large') return 'chat.compose.attachmentTooLarge';
if (error.code === 'empty_file') return 'chat.compose.attachmentEmpty';
diff --git a/ui/tsconfig.i18n-tests.json b/ui/tsconfig.i18n-tests.json
new file mode 100644
index 000000000..7aa1e0ec6
--- /dev/null
+++ b/ui/tsconfig.i18n-tests.json
@@ -0,0 +1,5 @@
+{
+ "extends": "./tsconfig.app.json",
+ "include": ["src/i18n/i18next.d.ts", "src/i18n/translationContract.test.ts"],
+ "exclude": []
+}