opencode icon indicating copy to clipboard operation
opencode copied to clipboard

[FEATURE]: i18n support for TUI (terminal interface)

Open apuromafo opened this issue 4 months ago • 27 comments

Description

The TUI (terminal interface) currently has all strings hardcoded in English. While the app/desktop/console packages have i18n support with 17+ locales, the TUI package (packages/tui) lacks any localization system.

This makes the terminal experience inaccessible for non-English speakers who form a significant portion of the user base.

Proposed solution

  1. Extract all hardcoded strings from packages/tui/src/ into an i18n key system similar to packages/app/src/i18n/.
  2. Add a locale config option in opencode.json (e.g. "locale": "es").
  3. Include at minimum: es, fr, de, zh, ja, ko, pt, ar, ru, uk, it, tr, pl, th, nl, vi, hi.

Current behavior

All TUI labels, prompts, error messages, and status text are in English with no way to change language.

Additional context

Related open issues:

  • #32095 - Spanish settings showing English labels
  • #36292 - i18n parity test failures across locales
  • #17652 - Spanish docs outdated
  • #12609 - ASCII-only output breaking non-English languages

The i18n infrastructure already exists in packages/app/src/i18n/ and could be adapted for TUI use.

apuromafo avatar Jul 16 '26 03:07 apuromafo

This issue might be a duplicate of existing issues. Please check:

  • #27445: Nearly identical feature request — "i18n / multi-language support for TUI interface" (closed), which proposed the same locale config option and TUI string localization
  • #21084: "add locale-aware CLI and TUI strings to packages/opencode" (closed), covering the same scope of making TUI strings locale-aware
  • #35831: "i18n / Locale support (Portuguese and other languages)" (open), which also discusses the existing i18n infrastructure in packages/app/src/i18n/

Please review those issues and the discussion there before proceeding, as the maintainers may have already provided relevant context or decisions.

github-actions[bot] avatar Jul 16 '26 03:07 github-actions[bot]

中文用户群体很大,很多非英语母语的开发者更习惯中文界面来降低认知负担。目前 Desktop 端已有 i18n 基础设施,希望 TUI 端也能尽快支持中文(zh-CN / zh-TW)。我们愿意帮忙测试和校对翻译。

xingxiulaomo avatar Jul 27 '26 05:07 xingxiulaomo

For context, a working V2 TUI i18n plugin already exists (opencode-i18n-v2, zh-Hans/zh-Hant palette translation shipped on npm). It is built entirely on shadow keymap commands, which requires perpetual polling of context.keymap.commands(), echo detection, and bind: false guards to avoid hijacking keys.

A small sanctioned hook — e.g. a display-time command transform or a "command registered" event — would let community plugins own localization of any surface/locale. Concrete proposal + evidence: #45490.

huahai0202 avatar Aug 27 '26 05:08 huahai0202

Thanks for the detailed request, @apuromafo!

You're asking for the terminal UI (packages/tui) to be localizable like the app, desktop and console packages. That would mean moving the hard-coded English strings into an i18n key system, adding a locale option in opencode.json, and shipping translations for the common locales. Today the TUI has no localization layer; only dates and times follow your system locale.

This can't be done as a plugin, because the TUI's strings are built in and there is no hook to replace them, so it would need changes in core. Maintainers will consider it.

Related issues you mentioned (all closed, none covers the TUI itself):

  • #32095: Spanish settings showing English labels in the app
  • #36292: i18n parity test failures in packages/app
  • #12609: system prompts forcing ASCII-only output for non-English languages

opencodejr[bot] avatar Oct 28 '26 23:10 opencodejr[bot]

Following the review of #61366, I'd like to agree on a smaller TUI i18n design before submitting the implementation in stages. @kommander, would this first step fit the intended direction?

  • Keep the translation layer inside packages/tui, using the app's flat catalog pattern and @solid-primitives/i18n. English defines the typed keys and remains the default; later catalogs load on demand with English fallback. Use Intl for numbers, dates and plural selection.
  • Persist a language setting through the existing TUI config/update mechanism. The initial PR would contain only an English catalog, a language picker and one converted dialog to demonstrate the pattern. Preserve existing English output and command IDs, bindings and behavior.
  • Translate built-in display text only. Paths, tool inputs/output, model identifiers and user content stay unchanged. The plugin command-display hook proposed in #45490 would need its own API discussion; this first step would not change the plugin or server protocol.
  • Cover fallback/loading, keys and interpolation, plural selection, persistence and keyboard/mouse selection. Keep existing English tests passing and check narrow terminal layouts.

