Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
feat(desktop): translate the desktop shell into Simplified Chinese
Kilyne127a907e7d4
diff --git a/apps/desktop/AGENTS.md b/apps/desktop/AGENTS.mdindex 9107a16c..dbb8393a 100644--- a/apps/desktop/AGENTS.md+++ b/apps/desktop/AGENTS.md@@ -349,6 +349,30 @@ Gateway and runs Agents. The daemon exits with the app.`voiceWindow` keeps the in-page windows.- `src/shell/*.html`: app-owned pages (title bar, offline/setup page). Theyhave no network access and talk to the main process via `src/preload/shell.ts`.+ Their text lives in the `*.messages.ts` beside them; the main process+ serves each page through `localizePage` (`src/i18n/page.ts`), which adds the+ page's messages in the current language and the small runtime in+ `src/shell/messages.html` (`t`, `tSpans`, and `data-t` / `data-t-<attribute>`+ fill-in). Markup carries message names, never English or translated text.+- `src/i18n`: the shell's languages (English and Simplified Chinese) on the+ shared core `@linger/service-kit/messages`. `language.ts` matches a language+ and formats messages; `locales/zh-CN.json` is the shell's Chinese catalog,+ one namespace per `*.messages.ts`, following the Web glossary+ (`apps/web/src/i18n/locales/zh-CN.glossary.md`). `catalog.test.ts` finds+ every `*.messages.ts` and fails on a missing or extra translation, a changed+ placeholder or tag, or a page naming a message it lacks.+- `src/main/language.ts`: Language. The shell follows the language picked in+ the Web client's Settings, which the SPA reports (`language.set`) once a+ choice is stored; the main process keeps it in its config. Before any+ choice it follows the system's preferred languages (Simplified Chinese for+ `zh`, `zh-CN`, `zh-Hans-*`; English otherwise). A change emits+ `language.changed`: the tray menu and status rebuild, the title bar reloads,+ and the offline page takes it on its next load. The setup page takes the+ language when it opens; it runs before the SPA has ever reported one, so it+ uses the stored choice or the system's language. Main-process text (menus,+ dialogs, notifications) uses `Language.t` with the messages in+ `src/main/*.messages.ts`; a message missing from the catalog shows in+ English. Errors from transfers and servers stay in English.- `src/preload/index.ts`: the only SPA API, `window.lingerDesktop`. Its`update` reads the Updater's state (without the release page URL) and runsthe tray's install and check, for the SPA's account menu.diff --git a/apps/desktop/src/i18n/catalog.test.ts b/apps/desktop/src/i18n/catalog.test.tsnew file mode 100644index 00000000..f93f7cda--- /dev/null+++ b/apps/desktop/src/i18n/catalog.test.ts@@ -0,0 +1,142 @@+import { readdirSync, readFileSync } from "node:fs";+import path from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++import type { Message, MessageSource } from "@linger/service-kit/messages";+import { describe, expect, it } from "vitest";++import { offlineMessages } from "../shell/offline.messages.js";+import { setupMessages } from "../shell/setup.messages.js";+import { titlebarMessages } from "../shell/titlebar.messages.js";+import { LANGUAGES, SOURCE_LANGUAGE, catalogFor } from "./language.js";++const SRC = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");++// Every namespace of the shell, found by file name so that a new+// `*.messages.ts` is checked without being listed here.+const messageFiles = (directory: string): string[] =>+ readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {+ const file = path.join(directory, entry.name);+ if (entry.isDirectory()) return messageFiles(file);+ return entry.name.endsWith(".messages.ts") ? [file] : [];+ });++const source = new Map<string, MessageSource>();+for (const file of messageFiles(SRC)) {+ const exports = (await import(pathToFileURL(file).href)) as Record<+ string,+ Record<string, Message>+ >;+ for (const messages of Object.values(exports))+ for (const message of Object.values(messages)) {+ if (source.has(message.id))+ throw new Error(`Two messages are named ${message.id}`);+ source.set(message.id, message.source);+ }+}++const forms = (text: MessageSource): string[] =>+ typeof text === "string" ? [text] : Object.values(text);++const names = (text: MessageSource, pattern: RegExp): string =>+ [+ ...new Set(+ forms(text).flatMap((form) =>+ [...form.matchAll(pattern)].map((match) => match[1]!),+ ),+ ),+ ]+ .sort()+ .join();++const placeholder = /\{(\w+)\}/gu;+const openingTag = /<(\w+)>/gu;+const span = /<(\w+)>.*?<\/\1>/gsu;++describe("desktop message catalogs", () => {+ it("finds the message modules of the shell", () => {+ expect(source.size).toBeGreaterThan(0);+ for (const id of source.keys()) expect(id.split(".")).toHaveLength(2);+ });++ describe.each(LANGUAGES.filter((language) => language !== SOURCE_LANGUAGE))(+ "%s",+ (language) => {+ const translated = new Map<string, MessageSource>(+ Object.entries(catalogFor(language) ?? {}).flatMap(+ ([namespace, messages]) =>+ Object.entries(messages).map(+ ([name, text]) => [`${namespace}.${name}`, text] as const,+ ),+ ),+ );++ it("translates every English message", () => {+ expect([...source.keys()].filter((id) => !translated.has(id))).toEqual(+ [],+ );+ });++ it("has no translation without an English message", () => {+ expect([...translated.keys()].filter((id) => !source.has(id))).toEqual(+ [],+ );+ });++ it("keeps the placeholders and tags of each message", () => {+ const different = [...translated]+ .filter(([id]) => source.has(id))+ .filter(([id, text]) => {+ const english = source.get(id)!;+ return (+ names(text, placeholder) !== names(english, placeholder) ||+ names(text, openingTag) !== names(english, openingTag) ||+ forms(text).some(+ (form) =>+ (form.match(openingTag) ?? []).length !==+ (form.match(span) ?? []).length,+ )+ );+ })+ .map(([id]) => id);+ expect(different).toEqual([]);+ });++ it("gives plural messages the forms the language uses", () => {+ const categories = [+ ...new Intl.PluralRules(language).resolvedOptions().pluralCategories,+ ]+ .sort()+ .join();+ const wrong = [...translated]+ .filter(([id]) => source.has(id))+ .filter(([id, text]) => {+ const plural = typeof source.get(id) !== "string";+ if (typeof text === "string") return plural;+ return !plural || Object.keys(text).sort().join() !== categories;+ })+ .map(([id]) => id);+ expect(wrong).toEqual([]);+ });+ },+ );+});++// A page names its messages in markup and script; a name the page's+// namespace lacks would show as the bare name.+describe.each([+ ["setup.html", setupMessages],+ ["offline.html", offlineMessages],+ ["titlebar.html", titlebarMessages],+] as const)("%s", (file, messages) => {+ const page = readFileSync(path.join(SRC, "shell", file), "utf8");+ const named = [+ ...page.matchAll(/\bdata-t(?:-[\w-]+)?="(\w+)"/gu),+ ...page.matchAll(/\b(?:t|tSpans|tHtml)\(\s*"(\w+)"/gu),+ ].map((match) => match[1]!);++ it("names only messages of its namespace", () => {+ expect(named.length).toBeGreaterThan(0);+ expect(named.filter((name) => !(name in messages))).toEqual([]);+ });+});diff --git a/apps/desktop/src/i18n/language.test.ts b/apps/desktop/src/i18n/language.test.tsnew file mode 100644index 00000000..a4420b2a--- /dev/null+++ b/apps/desktop/src/i18n/language.test.ts@@ -0,0 +1,42 @@+import { defineMessages } from "@linger/service-kit/messages";+import { describe, expect, it } from "vitest";++import { trayMessages } from "../main/tray.messages.js";+import { matchLanguage, translator } from "./language.js";+import zhCN from "./locales/zh-CN.json" with { type: "json" };++describe("matchLanguage", () => {+ it("picks the first preferred language the shell speaks", () => {+ expect(matchLanguage(["zh-CN", "en-US"])).toBe("zh-CN");+ expect(matchLanguage(["fr-FR", "zh-Hans-SG", "en"])).toBe("zh-CN");+ expect(matchLanguage(["en-GB", "zh-CN"])).toBe("en");+ expect(matchLanguage(["zh"])).toBe("zh-CN");+ });++ it("keeps Traditional Chinese and unknown languages in English", () => {+ expect(matchLanguage(["zh-TW"])).toBe("en");+ expect(matchLanguage(["zh-Hant-HK"])).toBe("en");+ expect(matchLanguage(["fr", "de"])).toBe("en");+ expect(matchLanguage(["not a tag"])).toBe("en");+ expect(matchLanguage([])).toBe("en");+ });+});++describe("translator", () => {+ it("formats a message in the chosen language", () => {+ expect(translator("en")(trayMessages.quit)).toBe("Quit Linger");+ expect(translator("zh-CN")(trayMessages.quit)).toBe(zhCN.tray.quit);+ expect(+ translator("zh-CN")(trayMessages.downloading, { version: "1.2.0" }),+ ).toBe(zhCN.tray.downloading.replace("{version}", "1.2.0"));+ });++ it("falls back to English for a message the catalog lacks", () => {+ const messages = defineMessages("tray", {+ notInTheCatalog: "Only in English {name}",+ });+ expect(+ translator("zh-CN")(messages.notInTheCatalog, { name: "Linger" }),+ ).toBe("Only in English Linger");+ });+});diff --git a/apps/desktop/src/i18n/language.ts b/apps/desktop/src/i18n/language.tsnew file mode 100644index 00000000..b586a6ef--- /dev/null+++ b/apps/desktop/src/i18n/language.ts@@ -0,0 +1,63 @@+import {+ formatMessage,+ type Catalog,+ type Message,+ type MessageArguments,+} from "@linger/service-kit/messages";++import zhCN from "./locales/zh-CN.json" with { type: "json" };++/**+ * The languages the desktop shell is offered in. The tags are the Web+ * client's, which reports its choice with them; English is the source every+ * message is written in and the fallback.+ */+export const LANGUAGES = ["en", "zh-CN"] as const;++export type Language = (typeof LANGUAGES)[number];++export const SOURCE_LANGUAGE = "en" satisfies Language;++// The shell is one small bundle, so every catalog ships with it.+const CATALOGS: Record<Exclude<Language, typeof SOURCE_LANGUAGE>, Catalog> = {+ "zh-CN": zhCN,+};++export function catalogFor(language: Language): Catalog | undefined {+ return language === SOURCE_LANGUAGE ? undefined : CATALOGS[language];+}++/**+ * The first of `preferred` (BCP 47 tags, most wanted first) that the shell+ * speaks, compared by language and script, so `zh-Hans-SG` and `zh-CN` both+ * pick Simplified Chinese and `zh-TW` does not; English when none matches.+ */+export function matchLanguage(preferred: readonly string[]): Language {+ const key = (tag: string): string | undefined => {+ try {+ const locale = new Intl.Locale(tag).maximize();+ return `${locale.language}-${locale.script}`;+ } catch {+ return undefined;+ }+ };+ const offered = LANGUAGES.map((language) => [key(language), language]);+ for (const tag of preferred) {+ const wanted = key(tag);+ const match = offered.find(([offeredKey]) => offeredKey === wanted);+ if (wanted && match) return match[1] as Language;+ }+ return SOURCE_LANGUAGE;+}++/** Formats one message in a fixed language. */+export type Translate = <M extends Message>(+ message: M,+ ...values: MessageArguments<M["source"]>+) => string;++export function translator(language: Language): Translate {+ const catalog = catalogFor(language);+ return (message, ...values) =>+ formatMessage(message, language, catalog, values[0]);+}diff --git a/apps/desktop/src/i18n/locales/zh-CN.json b/apps/desktop/src/i18n/locales/zh-CN.jsonnew file mode 100644index 00000000..17e2e088--- /dev/null+++ b/apps/desktop/src/i18n/locales/zh-CN.json@@ -0,0 +1,347 @@+{+ "titlebar": {+ "back": "返回",+ "forward": "前进",+ "reload": "重新加载",+ "minimize": "最小化",+ "maximize": "最大化",+ "restore": "还原",+ "close": "关闭"+ },+ "offline": {+ "unreachableTitle": "无法连接服务器",+ "unreachable": "Linger 无法连接 <host>{host}</host>。请检查网络或 VPN,并确认服务器正在运行。",+ "tryAgain": "重试",+ "changeServer": "更换服务器",+ "showLogs": "查看日志",+ "saveDiagnostics": "保存诊断信息",+ "sendDiagnostics": "发送诊断信息",+ "setUpAgain": "重新设置",+ "serverAddress": "服务器地址",+ "serverHint": "你的团队 Linger 服务器的地址。",+ "invalidServer": "请输入以 http:// 或 https:// 开头的服务器地址",+ "connect": "连接",+ "cancel": "取消",+ "updatingTitle": "正在更新 Linger",+ "updating": "Linger 正在这台电脑上以新版本重新启动,大约需要一分钟。",+ "startingTitle": "正在启动 Linger",+ "starting": "Linger 正在这台电脑上启动,大约需要一分钟。",+ "failedTitle": "Linger 无法在这台电脑上启动",+ "setupTitle": "连接到 Linger",+ "setup": "输入你的团队服务器地址,然后登录。",+ "backToSetup": "返回设置",+ "retrying": "{seconds} 秒后重试"+ },+ "setup": {+ "pageTitle": "设置 Linger",+ "welcomeEyebrow": "仅限这台电脑",+ "welcomeTitle": "设置 Linger",+ "welcomeLeadLocal": "在这台电脑上运行,只为你服务。只需几分钟。",+ "welcomeLeadTeam": "将这台电脑连接到你的团队 Linger。",+ "modelSource": "模型来源",+ "modelSourceHint": "你的 Agent 从哪里获取模型。",+ "localModel": "本地模型",+ "subscription": "订阅",+ "byokTooltip": "自带密钥(Bring Your Own Key):通过 Linger 的本地 Bifrost 网关,连接你自己的 OpenAI 兼容或 Anthropic API 端点、密钥和模型。",+ "localModelToggle": "用本地模型运行任务",+ "aiRuntime": "AI Runtime",+ "runtimeHint": "负责运行你的任务。",+ "auto": "自动",+ "appIntegrations": "应用集成(可选)",+ "appIntegrationsHint": "Composio 用于连接应用;语音可在应用内开启。密钥只保存在这台电脑上。",+ "composioKey": "Composio API 密钥",+ "show": "显示",+ "hide": "隐藏",+ "remove": "移除",+ "keep": "保留",+ "installLocation": "安装位置",+ "changeLocation": "更改…",+ "quickInstall": "快速安装",+ "install": "安装",+ "getStarted": "开始使用",+ "customize": "自定义",+ "useDefaults": "使用默认设置",+ "checkAgain": "重新检查",+ "teamServer": "已有团队服务器?",+ "connectInstead": "改为连接到团队服务器",+ "downloadingTools": "正在下载安装工具…",+ "checkingComputer": "正在检查这台电脑…",+ "findingSetup": "正在为这台电脑寻找最合适的配置",+ "recommendedPlan": "推荐这台电脑使用:{plan}",+ "bestRuntime": "最合适的 AI Runtime",+ "localModelPi": "本地模型 + Pi",+ "cannotCheck": "无法检查这台电脑能否运行本地模型。",+ "fitsGpu": "适合 {gpu}",+ "fitsComputer": "适合这台电脑",+ "memoryAmount": "{size} 内存",+ "downloadAmount": "下载 {size}",+ "diskAmount": "{size} 磁盘",+ "memoryWithServices": "含服务共需 {size} 内存",+ "heldWhy": "本地模型暂缓安装。{reasons}可以用“快速安装”现在设置 {plan},或在内存空出后选择“重新检查”。",+ "keyRemovedOnInstall": "安装时移除",+ "keySaved": "已保存 · 输入以替换",+ "apiKey": "API 密钥",+ "keysNote": "在安装运行时生效。",+ "recommendedLocal": "推荐:在这台电脑上使用本地模型。",+ "recommendedSubscription": "推荐:订阅({runtime})。",+ "chooseSource": "选择你的 Agent 如何运行。",+ "localRecommended": "推荐这台电脑使用 · 通过 Bifrost 在 Pi 上运行",+ "localRuns": "通过 Pi 在这台电脑上运行你的任务",+ "localNotAvailable": "这台电脑无法使用",+ "recommendedRuntime": "推荐:{runtime}。",+ "subscriptionHint": "使用你的 ChatGPT 或 Claude 订阅登录。",+ "locationHint": "请返回,把安装位置设为磁盘本身(Linger 会安装到 {folder}),或磁盘根目录下的一个空文件夹。",+ "lessThanMinuteLeft": "剩余不到 1 分钟",+ "minutesLeft": "剩余约 {minutes} 分钟",+ "hoursLeft": "剩余约 {hours} 小时",+ "hoursMinutesLeft": "剩余约 {hours} 小时 {minutes} 分钟",+ "thisFile": "当前文件:{amount}",+ "amountOf": "{done} / {total}",+ "amountLeft": "剩余 {size}",+ "memoryCounts": "(可用 {free},需要 {needed})",+ "reasonGpuMemory": "其他程序正在占用 GPU 显存{counts}。请关闭使用 GPU 的程序,例如游戏、视频或其他 AI 应用。",+ "reasonGpuMemoryOf": "其他程序正在占用 GPU {gpu} 的显存{counts}。请关闭使用 GPU 的程序,例如游戏、视频或其他 AI 应用。",+ "reasonFreeMemory": "其他程序正在占用所需的内存{counts}。请关闭其他程序。",+ "reasonGpuSharing": "GPU 上正在运行其他工作,请将其关闭。",+ "reasonGpuOwnership": "Linger 无法判断哪些程序在使用 GPU,因此无法共享 GPU。请关闭使用 GPU 的程序。",+ "reasonFacts": "Linger 无法读取这台电脑的内存、磁盘或 GPU 信息。",+ "reasonCudaUpdate": "你的 NVIDIA 驱动支持 CUDA {has},但本地模型需要 CUDA {needs} 或更高版本。请更新 NVIDIA 驱动,然后选择“重新检查”。",+ "reasonCudaTooOldNeeds": "你的 NVIDIA 驱动版本过旧,无法运行本地模型(需要 CUDA {needs} 或更高版本)。请更新 NVIDIA 驱动,然后选择“重新检查”。",+ "reasonCudaTooOld": "你的 NVIDIA 驱动版本过旧,无法运行本地模型。请更新 NVIDIA 驱动,然后选择“重新检查”。",+ "reasonCudaUnknownNeeds": "Linger 无法从 NVIDIA 驱动读取 CUDA 版本(需要 CUDA {needs} 或更高版本)。请更新或重新安装 NVIDIA 驱动,然后选择“重新检查”。",+ "reasonCudaUnknown": "Linger 无法从 NVIDIA 驱动读取 CUDA 版本。请更新或重新安装 NVIDIA 驱动,然后选择“重新检查”。",+ "reasonUnsupported": "本地模型无法在这个系统上运行。",+ "reasonPlanHeld": "另一个应用(例如其他 AI 应用)正在占用所需的内存。请退出该应用。",+ "reasonPlanUnavailable": "没有适合这台电脑的本地模型。",+ "reasonHeld": "其他程序正在占用所需的内存。请关闭其他程序。",+ "reasonUnavailable": "这台电脑现在无法运行本地模型。",+ "heldGpu": "暂缓:GPU 可用 {free},需要 {needed}",+ "heldGpuOf": "暂缓:GPU {gpu} 可用 {free},需要 {needed}",+ "heldMemory": "暂缓:可用内存 {free},需要 {needed}",+ "heldClose": "暂缓:请关闭其他程序,然后重新检查。",+ "pathMostProviders": "大多数服务商",+ "pathZhipu": "智谱 GLM(base https://open.bigmodel.cn)",+ "pathVolcano": "火山引擎方舟",+ "pathNone": "无路径,Base URL 已包含路径。",+ "endpointNone": "无端点,Base URL 即完整地址。",+ "noAnswer": "Linger 没有响应。",+ "showSuggestions": "显示 {field} 建议",+ "baseUrl": "Base URL",+ "baseUrlPlaceholder": "Base URL(https://…)",+ "apiKeyPlaceholder": "API 密钥(仅保存在这台电脑上)",+ "listModels": "列出模型",+ "listingModels": "正在列出模型",+ "test": "测试",+ "testing": "正在测试…",+ "path": "路径",+ "pathHeading": "路径 · 可选",+ "endpoint": "端点",+ "endpointHeading": "端点 · 可选",+ "defaultTag": "默认",+ "runtimeDefault": "{runtime} 默认值",+ "model": "模型",+ "modelPlaceholder": "模型 ID(例如 gpt-5.4 或 claude-sonnet-4-6)",+ "modelsHint": "点击刷新按钮列出端点上的模型,或直接输入 ID。",+ "listingFrom": "正在从 <url>{url}</url> 列出模型…",+ "modelsFrom": {+ "other": "<url>{url}</url> 上有 {count} 个模型"+ },+ "contextSize": "{size} 上下文",+ "connected": "已连接",+ "couldNotConnect": "无法连接",+ "dismiss": "关闭",+ "invalidParts": "路径和端点必须留空,或填写类似 /v1 的路径。",+ "greyDefaults": "灰色值为默认值。路径和端点是可选的。",+ "sendsTo": "向 <url>{url}</url> 发送 {format} 请求",+ "sendsToRuntime": "向 <url>{url}</url> 发送 {format}({runtime} 格式)请求",+ "installingTitle": "正在安装 Linger",+ "installStopped": "安装已停止",+ "startingLinger": "正在启动 Linger",+ "preparingUpdate": "正在更新这台电脑上的 Linger…",+ "preparingStart": "正在这台电脑上启动 Linger…",+ "dataKept": "你的数据已保留。解决问题后请重试。",+ "takesMinutes": "这需要几分钟,你可以继续工作。",+ "stepPrepare": "检查这台电脑",+ "stepDownload": "下载 Linger {version}",+ "stepServices": "设置 AI 和本地服务",+ "stepWorkspace": "设置你的账号",+ "stepSignIn": "登录 {runtime}",+ "stepSignInRuntime": "登录你的 AI Runtime",+ "stepConnect": "连接这台电脑",+ "stepAgents": "准备你的 Agent",+ "stepRunning": "正在{step}…",+ "showDetails": "显示详情",+ "hideDetails": "隐藏详情",+ "showLogs": "查看日志",+ "saveDiagnostics": "保存诊断信息",+ "sendDiagnostics": "发送诊断信息",+ "savedDiagnostics": "已保存 {file}。请把这个文件发给 Linger 支持团队。",+ "back": "返回",+ "tryAgain": "重试",+ "signInTo": "登录 {runtime}",+ "signInLeadPi": "Pi 需要一个模型服务商。在终端中运行 pi 登录,或使用下方的 BYOK;设置会自动继续。",+ "signInLeadCodex": "你的 Agent 运行在 Codex 上。请用你的 ChatGPT 账号授权后继续。",+ "signInLeadClaude": "你的 Agent 运行在 Claude Code 上。请用你的 Claude 账号授权后继续。",+ "signInWaiting": "正在等待你在浏览器中授权…",+ "deviceCode": "在浏览器中输入这个代码:",+ "signInFailed": "登录未完成。",+ "authorize": "授权",+ "retry": "重试",+ "otherRuntime": "使用其他 Runtime",+ "byokInstead": "改用 BYOK",+ "continueWithByok": "使用 BYOK 继续",+ "openBrowserAgain": "重新打开浏览器",+ "cancel": "取消",+ "havingTrouble": "遇到问题?",+ "signInHelpCode": "如果浏览器没有打开,请选择“重新打开浏览器”,然后粘贴页面上显示的代码。",+ "signInHelp": "如果浏览器没有打开,请选择“重新打开浏览器”。",+ "pastedCode": "登录页面上的代码",+ "pasteCode": "粘贴代码",+ "continue": "继续",+ "filesToSend": "要发送的文件",+ "reportId": "报告 ID",+ "sendPreparing": "正在准备诊断信息",+ "sendConfirm": "将诊断信息发送到 {host}?",+ "sendSending": "正在发送诊断信息",+ "sendSent": "诊断信息已发送",+ "sendFailed": "无法发送诊断信息",+ "sendCollecting": "正在收集日志和设置…",+ "sendConfirmLead": {+ "other": "{count} 个文件,共 {size}:这个应用和这台电脑上 Linger 的日志与设置。密码、令牌、密钥和你的主文件夹路径会先被移除;凭据文件和你的数据永远不会包含在内。只有运营 {host} 的人员能读取这份报告。"+ },+ "sendUploading": "正在上传到 {host}… {percent}%",+ "sendSentLead": "把这个报告 ID 告诉 Linger 支持团队,方便他们找到你的报告。",+ "sendByHand": "你仍然可以使用“保存诊断信息”,然后手动发送文件。",+ "send": "发送",+ "copyReportId": "复制报告 ID",+ "copied": "已复制",+ "done": "完成",+ "close": "关闭",+ "readyTitle": "Linger 已就绪",+ "readyLead": "在这台电脑上运行,只为你服务。",+ "computerConnected": "这台电脑已连接",+ "accountTitle": "你在这台电脑上的账号",+ "email": "邮箱",+ "password": "密码",+ "copy": "复制",+ "showPassword": "显示密码",+ "hidePassword": "隐藏密码",+ "copyPassword": "复制密码",+ "accountNote": "退出登录后可以用这些信息重新登录。",+ "accountReveal": "打开账号文件所在位置",+ "legacyNote": "旧版 Simplex 应用中的数据无法升级到 Linger,因此这是一个全新的工作区。旧数据已移动到 {folder},并未删除。",+ "openLinger": "打开 Linger",+ "stepOf": "第 {step} 步,共 {total} 步",+ "serverTitle": "你的团队 Linger 在哪里?",+ "serverLead": "输入你的团队使用的 Linger 地址。",+ "serverAddress": "服务器地址",+ "serverHint": "不确定的话,请询问你的管理员。",+ "signInTitle": "登录你的账号",+ "signInLead": "Linger 会在单独的窗口中打开。在那里登录后,这个窗口会自动继续。",+ "account": "账号",+ "signedIn": "已登录",+ "waiting": "正在等待…",+ "notSignedIn": "未登录",+ "openSignIn": "打开登录页",+ "connectTitle": "连接这台电脑",+ "connectLead": "你的工作区将能看到这台电脑,并可以向它发送任务。你可以随时断开连接。",+ "connect": "连接",+ "connecting": "正在连接…",+ "permissionsTitle": "几项权限",+ "changeLaterMenuBar": "之后可以在菜单栏或系统设置中更改这些选项。",+ "changeLaterTray": "之后可以在系统托盘或系统设置中更改这些选项。",+ "notifications": "通知",+ "notificationsHint": "任务完成或需要你处理时通知你。",+ "allowNotifications": "允许通知",+ "testSent": "已发送测试通知",+ "folders": "文件夹",+ "foldersHint": "任务可以读取和修改的文件夹。",+ "addFolder": "添加文件夹…",+ "fullDiskAccess": "完全磁盘访问权限",+ "fullDiskAbout": "推荐。涵盖所有文件夹,不再弹出提示。",+ "fullDiskMissing": "未开启。首次访问受保护的文件夹时会弹出提示。",+ "userFolders": "下载、文稿、桌面",+ "userFoldersAbout": "允许任务读取这些文件夹。",+ "userFoldersMissing": "未允许。任务无法读取这些文件夹。",+ "automation": "控制其他应用",+ "automationAbout": "允许任务操作浏览器等应用。",+ "automationMissing": "未允许。任务无法控制其他应用。",+ "allowed": "已允许",+ "openSettings": "打开设置",+ "allow": "允许…",+ "preventSleep": "防止休眠",+ "preventSleepHint": "让这台电脑保持唤醒,以便接收任务。",+ "openAtLogin": "登录时打开",+ "openAtLoginMenuBar": "登录系统时在菜单栏中启动。",+ "openAtLoginTray": "登录系统时在系统托盘中启动。",+ "startUsing": "开始使用 Linger"+ },+ "status": {+ "notConnected": "未连接",+ "signInExpired": "登录已过期 · 请重新连接这台电脑",+ "identityConflict": "电脑身份冲突 · 请重新连接这台电脑",+ "updateRequired": "需要更新",+ "runtimeError": "Runtime 出错 · 正在重启",+ "starting": "正在启动…",+ "offline": "离线 · 正在重新连接",+ "running": {+ "other": "正在运行 {count} 个任务"+ },+ "idle": "在线 · 空闲"+ },+ "tray": {+ "tooltip": "Linger · {status}",+ "open": "打开 Linger",+ "reconnect": "重新连接这台电脑",+ "connect": "连接这台电脑…",+ "preventSleep": "防止休眠",+ "showLogs": "查看日志",+ "saveDiagnostics": "保存诊断信息…",+ "sendDiagnostics": "发送诊断信息…",+ "quit": "退出 Linger",+ "downloading": "正在下载更新 {version}…",+ "restartToUpdate": "重启以更新({version})",+ "waiting": "任务完成后将更新到 {version}",+ "download": "下载 Linger {version}…",+ "updateFailed": "更新失败:{reason}",+ "tryUpdatingAgain": "重新尝试更新",+ "availableTitle": "有可用更新",+ "available": "Linger {version} 已发布。点击打开下载页面。",+ "readyTitle": "更新已就绪",+ "ready": "Linger {version} 已下载。点击重启 Linger 完成更新。",+ "signInFirst": "请先登录",+ "signInFirstDetail": "请先在窗口中登录 Linger,然后再次选择“连接这台电脑”。",+ "enrollFailed": "无法连接这台电脑"+ },+ "dialogs": {+ "quitConfirm": "退出 Linger 并停止正在运行的任务?",+ "quitConfirmDetail": "在你重新打开 Linger 之前,来自手机或网页的任务都无法在这台电脑上运行。",+ "quitAndStop": "退出并停止任务",+ "cancel": "取消",+ "startFailed": "Linger 启动失败:{error}",+ "setupTitle": "设置 Linger",+ "chooseInstallFolder": "选择 Linger 的安装位置",+ "choose": "选择",+ "notificationsOnTitle": "通知已开启",+ "notificationsOn": "有任务需要你处理时,Linger 会在这里通知你。",+ "sendConsent": "将诊断信息发送到 {host}?",+ "sendConsentFiles": {+ "other": "{count} 个文件,共 {size}:这个应用和这台电脑上 Linger 的日志与设置。"+ },+ "sendConsentRedacted": "密码、令牌、密钥和你的主文件夹路径会先被移除;凭据文件和你的数据永远不会包含在内。",+ "sendConsentReaders": "只有运营 {host} 的人员能读取这份报告。",+ "sendConsentMore": "以及另外 {count} 个",+ "send": "发送",+ "sent": "诊断信息已发送",+ "sentDetail": "报告 ID:{reportId}\n把这个 ID 告诉 Linger 支持团队,方便他们找到你的报告。",+ "copyReportId": "复制报告 ID",+ "done": "完成",+ "sendFailed": "无法发送诊断信息",+ "sendFailedSave": "你仍然可以使用“保存诊断信息”,然后手动发送文件。",+ "tryAgain": "重试",+ "close": "关闭",+ "sendBusy": "诊断信息正在发送中",+ "sendBusyDetail": "请在 Linger 设置窗口中完成或取消那份报告。",+ "ok": "好"+ }+}diff --git a/apps/desktop/src/i18n/page.test.ts b/apps/desktop/src/i18n/page.test.tsnew file mode 100644index 00000000..2080cb31--- /dev/null+++ b/apps/desktop/src/i18n/page.test.ts@@ -0,0 +1,110 @@+// @vitest-environment jsdom+import { readFileSync } from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";++import { defineMessages } from "@linger/service-kit/messages";+import { describe, expect, it } from "vitest";++import { offlineMessages } from "../shell/offline.messages.js";+import zhCN from "./locales/zh-CN.json" with { type: "json" };+import { localizePage } from "./page.js";++const runtime = readFileSync(+ path.join(+ path.dirname(fileURLToPath(import.meta.url)),+ "../shell/messages.html",+ ),+ "utf8",+);++const messages = {+ ...offlineMessages,+ ...defineMessages("offline", {+ onlyInEnglish: "Only in English",+ files: { one: "{count} file", other: "{count} files" },+ }),+};++const PAGE = `<!doctype html>+<html lang="en">+ <head><title data-t="unreachableTitle"></title></head>+ <body>+ <button data-t="tryAgain" data-t-title="changeServer"></button>+ <input data-t-placeholder="serverAddress" />+ <p id="english" data-t="onlyInEnglish"></p>+ <p id="reason"></p>+ <script>+ document.getElementById("reason").replaceChildren(+ ...tSpans("unreachable", { host: "<b>linger.example.com</b>" }),+ );+ window.result = {+ retrying: t("retrying", { seconds: 1200 }),+ one: t("files", { count: 1 }),+ many: t("files", { count: 3 }),+ };+ </script>+ </body>+</html>`;++// Runs a localized page in this document the way a shell window would.+const load = (language: "en" | "zh-CN") => {+ const html = localizePage(PAGE, runtime, messages, language);+ document.documentElement.innerHTML = html;+ document.documentElement.lang = /<html lang="([^"]+)"/u.exec(html)![1]!;+ const scripts = [...document.querySelectorAll("script:not([type])")];+ for (const script of scripts) new Function(script.textContent!)();+ return (window as unknown as { result: Record<string, string> }).result;+};++describe("localizePage", () => {+ it("fills the page in English", () => {+ const result = load("en");+ expect(document.documentElement.lang).toBe("en");+ expect(document.title).toBe("Can't reach the server");+ const button = document.querySelector("button")!;+ expect(button.textContent).toBe("Try Again");+ expect(button.title).toBe("Change Server");+ expect(document.querySelector("input")!.placeholder).toBe("Server address");+ expect(result).toEqual({+ retrying: "Retrying in 1,200s",+ one: "1 file",+ many: "3 files",+ });+ });++ it("fills the page in Chinese, English where the catalog has no message", () => {+ const result = load("zh-CN");+ expect(document.documentElement.lang).toBe("zh-CN");+ expect(document.title).toBe(zhCN.offline.unreachableTitle);+ expect(document.querySelector("button")!.textContent).toBe(+ zhCN.offline.tryAgain,+ );+ expect(document.getElementById("english")!.textContent).toBe(+ "Only in English",+ );+ expect(result.retrying).toBe(+ zhCN.offline.retrying.replace("{seconds}", "1,200"),+ );+ // English plural rules for the English fallback.+ expect(result.one).toBe("1 file");+ });++ it("makes spans from the message only, never from a value", () => {+ load("en");+ const reason = document.getElementById("reason")!;+ const host = reason.querySelector("span.host")!;+ expect(host.textContent).toBe("<b>linger.example.com</b>");+ expect(reason.querySelector("b")).toBeNull();+ });++ it("keeps text from closing the message block", () => {+ const html = localizePage(+ PAGE,+ runtime,+ defineMessages("offline", { tryAgain: "</script><script>alert(1)" }),+ "en",+ );+ expect(html).not.toContain("</script><script>alert(1)");+ });+});diff --git a/apps/desktop/src/i18n/page.ts b/apps/desktop/src/i18n/page.tsnew file mode 100644index 00000000..4f34f291--- /dev/null+++ b/apps/desktop/src/i18n/page.ts@@ -0,0 +1,48 @@+import { resolveMessage, type Message } from "@linger/service-kit/messages";++import { catalogFor, type Language } from "./language.js";++const SCRIPT = /<script>([\s\S]*?)<\/script>/u;++/**+ * A shell page in `language`. The pages are static HTML with one inline+ * script and no bundler, so the main process hands each its messages as a+ * JSON block, each already resolved to the language it is in (English for a+ * message the catalog lacks), and puts the page side of the lookup+ * (`runtime`, the script of `src/shell/messages.html`) in front of the+ * page's script. The page then only picks plural forms and fills+ * placeholders, with the same rules as `formatMessage`.+ */+export function localizePage(+ page: string,+ runtime: string,+ messages: Readonly<Record<string, Message>>,+ language: Language,+): string {+ const catalog = catalogFor(language);+ const resolved = Object.fromEntries(+ Object.entries(messages).map(([name, message]) => {+ const { language: shown, text } = resolveMessage(+ message,+ language,+ catalog,+ );+ return [name, [shown, text]];+ }),+ );+ // "<" escaped keeps any text from closing the JSON block.+ const data = JSON.stringify({ language, messages: resolved }).replace(+ /</gu,+ "\\u003c",+ );+ const lookup = SCRIPT.exec(runtime)?.[1];+ if (lookup === undefined || !SCRIPT.test(page))+ throw new Error("A shell page and its message runtime need a <script>");+ return page+ .replace(/<html lang="[^"]*"/u, `<html lang="${language}"`)+ .replace(+ SCRIPT,+ (_match, script: string) =>+ `<script type="application/json" id="linger-messages">${data}</script>\n <script>${lookup}${script}</script>`,+ );+}diff --git a/apps/desktop/src/main/config.ts b/apps/desktop/src/main/config.tsindex 5671c9e6..6bd5e1bd 100644--- a/apps/desktop/src/main/config.ts+++ b/apps/desktop/src/main/config.ts@@ -4,6 +4,7 @@ import path from "node:path";import { z } from "zod";+import { LANGUAGES } from "../i18n/language.js";import { isUploadUrl } from "./diagnostics-upload.js";const workspaceGrant = z.object({@@ -38,6 +39,10 @@ const desktopConfig = z.object({// or server switch renews the same Computer ID for the same account.savedEnrollments: z.record(z.string(), savedEnrollment).optional(),workspaceGrants: z.array(workspaceGrant).default([]),+ // The language the Web client last chose, which the shell's own text+ // follows; unset until the person chooses one (language.ts). A value+ // this version does not offer is dropped, not the whole file.+ language: z.enum(LANGUAGES).optional().catch(undefined),// Always-on mode: keep the system awake even when idle.preventSleep: z.boolean().default(false),// macOS permissions whose system prompt was shown once.diff --git a/apps/desktop/src/main/desktop-ipc.test.ts b/apps/desktop/src/main/desktop-ipc.test.tsindex b58c28b4..d80dcf11 100644--- a/apps/desktop/src/main/desktop-ipc.test.ts+++ b/apps/desktop/src/main/desktop-ipc.test.ts@@ -19,6 +19,7 @@ vi.mock("electron", () => ({}));const { DesktopIpcModule } = await import("./desktop-ipc.js");+const { LanguageModule } = await import("./language.js");const { EventBus } = await import("./modules.js");const { stubModule, testHost } = await import("./test-support.js");@@ -50,8 +51,11 @@ const fixture = async (show: vi.fn(),};const bus = new EventBus();+ const language = new LanguageModule({ systemLanguages: () => ["en-US"] });const host = testHost([+ stubModule("Config"),+ language,stubModule("Enrollment"),stubModule("PowerGuard"),stubModule("ComputerDaemon"),@@ -65,13 +69,23 @@ const fixture = async (bus,);await host.start();- const invoke = (channel: string, origin = SERVER) =>- handlers.get(channel)!({ senderFrame: { origin } });+ const invoke = (channel: string, origin = SERVER, ...args: unknown[]) =>+ handlers.get(channel)!({ senderFrame: { origin } }, ...args);const setUpdate = (state: UpdateState) => {updateState = state;bus.emit("update.changed", state.kind);};- return { host, local, updater, send, setUpdate, invoke, windows };+ return {+ host,+ bus,+ language,+ local,+ updater,+ send,+ setUpdate,+ invoke,+ windows,+ };};afterEach(() => handlers.clear());@@ -198,3 +212,29 @@ describe("DesktopIpcModule updates", () => {await f.host.stop("quit");});});++describe("DesktopIpcModule language", () => {+ it("keeps the page's choice and tells the shell once it changes", async () => {+ const f = await fixture();+ const changed = vi.fn();+ f.bus.on("language.changed", changed);+ expect(f.language.current()).toBe("en");+ await f.invoke(IPC.languageSet, SERVER, "zh-CN");+ expect(f.language.current()).toBe("zh-CN");+ expect(changed).toHaveBeenCalledExactlyOnceWith("zh-CN");+ // The page reports its language on every load; the same one is no news.+ await f.invoke(IPC.languageSet, SERVER, "zh-CN");+ expect(changed).toHaveBeenCalledOnce();+ await f.host.stop("quit");+ });++ it("accepts only the languages the shell speaks, from the server's page", async () => {+ const f = await fixture();+ expect(() => f.invoke(IPC.languageSet, SERVER, "fr")).toThrow();+ expect(() =>+ f.invoke(IPC.languageSet, "https://evil.example.com", "zh-CN"),+ ).toThrow("Not allowed");+ expect(f.language.current()).toBe("en");+ await f.host.stop("quit");+ });+});diff --git a/apps/desktop/src/main/desktop-ipc.ts b/apps/desktop/src/main/desktop-ipc.tsindex 7fbd0a23..ca7e5998 100644--- a/apps/desktop/src/main/desktop-ipc.ts+++ b/apps/desktop/src/main/desktop-ipc.ts@@ -9,10 +9,12 @@ import {type LocalAccountSignIn,type WorkspaceGrantView,} from "../shared/api.js";+import { LANGUAGES } from "../i18n/language.js";import type { ComputerDaemonModule } from "./computer-daemon.js";import type { WorkspaceGrant } from "./config.js";import { ConnectorOAuth } from "./connector-oauth.js";import type { EnrollmentModule } from "./enrollment.js";+import type { LanguageModule } from "./language.js";import type { LocalServerModule } from "./local-server.js";import type { Module, ModuleContext } from "./modules.js";import { sameOrigin } from "./navigation.js";@@ -26,6 +28,7 @@ import type { WindowManagerModule } from "./window-manager.js";import type { WorkspaceGrantsModule } from "./workspace-grants.js";const grantIdInput = z.string().min(1).max(128);+const languageInput = z.enum(LANGUAGES);// The server address is not settable from the SPA: a page served by one// server must not be able to repoint the app. It changes on app://offline.const settingsPatchInput = z@@ -74,6 +77,7 @@ export class DesktopIpcModule implements Module {"WindowManager","WorkspaceGrants","Updater",+ "Language",];readonly #defaultDisplayName: string;// Set on macOS only.@@ -96,6 +100,7 @@ export class DesktopIpcModule implements Module {const power = ctx.get<PowerGuardModule>("PowerGuard");const localServer = ctx.get<LocalServerModule>("LocalServer");const updater = ctx.get<UpdaterModule>("Updater");+ const language = ctx.get<LanguageModule>("Language");const oauth = new ConnectorOAuth();ipcMain.handle(IPC.connectorOAuthPrepare, (event: IpcMainInvokeEvent) => {@@ -203,6 +208,10 @@ export class DesktopIpcModule implements Module {windows.show();if (process.platform === "darwin") app.focus({ steal: true });});+ // The language picked in the page's Settings, for the shell's own text.+ handle(IPC.languageSet, (tag) => {+ language.choose(languageInput.parse(tag));+ });handle(IPC.updateState, () => updateView(updater.state()));handle(IPC.updateInstall, () => updater.install());handle(IPC.updateCheck, () => updater.check());diff --git a/apps/desktop/src/main/diagnostics-dialogs.ts b/apps/desktop/src/main/diagnostics-dialogs.tsindex 5b0282a3..191a80df 100644--- a/apps/desktop/src/main/diagnostics-dialogs.ts+++ b/apps/desktop/src/main/diagnostics-dialogs.ts@@ -5,11 +5,14 @@ import {type MessageBoxOptions,} from "electron";+import type { Translate } from "../i18n/language.js";+import { dialogMessages as m } from "./dialogs.messages.js";import { consentText, type DiagnosticsPrompts } from "./diagnostics-upload.js";// Send Diagnostics' native dialogs for the tray and the start failure page.export const diagnosticsDialogs = (window: () => BaseWindow | undefined,+ t: Translate,): DiagnosticsPrompts => {const show = async (options: MessageBoxOptions): Promise<number> => {const parent = window();@@ -22,17 +25,17 @@ export const diagnosticsDialogs = (consent: async (state) =>(await show({type: "question",- ...consentText(state),- buttons: ["Send", "Cancel"],+ ...consentText(state, t),+ buttons: [t(m.send), t(m.cancel)],defaultId: 0,cancelId: 1,})) === 0,sent: async (state) => {const copy = await show({type: "info",- message: "Diagnostics sent",- detail: `Report ID: ${state.reportId}\nGive this ID to Linger support so they can find your report.`,- buttons: ["Copy Report ID", "Done"],+ message: t(m.sent),+ detail: t(m.sentDetail, { reportId: state.reportId }),+ buttons: [t(m.copyReportId), t(m.done)],defaultId: 0,cancelId: 1,});@@ -41,20 +44,20 @@ export const diagnosticsDialogs = (failed: async (state) =>(await show({type: "warning",- message: "Couldn't send diagnostics",+ message: t(m.sendFailed),detail: state.retry? state.error- : `${state.error}\nYou can still use Save Diagnostics and send the file by hand.`,- buttons: state.retry ? ["Try Again", "Close"] : ["Close"],+ : `${state.error}\n${t(m.sendFailedSave)}`,+ buttons: state.retry ? [t(m.tryAgain), t(m.close)] : [t(m.close)],defaultId: 0,cancelId: state.retry ? 1 : 0,})) === 0 && state.retry,busy: async () => {await show({type: "info",- message: "Diagnostics are already being sent",- detail: "Finish or cancel that report in the Linger setup window.",- buttons: ["OK"],+ message: t(m.sendBusy),+ detail: t(m.sendBusyDetail),+ buttons: [t(m.ok)],});},};diff --git a/apps/desktop/src/main/diagnostics-upload.test.ts b/apps/desktop/src/main/diagnostics-upload.test.tsindex 5c021dd5..561e2b12 100644--- a/apps/desktop/src/main/diagnostics-upload.test.ts+++ b/apps/desktop/src/main/diagnostics-upload.test.ts@@ -26,6 +26,7 @@ import {type DiagnosticsPrompts,type PreparedDiagnostics,} from "./diagnostics-upload.js";+import { translator } from "../i18n/language.js";import { tempDirectory } from "./test-support.js";describe("isUploadUrl", () => {@@ -540,6 +541,7 @@ describe("consentText", () => {files: ["a", "b", "c"],bytes: 3 * 1024 * 1024,},+ translator("en"),2,);expect(text.message).toBe("Send diagnostics to diagnostics.example.com?");diff --git a/apps/desktop/src/main/diagnostics-upload.ts b/apps/desktop/src/main/diagnostics-upload.tsindex e2a43097..5d9047ca 100644--- a/apps/desktop/src/main/diagnostics-upload.ts+++ b/apps/desktop/src/main/diagnostics-upload.ts@@ -5,7 +5,9 @@ import https from "node:https";import { z } from "zod";+import type { Translate } from "../i18n/language.js";import type { SetupDiagnosticsSend } from "../shared/setup.js";+import { dialogMessages as m } from "./dialogs.messages.js";// Sends the diagnostics zip to a receiver that implements// docs/diagnostics-upload.md: one POST asks for a report id and a@@ -389,17 +391,23 @@ export const formatBytes = (bytes: number): string =>// start failure page; the setup page draws the same facts itself.export const consentText = (state: Extract<SetupDiagnosticsSend, { phase: "confirm" }>,+ t: Translate,shown = 12,): { readonly message: string; readonly detail: string } => {const files = state.files.slice(0, shown).map((file) => ` ${file}`);if (state.files.length > shown)- files.push(` and ${state.files.length - shown} more`);+ files.push(+ ` ${t(m.sendConsentMore, { count: state.files.length - shown })}`,+ );return {- message: `Send diagnostics to ${state.host}?`,+ message: t(m.sendConsent, { host: state.host }),detail: [- `${state.files.length} files, ${formatBytes(state.bytes)}: logs and settings of this app and of Linger on this computer.`,- "Passwords, tokens, keys and your home folder path are removed first; credential files and your data are never included.",- `Only the people who run ${state.host} can read the report.`,+ t(m.sendConsentFiles, {+ count: state.files.length,+ size: formatBytes(state.bytes),+ }),+ t(m.sendConsentRedacted),+ t(m.sendConsentReaders, { host: state.host }),"",...files,].join("\n"),diff --git a/apps/desktop/src/main/dialogs.messages.ts b/apps/desktop/src/main/dialogs.messages.tsnew file mode 100644index 00000000..3ce3a3bf--- /dev/null+++ b/apps/desktop/src/main/dialogs.messages.ts@@ -0,0 +1,40 @@+import { defineMessages } from "@linger/service-kit/messages";++// The main process's native dialogs, windows and notifications.+export const dialogMessages = defineMessages("dialogs", {+ quitConfirm: "Quit Linger and stop the running tasks?",+ quitConfirmDetail:+ "Until you open Linger again, tasks from your phone or the web can't run on this computer.",+ quitAndStop: "Quit and Stop Tasks",+ cancel: "Cancel",+ startFailed: "Linger failed to start: {error}",+ setupTitle: "Set Up Linger",+ chooseInstallFolder: "Choose Where to Install Linger",+ choose: "Choose",+ notificationsOnTitle: "Notifications are on",+ notificationsOn: "Linger will tell you here when a task needs you.",+ sendConsent: "Send diagnostics to {host}?",+ sendConsentFiles: {+ one: "{count} file, {size}: logs and settings of this app and of Linger on this computer.",+ other:+ "{count} files, {size}: logs and settings of this app and of Linger on this computer.",+ },+ sendConsentRedacted:+ "Passwords, tokens, keys and your home folder path are removed first; credential files and your data are never included.",+ sendConsentReaders: "Only the people who run {host} can read the report.",+ sendConsentMore: "and {count} more",+ send: "Send",+ sent: "Diagnostics sent",+ sentDetail:+ "Report ID: {reportId}\nGive this ID to Linger support so they can find your report.",+ copyReportId: "Copy Report ID",+ done: "Done",+ sendFailed: "Couldn't send diagnostics",+ sendFailedSave:+ "You can still use Save Diagnostics and send the file by hand.",+ tryAgain: "Try Again",+ close: "Close",+ sendBusy: "Diagnostics are already being sent",+ sendBusyDetail: "Finish or cancel that report in the Linger setup window.",+ ok: "OK",+});diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex 4d31186f..374a87b5 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -26,8 +26,10 @@ import {} from "./computer-daemon.js";import { ConfigStore } from "./config.js";import { DesktopIpcModule } from "./desktop-ipc.js";+import { dialogMessages } from "./dialogs.messages.js";import { DiagnosticsModule } from "./diagnostics.js";import { EnrollmentModule } from "./enrollment.js";+import { LanguageModule } from "./language.js";import {LocalServerModule,signInWithPassword,@@ -205,6 +207,9 @@ async function main(): Promise<void> {}: {}),});+ const language = new LanguageModule({+ systemLanguages: () => app.getPreferredSystemLanguages(),+ });const status = new StatusModule();// Set once the bundle was swapped, so quitting relaunches the new version.let relaunch = false;@@ -220,7 +225,7 @@ async function main(): Promise<void> {downloadDirectory: path.join(userData, "updates"),announce: (state) => {if (!Notification.isSupported()) return;- const notice = new Notification(updateNotice(state));+ const notice = new Notification(updateNotice(state, language.t));notice.on("click", () => void updater.install());notice.show();},@@ -266,6 +271,7 @@ async function main(): Promise<void> {start: async () => {},stop: async () => {},},+ language,new EnrollmentModule({defaultDisplayName,credentials,@@ -361,12 +367,14 @@ async function main(): Promise<void> {if (status.current().tone === "busy") {const { response } = await dialog.showMessageBox({type: "warning",- buttons: ["Quit and Stop Tasks", "Cancel"],+ buttons: [+ language.t(dialogMessages.quitAndStop),+ language.t(dialogMessages.cancel),+ ],defaultId: 1,cancelId: 1,- message: "Quit Linger and stop the running tasks?",- detail:- "Until you open Linger again, tasks from your phone or the web can't run on this computer.",+ message: language.t(dialogMessages.quitConfirm),+ detail: language.t(dialogMessages.quitConfirmDetail),});if (response !== 0) return;}@@ -384,7 +392,10 @@ async function main(): Promise<void> {});} catch (error) {log.error("desktop.start_failed", { error: String(error) });- dialog.showErrorBox("Linger", `Linger failed to start: ${String(error)}`);+ dialog.showErrorBox(+ "Linger",+ language.t(dialogMessages.startFailed, { error: String(error) }),+ );app.exit(1);}}diff --git a/apps/desktop/src/main/language.test.ts b/apps/desktop/src/main/language.test.tsnew file mode 100644index 00000000..a30dcdad--- /dev/null+++ b/apps/desktop/src/main/language.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it, vi } from "vitest";++import zhCN from "../i18n/locales/zh-CN.json" with { type: "json" };+import { LanguageModule } from "./language.js";+import { EventBus } from "./modules.js";+import { stubModule, testHost } from "./test-support.js";+import { trayMessages } from "./tray.messages.js";++const fixture = async (systemLanguages: string[], stored?: "en" | "zh-CN") => {+ const bus = new EventBus();+ const changed = vi.fn();+ bus.on("language.changed", changed);+ const language = new LanguageModule({+ systemLanguages: () => systemLanguages,+ });+ const host = testHost(+ [stubModule("Config"), language],+ stored ? { language: stored } : {},+ bus,+ );+ await host.start();+ return { language, host, changed };+};++describe("LanguageModule", () => {+ it("follows the system until the Web client reports a choice", async () => {+ const zh = await fixture(["zh-Hans-CN", "en-US"]);+ expect(zh.language.current()).toBe("zh-CN");+ expect(zh.language.t(trayMessages.quit)).toBe(zhCN.tray.quit);+ await zh.host.stop("quit");++ const other = await fixture(["fr-FR"]);+ expect(other.language.current()).toBe("en");+ expect(other.language.t(trayMessages.quit)).toBe("Quit Linger");+ await other.host.stop("quit");+ });++ it("keeps the choice over the system's languages", async () => {+ const f = await fixture(["zh-CN"], "en");+ expect(f.language.current()).toBe("en");+ await f.host.stop("quit");+ });++ it("announces a choice only when the shell's text changes", async () => {+ const f = await fixture(["zh-CN"]);+ // Choosing what the system already gave keeps the text as it is.+ f.language.choose("zh-CN");+ expect(f.changed).not.toHaveBeenCalled();+ f.language.choose("en");+ expect(f.changed).toHaveBeenCalledExactlyOnceWith("en");+ expect(f.language.current()).toBe("en");+ await f.host.stop("quit");+ });+});diff --git a/apps/desktop/src/main/language.ts b/apps/desktop/src/main/language.tsnew file mode 100644index 00000000..41dba0bc--- /dev/null+++ b/apps/desktop/src/main/language.ts@@ -0,0 +1,55 @@+import {+ matchLanguage,+ translator,+ type Language,+ type Translate,+} from "../i18n/language.js";+import type { Module, ModuleContext } from "./modules.js";++/**+ * The language of the shell's own text: menus, the tray, notifications,+ * dialogs and the shell pages. The choice is the Web client's: the page+ * reports it (desktop-ipc.ts) whenever the person picks one in Settings ›+ * Language, and it is kept in the desktop settings so the setup window,+ * which opens before any page loads, shows it too. Until a choice arrives+ * the shell follows the system's preferred languages, else English.+ */+export class LanguageModule implements Module {+ readonly name = "Language";+ readonly dependsOn = ["Config"];+ readonly #systemLanguages: () => readonly string[];+ #ctx: ModuleContext | undefined;++ constructor(options: { systemLanguages: () => readonly string[] }) {+ this.#systemLanguages = options.systemLanguages;+ }++ async start(ctx: ModuleContext): Promise<void> {+ this.#ctx = ctx;+ }++ async stop(): Promise<void> {+ this.#ctx = undefined;+ }++ current(): Language {+ return (+ this.#ctx?.config.get().language ?? matchLanguage(this.#systemLanguages())+ );+ }++ /** Formats a message in the current language. */+ readonly t: Translate = (message, ...values) =>+ translator(this.current())(message, ...values);++ /** Keeps the Web client's choice; what shows text redraws on the event. */+ choose(language: Language): void {+ const ctx = this.#ctx;+ if (!ctx) return;+ const stored = ctx.config.get().language;+ if (stored === language) return;+ const before = this.current();+ ctx.config.update({ language });+ if (language !== before) ctx.bus.emit("language.changed", language);+ }+}diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.tsindex f431171b..65418086 100644--- a/apps/desktop/src/main/local-server.ts+++ b/apps/desktop/src/main/local-server.ts@@ -227,6 +227,8 @@ export const LOCAL_STEPS = [] as const;export type LocalServerStep = (typeof LOCAL_STEPS)[number];+export type LocalServerPreparing = "updating" | "starting";+export type LocalServerPhase =| "idle"| "preparing"@@ -275,6 +277,9 @@ export interface LocalServerStatus {readonly available: boolean;readonly phase: LocalServerPhase;readonly message: string;+ // While preparing: whether the services restart on a new version or+ // only start, for pages that word it themselves.+ readonly preparing?: LocalServerPreparing;// While installing: the steps shown, the current one and the overall share// done (0-1).readonly steps: readonly LocalServerStep[];@@ -429,6 +434,7 @@ export class LocalServerModule implements Module {#ctx: ModuleContext | undefined;#phase: LocalServerPhase = "idle";#message = "";+ #preparing: LocalServerPreparing = "starting";#step: LocalServerStep = "prepare";#progress = 0;#transfer: LocalServerStatus["transfer"];@@ -624,6 +630,7 @@ export class LocalServerModule implements Module {available,phase: this.#phase,message: this.#message,+ ...(this.#phase === "preparing" ? { preparing: this.#preparing } : {}),steps: this.#steps(),step: this.#step,progress: this.#progress,@@ -2472,9 +2479,11 @@ export class LocalServerModule implements Module {const update = this.#sourceUpdate(record);if (update) {// The services restart even if they still answer.+ this.#preparing = "updating";this.#set("preparing", "Updating Linger on this computer…");windows?.showUpdating();} else {+ this.#preparing = "starting";this.#set("preparing", "Starting Linger on this computer…");// The window would show the server as unreachable until it is back.const checkStartedAt = Date.now();diff --git a/apps/desktop/src/main/modules.ts b/apps/desktop/src/main/modules.tsindex 6a45fec3..d3108f2b 100644--- a/apps/desktop/src/main/modules.ts+++ b/apps/desktop/src/main/modules.ts@@ -1,5 +1,6 @@import { EventEmitter } from "node:events";+import type { Language } from "../i18n/language.js";import type { ConfigStore } from "./config.js";import type { Logger } from "./log.js";@@ -23,6 +24,8 @@ export interface BusEvents {"computer.runtime": [];"diagnostics.changed": [];"grants.changed": [];+ // The shell's language changed; menus, the tray and shell pages redraw.+ "language.changed": [language: Language];"local-server.changed": [];// Forget the installation the window used and set this computer up again."local-server.reset": [];diff --git a/apps/desktop/src/main/setup-window.ts b/apps/desktop/src/main/setup-window.tsindex 32858d2b..912a38f6 100644--- a/apps/desktop/src/main/setup-window.ts+++ b/apps/desktop/src/main/setup-window.ts@@ -20,7 +20,11 @@ import logoPng from "../../resources/logo-horizontal.png";import scenePng from "../../../linger-installer/public/onboarding/welcome-scene.png";// The SPA's typeface, so the setup page reads like the app it opens.import geistWoff2 from "@fontsource-variable/geist/files/geist-latin-wght-normal.woff2";+import { localizePage } from "../i18n/page.js";+import messagesHtml from "../shell/messages.html";+import { offlineMessages } from "../shell/offline.messages.js";import setupHtml from "../shell/setup.html";+import { setupMessages } from "../shell/setup.messages.js";import {SETUP_IPC,type SetupCommand,@@ -28,8 +32,10 @@ import {type SetupState,} from "../shared/setup.js";import { appWindow } from "./app-window.js";+import { dialogMessages } from "./dialogs.messages.js";import type { DiagnosticsModule } from "./diagnostics.js";import type { EnrollmentModule } from "./enrollment.js";+import type { LanguageModule } from "./language.js";import type { LocalServerModule } from "./local-server.js";import {SETTINGS_URL,@@ -40,7 +46,7 @@ import type { Module, ModuleContext } from "./modules.js";import type { PowerGuardModule } from "./power-guard.js";import { SetupAccount } from "./setup-account.js";import { parseSetupCommand } from "./setup-command.js";-import { INVALID_SERVER, type WindowManagerModule } from "./window-manager.js";+import type { WindowManagerModule } from "./window-manager.js";import type { WorkspaceGrantsModule } from "./workspace-grants.js";export interface SetupWindowOptions {@@ -68,6 +74,7 @@ export class SetupWindowModule implements Module {readonly dependsOn = ["Diagnostics","Enrollment",+ "Language","LocalServer","PowerGuard","WindowManager",@@ -176,7 +183,7 @@ export class SetupWindowModule implements Module {maximizable: false,fullscreenable: false,show: false,- title: "Set Up Linger",+ title: this.#t(dialogMessages.setupTitle),backgroundColor: "#ffffff",icon: nativeImage.createFromBuffer(Buffer.from(iconPng)),...(process.platform === "darwin"@@ -218,13 +225,17 @@ export class SetupWindowModule implements Module {this.#ctx?.get<LocalServerModule>("LocalServer").inspect();}+ get #t() {+ return this.#ctx!.get<LanguageModule>("Language").t;+ }+async #run(command: SetupCommand): Promise<void> {const ctx = this.#ctx!;const windows = ctx.get<WindowManagerModule>("WindowManager");switch (command.op) {case "server.set":if (!windows.setServer(command.serverUrl))- throw new Error(INVALID_SERVER);+ throw new Error(this.#t(offlineMessages.invalidServer));await this.#refreshSignedIn();return;case "local.start": {@@ -253,8 +264,8 @@ export class SetupWindowModule implements Module {return;case "local.location.pick": {const picked = await dialog.showOpenDialog(this.#window!, {- title: "Choose Where to Install Linger",- buttonLabel: "Choose",+ title: this.#t(dialogMessages.chooseInstallFolder),+ buttonLabel: this.#t(dialogMessages.choose),properties: ["openDirectory", "createDirectory"],});if (picked.canceled || !picked.filePaths[0]) return;@@ -305,8 +316,8 @@ export class SetupWindowModule implements Module {case "notifications.test":if (Notification.isSupported())new Notification({- title: "Notifications are on",- body: "Linger will tell you here when a task needs you.",+ title: this.#t(dialogMessages.notificationsOnTitle),+ body: this.#t(dialogMessages.notificationsOn),}).show();return;case "prevent-sleep.set":@@ -438,7 +449,15 @@ export class SetupWindowModule implements Module {return new Response(Buffer.from(geistWoff2), {headers: { "content-type": "font/woff2" },});- return new Response(setupHtml, {+ // In the language of the moment it opens; the Web client, where the+ // language is chosen, is not on screen while setup is.+ const page = localizePage(+ setupHtml,+ messagesHtml,+ setupMessages,+ this.#ctx!.get<LanguageModule>("Language").current(),+ );+ return new Response(page, {headers: { "content-type": "text/html; charset=utf-8" },});}@@ -452,6 +471,7 @@ const localServerState = (available,phase,message,+ preparing,steps,step,progress,@@ -475,6 +495,7 @@ const localServerState = (available,phase,message,+ ...(preparing ? { preparing } : {}),steps,step,progress,diff --git a/apps/desktop/src/main/status.test.ts b/apps/desktop/src/main/status.test.tsindex 4b05a7b9..8fc69b47 100644--- a/apps/desktop/src/main/status.test.ts+++ b/apps/desktop/src/main/status.test.ts@@ -1,6 +1,11 @@import { describe, expect, it } from "vitest";-import { summarizeStatus } from "./status.js";+import zhCN from "../i18n/locales/zh-CN.json" with { type: "json" };+import { translator } from "../i18n/language.js";+import { summarizeStatus, type StatusInput } from "./status.js";++const summarize = (input: StatusInput) =>+ summarizeStatus(input, translator("en"));const base = {connection: "online",@@ -11,31 +16,29 @@ const base = {describe("summarizeStatus", () => {it("describes each state in one line", () => {- expect(summarizeStatus(base)).toEqual({+ expect(summarize(base)).toEqual({tone: "online",label: "Online · Idle",});- expect(summarizeStatus({ ...base, running: 2 })).toEqual({+ expect(summarize({ ...base, running: 2 })).toEqual({tone: "busy",label: "Running 2 Tasks",});- expect(summarizeStatus({ ...base, connection: "connecting" })).toEqual({+ expect(summarize({ ...base, connection: "connecting" })).toEqual({tone: "offline",label: "Offline · Reconnecting",});- expect(summarizeStatus({ ...base, connection: "auth_failed" }).tone).toBe(+ expect(summarize({ ...base, connection: "auth_failed" }).tone).toBe("error",);- expect(summarizeStatus({ ...base, runtime: "crashed" }).tone).toBe("error");- expect(summarizeStatus({ ...base, runtime: "starting" }).label).toBe(- "Starting…",- );- expect(summarizeStatus({ ...base, enrolled: false }).tone).toBe("setup");+ expect(summarize({ ...base, runtime: "crashed" }).tone).toBe("error");+ expect(summarize({ ...base, runtime: "starting" }).label).toBe("Starting…");+ expect(summarize({ ...base, enrolled: false }).tone).toBe("setup");});it("asks to reconnect when the daemon has no valid credential", () => {expect(- summarizeStatus({+ summarize({...base,connection: "auth_failed",runtime: "stopped",@@ -48,7 +51,7 @@ describe("summarizeStatus", () => {it("asks to reconnect on a Daemon Identity conflict", () => {expect(- summarizeStatus({+ summarize({...base,connection: "identity_conflict",}),@@ -57,4 +60,13 @@ describe("summarizeStatus", () => {label: "Computer Identity Conflict · Reconnect This Computer",});});++ it("speaks the shell's language, counting tasks its way", () => {+ expect(+ summarizeStatus({ ...base, running: 2 }, translator("zh-CN")).label,+ ).toBe(zhCN.status.running.other.replace("{count}", "2"));+ expect(summarizeStatus(base, translator("zh-CN")).label).toBe(+ zhCN.status.idle,+ );+ });});diff --git a/apps/desktop/src/main/status.ts b/apps/desktop/src/main/status.tsindex d718dfb5..5389de59 100644--- a/apps/desktop/src/main/status.ts+++ b/apps/desktop/src/main/status.ts@@ -1,6 +1,9 @@+import { translator, type Translate } from "../i18n/language.js";import type { RuntimeState } from "../shared/api.js";import type { ComputerDaemonModule } from "./computer-daemon.js";+import type { LanguageModule } from "./language.js";import type { Module, ModuleContext } from "./modules.js";+import { statusMessages as m } from "./tray.messages.js";export type StatusTone = "online" | "busy" | "offline" | "error" | "setup";@@ -18,41 +21,40 @@ export interface StatusSummary {}// One line shown at the top of the tray menu.-export const summarizeStatus = (input: StatusInput): StatusSummary => {- if (!input.enrolled) return { tone: "setup", label: "Not Connected" };+export const summarizeStatus = (+ input: StatusInput,+ t: Translate,+): StatusSummary => {+ if (!input.enrolled) return { tone: "setup", label: t(m.notConnected) };switch (input.connection) {case "auth_failed":- return {- tone: "error",- label: "Sign-in Expired · Reconnect This Computer",- };+ return { tone: "error", label: t(m.signInExpired) };case "identity_conflict":- return {- tone: "error",- label: "Computer Identity Conflict · Reconnect This Computer",- };+ return { tone: "error", label: t(m.identityConflict) };case "upgrade_required":- return { tone: "error", label: "Update Required" };+ return { tone: "error", label: t(m.updateRequired) };}if (input.runtime === "crashed")- return { tone: "error", label: "Runtime Error · Restarting" };- if (input.runtime !== "ready") return { tone: "offline", label: "Starting…" };+ return { tone: "error", label: t(m.runtimeError) };+ if (input.runtime !== "ready")+ return { tone: "offline", label: t(m.starting) };if (input.connection !== "online")- return { tone: "offline", label: "Offline · Reconnecting" };+ return { tone: "offline", label: t(m.offline) };if (input.running > 0)- return {- tone: "busy",- label: `Running ${input.running} ${input.running === 1 ? "Task" : "Tasks"}`,- };- return { tone: "online", label: "Online · Idle" };+ return { tone: "busy", label: t(m.running, { count: input.running }) };+ return { tone: "online", label: t(m.idle) };};// Recomputes the summary from module state and announces changes.export class StatusModule implements Module {readonly name = "Status";- readonly dependsOn = ["ComputerDaemon"];+ readonly dependsOn = ["ComputerDaemon", "Language"];#ctx: ModuleContext | undefined;- #current: StatusSummary = { tone: "offline", label: "Starting…" };+ // Replaced on start, in the shell's language.+ #current: StatusSummary = {+ tone: "offline",+ label: translator("en")(m.starting),+ };readonly #unsubscribe: (() => void)[] = [];async start(ctx: ModuleContext): Promise<void> {@@ -63,6 +65,7 @@ export class StatusModule implements Module {ctx.bus.on("runtime.state", update),ctx.bus.on("runtime.activity", update),ctx.bus.on("computer.changed", update),+ ctx.bus.on("language.changed", update),);this.#update();}@@ -78,12 +81,15 @@ export class StatusModule implements Module {#update(): void {const ctx = this.#ctx!;const daemon = ctx.get<ComputerDaemonModule>("ComputerDaemon");- const next = summarizeStatus({- connection: daemon.connection(),- runtime: daemon.state(),- enrolled: !!ctx.config.get().computerId,- running: daemon.running(),- });+ const next = summarizeStatus(+ {+ connection: daemon.connection(),+ runtime: daemon.state(),+ enrolled: !!ctx.config.get().computerId,+ running: daemon.running(),+ },+ ctx.get<LanguageModule>("Language").t,+ );if (next.tone === this.#current.tone && next.label === this.#current.label)return;this.#current = next;diff --git a/apps/desktop/src/main/tray-menu.test.ts b/apps/desktop/src/main/tray-menu.test.tsindex b165a1f8..f36b0236 100644--- a/apps/desktop/src/main/tray-menu.test.ts+++ b/apps/desktop/src/main/tray-menu.test.ts@@ -1,10 +1,17 @@import { describe, expect, it } from "vitest";-import { trayMenu, updateNotice } from "./tray-menu.js";+import zhCN from "../i18n/locales/zh-CN.json" with { type: "json" };+import { translator } from "../i18n/language.js";+import { trayMenu, updateNotice, type TrayMenuState } from "./tray-menu.js";+import type { AnnouncedUpdate } from "./updater.js";++const en = translator("en");+const menu = (state: TrayMenuState) => trayMenu(state, en);+const notice = (update: AnnouncedUpdate) => updateNotice(update, en);describe("trayMenu", () => {it("leads with the status and ends with quit", () => {- const items = trayMenu({+ const items = menu({status: { tone: "busy", label: "Running 2 Tasks" },preventSleep: true,enrolled: true,@@ -29,7 +36,7 @@ describe("trayMenu", () => {it("offers Send Diagnostics only while a receiver is set up", () => {const actions = (canSendDiagnostics: boolean) =>- trayMenu({+ menu({status: { tone: "error", label: "Offline" },preventSleep: false,enrolled: true,@@ -43,7 +50,7 @@ describe("trayMenu", () => {it("connects an unenrolled computer and reconnects an enrolled one", () => {const label = (enrolled: boolean) =>- trayMenu({+ menu({status: { tone: "setup", label: "Not Connected" },preventSleep: false,enrolled,@@ -53,26 +60,26 @@ describe("trayMenu", () => {});it("offers a downloaded update and says when it waits for tasks", () => {- const menu = (waiting: boolean) =>- trayMenu({+ const items = (waiting: boolean) =>+ menu({status: { tone: "busy", label: "Running 1 Task" },preventSleep: false,enrolled: true,update: { kind: waiting ? "waiting" : "ready", version: "0.17.0" },}).slice(0, 2);- expect(menu(false)[1]).toEqual({+ expect(items(false)[1]).toEqual({kind: "action",action: "install-update",label: "Restart to Update (0.17.0)",});- expect(menu(true)[1]).toEqual({+ expect(items(true)[1]).toEqual({kind: "label",label: "Updating to 0.17.0 When Tasks Finish",});});it("shows a download in progress", () => {- const items = trayMenu({+ const items = menu({status: { tone: "online", label: "Online" },preventSleep: false,enrolled: true,@@ -85,7 +92,7 @@ describe("trayMenu", () => {});it("says why an update failed and offers to try again", () => {- const items = trayMenu({+ const items = menu({status: { tone: "online", label: "Online" },preventSleep: false,enrolled: true,@@ -104,7 +111,7 @@ describe("trayMenu", () => {it("shows nothing while idle or checking", () => {for (const kind of ["idle", "checking"] as const) {- const items = trayMenu({+ const items = menu({status: { tone: "online", label: "Online" },preventSleep: false,enrolled: true,@@ -115,7 +122,7 @@ describe("trayMenu", () => {});it("links a release this installation cannot apply itself", () => {- const item = trayMenu({+ const item = menu({status: { tone: "online", label: "Online" },preventSleep: false,enrolled: true,@@ -135,15 +142,44 @@ describe("trayMenu", () => {describe("updateNotice", () => {it("names what clicking it does", () => {- expect(updateNotice({ kind: "ready", version: "0.17.0" })).toEqual({+ expect(notice({ kind: "ready", version: "0.17.0" })).toEqual({title: "Update ready",body: "Linger 0.17.0 is downloaded. Click to restart Linger and update.",});expect(- updateNotice({ kind: "available", version: "0.17.0", url: "https://x" }),+ notice({ kind: "available", version: "0.17.0", url: "https://x" }),).toEqual({title: "Update available",body: "Linger 0.17.0 is available. Click to open its download page.",});});});++describe("the tray in Chinese", () => {+ it("labels the menu and the notifications from the catalog", () => {+ const zh = translator("zh-CN");+ const items = trayMenu(+ {+ status: { tone: "online", label: zhCN.status.idle },+ preventSleep: false,+ enrolled: true,+ update: { kind: "ready", version: "0.17.0" },+ },+ zh,+ );+ expect(items).toContainEqual({+ kind: "action",+ action: "quit",+ label: zhCN.tray.quit,+ });+ expect(items).toContainEqual({+ kind: "action",+ action: "install-update",+ label: zhCN.tray.restartToUpdate.replace("{version}", "0.17.0"),+ });+ expect(updateNotice({ kind: "ready", version: "0.17.0" }, zh)).toEqual({+ title: zhCN.tray.readyTitle,+ body: zhCN.tray.ready.replace("{version}", "0.17.0"),+ });+ });+});diff --git a/apps/desktop/src/main/tray-menu.ts b/apps/desktop/src/main/tray-menu.tsindex 148f8ac2..6568a1db 100644--- a/apps/desktop/src/main/tray-menu.ts+++ b/apps/desktop/src/main/tray-menu.ts@@ -1,4 +1,6 @@+import type { Translate } from "../i18n/language.js";import type { StatusSummary } from "./status.js";+import { trayMessages as m } from "./tray.messages.js";import type { AnnouncedUpdate, UpdateState } from "./updater.js";export type TrayAction =@@ -35,66 +37,77 @@ export interface TrayMenuState {// The tray menu. Items for features that do not exist yet// (pause, approvals) are added with those features.-export const trayMenu = (state: TrayMenuState): TrayMenuItem[] => [+export const trayMenu = (+ state: TrayMenuState,+ t: Translate,+): TrayMenuItem[] => [{ kind: "label", label: state.status.label },- ...updateItems(state.update),+ ...updateItems(state.update, t),{ kind: "separator" },- { kind: "action", action: "open", label: "Open Linger" },+ { kind: "action", action: "open", label: t(m.open) },// Reconnecting re-enrolls the same computer, e.g. after its credential// was rejected or the server moved.{kind: "action",action: "enroll",- label: state.enrolled- ? "Reconnect This Computer"- : "Connect This Computer…",+ label: state.enrolled ? t(m.reconnect) : t(m.connect),},{kind: "action",action: "toggle-prevent-sleep",- label: "Prevent Sleep",+ label: t(m.preventSleep),checked: state.preventSleep,},{ kind: "separator" },// What to send when something goes wrong.- { kind: "action", action: "show-logs", label: "Show Logs" },- { kind: "action", action: "save-diagnostics", label: "Save Diagnostics…" },+ { kind: "action", action: "show-logs", label: t(m.showLogs) },+ {+ kind: "action",+ action: "save-diagnostics",+ label: t(m.saveDiagnostics),+ },...(state.canSendDiagnostics? [{kind: "action" as const,action: "send-diagnostics" as const,- label: "Send Diagnostics…",+ label: t(m.sendDiagnostics),},]: []),{ kind: "separator" },// Tasks run in the app, so quitting takes the computer offline.- { kind: "action", action: "quit", label: "Quit Linger" },+ { kind: "action", action: "quit", label: t(m.quit) },];// Long native errors would stretch the menu; the log has the full text.const REASON_LENGTH = 80;-const updateItems = (update: TrayMenuState["update"]): TrayMenuItem[] => {+const updateItems = (+ update: TrayMenuState["update"],+ t: Translate,+): TrayMenuItem[] => {switch (update?.kind) {case "downloading":return [- { kind: "label", label: `Downloading Update ${update.version}…` },+ {+ kind: "label",+ label: t(m.downloading, { version: update.version }),+ },];case "ready":return [{kind: "action",action: "install-update",- label: `Restart to Update (${update.version})`,+ label: t(m.restartToUpdate, { version: update.version }),},];case "waiting":return [{kind: "label",- label: `Updating to ${update.version} When Tasks Finish`,+ label: t(m.waiting, { version: update.version }),},];case "available":@@ -102,7 +115,7 @@ const updateItems = (update: TrayMenuState["update"]): TrayMenuItem[] => {{kind: "action",action: "install-update",- label: `Download Linger ${update.version}…`,+ label: t(m.download, { version: update.version }),},];case "failed": {@@ -111,11 +124,11 @@ const updateItems = (update: TrayMenuState["update"]): TrayMenuItem[] => {? `${update.error.slice(0, REASON_LENGTH - 1)}…`: update.error;return [- { kind: "label", label: `Update Failed: ${reason}` },+ { kind: "label", label: t(m.updateFailed, { reason }) },{kind: "action",action: "check-update",- label: "Try Updating Again",+ label: t(m.tryUpdatingAgain),},];}@@ -126,17 +139,15 @@ const updateItems = (update: TrayMenuState["update"]): TrayMenuItem[] => {// The notification for an update once it is ready or available; clicking it// does what the tray's update item does.-export function updateNotice(update: AnnouncedUpdate): {+export function updateNotice(+ update: AnnouncedUpdate,+ t: Translate,+): {title: string;body: string;} {+ const values = { version: update.version };if (update.kind === "available")- return {- title: "Update available",- body: `Linger ${update.version} is available. Click to open its download page.`,- };- return {- title: "Update ready",- body: `Linger ${update.version} is downloaded. Click to restart Linger and update.`,- };+ return { title: t(m.availableTitle), body: t(m.available, values) };+ return { title: t(m.readyTitle), body: t(m.ready, values) };}diff --git a/apps/desktop/src/main/tray.messages.ts b/apps/desktop/src/main/tray.messages.tsnew file mode 100644index 00000000..b89d9740--- /dev/null+++ b/apps/desktop/src/main/tray.messages.ts@@ -0,0 +1,41 @@+import { defineMessages } from "@linger/service-kit/messages";++// The status line at the top of the tray menu and in the title bar.+export const statusMessages = defineMessages("status", {+ notConnected: "Not Connected",+ signInExpired: "Sign-in Expired · Reconnect This Computer",+ identityConflict: "Computer Identity Conflict · Reconnect This Computer",+ updateRequired: "Update Required",+ runtimeError: "Runtime Error · Restarting",+ starting: "Starting…",+ offline: "Offline · Reconnecting",+ running: { one: "Running {count} Task", other: "Running {count} Tasks" },+ idle: "Online · Idle",+});++// The tray menu, its tooltip and the update notifications.+export const trayMessages = defineMessages("tray", {+ tooltip: "Linger · {status}",+ open: "Open Linger",+ reconnect: "Reconnect This Computer",+ connect: "Connect This Computer…",+ preventSleep: "Prevent Sleep",+ showLogs: "Show Logs",+ saveDiagnostics: "Save Diagnostics…",+ sendDiagnostics: "Send Diagnostics…",+ quit: "Quit Linger",+ downloading: "Downloading Update {version}…",+ restartToUpdate: "Restart to Update ({version})",+ waiting: "Updating to {version} When Tasks Finish",+ download: "Download Linger {version}…",+ updateFailed: "Update Failed: {reason}",+ tryUpdatingAgain: "Try Updating Again",+ availableTitle: "Update available",+ available: "Linger {version} is available. Click to open its download page.",+ readyTitle: "Update ready",+ ready: "Linger {version} is downloaded. Click to restart Linger and update.",+ signInFirst: "Sign in first",+ signInFirstDetail:+ "Sign in to Linger in the window, then choose Connect This Computer again.",+ enrollFailed: "Couldn't connect this computer",+});diff --git a/apps/desktop/src/main/tray.ts b/apps/desktop/src/main/tray.tsindex 4ab599b1..cd29c898 100644--- a/apps/desktop/src/main/tray.ts+++ b/apps/desktop/src/main/tray.ts@@ -16,12 +16,14 @@ import type { DiagnosticsModule } from "./diagnostics.js";import { diagnosticsDialogs } from "./diagnostics-dialogs.js";import { sendWithPrompts } from "./diagnostics-upload.js";import { EnrollmentError, type EnrollmentModule } from "./enrollment.js";+import type { LanguageModule } from "./language.js";import type { Module, ModuleContext } from "./modules.js";import type { PowerGuardModule } from "./power-guard.js";import type { SetupWindowModule } from "./setup-window.js";import type { StatusModule, StatusTone } from "./status.js";import { renderTrayIcon, type TrayArtwork } from "./tray-icon.js";import { trayMenu, type TrayAction, type TrayMenuItem } from "./tray-menu.js";+import { trayMessages } from "./tray.messages.js";import type { UpdaterModule } from "./updater.js";import type { WindowManagerModule } from "./window-manager.js";@@ -71,6 +73,7 @@ export class TrayModule implements Module {"SetupWindow","Updater","Diagnostics",+ "Language",];readonly #options: TrayOptions;#ctx: ModuleContext | undefined;@@ -101,6 +104,7 @@ export class TrayModule implements Module {ctx.bus.on("status.changed", () => this.#refresh()),ctx.bus.on("power.changed", () => this.#refresh()),ctx.bus.on("update.changed", () => this.#refresh()),+ ctx.bus.on("language.changed", () => this.#refresh()),);this.#refresh();}@@ -130,10 +134,16 @@ export class TrayModule implements Module {}if (!this.#tray) return;this.#tray.setImage(this.#icon());- this.#tray.setToolTip(`Linger · ${this.#status().label}`);+ this.#tray.setToolTip(+ this.#t(trayMessages.tooltip, { status: this.#status().label }),+ );this.#tray.setContextMenu(this.#menu());}+ get #t() {+ return this.#ctx!.get<LanguageModule>("Language").t;+ }+#icon(): NativeImage {const tone = this.#status().tone;const key = `${tone}:${tone === "busy" ? this.#frame : 0}`;@@ -149,14 +159,17 @@ export class TrayModule implements Module {const power = this.#ctx!.get<PowerGuardModule>("PowerGuard");const status = this.#status();const update = this.#ctx!.get<UpdaterModule>("Updater").state();- const items = trayMenu({- status,- preventSleep: power.alwaysOn(),- enrolled: !!this.#ctx!.config.get().computerId,- update,- canSendDiagnostics:- !!this.#ctx!.get<DiagnosticsModule>("Diagnostics").uploadUrl(),- });+ const items = trayMenu(+ {+ status,+ preventSleep: power.alwaysOn(),+ enrolled: !!this.#ctx!.config.get().computerId,+ update,+ canSendDiagnostics:+ !!this.#ctx!.get<DiagnosticsModule>("Diagnostics").uploadUrl(),+ },+ this.#t,+ );return Menu.buildFromTemplate(items.map((item) => this.#item(item)));}@@ -207,8 +220,9 @@ export class TrayModule implements Module {case "send-diagnostics":void sendWithPrompts(ctx.get<DiagnosticsModule>("Diagnostics").sender,- diagnosticsDialogs(() =>- ctx.get<WindowManagerModule>("WindowManager").window(),+ diagnosticsDialogs(+ () => ctx.get<WindowManagerModule>("WindowManager").window(),+ this.#t,),);break;@@ -231,9 +245,11 @@ export class TrayModule implements Module {const window = windows.window();const options = {type: "warning" as const,- message: signedOut ? "Sign in first" : "Couldn't connect this computer",+ message: signedOut+ ? this.#t(trayMessages.signInFirst)+ : this.#t(trayMessages.enrollFailed),detail: signedOut- ? "Sign in to Linger in the window, then choose Connect This Computer again."+ ? this.#t(trayMessages.signInFirstDetail): error instanceof Error? error.message: String(error),diff --git a/apps/desktop/src/main/window-manager.test.ts b/apps/desktop/src/main/window-manager.test.tsindex db0ebcf4..9ec91873 100644--- a/apps/desktop/src/main/window-manager.test.ts+++ b/apps/desktop/src/main/window-manager.test.ts@@ -126,13 +126,22 @@ vi.mock("electron", () => ({vi.mock("../../resources/icon.png", () => ({default: new Uint8Array([1, 2]),}));-vi.mock("../shell/offline.html", () => ({ default: "<html>offline</html>" }));-vi.mock("../shell/titlebar.html", () => ({ default: "<html>title</html>" }));+vi.mock("../shell/offline.html", () => ({+ default: '<html lang="en"><script>/* offline */</script></html>',+}));+vi.mock("../shell/titlebar.html", () => ({+ default: '<html lang="en"><script>/* titlebar */</script></html>',+}));+vi.mock("../shell/messages.html", () => ({+ default: "<script>/* messages */</script>",+}));-import { session } from "electron";+import { protocol, session } from "electron";import { IPC } from "../shared/api.js";import { ConfigStore } from "./config.js";+import zhCN from "../i18n/locales/zh-CN.json" with { type: "json" };+import { LanguageModule } from "./language.js";import { EventBus, ModuleHost, type Module } from "./modules.js";import { tempDirectory } from "./test-support.js";import { WindowManagerModule } from "./window-manager.js";@@ -164,6 +173,7 @@ function setup(stop: async () => {},};Object.assign(diagnosticsStub, { uploadUrl: () => undefined });+ const language = new LanguageModule({ systemLanguages: () => ["en-US"] });const manager = new WindowManagerModule({preload: "/preload.cjs",shellPreload: "/shell.cjs",@@ -181,6 +191,7 @@ function setup(stop: async () => {},},diagnosticsStub,+ language,manager,],{@@ -193,7 +204,7 @@ function setup(},},);- return { manager, host, config, bus, logs };+ return { manager, host, config, bus, logs, language };}function contentView() {@@ -540,4 +551,31 @@ describe("WindowManagerModule", () => {expect(content.send).toHaveBeenCalledTimes(1);await host.stop("quit");});++ it("serves the shell pages in the shell's language and redraws the title bar on a change", async () => {+ const platform = Object.getOwnPropertyDescriptor(process, "platform")!;+ // Only Windows and Linux draw the title bar.+ Object.defineProperty(process, "platform", { value: "linux" });+ try {+ const { host, language } = setup({ serverUrl: "http://localhost:3000" });+ await host.start();+ const serve = vi.mocked(protocol.handle).mock.calls.at(-1)![1];+ const page = async (url: string) =>+ (await serve(new Request(url) as never)).text();+ expect(await page("app://shell/titlebar")).toContain('lang="en"');++ const titlebar = state.views[0]!.webContents;+ language.choose("zh-CN");+ expect(titlebar.reload).toHaveBeenCalledOnce();+ const titlebarPage = await page("app://shell/titlebar");+ expect(titlebarPage).toContain('<html lang="zh-CN"');+ expect(titlebarPage).toContain(zhCN.titlebar.close);+ expect(await page("app://offline/")).toContain(+ zhCN.offline.unreachableTitle,+ );+ await host.stop("quit");+ } finally {+ Object.defineProperty(process, "platform", platform);+ }+ });});diff --git a/apps/desktop/src/main/window-manager.ts b/apps/desktop/src/main/window-manager.tsindex 654b1cec..34d66130 100644--- a/apps/desktop/src/main/window-manager.ts+++ b/apps/desktop/src/main/window-manager.ts@@ -14,8 +14,12 @@ import {} from "electron";import iconPng from "../../resources/icon.png";+import { localizePage } from "../i18n/page.js";+import messagesHtml from "../shell/messages.html";import offlineHtml from "../shell/offline.html";+import { offlineMessages } from "../shell/offline.messages.js";import titlebarHtml from "../shell/titlebar.html";+import { titlebarMessages } from "../shell/titlebar.messages.js";import {SHELL_IPC,type ShellCommand,@@ -26,6 +30,7 @@ import { IPC } from "../shared/api.js";import type { DiagnosticsModule } from "./diagnostics.js";import { diagnosticsDialogs } from "./diagnostics-dialogs.js";import { sendWithPrompts } from "./diagnostics-upload.js";+import type { LanguageModule } from "./language.js";import type { Module, ModuleContext } from "./modules.js";import {OFFLINE_ORIGIN,@@ -93,8 +98,8 @@ const chrome = (platform: NodeJS.Platform): BaseWindowConstructorOptions => {return { frame: false };};-export const INVALID_SERVER =- "Enter a server address that starts with http:// or https://";+// The offline page's code for an address it shows its own message for.+const INVALID_SERVER = "invalid-server";const html = (body: string): Response =>new Response(body, {@@ -141,7 +146,7 @@ const extractAssetPaths = (documentHtml: string): string[] => {// Closing hides the window; the tray keeps the app running.export class WindowManagerModule implements Module {readonly name = "WindowManager";- readonly dependsOn = ["Config"];+ readonly dependsOn = ["Config", "Language"];readonly #options: WindowManagerOptions;#ctx: ModuleContext | undefined;#window: BaseWindow | undefined;@@ -181,6 +186,10 @@ export class WindowManagerModule implements Module {this.#unsubscribe.push(() => ipcMain.removeHandler(SHELL_IPC.state),() => ipcMain.removeAllListeners(SHELL_IPC.command),+ // The title bar's button labels are filled in when it loads.+ ctx.bus.on("language.changed", () =>+ this.#titlebar?.webContents.reload(),+ ),);if (!this.#options.background) this.show();}@@ -813,7 +822,7 @@ export class WindowManagerModule implements Module {#serveApp(request: Request): Response {const url = new URL(request.url);if (url.host === "shell" && url.pathname === "/titlebar")- return html(titlebarHtml);+ return html(this.#localize(titlebarHtml, titlebarMessages));if (url.host !== "offline") return new Response(null, { status: 404 });if (url.pathname === "/logo.png")return new Response(Buffer.from(iconPng), {@@ -834,7 +843,7 @@ export class WindowManagerModule implements Module {if (url.pathname === "/send") {void sendWithPrompts(this.#ctx!.get<DiagnosticsModule>("Diagnostics").sender,- diagnosticsDialogs(() => this.#window),+ diagnosticsDialogs(() => this.#window, this.#language().t),);return new Response(null, { status: 204 });}@@ -855,6 +864,19 @@ export class WindowManagerModule implements Module {this.#loadOffline(INVALID_SERVER);return new Response(null, { status: 204 });}- return html(offlineHtml);+ return html(this.#localize(offlineHtml, offlineMessages));+ }++ #language(): LanguageModule {+ return this.#ctx!.get<LanguageModule>("Language");+ }++ #localize(page: string, messages: Parameters<typeof localizePage>[2]) {+ return localizePage(+ page,+ messagesHtml,+ messages,+ this.#language().current(),+ );}}diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.tsindex 271d1693..883abcf7 100644--- a/apps/desktop/src/preload/index.ts+++ b/apps/desktop/src/preload/index.ts@@ -72,6 +72,9 @@ const api: LingerDesktopApi = {voiceWindow: {showMainWindow: () => ipcRenderer.invoke(IPC.voiceWindowShowMain),},+ language: {+ set: (language) => ipcRenderer.invoke(IPC.languageSet, language),+ },...(process.platform === "darwin"? {permissions: {diff --git a/apps/desktop/src/shared/api.ts b/apps/desktop/src/shared/api.tsindex aab2176e..dd7cd0db 100644--- a/apps/desktop/src/shared/api.ts+++ b/apps/desktop/src/shared/api.ts@@ -120,6 +120,12 @@ export interface LingerDesktopApi {// Brings the main window to the front, from the floating window.showMainWindow(): Promise<void>;};+ // The page reports the language the person chose in Settings › Language,+ // and again on every change, so the app's menus, tray, notifications and+ // own windows follow it. No report means no choice yet.+ readonly language: {+ set(language: string): Promise<void>;+ };// macOS only.readonly permissions?: {act(step: DesktopPermissionStep): Promise<void>;@@ -147,4 +153,5 @@ export const IPC = {connectorOAuthReturn: "connector-oauth.return",previewFrameRefused: "preview.frame-refused",voiceWindowShowMain: "voice-window.show-main",+ languageSet: "language.set",} as const;diff --git a/apps/desktop/src/shared/setup.ts b/apps/desktop/src/shared/setup.tsindex 6449bff5..4e755ec3 100644--- a/apps/desktop/src/shared/setup.ts+++ b/apps/desktop/src/shared/setup.ts@@ -23,6 +23,9 @@ export interface SetupLocalServer {readonly available: boolean;readonly phase: "idle" | "preparing" | "installing" | "ready" | "failed";readonly message: string;+ // While preparing: a restart on a new version or a plain start; the page+ // words it in its own language.+ readonly preparing?: "updating" | "starting";// While installing: the steps shown, the current one and the overall share// done (0-1).readonly steps: readonly SetupLocalStep[];diff --git a/apps/desktop/src/shell/messages.html b/apps/desktop/src/shell/messages.htmlnew file mode 100644index 00000000..80e2ce3b--- /dev/null+++ b/apps/desktop/src/shell/messages.html@@ -0,0 +1,55 @@+<!-- The page side of a shell page's messages; src/i18n/page.ts puts this+script in front of the page's own, with the messages in a JSON block. -->+<script>+ const MESSAGES = JSON.parse(+ document.getElementById("linger-messages").textContent,+ );+ // A message's text in the language it resolved to, its plural form picked+ // by `count`.+ const pickMessage = (name, values) => {+ const [language, source] = MESSAGES.messages[name] ?? ["en", name];+ const text =+ typeof source === "string"+ ? source+ : (source[new Intl.PluralRules(language).select(values.count)] ??+ source.other);+ return { language, text };+ };+ // Fills each {name}; numbers are grouped the way the language writes them.+ const fillMessage = ({ language, text }, values) =>+ text.replace(/\{(\w+)\}/gu, (placeholder, key) => {+ const value = values[key];+ if (value === undefined) return placeholder;+ return typeof value === "number"+ ? new Intl.NumberFormat(language).format(value)+ : value;+ });+ const t = (name, values = {}) =>+ fillMessage(pickMessage(name, values), values);+ // The message as nodes, each <name>…</name> span as <span class="name"> so+ // the page can style it. The spans come from the message alone: a value+ // that contains a tag stays text.+ const tSpans = (name, values = {}) => {+ const picked = pickMessage(name, values);+ const fill = (text) => fillMessage({ ...picked, text }, values);+ const nodes = [];+ let end = 0;+ for (const match of picked.text.matchAll(/<(\w+)>(.*?)<\/\1>/gsu)) {+ nodes.push(fill(picked.text.slice(end, match.index)));+ const span = document.createElement("span");+ span.className = match[1];+ span.textContent = fill(match[2]);+ nodes.push(span);+ end = match.index + match[0].length;+ }+ nodes.push(fill(picked.text.slice(end)));+ return nodes.filter((node) => node !== "");+ };+ // Static text names its message: data-t for the text, data-t-<attribute>+ // for an attribute.+ for (const el of document.querySelectorAll("[data-t]"))+ el.textContent = t(el.dataset.t);+ for (const attribute of ["title", "aria-label", "placeholder", "alt"])+ for (const el of document.querySelectorAll(`[data-t-${attribute}]`))+ el.setAttribute(attribute, t(el.getAttribute(`data-t-${attribute}`)));+</script>diff --git a/apps/desktop/src/shell/offline.html b/apps/desktop/src/shell/offline.htmlindex 13cc7666..b15a393a 100644--- a/apps/desktop/src/shell/offline.html+++ b/apps/desktop/src/shell/offline.html@@ -224,31 +224,51 @@<div class="mark"><img src="app://offline/logo.png" alt="" /><span class="badge"></span></div>- <h1 id="title">Can't reach the server</h1>- <p id="reason">- Linger can't reach <span class="host" id="host"></span>. Check your- network or VPN and make sure the server is running.- </p>+ <h1 id="title" data-t="unreachableTitle"></h1>+ <p id="reason"></p><span class="code" id="code"></span><div class="actions">- <button class="primary" id="retry" type="button">Try Again</button>- <button class="link" id="edit" type="button">Change Server</button>- <button class="link failed-only" id="logs" type="button">- Show Logs- </button>- <button class="link failed-only" id="diagnostics" type="button">- Save Diagnostics- </button>- <button class="link failed-only" id="send" type="button" hidden>- Send Diagnostics- </button>- <button class="link failed-only" id="reset" type="button">- Set Up Again- </button>+ <button+ class="primary"+ id="retry"+ type="button"+ data-t="tryAgain"+ ></button>+ <button+ class="link"+ id="edit"+ type="button"+ data-t="changeServer"+ ></button>+ <button+ class="link failed-only"+ id="logs"+ type="button"+ data-t="showLogs"+ ></button>+ <button+ class="link failed-only"+ id="diagnostics"+ type="button"+ data-t="saveDiagnostics"+ ></button>+ <button+ class="link failed-only"+ id="send"+ type="button"+ data-t="sendDiagnostics"+ hidden+ ></button>+ <button+ class="link failed-only"+ id="reset"+ type="button"+ data-t="setUpAgain"+ ></button><span class="countdown" id="countdown"></span></div><form action="app://offline/connect" method="get" id="form">- <label for="server">Server address</label>+ <label for="server" data-t="serverAddress"></label><inputid="server"name="server"@@ -257,10 +277,15 @@spellcheck="false"required/>- <p class="hint" id="hint">The address of your team's Linger server.</p>+ <p class="hint" id="hint" data-t="serverHint"></p><div class="row">- <button class="primary" type="submit">Connect</button>- <button class="link" id="cancel" type="button">Cancel</button>+ <button class="primary" type="submit" data-t="connect"></button>+ <button+ class="link"+ id="cancel"+ type="button"+ data-t="cancel"+ ></button></div></form></main>@@ -279,32 +304,34 @@);if (local === "updating") {document.body.dataset.mode = "updating";- $("title").textContent = "Updating Linger";- $("reason").textContent =- "Linger is restarting on this computer with the new version. This takes about a minute.";+ $("title").textContent = t("updatingTitle");+ $("reason").textContent = t("updating");} else if (local === "starting") {document.body.dataset.mode = "starting";- $("title").textContent = "Starting Linger";- $("reason").textContent =- "Linger is starting on this computer. This takes about a minute.";+ $("title").textContent = t("startingTitle");+ $("reason").textContent = t("starting");} else if (local === "failed") {document.body.dataset.mode = "failed";- $("title").textContent = "Linger couldn't start on this computer";+ $("title").textContent = t("failedTitle");$("reason").textContent = params.get("failed");} else if (!server) {document.body.dataset.mode = "setup";- $("title").textContent = "Connect to Linger";- $("reason").textContent =- "Enter your team's server address, then sign in.";+ $("title").textContent = t("setupTitle");+ $("reason").textContent = t("setup");// Setup, where Linger can also be installed on this computer.- $("cancel").textContent = "Back to Setup";+ $("cancel").textContent = t("backToSetup");$("server").focus();} else {- $("host").textContent = new URL(server).host;+ $("reason").replaceChildren(+ ...tSpans("unreachable", { host: new URL(server).host }),+ );$("code").textContent = error;}+ // An address that is not one comes as a code, worded here; any other+ // text that is not a network error code shows as it is.if (error && !error.startsWith("ERR_")) {- $("hint").textContent = error;+ $("hint").textContent =+ error === "invalid-server" ? t("invalidServer") : error;$("hint").classList.add("invalid");if (server) document.body.classList.add("editing");}@@ -346,7 +373,7 @@}left -= 1;if (left <= 0) return connect(server);- $("countdown").textContent = "Retrying in " + left + "s";+ $("countdown").textContent = t("retrying", { seconds: left });};tick();setInterval(tick, 1000);diff --git a/apps/desktop/src/shell/offline.messages.ts b/apps/desktop/src/shell/offline.messages.tsnew file mode 100644index 00000000..44680998--- /dev/null+++ b/apps/desktop/src/shell/offline.messages.ts@@ -0,0 +1,31 @@+import { defineMessages } from "@linger/service-kit/messages";++// The page the window shows instead of the server (offline.html): the server+// is out of reach, the services on this computer start or update, or no+// server is set yet.+export const offlineMessages = defineMessages("offline", {+ unreachableTitle: "Can't reach the server",+ unreachable:+ "Linger can't reach <host>{host}</host>. Check your network or VPN and make sure the server is running.",+ tryAgain: "Try Again",+ changeServer: "Change Server",+ showLogs: "Show Logs",+ saveDiagnostics: "Save Diagnostics",+ sendDiagnostics: "Send Diagnostics",+ setUpAgain: "Set Up Again",+ serverAddress: "Server address",+ serverHint: "The address of your team's Linger server.",+ invalidServer: "Enter a server address that starts with http:// or https://",+ connect: "Connect",+ cancel: "Cancel",+ updatingTitle: "Updating Linger",+ updating:+ "Linger is restarting on this computer with the new version. This takes about a minute.",+ startingTitle: "Starting Linger",+ starting: "Linger is starting on this computer. This takes about a minute.",+ failedTitle: "Linger couldn't start on this computer",+ setupTitle: "Connect to Linger",+ setup: "Enter your team's server address, then sign in.",+ backToSetup: "Back to Setup",+ retrying: "Retrying in {seconds}s",+});diff --git a/apps/desktop/src/shell/setup-page.test.ts b/apps/desktop/src/shell/setup-page.test.tsindex 968f33cb..4e3f0443 100644--- a/apps/desktop/src/shell/setup-page.test.ts+++ b/apps/desktop/src/shell/setup-page.test.ts@@ -5,6 +5,9 @@ import { fileURLToPath } from "node:url";import { beforeEach, describe, expect, it, vi } from "vitest";+import type { Language } from "../i18n/language.js";+import zhCN from "../i18n/locales/zh-CN.json" with { type: "json" };+import { localizePage } from "../i18n/page.js";import type {SetupCommand,SetupLocalAccount,@@ -13,10 +16,15 @@ import type {SetupState,} from "../shared/setup.js";-const page = readFileSync(- path.join(path.dirname(fileURLToPath(import.meta.url)), "setup.html"),- "utf8",-);+import { setupMessages } from "./setup.messages.js";++const shellFile = (name: string) =>+ readFileSync(+ path.join(path.dirname(fileURLToPath(import.meta.url)), name),+ "utf8",+ );+const rawPage = shellFile("setup.html");+const messagesRuntime = shellFile("messages.html");const PASSWORD = "a-private-password";const state = (@@ -56,6 +64,7 @@ let stopPage = () => {};const openPage = async (initial: SetupState = state("installing"),step = "installing",+ language: Language = "en",) => {stopPage();const intervals: ReturnType<typeof setInterval>[] = [];@@ -64,6 +73,8 @@ const openPage = async (intervals.forEach(clearInterval);timeouts.forEach(clearTimeout);};+ // The page as setup-window.ts serves it.+ const page = localizePage(rawPage, messagesRuntime, setupMessages, language);const [, body] = /<body[^>]*>([\s\S]*)<\/body>/.exec(page)!;const [, script] = /<script>([\s\S]*)<\/script>/.exec(body!)!;document.body.innerHTML = body!.replace(/<script>[\s\S]*<\/script>/, "");@@ -1118,3 +1129,62 @@ describe("setup page refused install location", () => {expect($("installing-plan").textContent).toBe(usual);});});++describe("setup page in Chinese", () => {+ const zh = zhCN.setup;+ const fill = (text: string, values: Record<string, string>) =>+ text.replace(/\{(\w+)\}/gu, (_, name: string) => values[name]!);++ it("speaks the language it was served in", async () => {+ await openPage(welcome(capable), "welcome", "zh-CN");+ // The harness loads the body only; static text comes from data-t.+ expect(document.querySelector('[data-t="welcomeTitle"]')!.textContent).toBe(+ zh.welcomeTitle,+ );+ expect($("plan-summary").textContent).toBe(+ fill(zh.recommendedPlan, { plan: zh.localModelPi }),+ );+ expect($("plan-why").textContent).toBe(+ [+ "qwen3-8b",+ fill(zh.fitsGpu, { gpu: "RTX 4090" }),+ fill(zh.memoryAmount, { size: "64 GB" }),+ fill(zh.downloadAmount, { size: "6 GB" }),+ ].join(" · "),+ );+ expect($("local-install-label").textContent).toBe(zh.quickInstall);+ });++ it("words a held local model from the catalog", async () => {+ await openPage(welcome(held), "welcome", "zh-CN");+ expect($("plan-why").textContent).toBe(+ fill(zh.heldWhy, { reasons: zh.reasonHeld, plan: "Codex" }),+ );+ });++ it("counts the download its way", async () => {+ const base = state("installing");+ await openPage(+ {+ ...base,+ localServer: {+ ...base.localServer,+ transfer: {+ label: "Downloading the local model…",+ completed: 3 * GB,+ total: 4 * GB,+ bytesPerSecond: 50 * 1024 ** 2,+ partial: true,+ },+ },+ },+ "installing",+ "zh-CN",+ );+ expect($("installing-transfer-bytes").textContent).toBe(+ `${fill(zh.thisFile, {+ amount: fill(zh.amountOf, { done: "3.0 GB", total: "4.0 GB" }),+ })} · 50 MB/s`,+ );+ });+});diff --git a/apps/desktop/src/shell/setup.html b/apps/desktop/src/shell/setup.htmlindex 0441ae33..e469ea76 100644--- a/apps/desktop/src/shell/setup.html+++ b/apps/desktop/src/shell/setup.html@@ -6,7 +6,7 @@http-equiv="Content-Security-Policy"content="default-src 'none'; img-src 'self'; font-src 'self'; style-src 'unsafe-inline'; script-src 'unsafe-inline'"/>- <title>Set Up Linger</title>+ <title data-t="pageTitle"></title><style>@font-face {font-family: "Geist Variable";@@ -1816,33 +1816,41 @@><svg viewBox="0 0 24 24"><rect x="5" y="11" width="14" height="9" rx="2" /><path d="M8 11V8a4 4 0 0 1 8 0v3" /></svg- >Private to this computer</span- >- <h1 id="welcome-title">Set up Linger</h1>+ ><span data-t="welcomeEyebrow"></span+ ></span>+ <h1 id="welcome-title" data-t="welcomeTitle"></h1><p class="lead tight" id="welcome-lead"></p><div class="fold" id="local-options" data-open="false"><div><div class="choices"><div class="choice"><div class="text">- <strong>Model source</strong- ><span class="sub" id="source-sub"- >Where your agents get their models.</span- >+ <strong data-t="modelSource"></strong+ ><span+ class="sub"+ id="source-sub"+ data-t="modelSourceHint"+ ></span></div><divclass="seg"role="radiogroup"- aria-label="Model source"+ data-t-aria-label="modelSource"data-plan="source"><span class="knob"></span>- <button type="button" role="radio" data-value="local">- Local model- </button>- <button type="button" role="radio" data-value="subscription">- Subscription- </button>+ <button+ type="button"+ role="radio"+ data-value="local"+ data-t="localModel"+ ></button>+ <button+ type="button"+ role="radio"+ data-value="subscription"+ data-t="subscription"+ ></button><buttontype="button"role="radio"@@ -1851,17 +1859,18 @@aria-describedby="byok-tip-text">BYOK- <span class="byok-tooltip" id="byok-tip-text" role="tooltip"- >Bring Your Own Key — Connect your own OpenAI-compatible- or Anthropic API endpoint, key, and model through Linger's- local Bifrost gateway.</span- >+ <span+ class="byok-tooltip"+ id="byok-tip-text"+ role="tooltip"+ data-t="byokTooltip"+ ></span></button></div></div><div class="choice local" id="local-row" hidden><div class="text">- <strong>Local model</strong+ <strong data-t="localModel"></strong><span class="sub" id="local-sub"></span></div><button@@ -1869,7 +1878,7 @@class="pick"id="local-model"role="checkbox"- aria-label="Run tasks on a local model"+ data-t-aria-label="localModelToggle"hidden><span id="local-model-name"></span@@ -1878,19 +1887,26 @@</div><div class="choice" id="subscription-row" hidden><div class="text">- <strong>AI runtime</strong- ><span class="sub" id="runtime-sub">Runs your tasks.</span>+ <strong data-t="aiRuntime"></strong+ ><span+ class="sub"+ id="runtime-sub"+ data-t="runtimeHint"+ ></span></div><divclass="seg"role="radiogroup"- aria-label="AI runtime"+ data-t-aria-label="aiRuntime"data-plan="runtime"><span class="knob"></span>- <button type="button" role="radio" data-value="recommended">- Auto- </button>+ <button+ type="button"+ role="radio"+ data-value="recommended"+ data-t="auto"+ ></button><button type="button" role="radio" data-value="codex">Codex</button>@@ -1901,7 +1917,7 @@</div><div class="choice byok-box" id="byok-row" hidden><div class="byok-row">- <label id="byok-runtime-label">AI runtime</label>+ <label id="byok-runtime-label" data-t="aiRuntime"></label><divclass="seg"role="radiogroup"@@ -1923,12 +1939,9 @@<div class="byok-fields" id="byok-fields"></div></div><details class="choice optional-keys" id="optional-keys">- <summary>App integrations (optional)</summary>+ <summary data-t="appIntegrations"></summary><div class="text">- <span class="sub"- >Composio connects apps; turn on voice inside the app. Keys- stay on this computer.</span- >+ <span class="sub" data-t="appIntegrationsHint"></span></div><div class="keys"><label for="key-composio">Composio</label>@@ -1938,32 +1951,41 @@data-key="composio"autocomplete="off"spellcheck="false"- aria-label="Composio API key"+ data-t-aria-label="composioKey"/>- <button type="button" class="change" data-reveal="composio">- Show- </button>- <button type="button" class="change" data-remove="composio">- Remove- </button>+ <button+ type="button"+ class="change"+ data-reveal="composio"+ data-t="show"+ ></button>+ <button+ type="button"+ class="change"+ data-remove="composio"+ data-t="remove"+ ></button></div><p class="keys-note" id="keys-note"></p></details><div class="choice"><div class="text">- <strong>Install location</strong+ <strong data-t="installLocation"></strong><span class="sub" id="location-sub"></span></div>- <button type="button" class="change" id="location-change">- Change…- </button>+ <button+ type="button"+ class="change"+ id="location-change"+ data-t="changeLocation"+ ></button></div></div></div></div><div class="start"><button class="primary large" id="local-install" type="button">- <span id="local-install-label">Quick Install</span+ <span id="local-install-label" data-t="quickInstall"></span><svg viewBox="0 0 24 24"><path d="M5 12h14m-6-6 6 6-6 6" /></svg></button><button@@ -1971,9 +1993,8 @@id="get-started"data-go="server"type="button"- >- Get Started- </button>+ data-t="getStarted"+ ></button><p class="plan-line" id="plan-line"><span id="plan-summary"></span><span class="sep"></span><button@@ -1982,26 +2003,32 @@type="button"aria-expanded="false"aria-controls="local-options"- >- Customize- </button>+ data-t="customize"+ ></button></p><p class="plan-why" id="plan-why" hidden></p>- <button class="link quiet" id="local-recheck" type="button" hidden>- Check again- </button>+ <button+ class="link quiet"+ id="local-recheck"+ type="button"+ hidden+ data-t="checkAgain"+ ></button></div><p class="error" id="local-error" role="alert"></p><p class="team" id="team">- Have a team server?- <button class="link" data-go="server" type="button">- Connect to it instead- </button>+ <span data-t="teamServer"></span>+ <button+ class="link"+ data-go="server"+ type="button"+ data-t="connectInstead"+ ></button></p></section><section data-step="installing" aria-labelledby="installing-title">- <h1 id="installing-title">Installing Linger</h1>+ <h1 id="installing-title" data-t="installingTitle"></h1><p class="lead tight" id="installing-plan"></p><divclass="panel"@@ -2033,40 +2060,39 @@<h2 id="runtime-signin-title"></h2><p id="runtime-signin-lead"></p><p class="waiting" id="runtime-signin-waiting" role="status">- <span class="spinner"></span>Waiting for authorization in your- browser…+ <span class="spinner"></span><span data-t="signInWaiting"></span></p><p class="device-code" id="runtime-signin-device" hidden>- Enter this code in your browser:+ <span data-t="deviceCode"></span><strong id="runtime-signin-device-code"></strong></p><p class="problem" id="runtime-signin-error" role="alert"></p><div class="actions" id="runtime-signin-idle">- <button class="primary" id="runtime-signin-start" type="button">- Authorize- </button>+ <button+ class="primary"+ id="runtime-signin-start"+ type="button"+ data-t="authorize"+ ></button><div class="row"><buttonclass="link quiet"id="runtime-signin-other"type="button"- >- Use a different runtime- </button>+ data-t="otherRuntime"+ ></button><buttonclass="link quiet"id="runtime-signin-byok-toggle"type="button"- >- Use BYOK instead- </button>+ data-t="byokInstead"+ ></button><buttonclass="link quiet"id="runtime-signin-logs"type="button"- >- Show Logs- </button>+ data-t="showLogs"+ ></button></div><div class="runtimes" id="runtime-signin-runtimes" hidden><button class="secondary" data-switch="codex" type="button">@@ -2085,21 +2111,26 @@class="secondary"id="runtime-signin-byok-submit"type="submit"- >- Continue with BYOK- </button>+ data-t="continueWithByok"+ ></button></form></div><div class="row" id="runtime-signin-busy">- <button class="link quiet" id="runtime-signin-open" type="button">- Open browser again- </button>- <button class="ghost" id="runtime-signin-cancel" type="button">- Cancel- </button>+ <button+ class="link quiet"+ id="runtime-signin-open"+ type="button"+ data-t="openBrowserAgain"+ ></button>+ <button+ class="ghost"+ id="runtime-signin-cancel"+ type="button"+ data-t="cancel"+ ></button></div><details id="runtime-signin-trouble">- <summary class="link quiet">Having trouble?</summary>+ <summary class="link quiet" data-t="havingTrouble"></summary><p id="runtime-signin-help"></p><form id="runtime-signin-paste"><input@@ -2107,28 +2138,46 @@type="password"autocomplete="off"spellcheck="false"- aria-label="Code from the sign-in page"- placeholder="Paste the code"+ data-t-aria-label="pastedCode"+ data-t-placeholder="pasteCode"/>- <button class="secondary" type="submit">Continue</button>+ <button+ class="secondary"+ type="submit"+ data-t="continue"+ ></button></form></details></div></div><p class="problem" id="installing-error" role="alert"></p><div class="diagnostics" id="installing-diagnostics" hidden>- <button class="link quiet" id="installing-more" type="button" hidden>- Show Details- </button>- <button class="link quiet" id="show-logs" type="button">- Show Logs- </button>- <button class="link quiet" id="save-diagnostics" type="button">- Save Diagnostics- </button>- <button class="link quiet" id="send-diagnostics" type="button" hidden>- Send Diagnostics- </button>+ <button+ class="link quiet"+ id="installing-more"+ type="button"+ hidden+ data-t="showDetails"+ ></button>+ <button+ class="link quiet"+ id="show-logs"+ type="button"+ data-t="showLogs"+ ></button>+ <button+ class="link quiet"+ id="save-diagnostics"+ type="button"+ data-t="saveDiagnostics"+ ></button>+ <button+ class="link quiet"+ id="send-diagnostics"+ type="button"+ hidden+ data-t="sendDiagnostics"+ ></button><output id="diagnostics-note"></output></div><div@@ -2142,12 +2191,17 @@<div class="sheet"><h2 id="send-title"></h2><p id="send-lead"></p>- <ul class="files" id="send-files" aria-label="Files to send"></ul>+ <ul+ class="files"+ id="send-files"+ data-t-aria-label="filesToSend"+ ></ul><div class="track" id="send-track"><div class="fill" id="send-fill"></div></div><p class="report" id="send-report">- Report ID <strong id="send-report-id"></strong>+ <span data-t="reportId"></span>+ <strong id="send-report-id"></strong></p><p class="problem" id="send-error" role="alert"></p><div class="actions">@@ -2157,10 +2211,18 @@</div></div><footer class="actions" id="installing-actions">- <button class="ghost" data-go="welcome" type="button">Back</button>- <button class="primary" id="local-retry" type="button">- Try Again- </button>+ <button+ class="ghost"+ data-go="welcome"+ type="button"+ data-t="back"+ ></button>+ <button+ class="primary"+ id="local-retry"+ type="button"+ data-t="tryAgain"+ ></button></footer></section>@@ -2168,43 +2230,56 @@<span class="mark"><svg viewBox="0 0 24 24"><path d="m5 12 5 5 9-10" /></svg></span>- <h1 id="ready-title">Linger is ready</h1>+ <h1 id="ready-title" data-t="readyTitle"></h1><p class="lead tight" id="ready-lead"></p><p class="connected">- <span class="live"></span>This computer is connected+ <span class="live"></span><span data-t="computerConnected"></span></p><div class="account" id="account" hidden>- <p class="account-title">Your account on this computer</p>+ <p class="account-title" data-t="accountTitle"></p><dl id="account-fields">- <dt>Email</dt>+ <dt data-t="email"></dt><dd class="email" id="account-email"></dd>- <dt>Password</dt>+ <dt data-t="password"></dt><dd class="secret" id="account-password"></dd>- <button class="change" id="account-show" type="button">Show</button>- <button class="change" id="account-copy" type="button">Copy</button>+ <button+ class="change"+ id="account-show"+ type="button"+ data-t="show"+ ></button>+ <button+ class="change"+ id="account-copy"+ type="button"+ data-t="copy"+ ></button></dl><p class="account-note" id="account-note">- Use these to log in again if you log out.- <button class="link" id="account-reveal" type="button">- Open account file location- </button>+ <span data-t="accountNote"></span>+ <button+ class="link"+ id="account-reveal"+ type="button"+ data-t="accountReveal"+ ></button></p><p class="account-error" id="account-error" role="alert"></p></div><p class="legacy-note" id="legacy-note" hidden></p><div class="start"><button class="primary large" id="open" type="button">- <span>Open Linger</span+ <span data-t="openLinger"></span><svg viewBox="0 0 24 24"><path d="M5 12h14m-6-6 6 6-6 6" /></svg></button></div></section><section data-step="server" aria-labelledby="server-title">- <h1 id="server-title">Where is your team's Linger?</h1>- <p class="lead">Enter the address your team uses for Linger.</p>+ <h1 id="server-title" data-t="serverTitle"></h1>+ <p class="lead" data-t="serverLead"></p><form id="server-form" novalidate>- <label class="field" for="server">Server address</label>+ <label class="field" for="server" data-t="serverAddress"></label><inputid="server"type="text"@@ -2213,24 +2288,29 @@spellcheck="false"placeholder="https://linger.example.com"/>- <p class="hint">Ask your admin if you're not sure.</p>+ <p class="hint" data-t="serverHint"></p><p class="error" id="server-error" role="alert"></p></form><footer class="actions">- <button class="ghost" data-go="welcome" type="button">Back</button>+ <button+ class="ghost"+ data-go="welcome"+ type="button"+ data-t="back"+ ></button><span class="spacer"></span>- <button class="primary" form="server-form" type="submit">- Continue- </button>+ <button+ class="primary"+ form="server-form"+ type="submit"+ data-t="continue"+ ></button></footer></section><section data-step="signin" aria-labelledby="signin-title">- <h1 id="signin-title">Sign in to your account</h1>- <p class="lead">- Linger opens in its own window. Sign in there, and this window moves- on by itself.- </p>+ <h1 id="signin-title" data-t="signInTitle"></h1>+ <p class="lead" data-t="signInLead"></p><div class="card"><span class="icon"><svg viewBox="0 0 24 24">@@ -2238,25 +2318,30 @@<path d="M4 21a8 8 0 0 1 16 0" /></svg></span><div class="text">- <strong>Account</strong><span id="signin-host"></span>+ <strong data-t="account"></strong><span id="signin-host"></span></div><span class="badge" id="signin-badge"></span></div><footer class="actions">- <button class="ghost" data-go="server" type="button">Back</button>+ <button+ class="ghost"+ data-go="server"+ type="button"+ data-t="back"+ ></button><span class="spacer"></span>- <button class="primary" id="signin" type="button">- Open Sign-in- </button>+ <button+ class="primary"+ id="signin"+ type="button"+ data-t="openSignIn"+ ></button></footer></section><section data-step="connect" aria-labelledby="connect-title">- <h1 id="connect-title">Connect this computer</h1>- <p class="lead">- Your workspace will see this computer and can send it tasks. You can- disconnect it at any time.- </p>+ <h1 id="connect-title" data-t="connectTitle"></h1>+ <p class="lead" data-t="connectLead"></p><div class="card"><span class="icon"><svg viewBox="0 0 24 24">@@ -2270,18 +2355,25 @@</div><p class="error" id="connect-error" role="alert"></p><footer class="actions">- <button class="ghost" data-go="signin" type="button">Back</button>+ <button+ class="ghost"+ data-go="signin"+ type="button"+ data-t="back"+ ></button><span class="spacer"></span>- <button class="primary" id="connect" type="button">Connect</button>+ <button+ class="primary"+ id="connect"+ type="button"+ data-t="connect"+ ></button></footer></section><section data-step="permissions" aria-labelledby="permissions-title">- <h1 id="permissions-title">A few permissions</h1>- <p class="lead compact">- Change these later from the <span data-tray>menu bar</span> or in your- system settings.- </p>+ <h1 id="permissions-title" data-t="permissionsTitle"></h1>+ <p class="lead compact" data-tray="changeLater"></p><div class="rows"><div class="row"><span class="icon"@@ -2290,12 +2382,15 @@<path d="M10.3 21a1.94 1.94 0 0 0 3.4 0" /></svg></span><div class="text">- <strong>Notifications</strong- ><span class="sub">Know when a task finishes or needs you.</span>+ <strong data-t="notifications"></strong+ ><span class="sub" data-t="notificationsHint"></span></div>- <button class="secondary" id="notify" type="button">- Allow Notifications- </button>+ <button+ class="secondary"+ id="notify"+ type="button"+ data-t="allowNotifications"+ ></button></div><div class="row"><span class="icon"@@ -2305,13 +2400,16 @@/></svg></span><div class="text">- <strong>Folders</strong- ><span class="sub">Folders tasks may read and change.</span>+ <strong data-t="folders"></strong+ ><span class="sub" data-t="foldersHint"></span><div class="folders" id="folders"></div></div>- <button class="secondary" id="folder" type="button">- Add Folder…- </button>+ <button+ class="secondary"+ id="folder"+ type="button"+ data-t="addFolder"+ ></button></div><div class="row mac-only"><span class="icon"@@ -2320,13 +2418,16 @@<path d="M8 8h8M8 12h8M8 16h5" /></svg></span><div class="text">- <strong>Full Disk Access</strong+ <strong data-t="fullDiskAccess"></strong><span class="sub" id="perm-full-disk-sub"></span></div><span class="badge" id="perm-full-disk-badge"></span>- <button class="secondary" id="perm-full-disk" type="button">- Open Settings- </button>+ <button+ class="secondary"+ id="perm-full-disk"+ type="button"+ data-t="openSettings"+ ></button></div><div class="row mac-only"><span class="icon"@@ -2334,13 +2435,16 @@<path d="M12 4v11M7 10l5 5 5-5M5 20h14" /></svg></span><div class="text">- <strong>Downloads, Documents, Desktop</strong+ <strong data-t="userFolders"></strong><span class="sub" id="perm-folders-sub"></span></div><span class="badge" id="perm-folders-badge"></span>- <button class="secondary" id="perm-folders" type="button">- Allow…- </button>+ <button+ class="secondary"+ id="perm-folders"+ type="button"+ data-t="allow"+ ></button></div><div class="row mac-only"><span class="icon"@@ -2349,13 +2453,16 @@<path d="M3 9h18M8 14l2 2 4-4" /></svg></span><div class="text">- <strong>Control other apps</strong+ <strong data-t="automation"></strong><span class="sub" id="perm-automation-sub"></span></div><span class="badge" id="perm-automation-badge"></span>- <button class="secondary" id="perm-automation" type="button">- Allow…- </button>+ <button+ class="secondary"+ id="perm-automation"+ type="button"+ data-t="allow"+ ></button></div><div class="row"><span class="icon"@@ -2363,17 +2470,15 @@<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9" /></svg></span><div class="text">- <strong>Prevent sleep</strong- ><span class="sub"- >Keep this computer awake for incoming tasks.</span- >+ <strong data-t="preventSleep"></strong+ ><span class="sub" data-t="preventSleepHint"></span></div><buttonclass="switch"id="sleep"role="switch"aria-checked="false"- aria-label="Prevent sleep"+ data-t-aria-label="preventSleep"type="button"></button></div>@@ -2384,18 +2489,15 @@<path d="M18.4 6.6a9 9 0 1 1-12.77.04" /></svg></span><div class="text">- <strong>Open at login</strong- ><span class="sub"- >Start in the <span data-tray>menu bar</span> when you log- in.</span- >+ <strong data-t="openAtLogin"></strong+ ><span class="sub" data-tray="openAtLogin"></span></div><buttonclass="switch"id="login"role="switch"aria-checked="false"- aria-label="Open at login"+ data-t-aria-label="openAtLogin"type="button"></button></div>@@ -2403,9 +2505,12 @@<p class="error" id="permissions-error" role="alert"></p><footer class="actions"><span class="spacer"></span>- <button class="primary" id="finish" type="button">- Start Using Linger- </button>+ <button+ class="primary"+ id="finish"+ type="button"+ data-t="startUsing"+ ></button></footer></section></main>@@ -2426,18 +2531,9 @@// What each macOS permission is for, and what goes wrong without it.const PERMISSIONS = {- "full-disk": {- about: "Recommended. Covers every folder, no prompts.",- missing: "Off. Protected folders prompt the first time.",- },- folders: {- about: "Lets tasks read these folders.",- missing: "Not allowed. Tasks can't read these folders.",- },- automation: {- about: "Lets tasks drive apps like your browser.",- missing: "Not allowed. Tasks can't control other apps.",- },+ "full-disk": { about: "fullDiskAbout", missing: "fullDiskMissing" },+ folders: { about: "userFoldersAbout", missing: "userFoldersMissing" },+ automation: { about: "automationAbout", missing: "automationMissing" },};// What Install sets up; Quick Install keeps the defaults.@@ -2450,18 +2546,25 @@// The installing steps, as the main process reports them; it says// which of them this installation shows.const ALL_STEPS = [- ["prepare", () => "Checking this computer"],- ["download", () => "Downloading Linger " + state.version],- ["services", () => "Setting up AI and local services"],- ["workspace", () => "Setting up your account"],+ ["prepare", () => t("stepPrepare")],+ // A version is an identifier, so its digits stay as they are.+ [+ "download",+ () => t("stepDownload", { version: String(state.version) }),+ ],+ ["services", () => t("stepServices")],+ ["workspace", () => t("stepWorkspace")],["signin",- () =>- "Sign in to " +- (RUNTIMES[state.localServer.signIn?.runtime] || "your AI runtime"),+ () => {+ const runtime = RUNTIMES[state.localServer.signIn?.runtime];+ return runtime+ ? t("stepSignIn", { runtime })+ : t("stepSignInRuntime");+ },],- ["connect", () => "Connecting this computer"],- ["agents", () => "Preparing your agents"],+ ["connect", () => t("stepConnect")],+ ["agents", () => t("stepAgents")],];const gigabytes = (bytes) => Math.round(bytes / 1024 ** 3) + " GB";// Download sizes: MB below a gigabyte, one decimal GB above.@@ -2471,16 +2574,12 @@: (bytes / 1024 ** 3).toFixed(1) + " GB";const duration = (seconds) => {const minutes = Math.round(seconds / 60);- if (minutes < 1) return "less than a minute left";- if (minutes < 60) return "about " + minutes + " min left";+ if (minutes < 1) return t("lessThanMinuteLeft");+ if (minutes < 60) return t("minutesLeft", { minutes });const hours = Math.floor(minutes / 60);- return (- "about " +- hours +- " h" +- (minutes % 60 ? " " + (minutes % 60) + " min" : "") +- " left"- );+ return minutes % 60+ ? t("hoursMinutesLeft", { hours, minutes: minutes % 60 })+ : t("hoursLeft", { hours });};// A download as the localmodels tool or the installer counts it: how// much of how much, what remains, and the rate and time left when the@@ -2489,11 +2588,12 @@const transferParts = (transfer) => {const { completed, total, bytesPerSecond: rate, partial } = transfer;const left = total && !partial ? total - completed : undefined;+ const amount = total+ ? t("amountOf", { done: size(completed), total: size(total) })+ : size(completed);return [- (partial ? "This file: " : "") +- size(completed) +- (total ? " of " + size(total) : ""),- left !== undefined && size(left) + " left",+ partial ? t("thisFile", { amount }) : amount,+ left !== undefined && t("amountLeft", { size: size(left) }),rate > 0 && size(rate) + "/s",rate > 0 && left !== undefined && duration(left / rate),].filter(Boolean);@@ -2514,9 +2614,7 @@return drive &&local.refusal?.code === "WINDOWS_PRIVATE_PATH_UNSAFE" &&local.refusal.reason === "UNSAFE_PARENT_ACCESS"- ? "Go back and set the install location to the drive itself (Linger installs into " +- drive +- "Linger) or an empty folder directly on the drive."+ ? t("locationHint", { folder: drive + "Linger" }): "";};// Quick Install installs what the localmodels tool recommends for this@@ -2563,21 +2661,18 @@};const DEFAULT_PATH = "/v1";const PATH_OPTIONS = [- { value: "/v1", label: "Most providers" },- {- value: "/api/paas/v4",- label: "Zhipu GLM (base https://open.bigmodel.cn)",- },- { value: "/api/v3", label: "Volcano Engine Ark" },+ { value: "/v1", label: t("pathMostProviders") },+ { value: "/api/paas/v4", label: t("pathZhipu") },+ { value: "/api/v3", label: t("pathVolcano") },{ value: "/v1beta/openai", label: "Gemini" },- { value: "", label: "No path. The base URL already has it." },+ { value: "", label: t("pathNone") },];const ENDPOINT_OPTIONS = [...Object.values(BYOK_FORMATS).map((format) => ({value: format.suffix,label: format.label,})),- { value: "", label: "No endpoint. The base URL is the full address." },+ { value: "", label: t("endpointNone") },];// What the installer accepts as a path or endpoint: empty, or whole// segments, so neither can change the base URL's host.@@ -2600,6 +2695,13 @@(c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c],);const urlHtml = (url) => '<span class="url">' + esc(url) + "</span>";+ // A message with <url> spans, as HTML for the places that build it.+ const tHtml = (name, values) =>+ tSpans(name, values)+ .map((node) =>+ typeof node === "string" ? esc(node) : node.outerHTML,+ )+ .join("");const contextLabel = (tokens) =>tokens >= 1024 ** 2? Math.round((tokens / 1024 ** 2) * 10) / 10 + "M"@@ -2623,7 +2725,7 @@return (state.localServer[field] ?? {state: "failed",- message: "Linger did not answer.",+ message: t("noAnswer"),});} catch (error) {@@ -2642,11 +2744,11 @@<input class="cb-input" id="${cfg.id}" role="combobox"aria-autocomplete="none" aria-expanded="false"aria-controls="${cfg.id}-menu" autocomplete="off" spellcheck="false"- placeholder="${esc(cfg.placeholder)}" aria-label="${cfg.label}" />+ placeholder="${esc(cfg.placeholder)}" aria-label="${esc(cfg.label)}" /><button type="button" class="cb-caret" tabindex="-1"- aria-label="Show ${cfg.label} suggestions">${ICONS.chevron}</button>+ aria-label="${esc(t("showSuggestions", { field: cfg.label }))}">${ICONS.chevron}</button><div class="cb-menu" id="${cfg.id}-menu" role="listbox"- aria-label="${cfg.label}" hidden></div>`;+ aria-label="${esc(cfg.label)}" hidden></div>`;const input = root.querySelector(".cb-input");const caret = root.querySelector(".cb-caret");const menu = root.querySelector(".cb-menu");@@ -2765,18 +2867,19 @@<div class="ep"><span class="ep-base-wrap"><input class="ep-base" id="${prefix}-url"type="url" autocomplete="off" spellcheck="false"- aria-label="Base URL" placeholder="Base URL (https://…)" /></span>+ aria-label="${esc(t("baseUrl"))}"+ placeholder="${esc(t("baseUrlPlaceholder"))}" /></span><div></div><div></div></div><input class="byok-key" id="${prefix}-key" type="password"- autocomplete="off" spellcheck="false" aria-label="API key"- placeholder="API key (stored privately on this computer)" />+ autocomplete="off" spellcheck="false" aria-label="${esc(t("apiKey"))}"+ placeholder="${esc(t("apiKeyPlaceholder"))}" /><div class="model-row"><div class="standalone"></div><button type="button" class="change list-btn" id="${prefix}-list"- aria-label="List models" title="List models">${ICONS.refresh}</button>- <button type="button" class="change test-btn" id="${prefix}-test">Test</button>+ aria-label="${esc(t("listModels"))}" title="${esc(t("listModels"))}">${ICONS.refresh}</button>+ <button type="button" class="change test-btn" id="${prefix}-test">${esc(t("test"))}</button><div class="byok-toast" id="${prefix}-toast" role="status"aria-live="polite" hidden></div></div>@@ -2877,8 +2980,8 @@const [pathBox, endpointBox] = root.querySelectorAll(".ep > div");const path = combobox(pathBox, {id: prefix + "-path",- label: "Path",- heading: "Path · optional",+ label: t("path"),+ heading: esc(t("pathHeading")),placeholder: "-",get: () => f.path,set: (value) => edit({ path: value }, true),@@ -2889,13 +2992,13 @@items: () =>PATH_OPTIONS.map((option) => ({...option,- tag: option.value === DEFAULT_PATH ? "Default" : "",+ tag: option.value === DEFAULT_PATH ? t("defaultTag") : "",})),});const endpointCombo = combobox(endpointBox, {id: prefix + "-endpoint",- label: "Endpoint",- heading: "Endpoint · optional",+ label: t("endpoint"),+ heading: esc(t("endpointHeading")),placeholder: "-",get: endpointValue,set: (value) =>@@ -2917,49 +3020,36 @@...option,tag:option.value === defaultEndpoint()- ? RUNTIMES[runtimeOf()] + " default"+ ? t("runtimeDefault", { runtime: RUNTIMES[runtimeOf()] }): "",})),});const modelCombo = combobox(root.querySelector(".model-row > div"), {id: prefix + "-model",- label: "Model",- placeholder: "Model ID (e.g. gpt-5.4 or claude-sonnet-4-6)",+ label: t("model"),+ placeholder: t("modelPlaceholder"),get: () => f.modelId,set: (value) => edit({ modelId: value }, false),commit: () => {f = { ...f, modelId: f.modelId.trim() };},items: () => {- if (!models)- return [- {- note: "Use the refresh button to list the endpoint's models, or type an ID.",- },- ];+ if (!models) return [{ note: esc(t("modelsHint")) }];if (models.state === "loading")- return [- {- note: "Listing models from " + urlHtml(modelsUrl()) + "…",- },- ];+ return [{ note: tHtml("listingFrom", { url: modelsUrl() }) }];if (models.state === "failed")return [{ note: esc(models.message), tone: "err" }];const count = models.models.length;return [- {- note:- count +- (count === 1 ? " model" : " models") +- " from " +- urlHtml(models.url),- },+ { note: tHtml("modelsFrom", { count, url: models.url }) },...models.models.map((model) => ({value: model.id,label: [model.name !== model.id && model.name,model.contextWindow &&- contextLabel(model.contextWindow) + " context",+ t("contextSize", {+ size: contextLabel(model.contextWindow),+ }),].filter(Boolean).join(" · "),@@ -3054,10 +3144,10 @@list.dataset.busy = String(listing);list.setAttribute("aria-label",- listing ? "Listing models" : "List models",+ t(listing ? "listingModels" : "listModels"),);test.disabled = busy || checking || !complete();- test.textContent = checking ? "Testing…" : "Test";+ test.textContent = t(checking ? "testing" : "test");const shown = Boolean(toast && check && !checking);toastEl.hidden = !shown;if (shown) {@@ -3067,14 +3157,14 @@const html = `<span class="toast-icon">${ok ? ICONS.ok : ICONS.err}</span><div>- <strong>${ok ? "Connected" : "Couldn't connect"}</strong>+ <strong>${esc(t(ok ? "connected" : "couldNotConnect"))}</strong><div>${ok- ? `${esc(check.modelId)} · ${contextLabel(check.contextWindow)} context · ${BYOK_FORMATS[check.protocol].label}<br />${urlHtml(check.url)}`+ ? `${esc(check.modelId)} · ${esc(t("contextSize", { size: contextLabel(check.contextWindow) }))} · ${BYOK_FORMATS[check.protocol].label}<br />${urlHtml(check.url)}`: esc(check.message)}</div></div>- <button type="button" class="toast-close" aria-label="Dismiss">${ICONS.close}</button>`;+ <button type="button" class="toast-close" aria-label="${esc(t("dismiss"))}">${ICONS.close}</button>`;if (html !== toastShown) {toastEl.innerHTML = html;toastShown = html;@@ -3082,31 +3172,21 @@}let line;if (!validParts())- line = {- tone: "err",- html: "Path and endpoint must be empty or a path such as /v1.",- };+ line = { tone: "err", html: esc(t("invalidParts")) };else if (models?.state === "failed")line = { tone: "err", html: esc(models.message) };else if (listing)- line = {- html: "Listing models from " + urlHtml(modelsUrl()) + "…",- };- else if (!baseUrl())- line = {- html: "Grey values are defaults. Path and endpoint are optional.",- };+ line = { html: tHtml("listingFrom", { url: modelsUrl() }) };+ else if (!baseUrl()) line = { html: esc(t("greyDefaults")) };else {const { protocol, fromUrl } = format();+ const values = {+ format: BYOK_FORMATS[protocol].label,+ runtime: RUNTIMES[runtimeOf()],+ url: requestUrl(),+ };line = {- html:- "Sends " +- BYOK_FORMATS[protocol].label +- (fromUrl- ? ""- : " (the " + RUNTIMES[runtimeOf()] + " format)") +- " requests to " +- urlHtml(requestUrl()),+ html: tHtml(fromUrl ? "sendsTo" : "sendsToRuntime", values),};}if (line.tone) status.dataset.tone = line.tone;@@ -3326,10 +3406,12 @@render();}, 1000);- // Whose account each runtime signs in with.- const ACCOUNTS = {- codex: "your ChatGPT account",- claude: "your Claude account",+ // What the sign-in dialog says first for each runtime; each names+ // whose account it signs in with.+ const SIGN_IN_LEADS = {+ codex: "signInLeadCodex",+ claude: "signInLeadClaude",+ pi: "signInLeadPi",};let otherRuntimes = false;// The runtime installed but not signed in: a dialog starts its own@@ -3355,24 +3437,22 @@const running =sign.state === "starting" || sign.state === "waiting_user";const pi = sign.runtime === "pi";- $("runtime-signin-title").textContent = "Sign in to " + name;- $("runtime-signin-lead").textContent = pi- ? "Pi needs a model provider. Run pi in a terminal to sign in, or use BYOK below; setup continues by itself."- : "Your agents run on " +- name +- ". Authorize it with " +- ACCOUNTS[sign.runtime] +- " to continue.";+ $("runtime-signin-title").textContent = t("signInTo", {+ runtime: name,+ });+ $("runtime-signin-lead").textContent = t(SIGN_IN_LEADS[sign.runtime]);$("runtime-signin-lead").hidden = running;$("runtime-signin-waiting").hidden = !running;$("runtime-signin-device").hidden = !sign.deviceCode;$("runtime-signin-device-code").textContent = sign.deviceCode || "";$("runtime-signin-error").textContent = failed- ? sign.message || "Sign-in did not finish."+ ? sign.message || t("signInFailed"): "";$("runtime-signin-idle").hidden = running;$("runtime-signin-start").hidden = pi;- $("runtime-signin-start").textContent = failed ? "Retry" : "Authorize";+ $("runtime-signin-start").textContent = t(+ failed ? "retry" : "authorize",+ );$("runtime-signin-logs").hidden = !failed;$("runtime-signin-runtimes").hidden = !otherRuntimes && !pi;$("runtime-signin-other").hidden = pi;@@ -3389,9 +3469,9 @@// The fallback: the printed link, and for Claude Code the code its// page shows.$("runtime-signin-trouble").hidden = !sign.url || !!sign.deviceCode;- $("runtime-signin-help").textContent = sign.acceptsCode- ? "If your browser didn't open, choose Open browser again, then paste the code the page shows."- : "If your browser didn't open, choose Open browser again.";+ $("runtime-signin-help").textContent = t(+ sign.acceptsCode ? "signInHelpCode" : "signInHelp",+ );$("runtime-signin-paste").hidden = !sign.acceptsCode;requestAnimationFrame(placeKnobs);};@@ -3401,75 +3481,62 @@// model fits the hardware, but other programs hold memory it needs now.const counts = (free, needed) =>free != null && needed != null- ? " (" + size(free) + " free, " + size(needed) + " needed)"+ ? t("memoryCounts", { free: size(free), needed: size(needed) }): "";const reasonText = (reason, held, freeMemory) => {switch (reason.code) {- case "gpu-memory-required":- return (- "Other programs are using " +- (reason.gpuIndex != null- ? "GPU " + reason.gpuIndex + "'s"- : "the GPU's") +- " memory" +- counts(reason.freeBytes, reason.requiredBytes) +- ". Close programs that use the GPU, such as games, video or other AI apps."- );+ case "gpu-memory-required": {+ const values = {+ gpu: String(reason.gpuIndex),+ counts: counts(reason.freeBytes, reason.requiredBytes),+ };+ return reason.gpuIndex != null+ ? t("reasonGpuMemoryOf", values)+ : t("reasonGpuMemory", values);+ }case "free-memory-required":- return (- "Other programs are using the memory it needs" +- (counts(reason.freeBytes, reason.requiredBytes) ||+ return t("reasonFreeMemory", {+ counts:+ counts(reason.freeBytes, reason.requiredBytes) ||counts(freeMemory?.ramAvailableBytes,freeMemory?.ramRequiredBytes,- )) +- ". Close other programs."- );+ ),+ });case "gpu-sharing-required":- return "Other work is running on the GPU. Close it.";+ return t("reasonGpuSharing");// localmodels 0.1.0.dev39 reports it; later versions plan by the// GPU memory free instead.case "gpu-ownership-unknown":- return "Linger couldn't tell which programs are using the GPU, so it can't share it. Close programs that use the GPU.";+ return t("reasonGpuOwnership");case "facts-unavailable":- return "Linger couldn't read this computer's memory, disk or GPU.";+ return t("reasonFacts");case "cuda-driver-update-required": {const has = reason.detectedCudaVersion;const needs = reason.requiredCudaVersion;if (has && needs)- return (- "Your NVIDIA driver supports CUDA " +- has +- ", but local models require CUDA " +- needs +- " or newer. Update your NVIDIA driver, then choose Check again."- );+ return t("reasonCudaUpdate", {+ has: String(has),+ needs: String(needs),+ });if (needs)- return (- "Your NVIDIA driver is too old for local models (requires CUDA " +- needs +- " or newer). Update your NVIDIA driver, then choose Check again."- );- return "Your NVIDIA driver is too old for local models. Update your NVIDIA driver, then choose Check again.";+ return t("reasonCudaTooOldNeeds", { needs: String(needs) });+ return t("reasonCudaTooOld");}case "cuda-driver-version-unknown":return reason.requiredCudaVersion- ? "Linger couldn't read the CUDA version from your NVIDIA driver (requires CUDA " +- reason.requiredCudaVersion +- " or newer). Update or reinstall your NVIDIA driver, then choose Check again."- : "Linger couldn't read the CUDA version from your NVIDIA driver. Update or reinstall your NVIDIA driver, then choose Check again.";+ ? t("reasonCudaUnknownNeeds", {+ needs: String(reason.requiredCudaVersion),+ })+ : t("reasonCudaUnknown");case "unsupported-platform":- return "Local models don't run on this system.";+ return t("reasonUnsupported");// Blocked now, it names another inference app holding a Mac's// memory.case "plan-unavailable":- return held- ? "Another app is holding the memory it needs, such as another AI app. Quit it."- : "No local model fits this computer.";+ return t(held ? "reasonPlanHeld" : "reasonPlanUnavailable");default:- return held- ? "Other programs are using the memory it needs. Close other programs."- : "This computer can't run a local model now.";+ return t(held ? "reasonHeld" : "reasonUnavailable");}};const reasonsText = (models, held) =>@@ -3492,15 +3559,16 @@reason.freeBytes != null &&reason.requiredBytes != null,);- if (gpu)- return (- "On hold: " +- (gpu.gpuIndex != null ? "GPU " + gpu.gpuIndex : "The GPU") +- " has " +- size(gpu.freeBytes) +- " free, needs " +- size(gpu.requiredBytes)- );+ if (gpu) {+ const values = {+ gpu: String(gpu.gpuIndex),+ free: size(gpu.freeBytes),+ needed: size(gpu.requiredBytes),+ };+ return gpu.gpuIndex != null+ ? t("heldGpuOf", values)+ : t("heldGpu", values);+ }const ram = models.reasons?.find((reason) =>reason.code === "free-memory-required" &&@@ -3511,8 +3579,8 @@const needed =ram?.requiredBytes ?? models.freeMemory?.ramRequiredBytes;return free != null && needed != null- ? "On hold: " + size(free) + " of memory free, needs " + size(needed)- : "On hold: close other programs, then Check again.";+ ? t("heldMemory", { free: size(free), needed: size(needed) })+ : t("heldClose");};const renderLocal = (busy) => {@@ -3544,15 +3612,15 @@const following = JSON.stringify(plan) === JSON.stringify(recommended);const named = (choice) =>choice.source === "local"- ? "Local model + Pi"+ ? t("localModelPi"): choice.source === "byok"? ["BYOK", RUNTIMES[byokRuntime], mainByok.modelId()].filter(Boolean).join(" · "): RUNTIMES[choice.runtime];- $("welcome-lead").textContent = local.available- ? "Runs on this computer, just for you. Takes a few minutes."- : "Connect this computer to your team's Linger.";+ $("welcome-lead").textContent = t(+ local.available ? "welcomeLeadLocal" : "welcomeLeadTeam",+ );$("local-install").hidden = !local.available;$("team").hidden = !local.available || customizing;$("get-started").hidden = local.available;@@ -3560,19 +3628,17 @@customizing && local.available,);$("local-customize").setAttribute("aria-expanded", String(customizing));- $("local-customize").textContent = customizing- ? "Use the defaults"- : "Customize";+ $("local-customize").textContent = t(+ customizing ? "useDefaults" : "customize",+ );// Until the check ends the button says what it waits for: the first// run downloads the localmodels tool, then the check runs. The label// changes only when it differs, so the spinner keeps turning.const fetching = checking ? models.download : undefined;const label = checking? '<span class="spinner"></span>' +- (fetching ? "Downloading setup tools…" : "Checking this computer…")- : custom- ? "Install"- : "Quick Install";+ esc(t(fetching ? "downloadingTools" : "checkingComputer"))+ : esc(t(custom ? "install" : "quickInstall"));if ($("local-install-label").innerHTML !== label)$("local-install-label").innerHTML = label;document.querySelector('[data-step="welcome"]').dataset.customizing =@@ -3584,16 +3650,16 @@$("local-install").dataset.busy = String(checking);$("local-install").setAttribute("aria-busy", String(checking));$("plan-summary").textContent = checking- ? "Finding the best setup for this computer"+ ? t("findingSetup"): following && known- ? "Recommended for this computer: " + named(plan)- : named(plan) || "Best AI runtime";+ ? t("recommendedPlan", { plan: named(plan) })+ : named(plan) || t("bestRuntime");// Why: the localmodels tool's facts, and its reason codes in the// page's words.const unavailableText =models.state === "checked"? reasonsText(models, false)- : "Couldn't check this computer for a local model.";+ : t("cannotCheck");$("plan-why").textContent = fetching? transferParts(fetching).join(" · "): !following || checking@@ -3601,19 +3667,22 @@: plan.localModel? [model.name,- "fits " + (models.gpu || "this computer"),- gigabytes(models.memoryBytes) + " memory",+ models.gpu+ ? t("fitsGpu", { gpu: models.gpu })+ : t("fitsComputer"),+ t("memoryAmount", { size: gigabytes(models.memoryBytes) }),model.downloadBytes != null &&- gigabytes(model.downloadBytes) + " download",+ t("downloadAmount", {+ size: gigabytes(model.downloadBytes),+ }),].filter(Boolean).join(" · "): held- ? "Local model on hold. " +- reasonsText(models, true) +- " Quick Install sets up " +- named(plan) +- " now, or choose Check again once memory is free."+ ? t("heldWhy", {+ reasons: reasonsText(models, true),+ plan: named(plan),+ }): (models.state === "checked" && !models.eligible) ||models.state === "unavailable"? unavailableText@@ -3631,27 +3700,25 @@const provider = input.dataset.key;const saved = local.keys[provider];const removing = keys[provider] === "";- input.placeholder = removing- ? "Removed when you install"- : saved- ? "Saved · type to replace"- : "API key";+ input.placeholder = t(+ removing ? "keyRemovedOnInstall" : saved ? "keySaved" : "apiKey",+ );const remove = document.querySelector(`[data-remove="${provider}"]`);// Kept in place so the inputs line up.remove.style.visibility =saved || keys[provider] ? "visible" : "hidden";- remove.textContent = removing ? "Keep" : "Remove";+ remove.textContent = t(removing ? "keep" : "remove");}- $("keys-note").textContent = "Applies when the installation runs.";+ $("keys-note").textContent = t("keysNote");const shown = model || held;$("source-sub").textContent =recommended.source === "local"- ? "Recommended: Local model on this computer."+ ? t("recommendedLocal"): known- ? "Recommended: Subscription (" +- RUNTIMES[recommended.runtime] +- ")."- : "Choose how your agents run.";+ ? t("recommendedSubscription", {+ runtime: RUNTIMES[recommended.runtime],+ })+ : t("chooseSource");$("local-row").hidden = plan.source !== "local";$("subscription-row").hidden = plan.source !== "subscription";$("byok-row").hidden = plan.source !== "byok";@@ -3673,9 +3740,7 @@$("local-sub").textContent = held? heldLine(models): [- recommended.localModel- ? "Recommended for this computer · Runs on Pi via Bifrost"- : "Runs your tasks on this computer via Pi",+ t(recommended.localModel ? "localRecommended" : "localRuns"),models.gpu,].filter(Boolean)@@ -3683,33 +3748,33 @@$("local-model-name").textContent = shown.name;$("local-model-needs").textContent = [shown.downloadBytes != null &&- gigabytes(shown.downloadBytes) + " download",- shown.diskBytes != null && gigabytes(shown.diskBytes) + " disk",+ t("downloadAmount", { size: gigabytes(shown.downloadBytes) }),+ shown.diskBytes != null &&+ t("diskAmount", { size: gigabytes(shown.diskBytes) }),// The whole stack's memory, so more than the model's own on// the Local models page.shown.memoryBytes != null &&- gigabytes(shown.memoryBytes) + " memory with its services",+ t("memoryWithServices", { size: gigabytes(shown.memoryBytes) }),].filter(Boolean).join(" · ");$("local-model").setAttribute("aria-checked", String(!!model));$("local-model").disabled = busy || !model;} else if (settled) {- $("local-sub").textContent =- "Runs your tasks on this computer via Pi";- $("local-model-name").textContent = "Not available on this computer";+ $("local-sub").textContent = t("localRuns");+ $("local-model-name").textContent = t("localNotAvailable");$("local-model-needs").textContent = unavailableText;$("local-model").setAttribute("aria-checked", "false");$("local-model").disabled = true;} else {- $("local-sub").textContent = "Checking this computer…";+ $("local-sub").textContent = t("checkingComputer");}const subKnown =recommended.source === "subscription" &&recommended.runtime !== "recommended";$("runtime-sub").textContent = subKnown- ? "Recommended: " + RUNTIMES[recommended.runtime] + "."- : "Sign in with your ChatGPT or Claude subscription.";+ ? t("recommendedRuntime", { runtime: RUNTIMES[recommended.runtime] })+ : t("subscriptionHint");for (const seg of document.querySelectorAll("[data-plan]"))for (const option of seg.querySelectorAll("button")) {const field = seg.dataset.plan;@@ -3753,15 +3818,16 @@// Installing. A restart after a reboot shows here as starting.const failed = local.phase === "failed";const starting = local.phase === "preparing";- $("installing-title").textContent = failed- ? "Installation stopped"- : starting- ? "Starting Linger"- : "Installing Linger";+ $("installing-title").textContent = t(+ failed+ ? "installStopped"+ : starting+ ? "startingLinger"+ : "installingTitle",+ );$("installing-plan").textContent = failed- ? locationHint(local) ||- "Your data is kept. Fix the problem and try again."- : "This takes a few minutes. You can keep working.";+ ? locationHint(local) || t("dataKept")+ : t("takesMinutes");const section = document.querySelector('[data-step="installing"]');const steps = ALL_STEPS.filter(([id]) => local.steps.includes(id));section.dataset.failed = String(failed);@@ -3777,8 +3843,12 @@$("installing-step").textContent = failed? steps[at][1](): starting- ? local.message- : steps[at][1]() + "…";+ ? t(+ local.preparing === "updating"+ ? "preparingUpdate"+ : "preparingStart",+ )+ : t("stepRunning", { step: steps[at][1]() });$("installing-count").textContent = starting ? "" : percent + "%";// A download under way: what it is and how far, in the counts the// installer passes on from the localmodels tool.@@ -3832,9 +3902,9 @@const long = failed && problem.scrollHeight > problem.clientHeight + 1;problem.classList.toggle("folded", long && !detailsOpen);$("installing-more").hidden = !long;- $("installing-more").textContent = detailsOpen- ? "Hide Details"- : "Show Details";+ $("installing-more").textContent = t(+ detailsOpen ? "hideDetails" : "showDetails",+ );$("installing-diagnostics").hidden = !failed;// A new save result replaces the note; a failed "Show Logs" writes// its own error there and stays until the next result.@@ -3843,7 +3913,7 @@if (saved && savedKey !== shownDiagnostics)$("diagnostics-note").textContent = saved.error? saved.error- : "Saved " + saved.file + ". Send this file to Linger support.";+ : t("savedDiagnostics", { file: saved.file });shownDiagnostics = savedKey;$("installing-actions").hidden = !failed;renderSignIn(local, busy);@@ -3855,13 +3925,11 @@$("installing-actions").scrollIntoView({ block: "nearest" }),);}- $("ready-lead").textContent = "Running on this computer, just for you.";+ $("ready-lead").textContent = t("readyLead");renderAccount(local.account);$("legacy-note").hidden = !local.legacyBackup;$("legacy-note").textContent = local.legacyBackup- ? "Your data from the earlier Simplex app can't be upgraded to Linger, so this is a fresh workspace. The earlier data was moved, not deleted, to " +- local.legacyBackup +- "."+ ? t("legacyNote", { folder: local.legacyBackup }): "";};@@ -3879,13 +3947,13 @@$("account-email").textContent = account.email;$("account-password").textContent =account.password ?? "\u2022".repeat(12);- $("account-show").textContent = account.password ? "Hide" : "Show";+ $("account-show").textContent = t(account.password ? "hide" : "show");$("account-show").setAttribute("aria-label",- (account.password ? "Hide" : "Show") + " password",+ t(account.password ? "hidePassword" : "showPassword"),);- $("account-copy").textContent = copied ? "Copied" : "Copy";- $("account-copy").setAttribute("aria-label", "Copy password");+ $("account-copy").textContent = t(copied ? "copied" : "copy");+ $("account-copy").setAttribute("aria-label", t("copyPassword"));};const render = () => {@@ -3893,11 +3961,13 @@document.body.dataset.platform = state.platform;// Where the tray icon lives on this platform.for (const el of document.querySelectorAll("[data-tray]"))- el.textContent =- state.platform === "darwin" ? "menu bar" : "system tray";+ el.textContent = t(+ el.dataset.tray ++ (state.platform === "darwin" ? "MenuBar" : "Tray"),+ );const at = ORDER.indexOf(step);$("step-label").textContent =- at >= 0 ? "Step " + (at + 1) + " of " + ORDER.length : "";+ at >= 0 ? t("stepOf", { step: at + 1, total: ORDER.length }) : "";const busy = pending !== null;for (const el of document.querySelectorAll("main button"))el.disabled = busy && el.dataset.go === undefined;@@ -3909,21 +3979,21 @@$("signin-host").textContent = host(state.serverUrl);$("signin-badge").dataset.ok = String(state.signedIn);$("signin-badge").innerHTML = state.signedIn- ? check + "Signed in"+ ? check + esc(t("signedIn")): pending === "signin.open"- ? '<span class="spinner"></span>Waiting…'- : "Not signed in";- $("signin").textContent = state.signedIn ? "Continue" : "Open Sign-in";+ ? '<span class="spinner"></span>' + esc(t("waiting"))+ : esc(t("notSignedIn"));+ $("signin").textContent = t(state.signedIn ? "continue" : "openSignIn");$("computer-name").textContent = state.displayName;$("computer-host").textContent = host(state.serverUrl);$("connect-badge").dataset.ok = String(state.enrolled);$("connect-badge").innerHTML = state.enrolled- ? check + "Connected"+ ? check + esc(t("connected")): pending === "computer.connect"- ? '<span class="spinner"></span>Connecting…'+ ? '<span class="spinner"></span>' + esc(t("connecting")): "";- $("connect").textContent = state.enrolled ? "Continue" : "Connect";+ $("connect").textContent = t(state.enrolled ? "continue" : "connect");$("sleep").setAttribute("aria-checked", String(state.preventSleep));$("login").setAttribute("aria-checked", String(state.openAtLogin));@@ -3931,18 +4001,19 @@const status = state.permissions?.[id] ?? "unknown";const granted = status === "granted";const sub = $("perm-" + id + "-sub");- sub.textContent = status === "denied" ? text.missing : text.about;+ sub.textContent = t(status === "denied" ? text.missing : text.about);// Most Macs run without Full Disk Access; only refusals are warnings.sub.dataset.warn = String(status === "denied" && id !== "full-disk");const badge = $("perm-" + id + "-badge");badge.dataset.ok = String(granted);- badge.innerHTML = granted ? check + "Allowed" : "";+ badge.innerHTML = granted ? check + esc(t("allowed")) : "";const button = $("perm-" + id);button.hidden = granted;- button.textContent =+ button.textContent = t(id === "full-disk" || status === "denied"- ? "Open Settings"- : "Allow…";+ ? "openSettings"+ : "allow",+ );}const folders = $("folders");folders.replaceChildren(@@ -3968,37 +4039,37 @@$("send-modal").hidden = phase === "idle";if (phase === "idle") return;const title = {- preparing: "Preparing diagnostics",- confirm: "Send diagnostics to " + send.host + "?",- sending: "Sending diagnostics",- sent: "Diagnostics sent",- failed: "Couldn't send diagnostics",+ preparing: "sendPreparing",+ confirm: "sendConfirm",+ sending: "sendSending",+ sent: "sendSent",+ failed: "sendFailed",}[phase];- $("send-title").textContent = title;+ $("send-title").textContent = t(title, { host: send.host });const lead = $("send-lead");if (phase === "preparing")lead.innerHTML =- '<span class="spinner"></span>Collecting logs and settings…';+ '<span class="spinner"></span>' + esc(t("sendCollecting"));elselead.textContent =phase === "confirm"- ? send.files.length +- " files, " +- fileSize(send.bytes) +- ": logs and settings of this app and of Linger on this computer. Passwords, tokens, keys and your home folder path are removed first; credential files and your data are never included. Only the people who run " +- send.host +- " can read the report."+ ? t("sendConfirmLead", {+ count: send.files.length,+ size: fileSize(send.bytes),+ host: send.host,+ }): phase === "sending"- ? "Uploading to " +- send.host +- "… " +- Math.floor((send.sent / Math.max(1, send.total)) * 100) +- "%"+ ? t("sendUploading", {+ host: send.host,+ percent: Math.floor(+ (send.sent / Math.max(1, send.total)) * 100,+ ),+ }): phase === "sent"- ? "Give this report ID to Linger support so they can find your report."+ ? t("sendSentLead"): send.retry? ""- : "You can still use Save Diagnostics and send the file by hand.";+ : t("sendByHand");const files = $("send-files");files.hidden = phase !== "confirm";if (@@ -4022,17 +4093,17 @@$("send-report-id").textContent = phase === "sent" ? send.reportId : "";$("send-error").textContent = phase === "failed" ? send.error : "";const primary = {- confirm: "Send",- sent: copiedReport === send.reportId ? "Copied" : "Copy Report ID",- failed: send.retry ? "Try Again" : "",+ confirm: "send",+ sent: copiedReport === send.reportId ? "copied" : "copyReportId",+ failed: send.retry ? "tryAgain" : "",}[phase];$("send-primary").hidden = !primary;- $("send-primary").textContent = primary ?? "";- const close = { confirm: "Cancel", sent: "Done", failed: "Close" }[+ $("send-primary").textContent = primary ? t(primary) : "";+ const close = { confirm: "cancel", sent: "done", failed: "close" }[phase];$("send-close").hidden = !close;- $("send-close").textContent = close ?? "";+ $("send-close").textContent = close ? t(close) : "";};// Runs one command at a time; errors land next to the step.@@ -4180,7 +4251,7 @@input.type = "password";}for (const reveal of document.querySelectorAll("[data-reveal]"))- reveal.textContent = "Show";+ reveal.textContent = t("show");};for (const input of document.querySelectorAll("[data-key]"))input.addEventListener("input", () => {@@ -4196,7 +4267,7 @@reveal.addEventListener("click", () => {const input = $(`key-${reveal.dataset.reveal}`);input.type = input.type === "password" ? "text" : "password";- reveal.textContent = input.type === "password" ? "Show" : "Hide";+ reveal.textContent = t(input.type === "password" ? "show" : "hide");});for (const remove of document.querySelectorAll("[data-remove]"))remove.addEventListener("click", () => {@@ -4317,7 +4388,7 @@});$("notify").addEventListener("click", async () => {if (await run({ op: "notifications.test" }, "permissions-error"))- $("notify").textContent = "Test Sent";+ $("notify").textContent = t("testSent");});$("folder").addEventListener("click", () =>run({ op: "folder.add" }, "permissions-error"),diff --git a/apps/desktop/src/shell/setup.messages.ts b/apps/desktop/src/shell/setup.messages.tsnew file mode 100644index 00000000..843fecee--- /dev/null+++ b/apps/desktop/src/shell/setup.messages.ts@@ -0,0 +1,300 @@+import { defineMessages } from "@linger/service-kit/messages";++// The setup window (setup.html): installing Linger on this computer or+// connecting it to a team server, then the permissions it asks for.+export const setupMessages = defineMessages("setup", {+ pageTitle: "Set Up Linger",++ // Welcome and the install plan.+ welcomeEyebrow: "Private to this computer",+ welcomeTitle: "Set up Linger",+ welcomeLeadLocal: "Runs on this computer, just for you. Takes a few minutes.",+ welcomeLeadTeam: "Connect this computer to your team's Linger.",+ modelSource: "Model source",+ modelSourceHint: "Where your agents get their models.",+ localModel: "Local model",+ subscription: "Subscription",+ byokTooltip:+ "Bring Your Own Key — Connect your own OpenAI-compatible or Anthropic API endpoint, key, and model through Linger's local Bifrost gateway.",+ localModelToggle: "Run tasks on a local model",+ aiRuntime: "AI runtime",+ runtimeHint: "Runs your tasks.",+ auto: "Auto",+ appIntegrations: "App integrations (optional)",+ appIntegrationsHint:+ "Composio connects apps; turn on voice inside the app. Keys stay on this computer.",+ composioKey: "Composio API key",+ show: "Show",+ hide: "Hide",+ remove: "Remove",+ keep: "Keep",+ installLocation: "Install location",+ changeLocation: "Change…",+ quickInstall: "Quick Install",+ install: "Install",+ getStarted: "Get Started",+ customize: "Customize",+ useDefaults: "Use the defaults",+ checkAgain: "Check again",+ teamServer: "Have a team server?",+ connectInstead: "Connect to it instead",+ downloadingTools: "Downloading setup tools…",+ checkingComputer: "Checking this computer…",+ findingSetup: "Finding the best setup for this computer",+ recommendedPlan: "Recommended for this computer: {plan}",+ bestRuntime: "Best AI runtime",+ localModelPi: "Local model + Pi",+ cannotCheck: "Couldn't check this computer for a local model.",+ fitsGpu: "fits {gpu}",+ fitsComputer: "fits this computer",+ memoryAmount: "{size} memory",+ downloadAmount: "{size} download",+ diskAmount: "{size} disk",+ memoryWithServices: "{size} memory with its services",+ heldWhy:+ "Local model on hold. {reasons} Quick Install sets up {plan} now, or choose Check again once memory is free.",+ keyRemovedOnInstall: "Removed when you install",+ keySaved: "Saved · type to replace",+ apiKey: "API key",+ keysNote: "Applies when the installation runs.",+ recommendedLocal: "Recommended: Local model on this computer.",+ recommendedSubscription: "Recommended: Subscription ({runtime}).",+ chooseSource: "Choose how your agents run.",+ localRecommended: "Recommended for this computer · Runs on Pi via Bifrost",+ localRuns: "Runs your tasks on this computer via Pi",+ localNotAvailable: "Not available on this computer",+ recommendedRuntime: "Recommended: {runtime}.",+ subscriptionHint: "Sign in with your ChatGPT or Claude subscription.",+ locationHint:+ "Go back and set the install location to the drive itself (Linger installs into {folder}) or an empty folder directly on the drive.",++ // Download progress.+ lessThanMinuteLeft: "less than a minute left",+ minutesLeft: "about {minutes} min left",+ hoursLeft: "about {hours} h left",+ hoursMinutesLeft: "about {hours} h {minutes} min left",+ thisFile: "This file: {amount}",+ amountOf: "{done} of {total}",+ amountLeft: "{size} left",++ // Why a local model is not offered, in the page's words for each reason+ // code of the localmodels tool.+ memoryCounts: " ({free} free, {needed} needed)",+ reasonGpuMemory:+ "Other programs are using the GPU's memory{counts}. Close programs that use the GPU, such as games, video or other AI apps.",+ reasonGpuMemoryOf:+ "Other programs are using GPU {gpu}'s memory{counts}. Close programs that use the GPU, such as games, video or other AI apps.",+ reasonFreeMemory:+ "Other programs are using the memory it needs{counts}. Close other programs.",+ reasonGpuSharing: "Other work is running on the GPU. Close it.",+ reasonGpuOwnership:+ "Linger couldn't tell which programs are using the GPU, so it can't share it. Close programs that use the GPU.",+ reasonFacts: "Linger couldn't read this computer's memory, disk or GPU.",+ reasonCudaUpdate:+ "Your NVIDIA driver supports CUDA {has}, but local models require CUDA {needs} or newer. Update your NVIDIA driver, then choose Check again.",+ reasonCudaTooOldNeeds:+ "Your NVIDIA driver is too old for local models (requires CUDA {needs} or newer). Update your NVIDIA driver, then choose Check again.",+ reasonCudaTooOld:+ "Your NVIDIA driver is too old for local models. Update your NVIDIA driver, then choose Check again.",+ reasonCudaUnknownNeeds:+ "Linger couldn't read the CUDA version from your NVIDIA driver (requires CUDA {needs} or newer). Update or reinstall your NVIDIA driver, then choose Check again.",+ reasonCudaUnknown:+ "Linger couldn't read the CUDA version from your NVIDIA driver. Update or reinstall your NVIDIA driver, then choose Check again.",+ reasonUnsupported: "Local models don't run on this system.",+ reasonPlanHeld:+ "Another app is holding the memory it needs, such as another AI app. Quit it.",+ reasonPlanUnavailable: "No local model fits this computer.",+ reasonHeld:+ "Other programs are using the memory it needs. Close other programs.",+ reasonUnavailable: "This computer can't run a local model now.",+ heldGpu: "On hold: The GPU has {free} free, needs {needed}",+ heldGpuOf: "On hold: GPU {gpu} has {free} free, needs {needed}",+ heldMemory: "On hold: {free} of memory free, needs {needed}",+ heldClose: "On hold: close other programs, then Check again.",++ // BYOK fields.+ pathMostProviders: "Most providers",+ pathZhipu: "Zhipu GLM (base https://open.bigmodel.cn)",+ pathVolcano: "Volcano Engine Ark",+ pathNone: "No path. The base URL already has it.",+ endpointNone: "No endpoint. The base URL is the full address.",+ noAnswer: "Linger did not answer.",+ showSuggestions: "Show {field} suggestions",+ baseUrl: "Base URL",+ baseUrlPlaceholder: "Base URL (https://…)",+ apiKeyPlaceholder: "API key (stored privately on this computer)",+ listModels: "List models",+ listingModels: "Listing models",+ test: "Test",+ testing: "Testing…",+ path: "Path",+ pathHeading: "Path · optional",+ endpoint: "Endpoint",+ endpointHeading: "Endpoint · optional",+ defaultTag: "Default",+ runtimeDefault: "{runtime} default",+ model: "Model",+ modelPlaceholder: "Model ID (e.g. gpt-5.4 or claude-sonnet-4-6)",+ modelsHint:+ "Use the refresh button to list the endpoint's models, or type an ID.",+ listingFrom: "Listing models from <url>{url}</url>…",+ modelsFrom: {+ one: "{count} model from <url>{url}</url>",+ other: "{count} models from <url>{url}</url>",+ },+ contextSize: "{size} context",+ connected: "Connected",+ couldNotConnect: "Couldn't connect",+ dismiss: "Dismiss",+ invalidParts: "Path and endpoint must be empty or a path such as /v1.",+ greyDefaults: "Grey values are defaults. Path and endpoint are optional.",+ sendsTo: "Sends {format} requests to <url>{url}</url>",+ sendsToRuntime:+ "Sends {format} (the {runtime} format) requests to <url>{url}</url>",++ // Installing.+ installingTitle: "Installing Linger",+ installStopped: "Installation stopped",+ startingLinger: "Starting Linger",+ preparingUpdate: "Updating Linger on this computer…",+ preparingStart: "Starting Linger on this computer…",+ dataKept: "Your data is kept. Fix the problem and try again.",+ takesMinutes: "This takes a few minutes. You can keep working.",+ stepPrepare: "Checking this computer",+ stepDownload: "Downloading Linger {version}",+ stepServices: "Setting up AI and local services",+ stepWorkspace: "Setting up your account",+ stepSignIn: "Sign in to {runtime}",+ stepSignInRuntime: "Sign in to your AI runtime",+ stepConnect: "Connecting this computer",+ stepAgents: "Preparing your agents",+ stepRunning: "{step}…",+ showDetails: "Show Details",+ hideDetails: "Hide Details",+ showLogs: "Show Logs",+ saveDiagnostics: "Save Diagnostics",+ sendDiagnostics: "Send Diagnostics",+ savedDiagnostics: "Saved {file}. Send this file to Linger support.",+ back: "Back",+ tryAgain: "Try Again",++ // The AI runtime's sign-in.+ signInTo: "Sign in to {runtime}",+ signInLeadPi:+ "Pi needs a model provider. Run pi in a terminal to sign in, or use BYOK below; setup continues by itself.",+ signInLeadCodex:+ "Your agents run on Codex. Authorize it with your ChatGPT account to continue.",+ signInLeadClaude:+ "Your agents run on Claude Code. Authorize it with your Claude account to continue.",+ signInWaiting: "Waiting for authorization in your browser…",+ deviceCode: "Enter this code in your browser:",+ signInFailed: "Sign-in did not finish.",+ authorize: "Authorize",+ retry: "Retry",+ otherRuntime: "Use a different runtime",+ byokInstead: "Use BYOK instead",+ continueWithByok: "Continue with BYOK",+ openBrowserAgain: "Open browser again",+ cancel: "Cancel",+ havingTrouble: "Having trouble?",+ signInHelpCode:+ "If your browser didn't open, choose Open browser again, then paste the code the page shows.",+ signInHelp: "If your browser didn't open, choose Open browser again.",+ pastedCode: "Code from the sign-in page",+ pasteCode: "Paste the code",+ continue: "Continue",++ // Sending diagnostics.+ filesToSend: "Files to send",+ reportId: "Report ID",+ sendPreparing: "Preparing diagnostics",+ sendConfirm: "Send diagnostics to {host}?",+ sendSending: "Sending diagnostics",+ sendSent: "Diagnostics sent",+ sendFailed: "Couldn't send diagnostics",+ sendCollecting: "Collecting logs and settings…",+ sendConfirmLead: {+ one: "{count} file, {size}: logs and settings of this app and of Linger on this computer. Passwords, tokens, keys and your home folder path are removed first; credential files and your data are never included. Only the people who run {host} can read the report.",+ other:+ "{count} files, {size}: logs and settings of this app and of Linger on this computer. Passwords, tokens, keys and your home folder path are removed first; credential files and your data are never included. Only the people who run {host} can read the report.",+ },+ sendUploading: "Uploading to {host}… {percent}%",+ sendSentLead:+ "Give this report ID to Linger support so they can find your report.",+ sendByHand: "You can still use Save Diagnostics and send the file by hand.",+ send: "Send",+ copyReportId: "Copy Report ID",+ copied: "Copied",+ done: "Done",+ close: "Close",++ // Ready.+ readyTitle: "Linger is ready",+ readyLead: "Running on this computer, just for you.",+ computerConnected: "This computer is connected",+ accountTitle: "Your account on this computer",+ email: "Email",+ password: "Password",+ copy: "Copy",+ showPassword: "Show password",+ hidePassword: "Hide password",+ copyPassword: "Copy password",+ accountNote: "Use these to log in again if you log out.",+ accountReveal: "Open account file location",+ legacyNote:+ "Your data from the earlier Simplex app can't be upgraded to Linger, so this is a fresh workspace. The earlier data was moved, not deleted, to {folder}.",+ openLinger: "Open Linger",++ // Connecting to a team server.+ stepOf: "Step {step} of {total}",+ serverTitle: "Where is your team's Linger?",+ serverLead: "Enter the address your team uses for Linger.",+ serverAddress: "Server address",+ serverHint: "Ask your admin if you're not sure.",+ signInTitle: "Sign in to your account",+ signInLead:+ "Linger opens in its own window. Sign in there, and this window moves on by itself.",+ account: "Account",+ signedIn: "Signed in",+ waiting: "Waiting…",+ notSignedIn: "Not signed in",+ openSignIn: "Open Sign-in",+ connectTitle: "Connect this computer",+ connectLead:+ "Your workspace will see this computer and can send it tasks. You can disconnect it at any time.",+ connect: "Connect",+ connecting: "Connecting…",++ // Permissions. The tray icon sits in the menu bar on macOS and in the+ // system tray elsewhere, so those sentences come in both.+ permissionsTitle: "A few permissions",+ changeLaterMenuBar:+ "Change these later from the menu bar or in your system settings.",+ changeLaterTray:+ "Change these later from the system tray or in your system settings.",+ notifications: "Notifications",+ notificationsHint: "Know when a task finishes or needs you.",+ allowNotifications: "Allow Notifications",+ testSent: "Test Sent",+ folders: "Folders",+ foldersHint: "Folders tasks may read and change.",+ addFolder: "Add Folder…",+ fullDiskAccess: "Full Disk Access",+ fullDiskAbout: "Recommended. Covers every folder, no prompts.",+ fullDiskMissing: "Off. Protected folders prompt the first time.",+ userFolders: "Downloads, Documents, Desktop",+ userFoldersAbout: "Lets tasks read these folders.",+ userFoldersMissing: "Not allowed. Tasks can't read these folders.",+ automation: "Control other apps",+ automationAbout: "Lets tasks drive apps like your browser.",+ automationMissing: "Not allowed. Tasks can't control other apps.",+ allowed: "Allowed",+ openSettings: "Open Settings",+ allow: "Allow…",+ preventSleep: "Prevent sleep",+ preventSleepHint: "Keep this computer awake for incoming tasks.",+ openAtLogin: "Open at login",+ openAtLoginMenuBar: "Start in the menu bar when you log in.",+ openAtLoginTray: "Start in the system tray when you log in.",+ startUsing: "Start Using Linger",+});diff --git a/apps/desktop/src/shell/titlebar.html b/apps/desktop/src/shell/titlebar.htmlindex 58acdc87..840e6a99 100644--- a/apps/desktop/src/shell/titlebar.html+++ b/apps/desktop/src/shell/titlebar.html@@ -150,13 +150,13 @@</head><body data-platform="linux"><div class="nav dim-when-blurred">- <button id="back" title="Back" aria-label="Back">+ <button id="back" data-t-title="back" data-t-aria-label="back"><svg viewBox="0 0 24 24"><path d="m15 18-6-6 6-6" /></svg></button>- <button id="forward" title="Forward" aria-label="Forward">+ <button id="forward" data-t-title="forward" data-t-aria-label="forward"><svg viewBox="0 0 24 24"><path d="m9 18 6-6-6-6" /></svg></button>- <button id="reload" title="Reload" aria-label="Reload">+ <button id="reload" data-t-title="reload" data-t-aria-label="reload"><svg viewBox="0 0 24 24"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8" /><path d="M21 3v5h-5" />@@ -167,15 +167,28 @@<strong>Linger</strong><span id="host"></span></div><div class="controls">- <button id="minimize" title="Minimize" aria-label="Minimize">+ <button+ id="minimize"+ data-t-title="minimize"+ data-t-aria-label="minimize"+ ><svg viewBox="0 0 24 24"><path d="M5 12h14" /></svg></button>- <button id="maximize" title="Maximize" aria-label="Maximize">+ <button+ id="maximize"+ data-t-title="maximize"+ data-t-aria-label="maximize"+ ><svg viewBox="0 0 24 24" id="maximize-icon"><rect x="5" y="5" width="14" height="14" rx="1.5" /></svg></button>- <button id="close" class="close" title="Close" aria-label="Close">+ <button+ id="close"+ class="close"+ data-t-title="close"+ data-t-aria-label="close"+ ><svg viewBox="0 0 24 24"><path d="M6 6l12 12M18 6 6 18" /></svg></button></div>@@ -195,7 +208,9 @@$("back").disabled = !state.canGoBack;$("forward").disabled = !state.canGoForward;$("reload").classList.toggle("spinning", state.loading);- $("maximize").title = state.maximized ? "Restore" : "Maximize";+ const maximize = t(state.maximized ? "restore" : "maximize");+ $("maximize").title = maximize;+ $("maximize").setAttribute("aria-label", maximize);$("maximize-icon").innerHTML = state.maximized? restoreIcon: maximizeIcon;diff --git a/apps/desktop/src/shell/titlebar.messages.ts b/apps/desktop/src/shell/titlebar.messages.tsnew file mode 100644index 00000000..85d82af4--- /dev/null+++ b/apps/desktop/src/shell/titlebar.messages.ts@@ -0,0 +1,12 @@+import { defineMessages } from "@linger/service-kit/messages";++// The title bar drawn on Windows and Linux (titlebar.html).+export const titlebarMessages = defineMessages("titlebar", {+ back: "Back",+ forward: "Forward",+ reload: "Reload",+ minimize: "Minimize",+ maximize: "Maximize",+ restore: "Restore",+ close: "Close",+});