# Localization

Phantom's interface speaks English and Russian. English is the source of
truth; every other language is checked against it at type-check time and
in the unit tests. This page is the contract for anyone moving text out
of a component and into the catalogues.

## How it fits together

| Piece | Where | Job |
|---|---|---|
| Catalogues | `frontend/src/i18n/<lang>/<area>.ts` | The messages, one module per area of the interface |
| Entry | `frontend/src/i18n/index.ts` | Creates vue-i18n (Composition API, `legacy: false`), exports `t`, `tn`, `setLocale` |
| Keys | `frontend/src/i18n/keys.ts` | `MessageKey`: every dotted path to an English string, as a type |
| Plurals | `frontend/src/i18n/plural.ts` | One rule per language from `Intl.PluralRules` |
| Formatting | `frontend/src/i18n/format.ts` | Numbers, dates, ages, durations and sizes in the active language |
| Preference | `frontend/src/i18n/locale.ts`, `composables/useLocale.ts` | Which language, remembered on this device |
| Settings | `components/settings/PSettingsLanguage.vue` | The Language card under Appearance |

The language is a UI preference stored in `localStorage` under
`phantom.ui.locale`. Without a saved choice, a browser whose first
language is `ru*` starts in Russian and every other browser in English.
Switching applies at once, without a reload, and updates `<html lang>`.
A first-run flow can call `setLocale('ru')` from `useLocale()`.

Anything a language lacks falls back to English.

## Where strings live

One area per catalogue module, named after the part of the interface
(`shell`, `palette`, `menus`, `settings`, `ai`, `connections`, `agent`,
`common`, `time`, `welcome`). When a module grows past about 250 lines it becomes a
folder with an `index.ts` that merges its parts (`agent/page.ts`,
`agent/composer.ts`, ...). The import in `en/index.ts` does not change.

`common` holds only words that mean the same everywhere: Save, Cancel,
Delete, Loading…, Copied. Text that belongs to one place stays in its area,
even if another area happens to use the same English word.

Russian modules are typed with the English module's type:

```ts
import type { ShellMessages } from '../en/shell'

const shell: ShellMessages = { ... }
```

A key that English has and Russian lacks, or the other way round, fails
`vue-tsc`.

## Key naming

`area.component.purpose`, camelCase leaves, nested objects per component:

- `shell.rail.showSidebar`
- `settings.exports.redactText`
- `menus.common.copyLink`
- `agent.composer.placeholder`

Name a key for what the text does, not for its English words, so the key
survives a rewording. Group a component's keys together, even when that
means two keys with the same English text in different groups.

## Using messages

In a component, import `t` (and `tn` for counts) and call it in the
template or a computed:

```vue
<script setup lang="ts">
import { t } from '@/i18n'
</script>

<template>
  <PButton>{{ t('common.actions.save') }}</PButton>
</template>
```

`t` takes only a `MessageKey`, so a typo fails the type check. Both
functions are reactive: a template or computed that calls them renders
again when the language changes. They work outside components too: menu
builders in `utils/menus`, stores, toasts.

A module-level constant must not freeze English at import time. Pick one:

- a `computed` inside the component (`const CHOICES = computed(() => [...])`);
- a function that builds the list when called (`bridgeClients()`);
- a getter on the item, when other code reads `.label` and should keep
  working: `{ key: 'json', get label() { return t('menus.payloads.exportJson') } }`;
- a `MessageKey` stored on the item and translated where it is shown.

Toast text is fixed when the toast is raised, which is fine: it is gone
in four seconds.

## Interpolation and markup

Placeholders are named: `'Switch to {name}'`, called as
`t('palette.actions.switchVault', { name: vault.name })`. Never build a
sentence from fragments (`t('a') + host + t('b')`): word order differs
between languages.

When part of a sentence needs markup, use the `Translation` component
(imported as `I18nT` from `vue-i18n`) with a named slot:

```vue
<I18nT keypath="shell.selection.addScope" scope="global">
  <template #host><b>{{ selection.host }}</b></template>
</I18nT>
```

Without `tag` it renders its children directly, so a flex parent lays
them out as before.

The message syntax treats `{`, `}`, `@`, `$` and `|` as special. Write a
literal one as `{'@'}`. The catalogue test compiles every message and
fails on a syntax error.

## Plurals

English writes two forms, Russian three (one, few, many):

```ts
deleteMany: 'Delete {count} payload | Delete {count} payloads'
deleteMany: 'Удалить {count} полезную нагрузку | Удалить {count} полезные нагрузки | Удалить {count} полезных нагрузок'
```

Call `tn(key, count)`. It picks the form and fills `{count}` with the
number formatted for the language (`1,234` or `1 234`). The form index
comes from `Intl.PluralRules`; Russian fractions take the `few` form.

When English needs one form but Russian depends on the count, write the
English twice: `'{count} selected | {count} selected'`.