After that infrastructure PR: extract English strings in small batches (dialogs, prompt/session, sidebar/plugins), then Mini, then the Russian catalog and its coverage/plural tests. Each PR would have a limited scope and its own validation.

Could you confirm the core-layer approach and whether language belongs in TUI config, or prefer the issue's locale option in opencode.json? I'll keep the existing implementation as a reference and wait for maintainer design approval before opening the first implementation PR.

krotname avatar Nov 05 '26 11:11 krotname

Still true on 2.3.0 (Nov 2026): packages/tui ships no locale layer, and neither opencode.json nor cli.json exposes a locale/language key, so TUI strings are compiled into the binary. Two details from the current build that matter for the design:

  1. The session sidebar is assembled from built-in TUI plugins (opencode.sidebar.context, .limit, .mcp, .todo) that each call ui.slot({ append: "sidebar.content" }) with hardcoded English labels ("Context", "MCP", "Connected", "Error", "Todo"). A third-party plugin cannot reach those strings — the only workaround is replace: "sidebar.content" and reimplementing the whole panel. If internal plugins resolved labels through the same i18n layer, that workaround would disappear.
  2. Palette-only approaches (rewriting keymap title/description, which is what community plugins do today) leave static UI text untouched: the "Ask anything…" placeholder, sidebar labels, diff viewer chrome and status text stay English. A locale setting therefore has to cover host components, not just command registrations.

Happy to test a draft against 2.3.0 and contribute the full list of hardcoded TUI strings (grouped by surface) to seed en and ru dictionaries, if that would help move this forward.

ZuzeTt avatar Nov 14 '26 19:11 ZuzeTt

A list of hardcoded strings grouped by surface would be useful, especially host components and built-in sidebar plugins; Mini can be a separate group. Could you share it here, @ZuzeTt?

I've opened draft #63978 as the first small follow-up to #61366. It covers a typed English catalog and the alert dialog, preserving the existing English labels and behavior. It has no locale setting or Russian catalog yet. Maintainer agreement on the design and the first PR's scope is still pending; the inventory would help plan the later extraction and coverage tests once that scope is agreed.

krotname avatar Nov 16 '26 10:11 krotname

@krotname — here is the inventory. It was generated from packages/tui/src at 26f2522 with a small AST pass (JSX text nodes, title/label/message/placeholder/description props, and object literals passed to toasts and dialogs). Storybook, *.fixtures.*, simulation, devtools and animation internals are excluded, since they are not shipped copy.

Totals: 878 unique (surface, string) pairs, 611 interpolated template literals (at least 133 of them read as copy; the rest are paths, IDs and internal formatting), and 21 sites that branch English plurals inline (count === 1 ? "step" : "steps").

Surface Strings Examples
Session view 168 Background blocking tools, Cancel permission rejection
Composer (session) 24 Close composer, Interrupt subagent
Mini 61 Clear prompt or exit, Clear screen
Diff viewer 62 All files / single file, Base branch
Sidebar plugin · context 4 % used, Context
Sidebar plugin · limit 2 Limit, remaining
Sidebar plugin · mcp 7 active, Connected
Sidebar plugin · todo 2 remaining), Todo
Sidebar plugin · footer 4 Connect provider, Getting started
Home screen 4 MCP failed, failed
Composer plugin · btw 7 Ask a side question, Ask anything
Composer plugin · goal 6 Clear goal, Failed to update the goal
Composer plugin · footer 3 agents, commands
Dialog/component 286 Account name, Add account
Shared dialog 58 Change export option, Close dialog
Command registry 49 Agent cycle, Agent cycle reverse
Settings dialog 72 Accelerate scrolling from repeated input, Active attention sound pack ID
System 46 Add a favorite model to use this shortcut, Background blocking tools
System · stats 7 Could not load stats. Reopen /stats to try again., Gathering your stats…
System · plugins 3 Toggle internal plugins, Plugins
System · stats-data 2 active days, best streak
System · notifications 1 Session failed

Built-in sidebar plugins (complete)

