From 355c5b19b23d15008ba1811ae07aa1067808f8b3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=81=D0=B5=D0=BB=D1=8C?= Date: Sun, 15 Nov 2026 14:25:03 +0500 Subject: [PATCH] =?UTF-8?q?PEP-98:=20i18n=20core=20=E2=80=94=20dictionarie?= =?UTF-8?q?s,=20localizeText,=20user=20locale,=20web=20provider,=20bot=20a?= =?UTF-8?q?nd=20push=20localization,=20i18n-check?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- apps/bot/src/bot.ts | 43 +++- apps/web/app/(app)/actions.ts | 5 +- apps/web/app/auth/egov/complete/route.ts | 5 + apps/web/app/auth/google/callback/route.ts | 5 + apps/web/app/auth/link/route.ts | 5 + apps/web/app/layout.tsx | 17 +- apps/web/app/locale-actions.ts | 19 ++ apps/web/components/I18n.tsx | 53 ++++ apps/web/components/Sidebar.tsx | 47 ++-- apps/web/components/ThemeToggle.tsx | 4 +- apps/web/lib/i18n.ts | 38 +++ openspec/changes/pep-98-english-ui/design.md | 13 + packages/core/src/index.ts | 1 + packages/core/src/locale.ts | 50 ++++ packages/core/src/notifications.ts | 7 +- packages/shared/package.json | 3 +- packages/shared/src/i18n/en/common.ts | 58 +++++ packages/shared/src/i18n/en/index.ts | 6 + packages/shared/src/i18n/index.ts | 250 +++++++++++++++++++ packages/shared/src/i18n/kk.ts | 4 + scripts/i18n-check.ts | 106 ++++++++ 21 files changed, 705 insertions(+), 34 deletions(-) create mode 100644 apps/web/app/locale-actions.ts create mode 100644 apps/web/components/I18n.tsx create mode 100644 apps/web/lib/i18n.ts create mode 100644 packages/core/src/locale.ts create mode 100644 packages/shared/src/i18n/en/common.ts create mode 100644 packages/shared/src/i18n/en/index.ts create mode 100644 packages/shared/src/i18n/index.ts create mode 100644 packages/shared/src/i18n/kk.ts create mode 100644 scripts/i18n-check.ts diff --git a/apps/bot/src/bot.ts b/apps/bot/src/bot.ts index 0da94323..ef9a461f 100644 --- a/apps/bot/src/bot.ts +++ b/apps/bot/src/bot.ts @@ -2,7 +2,8 @@ // alerts) to the paired chat and turns button presses / replies into answers delivered // back into the agent session. Telegram is an adapter over the DB, not a remote shell: // it can only answer a specific pending question or resume/stop the session it is about. -import { reportPlatformError } from "@peppa/core"; +import { reportPlatformError, telegramChatLocale } from "@peppa/core"; +import { localizeText } from "@peppa/shared/i18n"; import { accountUsageForUser, describeUsage, @@ -146,11 +147,38 @@ export function createBot(o: BotOptions) { const ownBots = new Map(); const ownByChat = new Map(); const pick = (chatId?: unknown): TelegramApi => via.getStore()?.api ?? (typeof chatId === "number" ? ownByChat.get(chatId)?.api : undefined) ?? o.api; + // ── PEP-98: messages go out in the reader's language ───────────────────────────── + // Texts are rendered in Russian everywhere (core, runner, this file); right before the Bot API + // call the text, caption and button labels are translated for the chat's user. + const readerChat = new AsyncLocalStorage(); + const localizeParams = async (params: Record): Promise> => { + const chatId = typeof params.chat_id === "number" ? params.chat_id : readerChat.getStore(); + if (chatId == null) return params; + const locale = await telegramChatLocale(db, chatId).catch(() => "ru" as const); + if (locale === "ru") return params; + const tr = (v: unknown) => (typeof v === "string" ? localizeText(locale, v) : v); + const out: Record = { ...params, text: tr(params.text), caption: tr(params.caption) }; + if (params.text === undefined) delete out.text; + if (params.caption === undefined) delete out.caption; + const markup = params.reply_markup as { inline_keyboard?: { text: string }[][]; keyboard?: ({ text: string } | string)[][] } | undefined; + if (markup && typeof markup === "object") { + const btn = (b: B): B => (typeof b === "string" ? (tr(b) as B) : b && typeof b === "object" && "text" in b ? ({ ...b, text: tr((b as { text: string }).text) } as B) : b); + out.reply_markup = { + ...markup, + ...(markup.inline_keyboard ? { inline_keyboard: markup.inline_keyboard.map((row) => row.map(btn)) } : {}), + ...(markup.keyboard ? { keyboard: markup.keyboard.map((row) => row.map(btn)) } : {}), + }; + } + return out; + }; /** The same surface as TelegramApi, routed to the right bot per call. */ const api = { - call: (method: string, params: Record = {}, timeoutMs?: number) => pick(params.chat_id).call(method, params, timeoutMs), - sendMessage: (chatId: number, text: string, extra: Record = {}) => pick(chatId).sendMessage(chatId, text, extra), - answerCallbackQuery: (id: string, text?: string) => pick().answerCallbackQuery(id, text), + call: async (method: string, params: Record = {}, timeoutMs?: number) => pick(params.chat_id).call(method, await localizeParams(params), timeoutMs), + sendMessage: async (chatId: number, text: string, extra: Record = {}) => { + const p = await localizeParams({ ...extra, chat_id: chatId, text }); + return pick(chatId).sendMessage(chatId, p.text as string, p); + }, + answerCallbackQuery: async (id: string, text?: string) => pick().answerCallbackQuery(id, text === undefined ? undefined : ((await localizeParams({ text })).text as string)), getFile: (fileId: string) => pick().getFile(fileId), downloadFile: (filePath: string) => pick().downloadFile(filePath), getMe: () => o.api.getMe(), @@ -695,6 +723,13 @@ export function createBot(o: BotOptions) { } async function handleUpdate(u: TgUpdate): Promise { + // PEP-98: the person who sent the update reads the toasts and replies without a chat_id. + const reader = u.callback_query?.from?.id ?? u.message?.from?.id ?? u.message?.chat?.id; + if (reader != null) return readerChat.run(reader, () => handleUpdateIn(u)); + return handleUpdateIn(u); + } + + async function handleUpdateIn(u: TgUpdate): Promise { const botUserId = via.getStore()?.userId; if (!(await claimUpdate(db, u.update_id, botUserId))) return; try { diff --git a/apps/web/app/(app)/actions.ts b/apps/web/app/(app)/actions.ts index 65e9ed3b..21c3c71c 100644 --- a/apps/web/app/(app)/actions.ts +++ b/apps/web/app/(app)/actions.ts @@ -65,6 +65,7 @@ import { revalidatePath } from "next/cache"; import { redirect } from "next/navigation"; import { asWebActor, requireUser } from "@/lib/auth"; import { db } from "@/lib/db"; +import { getT } from "@/lib/i18n"; const str = (f: FormData, k: string) => String(f.get(k) ?? "").trim(); const back = (f: FormData) => str(f, "back") || "/"; @@ -75,7 +76,9 @@ async function attempt(f: FormData, fn: () => Promise): Promise + - - {children} + + + {children} + ); diff --git a/apps/web/app/locale-actions.ts b/apps/web/app/locale-actions.ts new file mode 100644 index 00000000..057984e2 --- /dev/null +++ b/apps/web/app/locale-actions.ts @@ -0,0 +1,19 @@ +"use server"; + +import { forgetChatLocales, setUserLocale } from "@peppa/core"; +import { LOCALE_COOKIE, normalizeLocale } from "@peppa/shared/i18n"; +import { cookies } from "next/headers"; +import { currentUser } from "@/lib/auth"; +import { db } from "@/lib/db"; +import { localeCookieOptions } from "@/lib/i18n"; + +/** PEP-98: language switcher — cookie for everyone, plus the user's setting when logged in. */ +export async function setLanguage(value: string): Promise { + const locale = normalizeLocale(value); + (await cookies()).set(LOCALE_COOKIE, locale, localeCookieOptions); + const user = await currentUser(); + if (user) { + await setUserLocale(db, user.id, locale); + forgetChatLocales(); + } +} diff --git a/apps/web/components/I18n.tsx b/apps/web/components/I18n.tsx new file mode 100644 index 00000000..dc22fea1 --- /dev/null +++ b/apps/web/components/I18n.tsx @@ -0,0 +1,53 @@ +"use client"; + +// Interface language in client components (PEP-98): the root layout passes the locale, +// `useT()` gives a translator over the bundled dictionaries. +import { createContext, useContext, useMemo, useTransition, type ReactNode } from "react"; +import { useRouter } from "next/navigation"; +import { LOCALE_LABELS, LOCALES, translator, type Locale, type Translator } from "@peppa/shared/i18n"; +import { setLanguage } from "@/app/locale-actions"; +import { cn } from "@/lib/utils"; + +const LocaleContext = createContext("ru"); + +export function I18nProvider({ locale, children }: { locale: Locale; children: ReactNode }) { + return {children}; +} + +export function useLocale(): Locale { + return useContext(LocaleContext); +} + +export function useT(): Translator { + const locale = useLocale(); + return useMemo(() => translator(locale), [locale]); +} + +/** RU / EN / KZ: saves the cookie (and the user's choice when logged in), then re-renders. */ +export function LanguageSwitcher({ className }: { className?: string }) { + const current = useLocale(); + const t = useT(); + const router = useRouter(); + const [pending, start] = useTransition(); + return ( +
+ {LOCALES.map((l) => ( + + ))} +
+ ); +} diff --git a/apps/web/components/Sidebar.tsx b/apps/web/components/Sidebar.tsx index c8125ae7..7dc3ef3c 100644 --- a/apps/web/components/Sidebar.tsx +++ b/apps/web/components/Sidebar.tsx @@ -7,6 +7,8 @@ import { Brand } from "@/components/Brand"; import { ThemeToggle } from "@/components/ThemeToggle"; import { Button } from "@/components/ui/button"; import { cn } from "@/lib/utils"; +import { useT } from "@/components/I18n"; +import { m } from "@peppa/shared/i18n"; interface Item { href: string; @@ -21,45 +23,46 @@ interface Item { } const ITEMS: Item[] = [ - { href: "/", label: "Главная", icon: House, match: (p) => p === "/", count: "questions" }, - { href: "/chats", label: "Чаты", icon: MessagesSquare, match: (p) => p.startsWith("/chats") }, - { href: "/projects", label: "Проекты", icon: FolderKanban, match: (p) => p.startsWith("/projects") || p.startsWith("/p/") || p.startsWith("/t/") }, - { href: "/runners", label: "Работа агентов", icon: Bot, match: (p) => p.startsWith("/runners"), count: "waitingRunners" }, - { href: "/team", label: "Команда", icon: Contact, match: (p) => p.startsWith("/team"), desktopOnly: true }, - { href: "/welcome", label: "О Пеппе", icon: Sparkles, match: (p) => p.startsWith("/welcome"), desktopOnly: true }, - { href: "/help", label: "Помощь", icon: LifeBuoy, match: (p) => p.startsWith("/help") }, - { href: "/subscriptions", label: "Подписки", icon: KeyRound, match: (p) => p.startsWith("/subscriptions"), admin: true }, - { href: "/secrets", label: "Секреты", icon: ShieldCheck, match: (p) => p.startsWith("/secrets"), admin: true }, - { href: "/hosts", label: "Хосты", icon: Server, match: (p) => p.startsWith("/hosts"), admin: true }, - { href: "/journal", label: "Журнал", icon: ScrollText, match: (p) => p.startsWith("/journal"), admin: true }, - { href: "/platform", label: "Платформа", icon: Megaphone, match: (p) => p.startsWith("/platform"), admin: true }, - { href: "/users", label: "Пользователи", icon: Users, match: (p) => p.startsWith("/users"), admin: true }, - { href: "/settings", label: "Настройки", icon: Settings, match: (p) => p.startsWith("/settings") }, + { href: "/", label: m("Главная"), icon: House, match: (p) => p === "/", count: "questions" }, + { href: "/chats", label: m("Чаты"), icon: MessagesSquare, match: (p) => p.startsWith("/chats") }, + { href: "/projects", label: m("Проекты"), icon: FolderKanban, match: (p) => p.startsWith("/projects") || p.startsWith("/p/") || p.startsWith("/t/") }, + { href: "/runners", label: m("Работа агентов"), icon: Bot, match: (p) => p.startsWith("/runners"), count: "waitingRunners" }, + { href: "/team", label: m("Команда"), icon: Contact, match: (p) => p.startsWith("/team"), desktopOnly: true }, + { href: "/welcome", label: m("О Пеппе"), icon: Sparkles, match: (p) => p.startsWith("/welcome"), desktopOnly: true }, + { href: "/help", label: m("Помощь"), icon: LifeBuoy, match: (p) => p.startsWith("/help") }, + { href: "/subscriptions", label: m("Подписки"), icon: KeyRound, match: (p) => p.startsWith("/subscriptions"), admin: true }, + { href: "/secrets", label: m("Секреты"), icon: ShieldCheck, match: (p) => p.startsWith("/secrets"), admin: true }, + { href: "/hosts", label: m("Хосты"), icon: Server, match: (p) => p.startsWith("/hosts"), admin: true }, + { href: "/journal", label: m("Журнал"), icon: ScrollText, match: (p) => p.startsWith("/journal"), admin: true }, + { href: "/platform", label: m("Платформа"), icon: Megaphone, match: (p) => p.startsWith("/platform"), admin: true }, + { href: "/users", label: m("Пользователи"), icon: Users, match: (p) => p.startsWith("/users"), admin: true }, + { href: "/settings", label: m("Настройки"), icon: Settings, match: (p) => p.startsWith("/settings") }, ]; -const COUNT_TITLE = { questions: "вопросов ждут тебя", waitingRunners: "раннеров ждут тебя" }; +const COUNT_TITLE = { questions: m("{n} вопросов ждут тебя"), waitingRunners: m("{n} раннеров ждут тебя") }; /** Left panel on desktop; on phones a top bar plus a bottom tab bar (PEP-38): sections with «ждут тебя» counters, theme, user. */ export function Sidebar({ login, avatarUrl, counts, superadmin = false }: { login: string; avatarUrl: string | null; counts: Record<"questions" | "waitingRunners", number>; superadmin?: boolean }) { const path = usePathname(); + const t = useT(); return (
- фабрика + {t("фабрика")} {/* PEP-52: the palette listens for clicks on [data-open-palette]. */}