## Numbers, dates and sizes

Never call `toLocaleString()`, `toFixed()` for display or hand-build
"3h ago". Use `@/i18n/format`:

| Helper | English | Russian |
|---|---|---|
| `formatNumber(1234)` | 1,234 | 1 234 |
| `formatFixed(12.34)` | 12.3 | 12,3 |
| `timeAgo(date)` | 8m ago, May 14 | 8 мин назад, 14 мая |
| `timeFromNow(date)` | in 3d | через 3 дн. |
| `shortUnit(4, 'hours')` | 4h | 4 ч |
| `shortDuration(185)` | 3m 05s | 3 мин 05 с |
| `formatBytes(12595)` | 12.3 KB | 12,3 КБ |
| `formatBytesCompact(12595)` | 12.3K | 12,3 КБ |
| `formatClock(date)`, `formatDateTime(date)` | via `Intl.DateTimeFormat` | |

The older helpers (`fmtRel`, `formatBytes` in `utils/format.ts` and
`utils/viewer/bodyMeta.ts`, `formatSize` in `utils/payloads.ts`,
`shortAge`, `shortAgo`, `relative`, `elapsedLabel`) now call these, so
their callers are localized already. English output is unchanged.

## What is never translated

Requests, responses, payloads, code, commands, paths, environment
variables, MCP tool names, model ids, user content (notes, findings,
conversation messages) and product names: Phantom, Bridge, MCP,
Claude Code, Codex, and the proxy tools Repeater, Intruder, Decoder,
Comparer.

## Russian terms

| English | Russian |
|---|---|
| request / response | запрос / ответ |
| payload | полезная нагрузка |
| scope, in scope | скоуп, в скоупе |
| vault | хранилище |
| target | цель |
| finding | находка |
| scan | сканирование |
| signature | сигнатура |
| conversation | диалог |
| capture | перехват |
| host | хост |
| token, access, connection | токен, доступ, подключение |

Buttons use the infinitive (Сохранить, Удалить); toasts are phrased so
they read correctly for any noun gender («Добавлено: {name}»).

The documentation uses the same terms, plus these:

| English | Russian |
|---|---|
| flow (a captured exchange) | запись трафика, коротко запись |
| HTTP history | HTTP-история |
| intercept (verb) | перехватывать; the Intercept tool keeps its name |
| proxy, listener | прокси, слушатель |
| replay | повторная отправка |
| research note, template | исследовательская заметка, шаблон |
| annotation, tag, backlink | аннотация, тег, обратная ссылка |
| evidence, proof of concept | доказательства, PoC |
| triage, severity | триаж, критичность |
| report, section, snapshot | отчёт, раздел, снимок |
| asset, observation, provenance | актив, наблюдение, происхождение |
| workspace | рабочее пространство |
| engagement, program | проект, программа |
| researcher, bug bounty | исследователь, баг-баунти |
| agent, tool (MCP), resource, prompt | агент, инструмент, ресурс, промпт |
| permission, capability, grant | разрешение, возможность, выданное право |
| personal access token | персональный токен доступа |
| model provider | провайдер моделей |
| turn (in a conversation), streaming | ход, потоковая передача |
| skill | навык; the Skills Engine keeps its name |
| matcher, extractor | матчер, экстрактор |
| wordlist, attack, position | словарь, атака, позиция |
| endpoint, route, event | эндпоинт, маршрут, событие |
| redaction, secret | маскирование, секрет |
| file storage | хранение файлов (not хранилище, which is the vault) |
| backend, frontend | бэкенд, фронтенд |
| roadmap, milestone | дорожная карта, этап |
| verification log, parity matrix | журнал проверок, матрица соответствия |
| body, upstream, handshake | тело, вышестоящий сервер (upstream), рукопожатие |
| draft, revision, retention | черновик, ревизия, срок хранения |
| dry run, false positive | пробный запуск, ложное срабатывание |
| credentials, placeholder | учётные данные, плейсхолдер |
| principal, lease, approval | субъект, аренда, подтверждение |
| rail, command palette, bookmark | панель навигации, палитра команд, закладка |
| saved view, inspector | сохранённое представление, инспектор |

## Documentation in Russian

The documentation site has the same two languages, and every address
names its language, so a shared link opens in the language it was copied
in. English pages live at the root of docs/ and are the source; they are
published under `/en/` without moving the files. The Russian translation
of `docs/<path>.md` is `docs/ru/<path>.md`, published under `/ru/`. The
sidebar, navigation and theme strings for Russian are in
`docs/.vitepress/config/ru/` and `docs/.vitepress/theme/i18n/`.

The site root sends a visitor to `/en/` or `/ru/`: the language last read
on this browser first, then the browser's languages. Addresses from
before the language prefix, such as `/guides/proxy/history`, redirect to
the English page and keep their fragment. Each language has its own
`llms.txt` and `llms-full.txt` (`/en/`, `/ru/`); the copies at the root
are English.