Plugin Strings
context % used, Context, spent, tokens
limit Limit, remaining
mcp active, Connected, Connecting, Disabled, Error, MCP, Sign in
todo remaining), Todo
footer Connect from 75+ providers to use other models, including Claude, GPT, Gemini etc, Connect provider, Getting started, OpenCode includes free models so you can start immediately.

Two caveats on this group. The copy is split around expressions, so Context and % used are separate keys today and {n} tokens / {n}% used / ${x} spent would each need one template key with a placeholder — that is a code change per site, not a move. And the same state is worded differently by surface: Sign in in the sidebar vs Sign in required → in the MCP dialog, so key naming needs a decision before extraction.

Command palette / keymap metadata

The 49 strings from app.tsx are keymap title/description values ("Show command palette", "Model cycle", "Suspend terminal"), not rendered copy. TUI plugins can already rewrite those through a keymap layer, so they are probably a separate namespace or out of scope for the first extraction — worth deciding explicitly so the catalog does not mix the two.

Notes that affect scope

  1. Expression-split fragments are common in host components (session view, sidebar, mini). A 1:1 extraction of JSXText nodes produces keys like "tokens", "remaining)", "% used" — the useful key is the whole sentence, which means touching each call site.
  2. Pluralization: 21 inline count === 1 ? ... sites. Russian needs three forms (1 / 2–4 / 5+), so the catalog needs a plural API rather than {n} items.
  3. Mini (packages/tui/src/mini, 61 strings) has its own vocabulary for the same concepts (Clear prompt or exit, Pending prompts, Previous prompt history). As a separate group it can share keys where the wording matches, but it is not a subset.
  4. Settings dialog (72 strings) is almost entirely description fields for cli.json options — long technical sentences, a good early candidate for isolated coverage tests.
  5. Session view (168) and dialogs (286 across component/*) hold the bulk of the copy; those are the two surfaces where a catalog will pay off immediately.

Full inventory (every string with file:line), the JSON it was generated from, and the script: https://gist.github.com/ZuzeTt/6986ce5a60048c90908444c5cfd984af. The script is deterministic, so it can be rerun at any commit to diff coverage once extraction starts.

Happy to refine key naming or turn this into a per-surface extraction plan if that helps unblock #63978.

ZuzeTt avatar Nov 16 '26 13:11 ZuzeTt

I checked the gist's JSON total (878 surface/string pairs) and spot-checked the sidebar and Mini locations against 26f2522; those samples match the source. This is useful for planning the extraction.

For the follow-ups, I'd keep whole messages with named placeholders rather than keys for fragments such as % used or remaining), use Intl.PluralRules with Russian one/few/many/other forms, and keep Mini as a separate batch. Command titles/descriptions are display text too; their IDs and bindings must stay unchanged.

One coverage caveat: extract.js deduplicates by surface/string, keeping only the first location, and its literal-only pass skips template expressions and strings longer than 140 characters. Could you include all occurrence locations plus the template/plural-site list as separate data? That would let us track converted call sites without treating the 878 entries as a complete coverage count.

#63978 stays a draft limited to the English catalog and alert dialog. Locale persistence, plural API and broader extraction still need maintainer design agreement before implementation.

krotname avatar Nov 17 '26 06:11 krotname

Updated the data the way you described — same commit (26f2522), same gist, new revisions:

  • Every occurrence, not just the first: 801 unique strings, 885 (surface, string) pairs, 984 occurrences, each with file, line and column, so a converted call site can be marked individually.
  • templates.md + templates in JSON: 562 interpolated templates, 124 of them read as copy. Each row carries the source of its placeholders, which is what named placeholders will be derived from ({0} left → {count} left); the rest are paths, ids and internal formatting and are kept only so they can be excluded explicitly rather than silently.
  • plurals.md + plurals in JSON: 21 sites with an x === 1 ternary, with both branches and a suffix flag (""/"s" in 15 of them, full words in 6). These are the exact call sites for Intl.PluralRules and the ru one/few/many/other forms.
  • commands.md + commands in JSON: 64 ids across 71 definitions, with id kept separate from title/description so the ids and bindings are out of scope by construction.
  • Length cap raised from 140 to 400; 2 strings exceed 140 and are flagged long (longest 158). Nothing in the TUI copy is longer than that today.
  • util/ is now included — it holds copy and 88 of the templates. plugin/, theme and config/v1 internals stay excluded; the skip list is explicit in extract.js.

Two things worth deciding before extraction, both visible in the new data:

  1. Ids are reused with different display text. app.exit is "Close diff viewer" in the diff viewer, "Dismiss form" in the form and "Reject permission" in the permission prompt; dialog.prompt.submit is "Submit answer" and "Submit dialog prompt". Keys therefore have to be per call site or per surface, not per command id.
  2. 75 strings occur more than once. With 984 occurrences across 885 surface pairs, one key can serve several call sites where the wording is truly shared (dialog buttons), and cannot where the text diverges (app.exit above). The occurrence list makes that choice explicit instead of hiding it in dedupe.

#63978 being an English-only catalog scoped to the alert dialog looks right as a seed. Since the datasets are pinned to a commit, coverage can be diffed by rerunning extract.js once extraction starts; happy to do that pass when the scope is agreed.

ZuzeTt avatar Nov 17 '26 06:11 ZuzeTt

For those reused command IDs, I'd key translations by the displayed action and surface: for example, diff.close, form.dismiss, and permission.reject can remain distinct while all three handlers keep the existing app.exit ID. That preserves command routing without forcing unrelated labels to share a translation.

I'd also share a key only when the meaning and UI context match. Identical English wording alone is insufficient: another language may need different grammatical forms or a different verb. The occurrence list makes that review possible while still tracking each converted call site separately.

These would be catalog conventions for the later extraction; #63978 can retain its current English-only alert-dialog scope while the broader design awaits maintainer agreement.

krotname avatar Nov 17 '26 08:11 krotname

That matches what the data says, so I applied the convention and pushed two derived files to the same gist:

  • conventions.md — a namespace per surface with examples: sidebar.context.tokens, diff.close, model.select, and command.<id> for palette titles. Handlers keep app.exit; only the displayed text diverges per surface.
  • shared-labels.md — every string that occurs more than once (122 of them), with its surfaces and a recommendation.

One correction to my previous comment: 75 was duplicates within a single surface; across all surfaces 122 strings repeat. Applying your rule splits them as:

  • 49 share — same surface, or genuine primitives
  • 24 separate — Mini batch
  • 8 separate — command titles vs UI copy
  • 6 share as dialog.* (Back, Close, Tools)
  • 26 need review — cross-surface pairs such as Next answer in a dialog and in the session view
  • 9 are fragments (esc, enter, more) that should be merged into the containing message, not keyed

Concrete end state for the sidebar: sidebar.context.title = "Context", sidebar.context.tokens = "{count} tokens", sidebar.context.used = "{percent}% used", sidebar.context.spent = "{amount} spent" — one key per message, no % used fragment.

dialog.alert.ok in #63978 already fits the scheme, so that draft needs no naming changes.

ZuzeTt avatar Nov 17 '26 08:11 ZuzeTt

The inventory feedback now has a concrete, tested follow-up. I prepared the four complete sidebar.context.* messages (Context, {count} tokens, {percent}% used, {amount} spent) with typed named parameters on tui-i18n-sidebar, based on #63978. Four files, English display and number formatting preserved; 90 test runs, TUI typecheck and formatting pass. This is a preparation branch, not another PR. Command IDs and bindings stay unchanged.

The shared-label recommendations still need call-site review: for example, Yes/No in the integration dialog and form utility are standalone choices, and alert ok is a complete button label. I will keep those distinct from actual sentence fragments rather than apply the fragment classification mechanically. Mini remains a separate batch.

@Hona @Brendonovich, could you review the two pending localization directions, or route the TUI design question to its maintainer?

  • App #61361: the latest review's English-fallback concern is fixed in 1a0036fc. Placeholder/plural checks remain; 64 targeted tests, typecheck and both upstream checks pass.
  • TUI draft #63978: still the four-file English catalog and alert example replacing closed #61366. Could a maintainer explicitly confirm that core TUI i18n is wanted, approve or adjust this first scope, and settle the runtime locale source/config key (locale versus language)? The proposed sequence is the foundation, small English extraction batches, Mini, then the Russian catalog and plural tests.

The community inventory and naming discussion help prepare the work, but maintainer design approval is still pending. #63978 stays draft, and I will wait for that decision before submitting later implementation PRs.

krotname avatar Nov 17 '26 08:11 krotname

Looked at tui-i18n-sidebar (f6a0a18). The message shape and the typed parameter plumbing look right — complete sentences, named parameters, Object.hasOwn, and the $& / {toString} tests cover the nasty cases. Two things worth fixing before the key shape hardens:

  1. Pass the number, not the formatted string. count: value().tokens.toLocaleString() and amount: money.format(cost()) bake host-locale formatting into the message argument. toLocaleString() without an argument follows the OS locale, not the selected catalog locale, so a Russian catalog on an en-US machine renders 12,345 токенов; Intl.NumberFormat("en-US", { currency: "USD" }) ignores the target locale completely. If the catalog owns the sentence, it should own number and currency formatting too: pass tokens as a number and format with the active locale in the i18n layer (or expose format.number / format.currency next to t).

  2. {count} tokens needs a plural decision before extraction spreads. English already prints 1 tokens; once this is a catalog key the shape matters, because ru needs one/few/many/other (1 токен, 2 токена, 5 токенов, 1,5 токена). Decide now whether t takes plural forms for a key or the key is sidebar.context.tokens.one / .few / .many / .other with CLDR categories per locale — migrating the key later means touching every extracted message again.

Smaller notes:

  • percent: value().percent ?? "" is unreachable given the surrounding Show; passing the narrowed value keeps the type honest.
  • A test asserting that every catalog entry has exactly the same placeholder set as English would catch translations that add or drop a {name}. The runtime leaves unknown placeholders visible, which is a good fallback but easy to miss in review.

Not blocking the branch as an English-only preparation — it is a good call site precisely because it shows why the plural and formatting decisions should land before the Russian catalog.

ZuzeTt avatar Nov 17 '26 08:11 ZuzeTt

Addressed the formatting and plural points from https://github.com/anomalyco/opencode/issues/37216#issuecomment-6943201338 in the preparation branch: https://github.com/krotname/opencode/commit/3878c0a1665655fdef121c4e0bf458835168c2e0.

  • The sidebar passes the raw token count to plural("sidebar.context.tokens", count). Selection uses Intl.PluralRules for the active catalog locale; the English catalog has one/other, and the tests exercise Russian one/few/many/other, including 1.5. Missing translated forms fall back to the English category. The English singular now reads 1 token.
  • format.number and format.currency read the current locale, including after a locale change. The sidebar no longer formats counts or currency with its own locale choice.
  • The percentage uses a narrowed value instead of the unreachable empty-string fallback; zero remains visible.

On the isolated non-root server runner: 20 tests repeated 10 times passed (200 executions, 0 failures), TUI TypeScript checking passed, and Prettier passed. The branch changes four files relative to the foundation. For the later translated catalogs, placeholder parity should check the entries actually present without requiring complete translation coverage; this preparation still ships only the English catalog, with Russian strings confined to test fixtures.

This remains preparation in tui-i18n-sidebar, with no additional PR opened. #63978 is still the original four-file draft at d6089a5; the catalog/locale selection API and subsequent submission scope still need a maintainer decision.

krotname avatar Nov 17 '26 08:11 krotname

Re-checked at 3878c0a — both points are addressed, and the Russian fixture is the right shape (1 / 2 / 5 / 21 / 1.5 plus the fallback case). Three small things in the types, no behavior change needed now:

  • PluralKey is derived by treating every key ending in .other as a plural base, and MessageKey hides everything ending in a CLDR category. It works today, but it makes .one/.other reserved suffixes: a future non-plural key such as dialog.other would silently disappear from t() and be interpreted as a plural base. A comment in en.ts or an explicit list of plural bases would make that constraint visible.
  • type PluralKey = Key extends infer K ? (K extends ... ) : never can be written as Key extends \${infer Base}.other` ? Base : never— same result without the extrainfer`.
  • The fallback chain catalog[{key}.{category}] ?? catalog[{key}.other] ?? dict[{key}.{englishCategory}] means a ru catalog that omits .other renders English for fractional counts (1.5). That is probably intended, but it is the one category where a partial Russian catalog degrades silently; a test pinning it would document the behavior.

Minor: format.number and format.currency build a new Intl.NumberFormat per call, and the sidebar re-renders on session events; a per-locale cache keeps that cheap once the locale provider lands.

Unrelated to the code: I set up a schedule on my side that watches this issue and only wakes when the last comment id changes, so I can follow the discussion without being pinged each time.

ZuzeTt avatar Nov 17 '26 08:11 ZuzeTt

Addressed the remaining recommendations from https://github.com/anomalyco/opencode/issues/37216#issuecomment-6943431510 in https://github.com/krotname/opencode/commit/3bdfd7e96cae35727e137cd988298cb8fc0c5d89.

  • en.ts explicitly lists the plural base in PluralKey, with a comment explaining the boundary. Ordinary keys ending in .one or .other are no longer inferred as plural groups. This also removes the nested conditional/infer entirely.
  • A partial Russian catalog test now pins the missing-other behavior: 1.5 becomes 1,5 tokens, retaining active-locale number formatting while falling back to English text; 2 токена still uses the available Russian form.
  • Number formatters are cached per locale; currency formatters are cached per locale and currency. Tests cover USD/EUR, en/ru, and switching back to a previously used locale.
  • The shared Russian test fixture now checks placeholder parity for entries that exist, without requiring full catalog coverage.

Validation on the isolated non-root Red runner: 22 tests repeated 10 times, 220 passed/0 failed, 460 assertions; TUI typecheck:tsc and Prettier passed. This updates the same preparation branch; #63978 remains the foundation draft pending the maintainer design/scope decision.

krotname avatar Nov 17 '26 09:11 krotname

Checked 3bdfd7e — all three points are closed:

  • PluralKey is now an explicit "sidebar.context.tokens" with the boundary comment, so .one/.other stop being reserved suffixes and the conditional/infer chain is gone.
  • The partial-catalog test pins the missing-.other case in both directions: 2 токена from the catalog, 1,5 tokens from the English fallback.
  • Number formatters are cached per locale, currencies per locale+currency, and the test walks en → ru → en including a second currency.

Two optional notes, neither blocking:

  1. The explicit list means a new plural base needs a matching edit in PluralKey; a type-level check that every listed base exists in dict with .one/.other would remove the review dependency.
  2. 1,5 tokens mixes a Russian decimal separator with English text. That is a defensible reading of "the active locale formats numbers", but if the sentence is English, 1.5 tokens may read more naturally. Either way the test documents the choice now, which was the point.

Nothing else from my side on this branch. The open item is unchanged: #63978 waits on the maintainer design/scope decision, and the extraction batches, Mini and the Russian catalog should follow it.

ZuzeTt avatar Nov 17 '26 09:11 ZuzeTt

Thanks for the thorough review and for re-checking 3bdfd7e, @ZuzeTt. I've noted the two optional suggestions. We'll wait for the maintainers' design/scope decision on #63978 before opening the remaining TUI parts.

krotname avatar Nov 17 '26 09:11 krotname

Following the review notes on #64258 and #64400, here is the shape of the Chinese work so it can be compared with #63978 before either lands.

  • #64400 is the same seed as #63978 (typed English catalog, alert dialog) plus the permission labels; the review asked to drop the language key, the environment detection and the ./i18n export, and those are gone.
  • t(key, params) types the placeholder names as well: they are derived from the English template with a template-literal type, so a call site must pass exactly the params its copy names. It caught two real call sites while splitting.
  • The extraction is four batches by surface (mini footer and palette, forms and permissions, tool labels and splash and CLI), then the Chinese catalogs last. Simplified and Traditional are separate dictionaries, Partial<Record<Key, string>> over en, and a coverage test fails if an English key has no Chinese translation. zh-TW/zh-HK/zh-MO/zh-Hant map to Traditional, other zh tags to Simplified.
  • All of it is on top of current dev now; the later patches are ready but I can only open two more pull requests once GitHub lets this account create them again (currently 404 on create), so they are branches for the moment.

One thing would unblock the last patch: where the setting lives. language in the TUI config is what the drafts use, because the TUI already owns a config surface and app.tsx/runtime.lifecycle.ts are the only two boot sites. If you prefer locale in opencode.json, say so and I will move it there instead; it is a two-line change plus the schema key.

I am happy to test #63978 or compare shapes in more detail if that helps settle the seed.

leiming2333 avatar Nov 17 '26 10:11 leiming2333