Not every page is translated. Design notes (`design/`) are engineering
documents that change with the code, and the roadmap pages other than
its overview are trackers updated with almost every commit, two of them
generated. The Russian sidebar lists them under their Russian names and
opens the English page.

### Keeping translations in sync

- A new English page under guides, agents, files, skills or reference
  gets its Russian counterpart in the same change, at the same path under
  `docs/ru/`, and an entry in the Russian sidebar.
- A Russian page keeps the English page's headings one for one, in the
  same order. The build gives each Russian heading the English heading's
  anchor, so links such as `vaults.md#scope` work in both languages.
- Links inside a Russian page point to Russian pages. A link to a page
  that is not translated goes to its English address, one folder further
  up and under `en/` (`../../en/roadmap/status.md` instead of
  `../roadmap/status.md`); a link to a file outside docs/ only goes one
  folder further up. Absolute links name the language (`/ru/support`,
  `/en/roadmap/status`).
- Code, commands, API paths, tool names, configuration keys and product
  names stay as they are. Interface labels use the wording of the Russian
  interface catalogue (`frontend/src/i18n/ru`).
- Containers carry an explicit Russian title (`::: tip Совет`), because
  the default labels are English.

`docs/.vitepress/scripts/translations.mjs` lists English pages without a
Russian counterpart, Russian pages whose heading count differs from the
English one, and Russian pages whose English source has newer commits.
The docs build prints the report as warnings, and the docs workflow runs
it as its own step with GitHub annotations. Neither fails: a missing
translation shows the reader the English page through the sidebar, it
does not break the site.

```sh
cd docs
npm run docs:i18n
```

## Adding a language

1. Copy `frontend/src/i18n/ru` to `frontend/src/i18n/<code>` and translate
   every module, keeping the types.
2. Add the code to `LOCALES` and its own name to `LOCALE_NAMES` in
   `i18n/locale.ts`, and the messages to `createI18n` in `i18n/index.ts`.
3. Add its plural categories to `ORDER` in `i18n/plural.ts`.
4. Add it to `LANGUAGES` in `i18n/__tests__/catalogue.spec.ts`, and a
   `settings.language.<code>` description in every catalogue.
5. Check `styles/fonts.css` covers its script (see below).

## How the tests hold it together

`frontend/src/i18n/__tests__/catalogue.spec.ts` fails when a language
misses or adds a key, uses different placeholder names from English,
writes the wrong number of plural forms, or has a message the compiler
rejects. `format.spec.ts` pins the English output of the formatting
helpers and their Russian counterparts. The type check catches unknown
keys at every call site.

## Fonts

Plus Jakarta Sans and Syne have no Cyrillic. `styles/fonts.css` declares
companions with a Cyrillic `unicode-range`, so Latin keeps the original
faces and Russian text uses Onest (interface) and Unbounded (display);
IBM Plex Mono brings its own Cyrillic subset. The companions download only
when Cyrillic is on screen. The stacks are in `styles/tokens.css`.

## Text from the backend

Some user-visible text comes from the backend. Every error has the shape
`{"error": {"code", "message", "details"}}`; the message is English. The
codes are stable: `not_found`, `conflict`, `out_of_scope`,
`invalid_value`, `too_large`, `invalid_state`, `signature_invalid`,
`unavailable`, `permission_denied`, `egress_refused`, `provider_error`
(with provider-specific codes), `unsupported_protocol`, `unauthenticated`.
The frontend adds `invalid_input` (FastAPI validation) and `http_error`.

Other backend text the interface shows as is: provider failure reasons,
agent hard rules and permission descriptions, scan log lines, signature
validation messages, report templates and export headings, and the
reasons in realtime events.

The proposed mapping, not built yet:

- An `errors` catalogue keyed by code (`errors.out_of_scope`), translated
  like any area.
- `ui.fail(error)` looks up `errors.<code>` for an `ApiError` when the
  active language is not English and shows that text, with the backend
  message available as detail; English keeps the backend message.
- Messages that need specifics (a field, a host, a limit) get structured
  `details` from the backend (`{"code": "too_large", "params": {"max": 1048576}}`),
  which the frontend fills into its own message. Validation errors list
  `{field, code, params}` per problem instead of English prose.
- Static backend vocabularies (permission names, preset descriptions,
  hard rules) move to stable ids with English defaults, so the frontend
  can translate the id and fall back to the default.

## Working on it locally

Replacing a catalogue file by a folder of the same name (`agent.ts` to
`agent/index.ts`) can leave the dev server resolving the old file when it
runs from WSL on a Windows drive. Save `i18n/en/index.ts` and
`i18n/ru/index.ts` once (no change needed) and reload.
